import { z } from 'zod'; const errorSchema = z.object({ code: z.string().optional(), error: z.string().optional() }); export class AgentApiError extends Error { constructor( public readonly status: number, public readonly code?: string ) { super(`Agent request failed (HTTP ${status}).${code ? ` Code: ${code}.` : ''}`); } } export async function agentRequest(url: string, init?: RequestInit): Promise { try { const timeout = AbortSignal.timeout(30_000); const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout; return await fetch(url, { ...init, redirect: 'error', signal }); } catch { throw new Error('Could not reach the agent service. Retry the same command.'); } } export async function agentResponse(response: Response, schema: z.ZodType): Promise { const body: unknown = await response.json().catch(() => null); if (!response.ok) { const error = errorSchema.safeParse(body); const code = error.success ? (error.data.code ?? error.data.error) : undefined; throw new AgentApiError(response.status, code?.match(/^[a-z_]{1,80}$/)?.[0]); } const parsed = schema.safeParse(body); if (!parsed.success) throw new Error('The agent service returned an unexpected response.'); return parsed.data; }