import {z} from 'zod' export type JsonRpcRequest = {jsonrpc: '2.0', id?: (string | number | null) | undefined, method: 'SendMessage' | 'GetTask' | 'ListTasks' | 'CancelTask', params: {[key: string]: unknown}}; export type CreateApiA2aArgs = {'A2A-Version'?: '1.0' | undefined, body: JsonRpcRequest}; export type CreateApiA2aOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const jsonRpcResponse = z.object({jsonrpc: z.literal("2.0"), id: z.union([z.string(), z.number().int()]).nullable(), result: z.unknown(), error: z.object({code: z.number().int(), message: z.string(), data: z.unknown()}).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Send an A2A 1.0 JSON-RPC request * * POST /a2a */ export const createApiA2a = async (args: CreateApiA2aArgs, options?: CreateApiA2aOptions) => { const {baseUrl = "https://api.temp.md", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/a2a+json") if (args['A2A-Version'] != null) headers.set("A2A-Version", String(args['A2A-Version'])) const url = `${baseUrl.replace(/\/+$/, '')}/a2a${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(jsonRpcResponse, await res.json()) };