import {z} from 'zod' export type FiHookEvent = {hook_event_name: 'UserPromptSubmit' | 'PreToolUse' | 'PostToolUse' | 'Stop', session_id: string, transcript_path: string, cwd?: (string | null) | undefined, permission_mode?: (string | null) | undefined, prompt?: (string | null) | undefined, tool_name?: (string | null) | undefined, tool_input?: ({[key: string]: unknown} | null) | undefined, tool_response: unknown, tool_use_id?: (string | null) | undefined, stop_hook_active?: (boolean | null) | undefined, last_assistant_message?: (string | null) | undefined}; export type CreateApiV4FiHookArgs = {authorization?: (string | null) | undefined, body: FiHookEvent}; export type CreateApiV4FiHookOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const fiHookResponse = z.object({ok: z.boolean(), panels_written: z.number().int().optional(), note: z.string().nullable().optional()}); export const responseMeta = z.object({requestId: z.string().optional(), timestamp: z.string().optional(), durationMs: z.number().int().nullable().optional()}); export const successResponseFiHookResponse = z.object({success: z.literal(true), data: fiHookResponse, meta: responseMeta.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 }; /** * Claude Code hook event from a Fi sandbox * * POST /v4/fi/hook */ export const createApiV4FiHook = async (args: CreateApiV4FiHookArgs, options: CreateApiV4FiHookOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.authorization != null) headers.set("authorization", String(args.authorization)) const url = `${baseUrl.replace(/\/+$/, '')}/v4/fi/hook${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(successResponseFiHookResponse, await res.json()) };