// The OpenAI-compatible wire (architecture, "The kernel owns shared mechanics"): the chat completions and Responses // shapes that many vendors serve as OpenAI defines them (OpenRouter, xAI, DeepSeek, Groq, Together, Fireworks, Cerebras // and more), for generative packs that run no model. A pack decides its turn (the World's scenario's, else a stub) and // its own facts (its ids, a provider field, a keep-alive comment); this module shapes the answer and its Server-Sent // Events as the wire defines them (https://platform.openai.com/docs/api-reference/chat and /responses). Importing it does // nothing. import type { HandlerContext } from './derived-core.ts'; import type { PackScenario } from './pack-fetch.ts'; import type { PackScenarioAdapter, ScenarioDecision, ScenarioFeatures } from './scenario.ts'; import { sampleFromSchema } from './schema-sample.ts'; type Row = Record; const obj = (v: unknown): Row => (v && typeof v === 'object' && !Array.isArray(v) ? v as Row : {}); const arr = (v: unknown): Row[] => (Array.isArray(v) ? v as Row[] : []); /** A turn: the text, or tool calls, the reasoning when there is some, and why it finished. */ export type WireTurn = { text?: string | null; toolCalls?: Array<{ name: string; arguments: Row }>; reasoning?: string | null; reasoningDetails?: Row[]; finishReason?: string }; /** Tokens, estimated at about four characters a token: a twin's count, not a tokenizer's. */ export const estimateTokens = (text: string): number => Math.max(1, Math.ceil(text.length / 4)); // ── chat completions: requests ───────────────────────────────────────────────────────────────── /** A message's content as text: a string, or its text parts joined. */ export const chatText = (content: unknown): string => (typeof content === 'string' ? content : arr(content).map((p) => (typeof p.text === 'string' ? p.text : '')).join('')); /** The last user message's text. */ export function chatLastUserText(messages: Row[]): string { for (let i = messages.length - 1; i >= 0; i--) if (messages[i]!.role === 'user') return chatText(messages[i]!.content); return ''; } /** The tool results the last message carries (a `tool` message), by its name or call id. */ export const chatToolResults = (messages: Row[]): string[] => (messages.at(-1)?.role === 'tool' ? [String(messages.at(-1)!.name ?? messages.at(-1)!.tool_call_id ?? '')] : []); /** The labeled stub for a chat request: with tools offered (`tool_choice` not `none`) and the last message not a tool's * result, it calls the tool the choice names, else the first, with arguments its schema admits; with a JSON response * format, it answers a value the schema admits; otherwise it echoes the last user message. `label` names the twin. */ export function chatStubTurn(body: Row, label: string): WireTurn { const model = String(body.model); const messages = arr(body.messages); const tools = arr(body.tools).filter((t) => obj(t.function).name !== undefined); const choice = body.tool_choice ?? 'auto'; const named = typeof choice === 'object' ? String(obj(obj(choice).function).name ?? '') : ''; if (tools.length && choice !== 'none' && (chatToolResults(messages).length === 0 || choice === 'required' || named)) { const f = obj(((named ? tools.find((t) => obj(t.function).name === named) : undefined) ?? tools[0]!).function); return { toolCalls: [{ name: String(f.name), arguments: sampleFromSchema(f.parameters, String(f.name)) as Row }] }; } const format = obj(body.response_format); if (format.type === 'json_schema') return { text: JSON.stringify(sampleFromSchema(obj(format.json_schema).schema)) }; if (format.type === 'json_object') return { text: JSON.stringify({ twin_stub: `deterministic stub from the ${label} (${model}): no model runs` }) }; const said = chatLastUserText(messages).trim(); return { text: `[twin-stub:${model}] This is a deterministic stub from the ${label} (no model runs). Your last message: ${said.length > 200 ? `${said.slice(0, 200)}…` : said || '(empty)'}` }; } // ── chat completions: answers ────────────────────────────────────────────────────────────────── export type ChatShape = { id: string; model: string; created: number; turn: WireTurn; messages: Row[]; /** the request's max_tokens / max_completion_tokens: a longer text is cut there and finishes `length` */ maxTokens?: number; /** each tool call's id */ callId: (i: number) => string; /** fields a vendor adds at the top of the answer and of each chunk (OpenRouter's `provider`) */ extra?: Row; /** top-level fields on interim stream chunks instead of extra; terminal chunks retain extra */ interimExtra?: Row; /** fields a vendor adds to the usage (OpenRouter's `cost`) */ usageExtra?: Row; /** the vendor also answers the provider's own finish reason (`native_finish_reason`) */ nativeFinish?: boolean; /** the name the reasoning takes in a message (`reasoning`, or `reasoning_content`) */ reasoningField?: string; }; function chatParts(s: ChatShape): { text: string | null; finish: string; calls: Row[]; usage: Row; reasoning: string | null } { let text = s.turn.text ?? null; let finish = s.turn.finishReason ?? (s.turn.toolCalls?.length ? 'tool_calls' : 'stop'); if (text !== null && s.maxTokens !== undefined && estimateTokens(text) > s.maxTokens) { text = text.slice(0, s.maxTokens * 4); finish = 'length'; } const calls = (s.turn.toolCalls ?? []).map((c, i) => ({ id: s.callId(i), type: 'function', function: { name: c.name, arguments: JSON.stringify(c.arguments ?? {}) } })); const reasoning = s.turn.reasoning ?? null; const prompt = estimateTokens(s.messages.map((m) => chatText(m.content)).join('\n')); const completion = estimateTokens([text ?? '', ...calls.map((c) => (c.function as Row).arguments as string)].join('')); const reasoningTokens = reasoning ? estimateTokens(reasoning) : 0; const usage = { prompt_tokens: prompt, completion_tokens: completion + reasoningTokens, total_tokens: prompt + completion + reasoningTokens, prompt_tokens_details: { cached_tokens: 0 }, completion_tokens_details: { reasoning_tokens: reasoningTokens }, ...(s.usageExtra ?? {}), }; return { text, finish, calls, usage, reasoning }; } /** A chat completion's body (`object: chat.completion`), one choice. */ export function chatCompletion(s: ChatShape): Row { const p = chatParts(s); const field = s.reasoningField ?? 'reasoning'; const message = { role: 'assistant', content: p.text, refusal: null, ...(p.reasoning ? { [field]: p.reasoning } : {}), ...(s.turn.reasoningDetails ? { reasoning_details: s.turn.reasoningDetails } : {}), ...(p.calls.length ? { tool_calls: p.calls } : {}) }; return { id: s.id, ...(s.extra ?? {}), model: s.model, object: 'chat.completion', created: s.created, choices: [{ index: 0, message, logprobs: null, finish_reason: p.finish, ...(s.nativeFinish ? { native_finish_reason: p.finish } : {}) }], usage: p.usage, }; } /** A chat completion streamed: its chunks (`object: chat.completion.chunk`) as Server-Sent Events, the text in two * deltas, the last chunk carrying the finish reason and the usage, then `data: [DONE]`. `comment` is a keep-alive a * vendor sends first (OpenRouter's `: OPENROUTER PROCESSING`). */ export function chatCompletionSSE(s: ChatShape & { comment?: string; separateUsageChunk?: boolean }): string { const p = chatParts(s); const field = s.reasoningField ?? 'reasoning'; const chunk = (delta: Row, last: boolean, usage = last): string => `data: ${JSON.stringify({ id: s.id, ...((last ? s.extra : s.interimExtra ?? s.extra) ?? {}), model: s.model, object: 'chat.completion.chunk', created: s.created, choices: [{ index: 0, delta, logprobs: null, finish_reason: last ? p.finish : null, ...(s.nativeFinish ? { native_finish_reason: last ? p.finish : null } : {}) }], ...(usage ? { usage: p.usage } : {}), })}\n\n`; const half = p.text ? Math.ceil(p.text.length / 2) : 0; return [ ...(s.comment ? [`: ${s.comment}\n\n`] : []), ...(p.reasoning || s.turn.reasoningDetails ? [chunk({ role: 'assistant', content: '', ...(p.reasoning ? { [field]: p.reasoning } : {}), ...(s.turn.reasoningDetails ? { reasoning_details: s.turn.reasoningDetails } : {}) }, false)] : []), ...(p.text ? [chunk({ role: 'assistant', content: p.text.slice(0, half) }, false), ...(p.text.length > half ? [chunk({ content: p.text.slice(half) }, false)] : [])] : []), ...(p.calls.length ? [chunk({ role: 'assistant', content: null, tool_calls: p.calls.map((c, i) => ({ index: i, ...c })) }, false)] : []), chunk(s.separateUsageChunk ? { role: 'assistant', content: '' } : {}, true, !s.separateUsageChunk), ...(s.separateUsageChunk ? [chunk({ role: 'assistant', content: '' }, true, true)] : []), 'data: [DONE]\n\n', ].join(''); } // ── the AI SDK's language-model protocol (Vercel's AI Gateway) ───────────────────────────────────── // `@ai-sdk/gateway` posts a model call's options as `@ai-sdk/provider`'s LanguageModelV4 defines them (the model in the // `ai-language-model-id` header) and reads back its generate result, or its stream parts as Server-Sent Events // (https://unpkg.com/@ai-sdk/provider@4.0.14/dist/index.d.ts, `LanguageModelV4GenerateResult`, `LanguageModelV4StreamPart`). /** A V4 call's options as the chat completions request they mean: its prompt as messages, its tools, tool choice, * response format and output limit; so the chat stub and the wire's scenario read it. */ export function aiSdkChatBody(call: Row, model: string): Row { const text = (content: unknown): string => (typeof content === 'string' ? content : arr(content).filter((p) => p.type === 'text' || p.type === 'reasoning').map((p) => String(p.text ?? '')).join('')); const messages: Row[] = []; for (const m of arr(call.prompt)) { if (m.role === 'tool') for (const r of arr(m.content).filter((p) => p.type === 'tool-result')) messages.push({ role: 'tool', tool_call_id: r.toolCallId, name: r.toolName, content: JSON.stringify(r.output ?? null) }); else if (m.role === 'assistant') { const calls = arr(m.content).filter((p) => p.type === 'tool-call').map((c) => ({ id: c.toolCallId, type: 'function', function: { name: c.toolName, arguments: typeof c.input === 'string' ? c.input : JSON.stringify(c.input ?? {}) } })); messages.push({ role: 'assistant', content: text(m.content), ...(calls.length ? { tool_calls: calls } : {}) }); } else messages.push({ role: String(m.role ?? 'user'), content: text(m.content) }); } const tools = arr(call.tools).filter((x) => x.type === 'function').map((x) => ({ type: 'function', function: { name: x.name, description: x.description, parameters: x.inputSchema } })); const choice = obj(call.toolChoice); const format = obj(call.responseFormat); return { model, messages, ...(tools.length ? { tools } : {}), ...(choice.type === 'tool' ? { tool_choice: { type: 'function', function: { name: choice.toolName } } } : typeof choice.type === 'string' ? { tool_choice: choice.type } : {}), ...(format.type === 'json' ? { response_format: format.schema ? { type: 'json_schema', json_schema: { name: format.name ?? 'response', schema: format.schema } } : { type: 'json_object' } } : {}), ...(typeof call.maxOutputTokens === 'number' ? { max_tokens: call.maxOutputTokens } : {}), }; } const UNIFIED: Record = { stop: 'stop', length: 'length', tool_calls: 'tool-calls', content_filter: 'content-filter' }; function lmParts(s: ChatShape): { content: Row[]; finishReason: Row; usage: Row } { const p = chatParts(s); const u = p.usage as { prompt_tokens: number; completion_tokens: number; completion_tokens_details: { reasoning_tokens: number } }; return { content: [ ...(p.reasoning ? [{ type: 'reasoning', text: p.reasoning }] : []), ...(p.text !== null ? [{ type: 'text', text: p.text }] : []), ...p.calls.map((c) => ({ type: 'tool-call', toolCallId: c.id, toolName: (c.function as Row).name, input: (c.function as Row).arguments })), ], finishReason: { unified: UNIFIED[p.finish] ?? 'other', raw: p.finish }, usage: { inputTokens: { total: u.prompt_tokens, noCache: u.prompt_tokens, cacheRead: 0, cacheWrite: 0 }, outputTokens: { total: u.completion_tokens, text: u.completion_tokens - u.completion_tokens_details.reasoning_tokens, reasoning: u.completion_tokens_details.reasoning_tokens }, }, }; } /** A V4 generate result: the turn's content (reasoning, text, tool calls with their input as JSON text), its finish * reason (unified, and the raw one) and its usage; `extra` is what the server adds (the gateway's provider metadata). */ export function languageModelResult(s: ChatShape): Row { const r = lmParts(s); return { ...r, response: { id: s.id, modelId: s.model, timestamp: new Date(s.created * 1000).toISOString() }, warnings: [], ...(s.extra ?? {}) }; } /** A V4 stream: its parts as Server-Sent Events (stream-start, response-metadata, the reasoning, the text in two deltas, * each tool call's input then the call, and the finish), with no `[DONE]`: the SDK reads every event as a part. */ export function languageModelSSE(s: ChatShape): string { const r = lmParts(s); const out: Row[] = [{ type: 'stream-start', warnings: [] }, { type: 'response-metadata', id: s.id, modelId: s.model, timestamp: new Date(s.created * 1000).toISOString() }]; for (const [i, c] of r.content.entries()) { if (c.type === 'reasoning') out.push({ type: 'reasoning-start', id: `reasoning-${i}` }, { type: 'reasoning-delta', id: `reasoning-${i}`, delta: c.text }, { type: 'reasoning-end', id: `reasoning-${i}` }); else if (c.type === 'text') { const text = String(c.text); const half = Math.ceil(text.length / 2); out.push({ type: 'text-start', id: `text-${i}` }, { type: 'text-delta', id: `text-${i}`, delta: text.slice(0, half) }, ...(text.length > half ? [{ type: 'text-delta', id: `text-${i}`, delta: text.slice(half) }] : []), { type: 'text-end', id: `text-${i}` }); } else out.push({ type: 'tool-input-start', id: c.toolCallId, toolName: c.toolName }, { type: 'tool-input-delta', id: c.toolCallId, delta: c.input }, { type: 'tool-input-end', id: c.toolCallId }, c); } out.push({ type: 'finish', finishReason: r.finishReason, usage: r.usage, ...(s.extra ?? {}) }); return out.map((part) => `data: ${JSON.stringify(part)}\n\n`).join(''); } // ── Responses: requests ──────────────────────────────────────────────────────────────────────── /** A Responses request's input as items: a string is one user message. */ export const responsesItems = (input: unknown): Row[] => (typeof input === 'string' ? [{ type: 'message', role: 'user', content: input }] : arr(input)); const itemText = (content: unknown): string => (typeof content === 'string' ? content : arr(content).map((p) => (typeof p.text === 'string' ? p.text : '')).join('')); /** The last user message's text in a Responses input. */ export function responsesLastUserText(input: unknown): string { const items = responsesItems(input); for (let i = items.length - 1; i >= 0; i--) if ((items[i]!.role ?? (items[i]!.type === 'message' ? 'user' : '')) === 'user') return itemText(items[i]!.content); return ''; } /** The function-call outputs the input ends with. */ export const responsesToolResults = (input: unknown): string[] => responsesItems(input).filter((i) => i.type === 'function_call_output').map((i) => String(i.call_id ?? '')); /** The labeled stub for a Responses request: a function tool is called (unless the input already carries its output or * `tool_choice` is `none`), a JSON schema format answers a value it admits, otherwise the last user text is echoed. */ export function responsesStubTurn(body: Row, label: string): WireTurn { const model = String(body.model); const tools = arr(body.tools).filter((t) => t.type === 'function' && typeof t.name === 'string'); const choice = body.tool_choice ?? 'auto'; const named = typeof choice === 'object' ? String(obj(choice).name ?? '') : ''; if (tools.length && choice !== 'none' && (responsesToolResults(body.input).length === 0 || choice === 'required' || named)) { const t = (named ? tools.find((x) => x.name === named) : undefined) ?? tools[0]!; return { toolCalls: [{ name: String(t.name), arguments: sampleFromSchema(t.parameters, String(t.name)) as Row }] }; } const format = obj(obj(body.text).format); if (format.type === 'json_schema') return { text: JSON.stringify(sampleFromSchema(format.schema)) }; if (format.type === 'json_object') return { text: JSON.stringify({ twin_stub: `deterministic stub from the ${label} (${model}): no model runs` }) }; const said = responsesLastUserText(body.input).trim(); return { text: `[twin-stub:${model}] This is a deterministic stub from the ${label} (no model runs). Your last message: ${said.length > 200 ? `${said.slice(0, 200)}…` : said || '(empty)'}` }; } // ── Responses: answers ───────────────────────────────────────────────────────────────────────── export type ResponsesShape = { id: string; model: string; createdAt: number; turn: WireTurn; body: Row; /** ids for the output items: the message, the reasoning, each function call and its call id */ itemId: (kind: 'msg' | 'rs' | 'fc' | 'call', i: number) => string; extra?: Row; /** Vendor defaults; explicit request values win, including nullable gateway defaults. */ defaults?: Row; }; /** A Responses object (`object: response`, `status: completed`): its output items (the reasoning when there is some, * the message with its output text, or function calls) and its usage. */ export function responsesAnswer(s: ResponsesShape): Row { const b = s.body; const defaultOf = (field: string, fallback: unknown): unknown => s.defaults && Object.hasOwn(s.defaults, field) ? s.defaults[field] : fallback; let text = s.turn.text ?? null; const max = typeof b.max_output_tokens === 'number' ? b.max_output_tokens : undefined; let incomplete: Row | null = null; if (text !== null && max !== undefined && estimateTokens(text) > max) { text = text.slice(0, max * 4); incomplete = { reason: 'max_output_tokens' }; } const output: Row[] = [ ...(s.turn.reasoning ? [{ type: 'reasoning', id: s.itemId('rs', 0), summary: [{ type: 'summary_text', text: s.turn.reasoning }], status: 'completed' }] : []), ...(text !== null ? [{ type: 'message', id: s.itemId('msg', 0), status: incomplete ? 'incomplete' : 'completed', role: 'assistant', content: [{ type: 'output_text', text, annotations: [], logprobs: [] }] }] : []), ...(s.turn.toolCalls ?? []).map((c, i) => ({ type: 'function_call', id: s.itemId('fc', i), call_id: s.itemId('call', i), name: c.name, arguments: JSON.stringify(c.arguments ?? {}), status: 'completed' })), ]; const input = estimateTokens([String(b.instructions ?? ''), ...responsesItems(b.input).map((i) => itemText(i.content ?? i.output))].join('\n')); const out = estimateTokens([text ?? '', ...(s.turn.toolCalls ?? []).map((c) => JSON.stringify(c.arguments ?? {}))].join('')); const reasoningTokens = s.turn.reasoning ? estimateTokens(s.turn.reasoning) : 0; return { id: s.id, object: 'response', created_at: s.createdAt, status: incomplete ? 'incomplete' : 'completed', ...(s.extra ?? {}), error: null, incomplete_details: incomplete, instructions: b.instructions ?? null, max_output_tokens: max ?? null, model: s.model, output, parallel_tool_calls: b.parallel_tool_calls ?? true, previous_response_id: b.previous_response_id ?? null, reasoning: { effort: obj(b.reasoning).effort ?? null, summary: obj(b.reasoning).summary ?? null }, store: b.store ?? defaultOf('store', true), temperature: b.temperature ?? defaultOf('temperature', 1), text: b.text ?? { format: { type: 'text' } }, tool_choice: b.tool_choice ?? 'auto', tools: b.tools ?? [], top_p: b.top_p ?? defaultOf('top_p', 1), usage: { input_tokens: input, input_tokens_details: { cached_tokens: 0 }, output_tokens: out + reasoningTokens, output_tokens_details: { reasoning_tokens: reasoningTokens }, total_tokens: input + out + reasoningTokens }, metadata: b.metadata ?? defaultOf('metadata', {}), }; } /** A Responses object streamed: the events the wire sends (`response.created`, `response.in_progress`, each output * item's added, its text deltas and done, `response.completed`), each `event:` and `data:` with its sequence number. */ export function responsesSSE(s: ResponsesShape): string { const done = responsesAnswer(s); const pending = { ...done, status: 'in_progress', output: [], usage: null }; const events: Row[] = [{ type: 'response.created', response: pending }, { type: 'response.in_progress', response: pending }]; for (const [i, item] of (done.output as Row[]).entries()) { if (item.type === 'message') { const text = String(((item.content as Row[])[0] ?? {}).text ?? ''); events.push({ type: 'response.output_item.added', output_index: i, item: { ...item, status: 'in_progress', content: [] } }); events.push({ type: 'response.content_part.added', item_id: item.id, output_index: i, content_index: 0, part: { type: 'output_text', text: '', annotations: [] } }); const half = Math.ceil(text.length / 2); for (const delta of [text.slice(0, half), text.slice(half)].filter(Boolean)) events.push({ type: 'response.output_text.delta', item_id: item.id, output_index: i, content_index: 0, delta, logprobs: [] }); events.push({ type: 'response.output_text.done', item_id: item.id, output_index: i, content_index: 0, text, logprobs: [] }); events.push({ type: 'response.content_part.done', item_id: item.id, output_index: i, content_index: 0, part: (item.content as Row[])[0] }); } else if (item.type === 'function_call') { events.push({ type: 'response.output_item.added', output_index: i, item: { ...item, arguments: '', status: 'in_progress' } }); events.push({ type: 'response.function_call_arguments.delta', item_id: item.id, output_index: i, delta: item.arguments }); events.push({ type: 'response.function_call_arguments.done', item_id: item.id, output_index: i, arguments: item.arguments }); } else { // announced empty, as a message item is: an SDK's accumulator appends each summary part the events below add events.push({ type: 'response.output_item.added', output_index: i, item: { ...item, summary: [], status: 'in_progress' } }); for (const [n, summary] of arr(item.summary).entries()) { events.push({ type: 'response.reasoning_summary_part.added', item_id: item.id, output_index: i, summary_index: n, part: { type: 'summary_text', text: '' } }); events.push({ type: 'response.reasoning_summary_text.delta', item_id: item.id, output_index: i, summary_index: n, delta: summary.text }); events.push({ type: 'response.reasoning_summary_text.done', item_id: item.id, output_index: i, summary_index: n, text: summary.text }); events.push({ type: 'response.reasoning_summary_part.done', item_id: item.id, output_index: i, summary_index: n, part: summary }); } } events.push({ type: 'response.output_item.done', output_index: i, item }); } events.push({ type: done.status === 'incomplete' ? 'response.incomplete' : 'response.completed', response: done }); return events.map((e, n) => `event: ${String(e.type)}\ndata: ${JSON.stringify({ ...e, sequence_number: n })}\n\n`).join(''); } // ── the scenario ─────────────────────────────────────────────────────────────────────────────── // A generative pack's turn is the World's scenario's when it scripts one (architecture, "Behaviour"): the same request // features, `on` matchers and `respond` keys for every vendor on this wire, over a chat completion or a Responses // request alike. The pack names its vendor, its operations and its fault's error body. export type WireRequest = { model: string; text: string; lastUser: string; tools: string[]; results: string[]; toolsForbidden?: boolean }; /** Whether a request forbids every tool call: OpenAI's `tool_choice: 'none'`, Anthropic's `{ type: 'none' }`. */ export const forbidsTools = (choice: unknown): boolean => choice === 'none' || obj(choice).type === 'none'; /** The turn a scenario's decision scripts (`respond`: text, toolCalls, reasoning, finishReason), or undefined. */ export function scenarioTurn(decision: ScenarioDecision | undefined): WireTurn | undefined { if (!decision || decision.kind !== 'handler' || decision.fault?.kind === 'generation') return undefined; const r = obj(decision.respond); return { ...(typeof r.text === 'string' ? { text: r.text } : {}), ...(r.toolCalls !== undefined ? { toolCalls: (Array.isArray(r.toolCalls) ? r.toolCalls : [r.toolCalls]) as WireTurn['toolCalls'] } : {}), ...(typeof r.reasoning === 'string' ? { reasoning: r.reasoning } : {}), ...(Array.isArray(r.reasoningDetails) ? { reasoningDetails: r.reasoningDetails as Row[] } : {}), ...(typeof r.finishReason === 'string' ? { finishReason: r.finishReason } : {}), }; } const nonEmpty = (v: unknown): v is string => typeof v === 'string' && v.length > 0; const RESPOND_KEYS = new Set(['text', 'toolCalls', 'reasoning', 'reasoningDetails', 'finishReason']); /** A request as the scenario reads it: its model, its text, its last user text, the tools it offers and the tool * results it ends with, from a chat completion's messages or a Responses input. */ export function wireRequest(body: Row): WireRequest { const messages = arr(body.messages); const tools = arr(body.tools).map((t) => String(obj(t.function).name ?? t.name ?? '')).filter(Boolean); const forbidden = forbidsTools(body.tool_choice) ? { toolsForbidden: true } : {}; if (messages.length) return { model: String(body.model ?? ''), text: messages.map((m) => chatText(m.content)).join('\n'), lastUser: chatLastUserText(messages), tools, results: chatToolResults(messages), ...forbidden }; const items = responsesItems(body.input); return { model: String(body.model ?? ''), text: [String(body.instructions ?? ''), ...items.map((i) => itemText(i.content))].join('\n'), lastUser: responsesLastUserText(body.input), tools, results: responsesToolResults(body.input), ...forbidden }; } /** The scenario of a vendor on this wire: its operations, and its error body for a scripted fault. `readers` reads an * operation whose request is another wire's (a gateway's Anthropic Messages surface: anthropicWire's * `messagesWireRequest`), so one scenario scripts every surface's turns alike. */ export function scenario(vendor: string, operations: string[], faultBody: (status: number, message: string | undefined) => unknown, readers: Record WireRequest> = {}): PackScenario { const adapter: PackScenarioAdapter = { vendor, renderFault: (f) => ({ body: faultBody(f.status, f.message) }), features: (r): ScenarioFeatures => ({ model: r.model, lastUserText: r.lastUser.slice(0, 300), tools: r.tools, lastMessageIsToolResult: r.results.length > 0, toolResultFor: r.results }), matchers: { modelEquals: (r, c) => nonEmpty(c) && r.model === c, userTextIncludes: (r, c) => nonEmpty(c) && r.lastUser.toLowerCase().includes(c.toLowerCase()), anyTextIncludes: (r, c) => nonEmpty(c) && r.text.toLowerCase().includes(c.toLowerCase()), lastMessageIsToolResult: (r, c) => typeof c === 'boolean' && (r.results.length > 0) === c, toolResultFor: (r, c) => nonEmpty(c) && r.results.includes(c), hasTool: (r, c) => nonEmpty(c) && r.tools.includes(c), }, // source: https://platform.openai.com/docs/api-reference/chat/create "none means the model will not call any tool and instead generates a message" admits: (r, respond) => !(r.toolsForbidden && obj(respond).toolCalls !== undefined), validateOn: (on) => { for (const k of ['modelEquals', 'userTextIncludes', 'anyTextIncludes', 'toolResultFor', 'hasTool'] as const) if (on[k] !== undefined && !nonEmpty(on[k])) return `on.${k} is a non-empty string`; if (on.lastMessageIsToolResult !== undefined && typeof on.lastMessageIsToolResult !== 'boolean') return 'on.lastMessageIsToolResult is a boolean'; return null; }, validateRespond: (respond) => { if (typeof respond !== 'object' || respond === null || Array.isArray(respond)) return 'respond is an object { text?, toolCalls?, reasoning?, reasoningDetails?, finishReason? }'; const r = respond as Row; for (const k of Object.keys(r)) if (!RESPOND_KEYS.has(k)) return `respond: unknown key "${k}" (valid: ${[...RESPOND_KEYS].join(', ')})`; if (r.text !== undefined && typeof r.text !== 'string') return 'respond.text is a string'; if (r.reasoningDetails !== undefined && (!Array.isArray(r.reasoningDetails) || r.reasoningDetails.some((d) => !d || typeof d !== 'object' || Array.isArray(d)))) return 'respond.reasoningDetails is an array of JSON objects'; if (r.reasoning !== undefined && typeof r.reasoning !== 'string') return 'respond.reasoning is a string'; for (const c of r.toolCalls === undefined ? [] : Array.isArray(r.toolCalls) ? r.toolCalls : [r.toolCalls]) { const u = c as Row; if (!u || typeof u !== 'object' || Array.isArray(u) || !nonEmpty(u.name)) return 'respond.toolCalls[].name is a non-empty string'; } if (r.text === undefined && r.toolCalls === undefined) return 'respond needs text or toolCalls'; return null; }, }; // a V4 call (the AI SDK's protocol) is read as the chat request it means, its model in its header const request = (ctx: HandlerContext): WireRequest => { const body = (ctx.body ?? {}) as Row; const read = Object.hasOwn(readers, ctx.call.operation.id) ? readers[ctx.call.operation.id] : undefined; if (read) return read(body); return wireRequest(Array.isArray(body.prompt) ? aiSdkChatBody(body, ctx.call.request.headers.get('ai-language-model-id') ?? '') : body); }; return { adapter, operations, request }; } /** An admitted generation that fails: partial JSON or actual Chat Completions error frames. * The pack supplies its error envelope/type; the shared wire owns the SDK framing. */ export function chatCompletionFailure(s: { id: string; model: string; created: number; error: Row; text?: string; extra?: Row }, stream: boolean): Row | string { const common = { id: s.id, model: s.model, created: s.created, ...s.extra }; if (!stream) return { ...common, object: 'chat.completion', choices: [{ index: 0, message: { role: 'assistant', content: s.text ?? '' }, finish_reason: 'error', error: s.error }] }; const frames: Row[] = []; if (s.text) frames.push({ ...common, object: 'chat.completion.chunk', choices: [{ index: 0, delta: { role: 'assistant', content: s.text }, finish_reason: null }] }); frames.push({ ...common, object: 'chat.completion.chunk', choices: [{ index: 0, delta: { content: '' }, finish_reason: 'error' }], error: s.error }); return frames.map((f) => `data: ${JSON.stringify(f)}\n\n`).join('') + 'data: [DONE]\n\n'; } /** Responses generation failures keep the response's canonical fields and native error code. */ export function responsesFailure(response: Row, stream: boolean, event = 'response.failed'): Row | string { if (!stream) return response; const data = event === 'response.failed' ? { type: event, response } : { type: event, error: response.error }; return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; }