@a-dray/aglib 0.3.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/openai-responses/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAQ5D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAE1D,MAAM,QAAQ,GAAG,kBAAkB,CAAC;AACpC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,YAAY,GAAG,EAAE,CAAC;AAgDxB,MAAM,YAAY;IACP,WAAW,CAA4B;IACvC,MAAM,GAAG,IAAI,GAAG,EAAmB,CAAC;IACpC,QAAQ,GAAa,EAAE,CAAC;IACxB,MAAM,CAAa;IAC5B,gBAAgB,GAAG,CAAC,CAAC;IACrB,UAAU,GAAG,CAAC,CAAC;IACf,SAAS,GAAG,KAAK,CAAC;IAClB,MAAM,GAAG,KAAK,CAAC;IAEf,YAAY,UAAqC,EAAE,KAAiB;QAClE,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;QAC9B,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QACpB,KAAK,IAAI,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;IAED,IAAI;QACF,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,gBAAgB,IAAI,kBAAkB;YAAE,OAAO,SAAS,CAAC;QACnG,IAAI,EAAE,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC;QAC7B,IAAI,CAAC,EAAE,EAAE,CAAC;YACR,IAAI,IAAI,CAAC,UAAU,IAAI,YAAY;gBAAE,OAAO,SAAS,CAAC;YACtD,EAAE,GAAG,SAAS,MAA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AS,CAAC;AACtH,MAAM,KAAK,GAAG,CAAC,KAAc,EAAsB,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AACxF,MAAM,MAAM,GAAG,CAAC,KAAc,EAAsB,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACrG,MAAM,MAAM,GAAG,CAAC,KAAc,EAAsB,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC","sourcesContent":["import OpenAI from \"openai\";\nimport { ResponsesWS } from \"openai/resources/responses/ws\";\nimport type { ResponsesClientEvent } from \"openai/resources/responses/responses\";\nimport type {\n Message, Model, ModelDelta, ModelError, ModelGeneration, ModelRequest,\n ModelResponse, ModelSteerResult, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport type { Content } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\n\nconst provider = \"openai-responses\";\nconst maxActiveResponses = 16;\nconst maxStreamIds = 32;\n\ninterface StreamEnvelope {\n type: string;\n message?: unknown;\n error?: unknown;\n code?: number;\n reason?: string;\n}\n\n/** The small part of ResponsesWS used here, injectable so the wire can be tested without a model call. */\nexport interface OpenAiResponsesConnection {\n send(event: unknown): void;\n close(): void;\n [Symbol.asyncIterator](): AsyncIterableIterator<StreamEnvelope>;\n}\n\nexport interface OpenAiResponsesOptions {\n apiKey: string;\n model: string;\n baseURL?: string;\n headers?: Readonly<Record<string, string>>;\n /** Declare function tools with OpenAI's asynchronous execution extension. */\n asyncTools?: boolean;\n /** Expose mid-generation steering. The provider remains the capability authority. */\n steering?: boolean;\n /** Injectable for tests; the default is the official SDK's ResponsesWS. */\n connect?: () => OpenAiResponsesConnection;\n}\n\nexport interface OpenAiResponsesModel extends Model {\n /** Close the reusable WebSocket and fail any generations still using it. */\n close(): void;\n}\n\ninterface ResponsesLane extends AsyncIterable<StreamEnvelope> {\n send(event: ResponsesClientEvent): void;\n /** Stop this consumer while leaving the shared transport available to other lanes. */\n cancel(): void;\n /** Release a terminal lane for reuse, or quarantine an unfinished lane. */\n release(terminal: boolean): void;\n}\n\ninterface HubLane {\n active: boolean;\n queue: EnvelopeQueue;\n}\n\nclass ResponsesHub {\n readonly #connection: OpenAiResponsesConnection;\n readonly #lanes = new Map<string, HubLane>();\n readonly #freeIds: string[] = [];\n readonly #onEnd: () => void;\n #activeResponses = 0;\n #issuedIds = 0;\n #retiring = false;\n #ended = false;\n\n constructor(connection: OpenAiResponsesConnection, onEnd: () => void) {\n this.#connection = connection;\n this.#onEnd = onEnd;\n void this.#read();\n }\n\n open(): ResponsesLane | undefined {\n if (this.#ended || this.#retiring || this.#activeResponses >= maxActiveResponses) return undefined;\n let id = this.#freeIds.pop();\n if (!id) {\n if (this.#issuedIds >= maxStreamIds) return undefined;\n id = `aglib-${crypto.randomUUID()}`;\n this.#issuedIds += 1;\n }\n const queue = new EnvelopeQueue();\n this.#lanes.set(id, { active: true, queue });\n this.#activeResponses += 1;\n let released = false;\n const release = (terminal: boolean) => {\n if (released) return;\n released = true;\n this.#release(id, terminal);\n };\n return {\n send: (event) => {\n if (event.type === \"response.create\") {\n this.#connection.send({ ...event, stream_id: id });\n } else {\n this.#connection.send(event);\n }\n },\n cancel: () => {\n queue.push({ type: \"close\", reason: \"generation cancelled\" });\n release(false);\n },\n release,\n [Symbol.asyncIterator]: () => queue[Symbol.asyncIterator](),\n };\n }\n\n retire(): void {\n if (this.#ended) return;\n this.#retiring = true;\n this.#closeWhenDrained();\n }\n\n close(): void {\n if (this.#ended) return;\n this.#finish({ type: \"close\", reason: \"Responses model closed\" });\n this.#connection.close();\n }\n\n async #read(): Promise<void> {\n try {\n for await (const envelope of this.#connection) {\n if (envelope.type === \"message\" && envelope.message) {\n const event = envelope.message as unknown as Record<string, unknown>;\n const lane = string(event[\"stream_id\"]);\n if (lane) {\n this.#lanes.get(lane)?.queue.push(envelope);\n } else if (string(event[\"type\"]) === \"error\") {\n this.#broadcast(envelope);\n } else if (this.#lanes.size === 1) {\n this.#lanes.values().next().value?.queue.push(envelope);\n } else {\n this.#finish({\n type: \"error\",\n error: new Error(\"Responses event omitted stream_id while multiple generations were active\"),\n });\n }\n continue;\n }\n if (envelope.type === \"error\" || envelope.type === \"close\") {\n this.#finish(envelope);\n return;\n }\n }\n this.#finish({ type: \"close\", reason: \"Responses WebSocket ended\" });\n } catch (error) {\n this.#finish({ type: \"error\", error });\n }\n }\n\n #broadcast(envelope: StreamEnvelope): void {\n for (const lane of this.#lanes.values()) lane.queue.push(envelope);\n }\n\n #release(id: string, terminal: boolean): void {\n const lane = this.#lanes.get(id);\n if (!lane) return;\n lane.active = false;\n this.#activeResponses -= 1;\n lane.queue.end();\n if (terminal) {\n this.#lanes.delete(id);\n this.#freeIds.push(id);\n } else {\n // An unfinished response can still emit events carrying this stream id.\n // Retire the connection rather than let those events enter another generation.\n this.#retiring = true;\n }\n this.#closeWhenDrained();\n }\n\n #closeWhenDrained(): void {\n if (this.#retiring && ![...this.#lanes.values()].some((lane) => lane.active)) this.close();\n }\n\n #finish(envelope: StreamEnvelope): void {\n if (this.#ended) return;\n this.#ended = true;\n this.#broadcast(envelope);\n for (const lane of this.#lanes.values()) lane.queue.end();\n this.#lanes.clear();\n this.#onEnd();\n }\n}\n\nclass EnvelopeQueue implements AsyncIterableIterator<StreamEnvelope> {\n readonly #values: StreamEnvelope[] = [];\n readonly #waiters: Array<(step: IteratorResult<StreamEnvelope>) => void> = [];\n #ended = false;\n\n push(value: StreamEnvelope): void {\n if (this.#ended) return;\n const waiter = this.#waiters.shift();\n if (waiter) waiter({ done: false, value });\n else this.#values.push(value);\n }\n\n end(): void {\n if (this.#ended) return;\n this.#ended = true;\n for (const waiter of this.#waiters.splice(0)) waiter({ done: true, value: undefined });\n }\n\n next(): Promise<IteratorResult<StreamEnvelope>> {\n const value = this.#values.shift();\n if (value) return Promise.resolve({ done: false, value });\n if (this.#ended) return Promise.resolve({ done: true, value: undefined });\n return new Promise((resolve) => this.#waiters.push(resolve));\n }\n\n [Symbol.asyncIterator](): AsyncIterableIterator<StreamEnvelope> { return this; }\n}\n\n/** OpenAI's Responses wire, including completed output items, async tools and optional steering. */\nexport function createOpenAiResponsesModel(options: OpenAiResponsesOptions): OpenAiResponsesModel {\n const client = new OpenAI({\n apiKey: options.apiKey,\n ...(options.baseURL ? { baseURL: options.baseURL } : {}),\n ...(options.headers ? { defaultHeaders: options.headers } : {}),\n });\n const connect = options.connect ?? (() => {\n const socket = new ResponsesWS(client);\n return {\n send(event: unknown) { socket.send(event as ResponsesClientEvent); },\n close() { socket.close(); },\n [Symbol.asyncIterator]() {\n return socket[Symbol.asyncIterator]() as AsyncIterableIterator<StreamEnvelope>;\n },\n };\n });\n const hubs = new Set<ResponsesHub>();\n let hub: ResponsesHub | undefined;\n\n const lane = () => {\n const existing = hub?.open();\n if (existing) return existing;\n hub?.retire();\n const next = new ResponsesHub(connect(), () => {\n hubs.delete(next);\n if (hub === next) hub = undefined;\n });\n hubs.add(next);\n hub = next;\n const opened = next.open();\n if (!opened) throw new Error(\"Responses WebSocket opened without an available lane\");\n return opened;\n };\n\n return {\n id: `${provider}:${options.model}`,\n ...(options.asyncTools ? { asyncTools: true as const } : {}),\n generate(request: ModelRequest): ModelGeneration {\n return generation(lane, options.model, request, options.steering === true);\n },\n close() {\n for (const openHub of [...hubs]) openHub.close();\n hub = undefined;\n },\n };\n}\n\nfunction generation(\n connect: () => ResponsesLane,\n configuredModel: string,\n request: ModelRequest,\n steering: boolean,\n): ModelGeneration {\n let connection: ResponsesLane | undefined;\n let activeResponseId: string | undefined;\n let ended = false;\n let wakeStarted!: () => void;\n const started = new Promise<void>((resolve) => { wakeStarted = resolve; });\n const steers: Steer[] = [];\n let steerTail = Promise.resolve();\n\n const iterator = (async function* (): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n if (request.signal?.aborted) {\n ended = true;\n wakeStarted();\n return err(cancelled());\n }\n\n try {\n connection = connect();\n } catch (error) {\n ended = true;\n wakeStarted();\n return err(providerError(error));\n }\n wakeStarted();\n\n const abort = () => connection?.cancel();\n request.signal?.addEventListener(\"abort\", abort, { once: true });\n\n const text: string[] = [];\n const calls = new Map<string, ToolCall>();\n const itemCalls = new Map<string, string>();\n const providerItems: JsonValue[] = [];\n const seenItems = new Set<string>();\n const itemPhases = new Map<string, \"commentary\" | \"final_answer\">();\n let usage: Usage = {};\n let servedModel: string | undefined;\n let completed: Record<string, unknown> | undefined;\n let refused = false;\n let terminal = false;\n\n try {\n connection.send(encodeRequest(configuredModel, request));\n\n for await (const envelope of connection) {\n if (envelope.type === \"error\") {\n rejectSteers(steers, providerError(envelope.error));\n return err(providerError(envelope.error));\n }\n if (envelope.type === \"close\") {\n const failure = request.signal?.aborted\n ? cancelled()\n : { code: \"provider\" as const, message: `Responses WebSocket closed${envelope.code ? ` (${envelope.code})` : \"\"}${envelope.reason ? `: ${envelope.reason}` : \"\"}`, retryable: true };\n rejectSteers(steers, failure);\n return err(failure);\n }\n if (envelope.type !== \"message\" || !envelope.message) continue;\n const event = envelope.message as unknown as Record<string, unknown>;\n const type = string(event[\"type\"]);\n\n if (type === \"error\") {\n const failure = eventError(event);\n rejectSteers(steers, failure);\n return err(failure);\n }\n\n if (type === \"response.created\") {\n const response = record(event[\"response\"]);\n const id = string(response?.[\"id\"]);\n if (id) {\n const wasActive = activeResponseId;\n activeResponseId = id;\n servedModel = string(response?.[\"model\"]) ?? servedModel;\n if (wasActive) applyNextSteer(steers, id);\n }\n continue;\n }\n\n if (type === \"response.steer.accepted\") {\n const detail = record(event[\"steer\"]);\n const waiting = steers.find((steer) => steer.sent && !steer.providerId && !steer.done);\n if (waiting) waiting.providerId = string(detail?.[\"id\"]);\n continue;\n }\n if (type === \"response.steer.failed\") {\n const detail = record(event[\"steer\"]);\n const id = string(detail?.[\"id\"]);\n const waiting = (id ? steers.find((steer) => steer.providerId === id) : undefined)\n ?? steers.find((steer) => steer.sent && !steer.done);\n waiting?.reject(eventError(event));\n continue;\n }\n if (type === \"response.steer.pending\") {\n const detail = record(event[\"steer\"]);\n const id = string(detail?.[\"id\"]);\n const waiting = steers.find((steer) => steer.providerId === id && !steer.done);\n waiting?.reject({\n code: \"failed\", retryable: true,\n message: \"Steering awaits client tool input; replay the durable input at the next model boundary\",\n });\n if (completed && noLiveSteers(steers)) {\n terminal = true;\n return finish(completed, text, calls, providerItems, usage, refused, servedModel);\n }\n continue;\n }\n\n if (type === \"response.output_text.delta\") {\n const delta = string(event[\"delta\"]);\n const phase = itemPhases.get(string(event[\"item_id\"]) ?? \"\");\n if (delta) {\n text.push(delta);\n yield { type: \"text.delta\", text: delta, ...(phase ? { phase } : {}) };\n }\n continue;\n }\n if (type === \"response.refusal.delta\" || type === \"response.refusal.done\") {\n refused = true;\n continue;\n }\n if (type === \"response.reasoning_summary_text.delta\") {\n const delta = string(event[\"delta\"]);\n if (delta) yield { type: \"reasoning.delta\", text: delta };\n continue;\n }\n if (type === \"response.output_item.added\") {\n const item = record(event[\"item\"]);\n const itemId = string(item?.[\"id\"]);\n const phase = outputPhase(item?.[\"phase\"]);\n if (itemId && phase) itemPhases.set(itemId, phase);\n if (item?.[\"type\"] === \"function_call\") {\n const callId = string(item[\"call_id\"]);\n if (itemId && callId) itemCalls.set(itemId, callId);\n }\n continue;\n }\n if (type === \"response.function_call_arguments.delta\") {\n const callId = itemCalls.get(string(event[\"item_id\"]) ?? \"\");\n const delta = string(event[\"delta\"]);\n if (callId && delta) yield { type: \"tool-call.delta\", callId, arguments: delta };\n continue;\n }\n if (type === \"response.output_item.done\") {\n const item = record(event[\"item\"]);\n if (item) appendItem(providerItems, seenItems, item);\n const call = decodeCall(item);\n if (call && !calls.has(call.callId)) {\n calls.set(call.callId, call);\n yield { type: \"tool-call.done\", call };\n }\n continue;\n }\n\n if (type === \"response.completed\") {\n const response = record(event[\"response\"]);\n if (!response) return err({ code: \"provider\", message: \"Responses completion omitted its response\", retryable: true });\n completed = response;\n servedModel = string(response[\"model\"]) ?? servedModel;\n refused ||= hasRefusal(response);\n usage = addUsage(usage, decodeUsage(record(response[\"usage\"])));\n for (const item of array(response[\"output\"])) {\n const value = record(item);\n if (!value) continue;\n appendItem(providerItems, seenItems, value);\n const call = decodeCall(value);\n if (call && !calls.has(call.callId)) {\n calls.set(call.callId, call);\n yield { type: \"tool-call.done\", call };\n }\n }\n\n const blocking = [...calls.values()].some((call) => call.async !== true);\n if (blocking) {\n rejectSteers(steers, {\n code: \"failed\", retryable: true,\n message: \"Steering did not reach a successor before client tool input became required\",\n });\n terminal = true;\n return finish(response, text, calls, providerItems, usage, refused, servedModel);\n }\n if (noLiveSteers(steers)) {\n terminal = true;\n return finish(response, text, calls, providerItems, usage, refused, servedModel);\n }\n continue;\n }\n\n if (type === \"response.incomplete\") {\n const response = record(event[\"response\"]);\n if (!response) return err({ code: \"provider\", message: \"Incomplete event omitted its response\", retryable: true });\n for (const item of array(response[\"output\"])) {\n const value = record(item);\n if (value) appendItem(providerItems, seenItems, value);\n }\n usage = addUsage(usage, decodeUsage(record(response[\"usage\"])));\n if (record(response[\"incomplete_details\"])?.[\"reason\"] === \"steered\") continue;\n rejectSteers(steers, { code: \"failed\", message: \"Response ended incomplete\", retryable: true });\n terminal = true;\n return finish(response, text, calls, providerItems, usage, refused || hasRefusal(response), servedModel);\n }\n\n if (type === \"response.failed\") {\n const failure = responseFailure(record(event[\"response\"]));\n rejectSteers(steers, failure);\n terminal = true;\n return err(failure);\n }\n }\n\n const failure = request.signal?.aborted ? cancelled() : {\n code: \"provider\" as const, message: \"Responses WebSocket ended before completion\", retryable: true,\n };\n rejectSteers(steers, failure);\n return err(failure);\n } catch (error) {\n const failure = request.signal?.aborted ? cancelled() : providerError(error);\n rejectSteers(steers, failure);\n return err(failure);\n } finally {\n ended = true;\n request.signal?.removeEventListener(\"abort\", abort);\n connection.release(terminal);\n rejectSteers(steers, {\n code: \"failed\", message: \"Generation ended before steering reached a successor\", retryable: true,\n });\n }\n })();\n\n const steer = async (input: readonly Message[]): Promise<ModelSteerResult> => {\n await started;\n if (ended || !connection || !activeResponseId) {\n return { status: \"rejected\", error: { code: \"failed\", message: \"No active response to steer\", retryable: true } };\n }\n const encoded = encodeSteer(input);\n if (!encoded.ok) return { status: \"rejected\", error: encoded.error };\n\n let release!: () => void;\n const before = steerTail;\n steerTail = new Promise<void>((resolve) => { release = resolve; });\n await before;\n if (ended || !connection || !activeResponseId) {\n release();\n return { status: \"rejected\", error: { code: \"failed\", message: \"No active response to steer\", retryable: true } };\n }\n\n const pending = createSteer(release);\n steers.push(pending);\n pending.sent = true;\n connection.send({\n type: \"response.steer\",\n previous_response_id: activeResponseId,\n input: encoded.value,\n } as ResponsesClientEvent);\n return pending.promise;\n };\n\n return steering ? Object.assign(iterator, { steer }) : iterator;\n}\n\ninterface Steer {\n sent: boolean;\n done: boolean;\n providerId?: string;\n promise: Promise<ModelSteerResult>;\n accept(responseId: string): void;\n reject(error: ModelError): void;\n}\n\nfunction createSteer(release: () => void): Steer {\n let resolve!: (result: ModelSteerResult) => void;\n const promise = new Promise<ModelSteerResult>((done) => { resolve = done; });\n const steer: Steer = {\n sent: false, done: false, promise,\n accept(responseId) {\n if (steer.done) return;\n steer.done = true;\n release();\n resolve({ status: \"accepted\", id: responseId });\n },\n reject(error) {\n if (steer.done) return;\n steer.done = true;\n release();\n resolve({ status: \"rejected\", error });\n },\n };\n return steer;\n}\n\nfunction applyNextSteer(steers: readonly Steer[], responseId: string): void {\n steers.find((steer) => steer.providerId && !steer.done)?.accept(responseId);\n}\n\nconst noLiveSteers = (steers: readonly Steer[]) => !steers.some((steer) => steer.sent && !steer.done);\n\nfunction rejectSteers(steers: readonly Steer[], error: ModelError): void {\n for (const steer of steers) steer.reject(error);\n}\n\nfunction encodeRequest(model: string, request: ModelRequest): ResponsesClientEvent {\n return {\n type: \"response.create\",\n model,\n store: false,\n include: [\"reasoning.encrypted_content\"],\n input: encodeMessages(request.messages),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.maxOutputTokens !== undefined ? { max_output_tokens: request.maxOutputTokens } : {}),\n ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),\n ...(request.effort ? { reasoning: { effort: request.effort, summary: \"auto\" } } : {}),\n } as ResponsesClientEvent;\n}\n\nfunction encodeMessages(messages: readonly Message[]): unknown[] {\n const input: unknown[] = [];\n const calls = new Set<string>();\n const providerCalls = new Set(messages.flatMap((message) =>\n message.role === \"assistant\" && message.providerState?.provider === provider\n ? message.providerState.items.flatMap((item) => {\n const value = record(item);\n const callId = value?.[\"type\"] === \"function_call\" ? string(value[\"call_id\"]) : undefined;\n return callId ? [callId] : [];\n })\n : []));\n const reachedProviderCall = new Set<string>();\n const deferredResults = new Map<string, unknown[]>();\n\n for (const message of messages) {\n if (message.role === \"assistant\" && message.providerState?.provider === provider) {\n const represented: string[] = [];\n for (const item of message.providerState.items) {\n const value = record(item);\n const callId = value?.[\"type\"] === \"function_call\" ? string(value[\"call_id\"]) : undefined;\n if (callId && calls.has(callId)) continue;\n if (callId) {\n calls.add(callId);\n reachedProviderCall.add(callId);\n represented.push(callId);\n }\n input.push(item);\n }\n // A fast async tool can finish before the response that launched it has\n // completed. The log keeps that chronology. The provider continuation\n // still requires its whole output before any result that answers it.\n for (const callId of represented) {\n input.push(...(deferredResults.get(callId) ?? []));\n deferredResults.delete(callId);\n }\n continue;\n }\n if (message.role === \"tool\") {\n const output = {\n type: \"function_call_output\", call_id: message.callId,\n output: encodeToolOutput(message.content),\n };\n if (providerCalls.has(message.callId) && !reachedProviderCall.has(message.callId)) {\n const waiting = deferredResults.get(message.callId) ?? [];\n waiting.push(output);\n deferredResults.set(message.callId, waiting);\n } else {\n input.push(output);\n }\n continue;\n }\n const role = message.role === \"system\" ? \"developer\" : message.role;\n if (message.content.length) {\n input.push({ type: \"message\", role, content: encodeContent(message.content, role === \"assistant\") });\n }\n if (message.role === \"assistant\") {\n for (const call of message.calls ?? []) {\n if (providerCalls.has(call.callId)) continue;\n if (calls.has(call.callId)) continue;\n calls.add(call.callId);\n input.push({\n type: \"function_call\", call_id: call.callId, name: call.name, arguments: call.arguments,\n ...(call.async ? { async: true } : {}),\n });\n }\n }\n }\n for (const outputs of deferredResults.values()) input.push(...outputs);\n return input;\n}\n\nfunction encodeSteer(messages: readonly Message[]): Result<unknown[], ModelError> {\n if (!messages.length || messages.some((message) => message.role !== \"user\")) {\n return err({ code: \"failed\", message: \"Responses steering accepts one or more user messages only\", retryable: false });\n }\n return ok(messages.map((message) => ({\n type: \"message\", role: \"user\", content: encodeContent(message.content, false),\n })));\n}\n\nfunction encodeContent(content: Content, output: boolean): unknown {\n if (typeof content === \"string\") return content;\n const parts: unknown[] = [];\n for (const part of content) {\n if (part.type === \"text\") {\n parts.push({ type: output ? \"output_text\" : \"input_text\", text: part.text });\n continue;\n }\n if (part.type === \"image\" && !output) {\n parts.push({\n type: \"input_image\",\n image_url: part.source.kind === \"url\" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`,\n });\n continue;\n }\n if (part.type === \"file\" && !output) {\n parts.push(part.source.kind === \"url\"\n ? { type: \"input_file\", file_url: part.source.url }\n : { type: \"input_file\", file_data: part.source.data, ...(part.name ? { filename: part.name } : {}) });\n continue;\n }\n if (part.type === \"opaque\" && part.provider === provider) parts.push(part.data);\n }\n return parts;\n}\n\nfunction encodeToolOutput(content: Content): unknown {\n if (typeof content === \"string\") return content;\n return encodeContent(content, false);\n}\n\nconst encodeTool = (tool: ToolSpec) => ({\n type: \"function\" as const,\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n strict: false,\n ...(tool.async === true ? { async: true } : {}),\n});\n\nfunction decodeCall(item: Record<string, unknown> | undefined): ToolCall | undefined {\n if (!item || item[\"type\"] !== \"function_call\") return undefined;\n const callId = string(item[\"call_id\"]);\n const name = string(item[\"name\"]);\n if (!callId || !name) return undefined;\n return {\n callId,\n name,\n arguments: string(item[\"arguments\"]) || \"{}\",\n ...(item[\"async\"] === true ? { async: true } : {}),\n };\n}\n\nfunction finish(\n response: Record<string, unknown>,\n text: readonly string[],\n calls: ReadonlyMap<string, ToolCall>,\n providerItems: readonly JsonValue[],\n usage: Usage,\n refused: boolean,\n servedModel?: string,\n): Result<ModelResponse, ModelError> {\n const collected = [...calls.values()];\n const reason = string(record(response[\"incomplete_details\"])?.[\"reason\"]);\n const finishReason: ModelResponse[\"finishReason\"] =\n reason === \"max_output_tokens\" ? \"length\"\n : reason === \"content_filter\" || refused ? \"refusal\"\n : collected.some((call) => call.async !== true) ? \"tool-calls\"\n : \"stop\";\n return ok({\n message: { content: text.join(\"\"), ...(collected.length ? { calls: collected } : {}) },\n finishReason,\n usage,\n ...(servedModel ? { model: servedModel } : {}),\n ...(providerItems.length ? { providerState: { provider, items: providerItems } } : {}),\n });\n}\n\nfunction hasRefusal(response: Record<string, unknown>): boolean {\n return array(response[\"output\"]).some((item) =>\n array(record(item)?.[\"content\"]).some((part) => record(part)?.[\"type\"] === \"refusal\"));\n}\n\nfunction appendItem(target: JsonValue[], seen: Set<string>, item: Record<string, unknown>): void {\n const id = string(item[\"id\"]);\n if (id && seen.has(id)) return;\n if (id) seen.add(id);\n target.push(JSON.parse(JSON.stringify(item)) as JsonValue);\n}\n\nfunction decodeUsage(value: Record<string, unknown> | undefined): Usage {\n if (!value) return {};\n const details = record(value[\"input_tokens_details\"]);\n const input = number(value[\"input_tokens\"]);\n const cached = number(details?.[\"cached_tokens\"]);\n const written = number(details?.[\"cache_write_tokens\"]);\n return {\n ...(input !== undefined ? { inputTokens: Math.max(input - (cached ?? 0) - (written ?? 0), 0) } : {}),\n ...(cached !== undefined ? { cacheReadTokens: cached } : {}),\n ...(written !== undefined ? { cacheWriteTokens: written } : {}),\n ...(number(value[\"output_tokens\"]) !== undefined ? { outputTokens: number(value[\"output_tokens\"]) } : {}),\n };\n}\n\nfunction addUsage(left: Usage, right: Usage): Usage {\n const total: Usage = {};\n for (const key of [\"inputTokens\", \"outputTokens\", \"cacheReadTokens\", \"cacheWriteTokens\", \"costUsd\"] as const) {\n const a = left[key];\n const b = right[key];\n if (a !== undefined || b !== undefined) total[key] = (a ?? 0) + (b ?? 0);\n }\n return total;\n}\n\nfunction responseFailure(response: Record<string, unknown> | undefined): ModelError {\n const error = record(response?.[\"error\"]);\n return {\n code: \"provider\",\n message: string(error?.[\"message\"]) ?? \"Responses generation failed\",\n retryable: true,\n };\n}\n\nfunction eventError(event: Record<string, unknown>): ModelError {\n const error = record(event[\"error\"]);\n const code = string(error?.[\"code\"]);\n return {\n code: code === \"rate_limit_exceeded\" ? \"rate-limit\" : \"failed\",\n message: string(error?.[\"message\"]) ?? \"Responses command failed\",\n retryable: code === \"rate_limit_exceeded\" || code === \"server_error\" || code === \"response_not_found\",\n };\n}\n\nfunction providerError(error: unknown): ModelError {\n const message = error instanceof Error ? error.message : String(error ?? \"Responses transport failed\");\n return { code: \"provider\", message, retryable: true };\n}\n\nconst cancelled = (): ModelError => ({ code: \"cancelled\", message: \"Generation cancelled\", retryable: false });\nconst outputPhase = (value: unknown): \"commentary\" | \"final_answer\" | undefined =>\n value === \"commentary\" || value === \"final_answer\" ? value : undefined;\nconst record = (value: unknown): Record<string, unknown> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;\nconst array = (value: unknown): readonly unknown[] => Array.isArray(value) ? value : [];\nconst string = (value: unknown): string | undefined => typeof value === \"string\" ? value : undefined;\nconst number = (value: unknown): number | undefined => typeof value === \"number\" ? value : undefined;\n"]}
@@ -40,7 +40,7 @@ function failed(result, code, what) {
40
40
  equals(result.error.code, code, `${what} — the code says ${code}`);
41
41
  return result.error;
42
42
  }
43
- const joined = (deltas, type) => deltas.filter((delta) => delta.type === type).map((delta) => "text" in delta ? delta.text : delta.arguments).join("");
43
+ const joined = (deltas, type) => deltas.filter((delta) => delta.type === type).map((delta) => "text" in delta ? delta.text : "arguments" in delta ? delta.arguments : "").join("");
44
44
  /** Drains a generation, keeping what it streamed on the way to its result. */
45
45
  async function drive(generation) {
46
46
  const deltas = [];
@@ -1 +1 @@
1
- {"version":3,"file":"conformance.js","sourceRoot":"","sources":["../../src/model/conformance.ts"],"names":[],"mappings":"AAyCA,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAyJvC,SAAS,IAAI,CAAC,IAAY;IACxB,MAAM,IAAI,KAAK,CAAC,sBAAsB,IAAI,EAAE,CAAC,CAAC;AAChD,CAAC;AAED,SAAS,KAAK,CAAC,SAAkB,EAAE,IAAY;IAC7C,IAAI,CAAC,SAAS;QAAE,IAAI,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,IAAI,CAAC,MAAe,EAAE,QAAiB;IAC9C,IAAI,MAAM,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IACrC,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;QACrD,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IACnG,CAAC;IACD,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,CAAC,MAAM,IAAI,CAAC,QAAQ;QAAE,OAAO,KAAK,CAAC;IACrG,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,MAAgB,CAAC,CAAC,IAAI,EAAE,CAAC;IAClD,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,QAAkB,CAAC,CAAC,IAAI,EAAE,CAAC;IACrD,OAAO,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AAY,EAAE,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,EAAE,mDAAmD,CAAC,CAAC;QACvH,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;YAC7B,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,EAAE,qEAAqE,CAAC,CAAC;YACpG,OAAO;QACT,CAAC;QACD,KAAK,CAAC,MAAM,CAAC,UAAU,GAAG,CAAC,EAAE,iFAAiF,CAAC,CAAC;IAClH,CAAC,CAAC,CAAC;IAEL,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/**\n * What any implementation of the model port must do.\n *\n * The port is one method, and almost everything it promises is about the shape\n * of an answer rather than its content: exactly one result and nothing after it,\n * a cancellation that arrives as a value, deltas that add up to the message,\n * tool arguments that parse, counts that stay absent when nobody reported them.\n * Those are the promises a run recovers on — and every one of them is invisible\n * to a test that only asks a model a question and reads the reply.\n *\n * So the suite cannot supply requests and expect responses: what a provider says\n * is the provider's, and two of the three implementations here reach one. What\n * a subject is asked for instead is a model **primed to say a scripted thing** —\n * the script in the port's own vocabulary, rendered by the subject onto whatever\n * it actually speaks, which for a wire is a stream of frames and for a fake is a\n * scripted response. A case then drives that model and holds the answer to the\n * port, without ever naming a provider's fields.\n *\n * The same trick runs the other way. An adapter that decodes a response\n * perfectly and never transmits the caller's tools is useless, and that half of\n * an adapter is pure encoding — which is why a wire also hands back a\n * `SentRequest`: its own translation of what went out, back into the port's\n * vocabulary. The alternative was to assert on the raw body, which would make\n * every case provider-specific and so not a shared contract at all.\n *\n * One request per model. Nothing in this port is a conversation — a `Model` is a\n * value you call — so a case wanting a second answer asks for a second model,\n * and no subject has to decide what a spent script means.\n *\n * Inert on purpose. Each case is a name and a function that throws, so the suite\n * drags no test framework into the package:\n *\n * ```ts\n * for (const item of defineModelConformance(subject)) test(item.name, item.run);\n * ```\n */\nimport type {\n Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"./model.js\";\nimport type { Result } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\nimport { textOf } from \"../content.js\";\n\n/** One case: a name, and a function that throws when the contract is broken. */\nexport interface ConformanceCase {\n name: string;\n run(): Promise<void>;\n}\n\n/**\n * What the provider should say, in the port's vocabulary.\n *\n * A subject renders each of these onto whatever it speaks. Two rendering rules\n * carry cases of their own, so they are stated here rather than assumed:\n *\n * - **Deltas arrive one at a time.** A subject that hands the whole body over at\n * once cannot be cancelled part way through, and the case that pulls one delta\n * and then gives up would prove nothing.\n * - **A wire behaves as `fetch` does about the signal.** An already-aborted\n * request never reaches the provider, and a body dies when the caller gives\n * up. A transport that ignores the signal lets an adapter that never forwarded\n * it pass both cancellation cases.\n */\nexport type ModelScript =\n /** An answer that arrives in pieces. */\n | { kind: \"text\"; deltas: readonly string[] }\n /** An answer the model thought about first, aloud. */\n | { kind: \"reasoning\"; thoughts: readonly string[]; text: string }\n /** A turn that asks for tools, with each call's arguments fragmented on the way. */\n | { kind: \"tool-calls\"; calls: readonly ToolCall[] }\n /** An answer the provider cut off at the output ceiling, mid-sentence or mid-call. */\n | { kind: \"truncated\"; text: string; calls?: readonly ToolCall[] }\n /** An answer the provider declined to give. */\n | { kind: \"refused\" }\n /** An answer reporting exactly these counts, from exactly this model. */\n | { kind: \"usage\"; usage: Usage; model: string }\n /** An answer that says nothing about counts or about which model served it. */\n | { kind: \"silent\" }\n /** The provider refusing the request outright. Wires only. */\n | { kind: \"status\"; status: number; body: string }\n /** A body that delivers this much and then dies. Wires only. */\n | { kind: \"cut\"; text: string };\n\n/**\n * What one outgoing request carried, translated back out of the wire's own\n * vocabulary by the subject. Absence is meaningful: an empty `toolNames`\n * asserts the request advertised no tools, and a missing `effort` asserts it\n * carried no reasoning control at all.\n */\nexport interface SentRequest {\n /**\n * Every text the request transmitted for the model to read, in order —\n * instructions first, then the conversation, wherever this wire puts them.\n * One list rather than a field per role, because the roles are exactly what\n * the wires disagree about: a tool result is a message on one and a block\n * inside the previous user turn on another, and what an adapter owes is that\n * the words arrive in the order they were said.\n */\n text: readonly string[];\n /** The names of the tools the request advertised. */\n toolNames: readonly string[];\n /** The JSON Schema the request advertised for each advertised tool. */\n toolSchemas: Readonly<Record<string, JsonValue>>;\n /** Each tool result the request carried, paired with the call it answers. */\n toolResults: readonly { callId: string; content: string }[];\n /** Each tool call the request carried back, so the provider can pair the result with it. */\n toolCalls: readonly ToolCall[];\n /** Media types of the image and file content the request transmitted, in order. */\n mediaTypes: readonly string[];\n /** The output ceiling the request carried, or absent where it carried none. */\n maxOutputTokens?: number;\n /** The provider-native reasoning control the request carried, verbatim, or absent. */\n effort?: JsonValue;\n /** The sampling control the request carried, or absent. */\n temperature?: number;\n /** How many cache breakpoints the request marked. */\n cacheMarks: number;\n}\n\n/** A model primed to answer one request, and — where there is a wire — that request. */\nexport interface Answering {\n model: Model;\n /** What the one request this model was given actually carried. Wires only. */\n sent?(): SentRequest;\n}\n\n/**\n * What this implementation does with the three request options a provider may\n * refuse, each of which the port says is honoured or honestly ignored.\n *\n * Declared rather than inferred from the request, because both answers look\n * identical from outside and only one of them is a defect: dropping `temperature`\n * is what the current Anthropic models require, and dropping it silently on a\n * wire that would have accepted it is a caller's control going nowhere.\n */\nexport interface Wire {\n /** Whether a level reaches the provider as its own depth control. */\n effort: \"sent\" | \"ignored\";\n /** Whether a sampling control reaches a provider that accepts one. */\n temperature: \"sent\" | \"ignored\";\n /** Whether `cacheAfter` reaches the provider as a breakpoint. */\n cache: \"sent\" | \"ignored\";\n}\n\nexport interface ModelUnderTest {\n /**\n * A model primed to answer one request with `script`.\n *\n * Called once per request, so nothing leaks between cases, and never with a\n * script this subject's declarations say it cannot play.\n */\n answering(script: ModelScript): Answering | Promise<Answering>;\n /**\n * The transport under this implementation, where there is one the subject can\n * script and read back.\n *\n * `\"none\"` is a claim about the implementation, not a way out of the cases: a\n * model answering from something it already holds has no status to return, no\n * body to cut in half and no request to report — and those are the cases a\n * provider adapter most needs, so one that declares `\"none\"` is untested where\n * it matters.\n */\n wire: Wire | \"none\";\n /**\n * Whether a tool call's arguments reach the caller as they arrive.\n *\n * Declared rather than inferred from an empty stream, because \"streamed\n * nothing\" and \"asked for no tools this turn\" look the same from outside, and\n * an application rendering a call as it is typed would find out in production.\n */\n toolArguments: \"streamed\" | \"whole\";\n /** Whether this implementation can carry a model's reasoning back as deltas. */\n reasoning: \"streamed\" | \"none\";\n /**\n * Whether this wire states what a generation cost.\n *\n * A router does — it picks an upstream provider per request and adds its own\n * margin, so what it charged is a thing only it can say, and no rate table an\n * application keeps can reconstruct it. Most wires do not, and there the\n * field stays absent rather than being estimated from one.\n *\n * Declared both ways, because both are a promise: one that reports a cost has\n * to carry it, and one that does not has to leave it alone rather than\n * inventing a zero.\n */\n cost: \"reported\" | \"none\";\n}\n\n/** One generation, driven to its end. */\ninterface Streamed {\n deltas: readonly ModelDelta[];\n result: Result<ModelResponse, ModelError>;\n}\n\nfunction fail(what: string): never {\n throw new Error(`model conformance: ${what}`);\n}\n\nfunction holds(condition: boolean, what: string): asserts condition {\n if (!condition) fail(what);\n}\n\nfunction same(actual: unknown, expected: unknown): boolean {\n if (actual === expected) return true;\n if (Array.isArray(actual) && Array.isArray(expected)) {\n return actual.length === expected.length && actual.every((item, at) => same(item, expected[at]));\n }\n if (typeof actual !== \"object\" || typeof expected !== \"object\" || !actual || !expected) return false;\n const left = Object.keys(actual as object).sort();\n const right = Object.keys(expected as object).sort();\n return same(left, right)\n && left.every((key) => same((actual as Record<string, unknown>)[key], (expected as Record<string, unknown>)[key]));\n}\n\nfunction equals(actual: unknown, expected: unknown, what: string): void {\n if (!same(actual, expected)) {\n fail(`${what} — expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);\n }\n}\n\nfunction absent(actual: unknown, what: string): void {\n if (actual !== undefined) fail(`${what} — expected nothing, got ${JSON.stringify(actual)}`);\n}\n\n/** Unwraps a result the case expects to have succeeded. */\nfunction got(result: Result<ModelResponse, ModelError>, what: string): ModelResponse {\n if (!result.ok) fail(`${what} — ${result.error.code}: ${result.error.message}`);\n return result.value;\n}\n\n/** Unwraps a result the case expects to have failed, with this code. */\nfunction failed(result: Result<ModelResponse, ModelError>, code: ModelError[\"code\"], what: string): ModelError {\n holds(!result.ok, `${what} — it succeeded instead`);\n equals(result.error.code, code, `${what} — the code says ${code}`);\n return result.error;\n}\n\nconst joined = (deltas: readonly ModelDelta[], type: ModelDelta[\"type\"]): string =>\n deltas.filter((delta) => delta.type === type).map((delta) => \"text\" in delta ? delta.text : delta.arguments).join(\"\");\n\n/** Drains a generation, keeping what it streamed on the way to its result. */\nasync function drive(\n generation: AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>>,\n): Promise<Streamed> {\n const deltas: ModelDelta[] = [];\n let step = await generation.next();\n while (!step.done) {\n deltas.push(step.value);\n step = await generation.next();\n }\n return { deltas, result: step.value };\n}\n\n/** One opaque pixel: enough for an adapter to carry, too small to matter. */\nconst PIXEL = \"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==\";\n\nconst user = (text: string): Message => ({ role: \"user\", content: text });\n\n/** The arguments a call carries, compared as JSON rather than as a string a wire may re-spell. */\nconst parsed = (raw: string, what: string): unknown => {\n try { return JSON.parse(raw) as unknown; } catch { return fail(`${what} — ${JSON.stringify(raw)} is not JSON`); }\n};\n\nconst asked: readonly ToolCall[] = [\n { callId: \"call-1\", name: \"balance\", arguments: \"{\\\"account\\\":\\\"main\\\",\\\"limit\\\":3}\" },\n // A call with nothing to pass. Both wires stream no fragments for it, and a\n // caller still has to be handed arguments it can parse.\n { callId: \"call-2\", name: \"clock\", arguments: \"{}\" },\n];\n\nconst tools: readonly ToolSpec[] = [\n {\n name: \"balance\", description: \"Read an account balance\",\n parameters: { type: \"object\", properties: { account: { type: \"string\" } }, required: [\"account\"] },\n },\n { name: \"clock\", description: \"The time now\", parameters: { type: \"object\", properties: {} } },\n];\n\n/** A turn of every shape the port carries: instruction, question, call, result, reply. */\nconst conversation: readonly Message[] = [\n { role: \"system\", content: \"You are a bookkeeper.\" },\n { role: \"user\", content: \"What is the balance?\" },\n { role: \"assistant\", content: \"Looking that up.\", calls: [{ callId: \"call-1\", name: \"balance\", arguments: \"{\\\"account\\\":\\\"main\\\"}\" }] },\n { role: \"tool\", callId: \"call-1\", content: \"1250\" },\n { role: \"user\", content: \"Thanks.\" },\n];\n\nexport function defineModelConformance(subject: ModelUnderTest): readonly ConformanceCase[] {\n const cases: ConformanceCase[] = [];\n const define = (name: string, run: () => Promise<void>): void => { cases.push({ name, run }); };\n\n /** One scripted generation, driven to its end. */\n const answering = async (script: ModelScript, request: ModelRequest): Promise<Streamed> => {\n const primed = await subject.answering(script);\n return await drive(primed.model.generate(request));\n };\n\n // ---- The shape of an answer ---------------------------------------------\n\n define(\"a generation ends in one result, and yields nothing after it\", async () => {\n // A generator that falls off its end returns `undefined`, which typechecks\n // as nothing and tells a caller nothing: the loop reads `step.value.ok` to\n // decide whether the run failed, and would throw on the way to deciding.\n const primed = await subject.answering({ kind: \"text\", deltas: [\"one \", \"two\"] });\n const generation = primed.model.generate({ messages: [user(\"say something\")] });\n\n let step = await generation.next();\n while (!step.done) {\n holds([\"text.delta\", \"reasoning.delta\", \"tool-call.delta\"].includes(step.value.type),\n `every delta is one of the port's three kinds — got ${JSON.stringify(step.value)}`);\n step = await generation.next();\n }\n holds(typeof (step.value as { ok?: unknown } | undefined)?.ok === \"boolean\",\n \"a generation returns a Result, never nothing\");\n\n const after = await generation.next();\n holds(after.done === true && after.value === undefined, \"and nothing follows the result\");\n });\n\n define(\"the text a caller streamed is the text the message ends up holding\", async () => {\n const deltas = [\"The \", \"balance \", \"is 1250.\"];\n const streamed = await answering({ kind: \"text\", deltas }, { messages: [user(\"what is the balance?\")] });\n const response = got(streamed.result, \"generate\");\n\n equals(joined(streamed.deltas, \"text.delta\"), deltas.join(\"\"), \"the caller saw the answer arrive\");\n equals(textOf(response.message.content), deltas.join(\"\"), \"and the message holds the same words\");\n equals(response.finishReason, \"stop\", \"a turn that simply answered stopped\");\n equals(response.message.calls ?? [], [], \"and asked for nothing\");\n });\n\n define(\"a turn that asks for tools carries every call, with its id and arguments that parse\", async () => {\n const streamed = await answering({ kind: \"tool-calls\", calls: asked }, {\n messages: [user(\"look it up\")], tools,\n });\n const response = got(streamed.result, \"generate\");\n const reported = response.message.calls ?? [];\n\n equals(reported.map((call) => call.callId), asked.map((call) => call.callId),\n \"every call comes back, under the id the provider gave it — the id is what a result is paired with\");\n equals(reported.map((call) => call.name), asked.map((call) => call.name), \"and the tool it asked for\");\n for (const [at, call] of reported.entries()) {\n // Complete JSON, not the fragments it arrived as. A caller parses this to\n // decide whether a tool may run at all, so half of an object is worse than\n // none — it parses on a good day.\n equals(parsed(call.arguments, `call ${call.callId}`), parsed(asked[at]!.arguments, \"the script\"),\n \"the arguments parse, whole\");\n }\n equals(response.finishReason, \"tool-calls\", \"a turn holding calls says that is why it stopped\");\n });\n\n define(\"a turn cut off at the output ceiling says so\", async () => {\n // The reason the loop cannot read this from the absence of tool calls: a\n // truncated turn looks exactly like a finished one, and reporting it as an\n // answer hands the caller half a sentence dressed as a whole one.\n const streamed = await answering({ kind: \"truncated\", text: \"The balance is 12\" }, { messages: [user(\"go\")] });\n const response = got(streamed.result, \"generate\");\n equals(response.finishReason, \"length\", \"the ceiling, not a full stop\");\n equals(textOf(response.message.content), \"The balance is 12\", \"and what did arrive is kept\");\n });\n\n define(\"a turn cut off while it was asking for tools still says it was cut off\", async () => {\n // The precedence the loop's truncation guard rests on. A response holding\n // calls looks like a turn that asked for them, and half a request can parse\n // as whole JSON — so an adapter that lets the calls decide the reason hands\n // a batch built from a severed argument list to a tool that will run it.\n const streamed = await answering({ kind: \"truncated\", text: \"Looking\", calls: [asked[0]!] }, {\n messages: [user(\"go\")], tools,\n });\n const response = got(streamed.result, \"generate\");\n equals(response.finishReason, \"length\", \"the ceiling outranks the calls\");\n equals((response.message.calls ?? []).length, 1,\n \"and the calls that did arrive are still reported, so the model can be told why they did not run\");\n });\n\n define(\"a turn the provider declined says so\", async () => {\n const streamed = await answering({ kind: \"refused\" }, { messages: [user(\"go\")] });\n equals(got(streamed.result, \"generate\").finishReason, \"refusal\", \"a refusal is not a completed answer\");\n });\n\n define(\"the counts the provider reported reach the caller, and so does which model answered\", async () => {\n const counted: Usage = { inputTokens: 120, outputTokens: 6, cacheReadTokens: 80 };\n const streamed = await answering({ kind: \"usage\", usage: counted, model: \"acme/small\" }, {\n messages: [user(\"say ok\")],\n });\n const response = got(streamed.result, \"generate\");\n equals(response.usage, counted, \"the counts come back as they were reported\");\n // Not the id the model was built with: a provider may answer with a dated\n // variant, and an application pricing a run has to price what served it.\n equals(response.model, \"acme/small\", \"and the model that actually served the request\");\n });\n\n define(\"the input counts do not overlap, whichever wire answered\", async () => {\n // The wires disagree: Anthropic's `input_tokens` already excludes what was\n // cached, OpenAI's `prompt_tokens` includes it. `Usage` picks one meaning —\n // disjoint — so an application never has to ask which one it is holding.\n //\n // A caller sums. This is the case that lets it: the total below is only\n // right if no field is counted twice, and the one that used to subtract\n // instead priced a cached Anthropic turn's fresh tokens at zero.\n const split: Usage = { inputTokens: 40, outputTokens: 6, cacheReadTokens: 80 };\n const streamed = await answering({ kind: \"usage\", usage: split, model: \"acme/small\" }, {\n messages: [user(\"say ok\")],\n });\n const { usage } = got(streamed.result, \"generate\");\n equals(usage.inputTokens, 40, \"input excludes what was served from cache\");\n equals(usage.cacheReadTokens, 80, \"and the cached tokens are reported beside it, not inside it\");\n equals((usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0), 120, \"so the prompt's size is the sum\");\n });\n\n if (subject.cost === \"reported\") {\n define(\"a cost the provider states reaches the caller\", async () => {\n // Carried, never computed. An application that had to price this itself\n // was reconstructing, from a table it maintains by hand, a number the\n // wire had already given it — and for a router it could not: the upstream\n // provider is chosen per request.\n const charged: Usage = { inputTokens: 120, outputTokens: 6, costUsd: 0.0042 };\n const streamed = await answering({ kind: \"usage\", usage: charged, model: \"acme/small\" }, {\n messages: [user(\"say ok\")],\n });\n equals(got(streamed.result, \"generate\").usage.costUsd, 0.0042, \"the charge comes back as it was reported\");\n });\n } else {\n define(\"a wire that states no cost does not invent one\", async () => {\n const streamed = await answering(\n { kind: \"usage\", usage: { inputTokens: 120, outputTokens: 6 }, model: \"acme/small\" },\n { messages: [user(\"say ok\")] },\n );\n absent(got(streamed.result, \"generate\").usage.costUsd,\n \"usage.costUsd is absent on a wire that does not carry one\");\n });\n }\n\n define(\"what the provider did not report is absent, not zero\", async () => {\n const streamed = await answering({ kind: \"silent\" }, { messages: [user(\"say ok\")] });\n const response = got(streamed.result, \"generate\");\n for (const field of [\"inputTokens\", \"outputTokens\", \"cacheReadTokens\", \"cacheWriteTokens\", \"costUsd\"] as const) {\n // A zero is a count. An application summing them for a ceiling would be\n // told this generation was free, which is a different claim from silence.\n absent(response.usage[field], `usage.${field} is absent when the provider reported none`);\n }\n absent(response.model, \"and the model that answered is not invented\");\n });\n\n define(\"a model names itself\", async () => {\n const { model } = await subject.answering({ kind: \"text\", deltas: [\"hello\"] });\n holds(typeof model.id === \"string\" && model.id.length > 0, \"a model has an id, so a log can say which one ran\");\n });\n\n // ---- Giving up ----------------------------------------------------------\n\n define(\"a generation cancelled before it starts fails cancelled, and does not throw\", async () => {\n const streamed = await answering({ kind: \"text\", deltas: [\"never \", \"delivered\"] }, {\n messages: [user(\"go\")], signal: AbortSignal.abort(),\n });\n const error = failed(streamed.result, \"cancelled\", \"an already-cancelled generation reports cancelled\");\n equals(error.retryable, false, \"a caller that gave up is not told to try again\");\n equals(streamed.deltas, [], \"and nothing was streamed to it\");\n });\n\n // ---- What differs, as the subject declares it ---------------------------\n\n if (subject.reasoning === \"streamed\") {\n define(\"reasoning reaches the caller as deltas, and never as something the model said\", async () => {\n const streamed = await answering({ kind: \"reasoning\", thoughts: [\"Check \", \"the ledger.\"], text: \"1250\" }, {\n messages: [user(\"what is the balance?\")], effort: \"high\",\n });\n const response = got(streamed.result, \"generate\");\n equals(joined(streamed.deltas, \"reasoning.delta\"), \"Check the ledger.\", \"the caller saw it being thought\");\n // Reasoning is not speech. Folded into the message it would be committed\n // as the assistant's words and replayed to the provider next turn, as if\n // the model had said aloud what it only thought.\n equals(textOf(response.message.content), \"1250\", \"and the message holds only what was said\");\n });\n } else {\n define(\"an implementation that carries no reasoning emits none\", async () => {\n const streamed = await answering({ kind: \"text\", deltas: [\"hello\"] }, { messages: [user(\"go\")] });\n holds(!streamed.deltas.some((delta) => delta.type === \"reasoning.delta\"),\n \"a subject declaring no reasoning must not emit a delta the suite would then not check\");\n });\n }\n\n if (subject.toolArguments === \"streamed\") {\n define(\"a tool call's arguments reach the caller as they are produced\", async () => {\n const call = asked[0]!;\n const streamed = await answering({ kind: \"tool-calls\", calls: [call] }, {\n messages: [user(\"look it up\")], tools,\n });\n const [reported] = got(streamed.result, \"generate\").message.calls ?? [];\n holds(reported !== undefined, \"the call came back\");\n\n const fragments = streamed.deltas\n .filter((delta): delta is Extract<ModelDelta, { type: \"tool-call.delta\" }> => delta.type === \"tool-call.delta\");\n holds(fragments.length > 0, \"the arguments were streamed at all\");\n equals([...new Set(fragments.map((delta) => delta.callId))], [reported.callId],\n \"every fragment names the call it belongs to — an application renders them per call\");\n equals(fragments.map((delta) => delta.arguments).join(\"\"), reported.arguments,\n \"and they reassemble into exactly what the call ended up holding\");\n });\n } else {\n define(\"an implementation that does not stream arguments emits no tool-call deltas\", async () => {\n const streamed = await answering({ kind: \"tool-calls\", calls: asked }, {\n messages: [user(\"look it up\")], tools,\n });\n holds(!streamed.deltas.some((delta) => delta.type === \"tool-call.delta\"),\n \"a subject declaring `whole` must not emit a delta the suite would then not check\");\n });\n }\n\n if (subject.wire === \"none\") {\n define(\"an implementation with no wire under it says so by not offering one\", async () => {\n const primed = await subject.answering({ kind: \"text\", deltas: [\"hello\"] });\n holds(primed.sent === undefined,\n \"a subject that can report what it sent declares a wire, rather than offering a report nothing reads\");\n });\n return cases;\n }\n\n const wire = subject.wire;\n\n // ---- What the provider refused ------------------------------------------\n\n const refusals = [\n { status: 401, body: \"{\\\"error\\\":{\\\"message\\\":\\\"invalid api key\\\"}}\", code: \"auth\", retryable: false },\n { status: 429, body: \"{\\\"error\\\":{\\\"message\\\":\\\"rate limit exceeded\\\"}}\", code: \"rate-limit\", retryable: true },\n {\n status: 400,\n body: \"{\\\"error\\\":{\\\"message\\\":\\\"prompt is too long: 300000 tokens > 200000 maximum context length\\\"}}\",\n code: \"context-length\", retryable: false,\n },\n { status: 500, body: \"upstream is unwell\", code: \"provider\", retryable: true },\n { status: 404, body: \"{\\\"error\\\":{\\\"message\\\":\\\"no such model\\\"}}\", code: \"failed\", retryable: false },\n ] as const;\n\n for (const refusal of refusals) {\n define(`a ${refusal.status} from the provider is a ${refusal.code} failure a caller can act on`, async () => {\n const streamed = await answering({ kind: \"status\", status: refusal.status, body: refusal.body }, {\n messages: [user(\"go\")],\n });\n const error = failed(streamed.result, refusal.code, `${refusal.status} is ${refusal.code}`);\n // The whole of what a backoff loop reads. Getting it wrong costs either a\n // run that gives up on a rate limit or one that hammers a bad credential.\n equals(error.retryable, refusal.retryable, `a ${refusal.code} failure says whether trying again is worth it`);\n holds(error.message.length > 0, \"and carries something a human can read\");\n equals(streamed.deltas, [], \"a refused request streamed nothing\");\n });\n }\n\n define(\"a body that dies part way through is a failure, not a thrown generator\", async () => {\n // Without this the generator throws, `run.result` rejects instead of\n // resolving, no `run.finished` is ever committed, and the activation stays\n // open until its claim expires.\n const streamed = await answering({ kind: \"cut\", text: \"The bal\" }, { messages: [user(\"go\")] });\n const error = failed(streamed.result, \"provider\", \"a dropped body is a provider failure\");\n equals(error.retryable, true, \"a connection that dropped is worth trying again\");\n holds(streamed.deltas.length > 0, \"and what did arrive had already reached the caller\");\n });\n\n define(\"a generation cancelled while it streams ends cancelled, not as a provider fault\", async () => {\n const primed = await subject.answering({ kind: \"text\", deltas: [\"one \", \"two \", \"three\"] });\n const controller = new AbortController();\n const generation = primed.model.generate({ messages: [user(\"count\")], signal: controller.signal });\n\n const first = await generation.next();\n holds(first.done === false, \"the first delta arrived\");\n // The moment that matters: a caller that has read something and then gives\n // up. A stream torn down under an adapter looks exactly like one the network\n // dropped, and only the signal tells them apart.\n controller.abort();\n\n let step = await generation.next();\n while (!step.done) step = await generation.next();\n equals(failed(step.value, \"cancelled\", \"a cancelled stream reports cancelled\").retryable, false,\n \"a caller that gave up is not told to try again\");\n });\n\n // ---- What went out ------------------------------------------------------\n\n /** One scripted generation, reported back as the request it put on the wire. */\n const sending = async (request: ModelRequest): Promise<SentRequest> => {\n const primed = await subject.answering({ kind: \"text\", deltas: [\"ok\"] });\n holds(primed.sent !== undefined, \"a subject declaring a wire owes a report of what it sent\");\n got((await drive(primed.model.generate(request))).result, \"generate\");\n return primed.sent();\n };\n\n define(\"everything the caller said reaches the provider, in the order it was said\", async () => {\n // Every role the port carries, in one turn. The wires disagree about where\n // each one goes — an instruction is hoisted out of the list on one and left\n // in it on the other, a tool result is a message here and a block inside the\n // previous user turn there — and none of that may lose a word or reorder one.\n const sent = await sending({ messages: conversation });\n equals(sent.text, [\"You are a bookkeeper.\", \"What is the balance?\", \"Looking that up.\", \"1250\", \"Thanks.\"],\n \"the instruction, the question, the reply, the result and the follow-up all arrive, in that order\");\n });\n\n define(\"a tool result reaches the provider paired with the call it answers\", async () => {\n // Unpaired, a provider rejects the turn outright: it has an answer and no\n // question. This is the one encoding mistake that makes a session unusable\n // rather than merely worse.\n const sent = await sending({ messages: conversation, tools });\n equals(sent.toolResults, [{ callId: \"call-1\", content: \"1250\" }], \"the result carries the id it answers\");\n equals(sent.toolCalls.map((call) => call.callId), [\"call-1\"], \"and the call it answers went back with it\");\n equals(parsed(sent.toolCalls[0]!.arguments, \"the call sent back\"), { account: \"main\" },\n \"still holding the arguments the model asked with\");\n });\n\n define(\"the tools the caller advertised reach the provider with their schemas\", async () => {\n const sent = await sending({ messages: [user(\"look it up\")], tools });\n equals([...sent.toolNames].sort(), tools.map((tool) => tool.name).sort(), \"every tool is advertised\");\n for (const tool of tools) {\n equals(sent.toolSchemas[tool.name], tool.parameters,\n `${tool.name} is advertised with the schema it declared — the model calls what it was shown`);\n }\n equals((await sending({ messages: [user(\"look it up\")] })).toolNames, [],\n \"and a request with no tools advertises none\");\n });\n\n define(\"an image reaches the provider as an image\", async () => {\n const sent = await sending({\n messages: [{\n role: \"user\",\n content: [\n { type: \"text\", text: \"what is this?\" },\n { type: \"image\", mediaType: \"image/png\", source: { kind: \"inline\", data: PIXEL } },\n ],\n }],\n });\n equals(sent.mediaTypes, [\"image/png\"], \"the picture is transmitted as a picture, not as prose about one\");\n holds(sent.text.includes(\"what is this?\"), \"and the text beside it is not lost carrying it\");\n });\n\n define(\"a block this wire cannot carry is dropped, not stringified into something the model reads\", async () => {\n // An opaque block belongs to the provider that made it and is valid on no\n // other wire. The tempting fix is to serialize what cannot be sent, which\n // puts another provider's internals — signatures and all — in front of the\n // model as if a person had typed them.\n const sent = await sending({\n messages: [{\n role: \"user\",\n content: [\n { type: \"text\", text: \"what is this?\" },\n { type: \"opaque\", provider: \"another-provider\", data: { signature: \"sig-9\" } },\n ],\n }],\n });\n equals(sent.text, [\"what is this?\"], \"the words go, the block this wire has no place for does not\");\n });\n\n define(\"the output ceiling the caller set reaches the provider\", async () => {\n equals((await sending({ messages: [user(\"go\")], maxOutputTokens: 64 })).maxOutputTokens, 64,\n \"a ceiling nothing transmits is a ceiling nothing enforces\");\n });\n\n define(`effort is ${wire.effort === \"sent\" ? \"sent as this provider's own depth control\" : \"dropped rather than sent\"}`,\n async () => {\n const withEffort = await sending({ messages: [user(\"think first\")], effort: \"high\" });\n absent((await sending({ messages: [user(\"think first\")] })).effort,\n \"a request that asked for no effort carries no depth control\");\n if (wire.effort === \"ignored\") {\n absent(withEffort.effort, \"a provider with no such control is given none, rather than a budget invented for it\");\n return;\n }\n holds(withEffort.effort !== undefined, \"the level the caller asked for reaches the provider\");\n });\n\n define(`temperature is ${wire.temperature === \"sent\" ? \"sent\" : \"dropped rather than sent to a provider that rejects it\"}`,\n async () => {\n const withTemperature = await sending({ messages: [user(\"go\")], temperature: 0.2 });\n absent((await sending({ messages: [user(\"go\")] })).temperature, \"a request that set none carries none\");\n if (wire.temperature === \"ignored\") {\n // Not an oversight: the current Anthropic models reject sampling\n // controls, so forwarding one turns every request into a 400.\n absent(withTemperature.temperature, \"a provider that rejects sampling controls is sent none\");\n return;\n }\n equals(withTemperature.temperature, 0.2, \"the value the caller set reaches the provider\");\n });\n\n define(`cacheAfter is ${wire.cache === \"sent\" ? \"marked on the wire\" : \"dropped on a wire with no breakpoint\"}`,\n async () => {\n const marked = await sending({ messages: conversation, cacheAfter: 1 });\n equals((await sending({ messages: conversation })).cacheMarks, 0, \"a request that asked for no breakpoint marks none\");\n if (wire.cache === \"ignored\") {\n equals(marked.cacheMarks, 0, \"a wire that caches by itself is not sent a mark it has no field for\");\n return;\n }\n holds(marked.cacheMarks > 0, \"the prefix the caller ended is marked, or nothing is cached and every turn pays\");\n });\n\n return cases;\n}\n"]}
1
+ {"version":3,"file":"conformance.js","sourceRoot":"","sources":["../../src/model/conformance.ts"],"names":[],"mappings":"AAyCA,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAyJvC,SAAS,IAAI,CAAC,IAAY;IACxB,MAAM,IAAI,KAAK,CAAC,sBAAsB,IAAI,EAAE,CAAC,CAAC;AAChD,CAAC;AAED,SAAS,KAAK,CAAC,SAAkB,EAAE,IAAY;IAC7C,IAAI,CAAC,SAAS;QAAE,IAAI,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,IAAI,CAAC,MAAe,EAAE,QAAiB;IAC9C,IAAI,MAAM,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IACrC,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAA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sC,CAAC,CAAC;QACxG,IAAI,IAAI,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;YACnC,iEAAiE;YACjE,8DAA8D;YAC9D,MAAM,CAAC,eAAe,CAAC,WAAW,EAAE,wDAAwD,CAAC,CAAC;YAC9F,OAAO;QACT,CAAC;QACD,MAAM,CAAC,eAAe,CAAC,WAAW,EAAE,GAAG,EAAE,+CAA+C,CAAC,CAAC;IAC5F,CAAC,CAAC,CAAC;IAEL,MAAM,CAAC,iBAAiB,IAAI,CAAC,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,sCAAsC,EAAE,EAC7G,KAAK,IAAI,EAAE;QACT,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,EAAE,QAAQ,EAAE,YAAY,EAAE,UAAU,EAAE,CAAC,EAAE,CAAC,CAAC;QACxE,MAAM,CAAC,CAAC,MAAM,OAAO,CAAC,EAAE,QAAQ,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,EAAE,mDAAmD,CAAC,CAAC;QACvH,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;YAC7B,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,EAAE,qEAAqE,CAAC,CAAC;YACpG,OAAO;QACT,CAAC;QACD,KAAK,CAAC,MAAM,CAAC,UAAU,GAAG,CAAC,EAAE,iFAAiF,CAAC,CAAC;IAClH,CAAC,CAAC,CAAC;IAEL,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/**\n * What any implementation of the model port must do.\n *\n * The port is one method, and almost everything it promises is about the shape\n * of an answer rather than its content: exactly one result and nothing after it,\n * a cancellation that arrives as a value, deltas that add up to the message,\n * tool arguments that parse, counts that stay absent when nobody reported them.\n * Those are the promises a run recovers on — and every one of them is invisible\n * to a test that only asks a model a question and reads the reply.\n *\n * So the suite cannot supply requests and expect responses: what a provider says\n * is the provider's, and two of the three implementations here reach one. What\n * a subject is asked for instead is a model **primed to say a scripted thing** —\n * the script in the port's own vocabulary, rendered by the subject onto whatever\n * it actually speaks, which for a wire is a stream of frames and for a fake is a\n * scripted response. A case then drives that model and holds the answer to the\n * port, without ever naming a provider's fields.\n *\n * The same trick runs the other way. An adapter that decodes a response\n * perfectly and never transmits the caller's tools is useless, and that half of\n * an adapter is pure encoding — which is why a wire also hands back a\n * `SentRequest`: its own translation of what went out, back into the port's\n * vocabulary. The alternative was to assert on the raw body, which would make\n * every case provider-specific and so not a shared contract at all.\n *\n * One request per model. Nothing in this port is a conversation — a `Model` is a\n * value you call — so a case wanting a second answer asks for a second model,\n * and no subject has to decide what a spent script means.\n *\n * Inert on purpose. Each case is a name and a function that throws, so the suite\n * drags no test framework into the package:\n *\n * ```ts\n * for (const item of defineModelConformance(subject)) test(item.name, item.run);\n * ```\n */\nimport type {\n Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"./model.js\";\nimport type { Result } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\nimport { textOf } from \"../content.js\";\n\n/** One case: a name, and a function that throws when the contract is broken. */\nexport interface ConformanceCase {\n name: string;\n run(): Promise<void>;\n}\n\n/**\n * What the provider should say, in the port's vocabulary.\n *\n * A subject renders each of these onto whatever it speaks. Two rendering rules\n * carry cases of their own, so they are stated here rather than assumed:\n *\n * - **Deltas arrive one at a time.** A subject that hands the whole body over at\n * once cannot be cancelled part way through, and the case that pulls one delta\n * and then gives up would prove nothing.\n * - **A wire behaves as `fetch` does about the signal.** An already-aborted\n * request never reaches the provider, and a body dies when the caller gives\n * up. A transport that ignores the signal lets an adapter that never forwarded\n * it pass both cancellation cases.\n */\nexport type ModelScript =\n /** An answer that arrives in pieces. */\n | { kind: \"text\"; deltas: readonly string[] }\n /** An answer the model thought about first, aloud. */\n | { kind: \"reasoning\"; thoughts: readonly string[]; text: string }\n /** A turn that asks for tools, with each call's arguments fragmented on the way. */\n | { kind: \"tool-calls\"; calls: readonly ToolCall[] }\n /** An answer the provider cut off at the output ceiling, mid-sentence or mid-call. */\n | { kind: \"truncated\"; text: string; calls?: readonly ToolCall[] }\n /** An answer the provider declined to give. */\n | { kind: \"refused\" }\n /** An answer reporting exactly these counts, from exactly this model. */\n | { kind: \"usage\"; usage: Usage; model: string }\n /** An answer that says nothing about counts or about which model served it. */\n | { kind: \"silent\" }\n /** The provider refusing the request outright. Wires only. */\n | { kind: \"status\"; status: number; body: string }\n /** A body that delivers this much and then dies. Wires only. */\n | { kind: \"cut\"; text: string };\n\n/**\n * What one outgoing request carried, translated back out of the wire's own\n * vocabulary by the subject. Absence is meaningful: an empty `toolNames`\n * asserts the request advertised no tools, and a missing `effort` asserts it\n * carried no reasoning control at all.\n */\nexport interface SentRequest {\n /**\n * Every text the request transmitted for the model to read, in order —\n * instructions first, then the conversation, wherever this wire puts them.\n * One list rather than a field per role, because the roles are exactly what\n * the wires disagree about: a tool result is a message on one and a block\n * inside the previous user turn on another, and what an adapter owes is that\n * the words arrive in the order they were said.\n */\n text: readonly string[];\n /** The names of the tools the request advertised. */\n toolNames: readonly string[];\n /** The JSON Schema the request advertised for each advertised tool. */\n toolSchemas: Readonly<Record<string, JsonValue>>;\n /** Each tool result the request carried, paired with the call it answers. */\n toolResults: readonly { callId: string; content: string }[];\n /** Each tool call the request carried back, so the provider can pair the result with it. */\n toolCalls: readonly ToolCall[];\n /** Media types of the image and file content the request transmitted, in order. */\n mediaTypes: readonly string[];\n /** The output ceiling the request carried, or absent where it carried none. */\n maxOutputTokens?: number;\n /** The provider-native reasoning control the request carried, verbatim, or absent. */\n effort?: JsonValue;\n /** The sampling control the request carried, or absent. */\n temperature?: number;\n /** How many cache breakpoints the request marked. */\n cacheMarks: number;\n}\n\n/** A model primed to answer one request, and — where there is a wire — that request. */\nexport interface Answering {\n model: Model;\n /** What the one request this model was given actually carried. Wires only. */\n sent?(): SentRequest;\n}\n\n/**\n * What this implementation does with the three request options a provider may\n * refuse, each of which the port says is honoured or honestly ignored.\n *\n * Declared rather than inferred from the request, because both answers look\n * identical from outside and only one of them is a defect: dropping `temperature`\n * is what the current Anthropic models require, and dropping it silently on a\n * wire that would have accepted it is a caller's control going nowhere.\n */\nexport interface Wire {\n /** Whether a level reaches the provider as its own depth control. */\n effort: \"sent\" | \"ignored\";\n /** Whether a sampling control reaches a provider that accepts one. */\n temperature: \"sent\" | \"ignored\";\n /** Whether `cacheAfter` reaches the provider as a breakpoint. */\n cache: \"sent\" | \"ignored\";\n}\n\nexport interface ModelUnderTest {\n /**\n * A model primed to answer one request with `script`.\n *\n * Called once per request, so nothing leaks between cases, and never with a\n * script this subject's declarations say it cannot play.\n */\n answering(script: ModelScript): Answering | Promise<Answering>;\n /**\n * The transport under this implementation, where there is one the subject can\n * script and read back.\n *\n * `\"none\"` is a claim about the implementation, not a way out of the cases: a\n * model answering from something it already holds has no status to return, no\n * body to cut in half and no request to report — and those are the cases a\n * provider adapter most needs, so one that declares `\"none\"` is untested where\n * it matters.\n */\n wire: Wire | \"none\";\n /**\n * Whether a tool call's arguments reach the caller as they arrive.\n *\n * Declared rather than inferred from an empty stream, because \"streamed\n * nothing\" and \"asked for no tools this turn\" look the same from outside, and\n * an application rendering a call as it is typed would find out in production.\n */\n toolArguments: \"streamed\" | \"whole\";\n /** Whether this implementation can carry a model's reasoning back as deltas. */\n reasoning: \"streamed\" | \"none\";\n /**\n * Whether this wire states what a generation cost.\n *\n * A router does — it picks an upstream provider per request and adds its own\n * margin, so what it charged is a thing only it can say, and no rate table an\n * application keeps can reconstruct it. Most wires do not, and there the\n * field stays absent rather than being estimated from one.\n *\n * Declared both ways, because both are a promise: one that reports a cost has\n * to carry it, and one that does not has to leave it alone rather than\n * inventing a zero.\n */\n cost: \"reported\" | \"none\";\n}\n\n/** One generation, driven to its end. */\ninterface Streamed {\n deltas: readonly ModelDelta[];\n result: Result<ModelResponse, ModelError>;\n}\n\nfunction fail(what: string): never {\n throw new Error(`model conformance: ${what}`);\n}\n\nfunction holds(condition: boolean, what: string): asserts condition {\n if (!condition) fail(what);\n}\n\nfunction same(actual: unknown, expected: unknown): boolean {\n if (actual === expected) return true;\n if (Array.isArray(actual) && Array.isArray(expected)) {\n return actual.length === expected.length && actual.every((item, at) => same(item, expected[at]));\n }\n if (typeof actual !== \"object\" || typeof expected !== \"object\" || !actual || !expected) return false;\n const left = Object.keys(actual as object).sort();\n const right = Object.keys(expected as object).sort();\n return same(left, right)\n && left.every((key) => same((actual as Record<string, unknown>)[key], (expected as Record<string, unknown>)[key]));\n}\n\nfunction equals(actual: unknown, expected: unknown, what: string): void {\n if (!same(actual, expected)) {\n fail(`${what} — expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);\n }\n}\n\nfunction absent(actual: unknown, what: string): void {\n if (actual !== undefined) fail(`${what} — expected nothing, got ${JSON.stringify(actual)}`);\n}\n\n/** Unwraps a result the case expects to have succeeded. */\nfunction got(result: Result<ModelResponse, ModelError>, what: string): ModelResponse {\n if (!result.ok) fail(`${what} — ${result.error.code}: ${result.error.message}`);\n return result.value;\n}\n\n/** Unwraps a result the case expects to have failed, with this code. */\nfunction failed(result: Result<ModelResponse, ModelError>, code: ModelError[\"code\"], what: string): ModelError {\n holds(!result.ok, `${what} — it succeeded instead`);\n equals(result.error.code, code, `${what} — the code says ${code}`);\n return result.error;\n}\n\nconst joined = (deltas: readonly ModelDelta[], type: ModelDelta[\"type\"]): string =>\n deltas.filter((delta) => delta.type === type).map((delta) =>\n \"text\" in delta ? delta.text : \"arguments\" in delta ? delta.arguments : \"\",\n ).join(\"\");\n\n/** Drains a generation, keeping what it streamed on the way to its result. */\nasync function drive(\n generation: AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>>,\n): Promise<Streamed> {\n const deltas: ModelDelta[] = [];\n let step = await generation.next();\n while (!step.done) {\n deltas.push(step.value);\n step = await generation.next();\n }\n return { deltas, result: step.value };\n}\n\n/** One opaque pixel: enough for an adapter to carry, too small to matter. */\nconst PIXEL = \"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==\";\n\nconst user = (text: string): Message => ({ role: \"user\", content: text });\n\n/** The arguments a call carries, compared as JSON rather than as a string a wire may re-spell. */\nconst parsed = (raw: string, what: string): unknown => {\n try { return JSON.parse(raw) as unknown; } catch { return fail(`${what} — ${JSON.stringify(raw)} is not JSON`); }\n};\n\nconst asked: readonly ToolCall[] = [\n { callId: \"call-1\", name: \"balance\", arguments: \"{\\\"account\\\":\\\"main\\\",\\\"limit\\\":3}\" },\n // A call with nothing to pass. Both wires stream no fragments for it, and a\n // caller still has to be handed arguments it can parse.\n { callId: \"call-2\", name: \"clock\", arguments: \"{}\" },\n];\n\nconst tools: readonly ToolSpec[] = [\n {\n name: \"balance\", description: \"Read an account balance\",\n parameters: { type: \"object\", properties: { account: { type: \"string\" } }, required: [\"account\"] },\n },\n { name: \"clock\", description: \"The time now\", parameters: { type: \"object\", properties: {} } },\n];\n\n/** A turn of every shape the port carries: instruction, question, call, result, reply. */\nconst conversation: readonly Message[] = [\n { role: \"system\", content: \"You are a bookkeeper.\" },\n { role: \"user\", content: \"What is the balance?\" },\n { role: \"assistant\", content: \"Looking that up.\", calls: [{ callId: \"call-1\", name: \"balance\", arguments: \"{\\\"account\\\":\\\"main\\\"}\" }] },\n { role: \"tool\", callId: \"call-1\", content: \"1250\" },\n { role: \"user\", content: \"Thanks.\" },\n];\n\nexport function defineModelConformance(subject: ModelUnderTest): readonly ConformanceCase[] {\n const cases: ConformanceCase[] = [];\n const define = (name: string, run: () => Promise<void>): void => { cases.push({ name, run }); };\n\n /** One scripted generation, driven to its end. */\n const answering = async (script: ModelScript, request: ModelRequest): Promise<Streamed> => {\n const primed = await subject.answering(script);\n return await drive(primed.model.generate(request));\n };\n\n // ---- The shape of an answer ---------------------------------------------\n\n define(\"a generation ends in one result, and yields nothing after it\", async () => {\n // A generator that falls off its end returns `undefined`, which typechecks\n // as nothing and tells a caller nothing: the loop reads `step.value.ok` to\n // decide whether the run failed, and would throw on the way to deciding.\n const primed = await subject.answering({ kind: \"text\", deltas: [\"one \", \"two\"] });\n const generation = primed.model.generate({ messages: [user(\"say something\")] });\n\n let step = await generation.next();\n while (!step.done) {\n holds([\"text.delta\", \"reasoning.delta\", \"tool-call.delta\"].includes(step.value.type),\n `every delta is one of the port's three kinds — got ${JSON.stringify(step.value)}`);\n step = await generation.next();\n }\n holds(typeof (step.value as { ok?: unknown } | undefined)?.ok === \"boolean\",\n \"a generation returns a Result, never nothing\");\n\n const after = await generation.next();\n holds(after.done === true && after.value === undefined, \"and nothing follows the result\");\n });\n\n define(\"the text a caller streamed is the text the message ends up holding\", async () => {\n const deltas = [\"The \", \"balance \", \"is 1250.\"];\n const streamed = await answering({ kind: \"text\", deltas }, { messages: [user(\"what is the balance?\")] });\n const response = got(streamed.result, \"generate\");\n\n equals(joined(streamed.deltas, \"text.delta\"), deltas.join(\"\"), \"the caller saw the answer arrive\");\n equals(textOf(response.message.content), deltas.join(\"\"), \"and the message holds the same words\");\n equals(response.finishReason, \"stop\", \"a turn that simply answered stopped\");\n equals(response.message.calls ?? [], [], \"and asked for nothing\");\n });\n\n define(\"a turn that asks for tools carries every call, with its id and arguments that parse\", async () => {\n const streamed = await answering({ kind: \"tool-calls\", calls: asked }, {\n messages: [user(\"look it up\")], tools,\n });\n const response = got(streamed.result, \"generate\");\n const reported = response.message.calls ?? [];\n\n equals(reported.map((call) => call.callId), asked.map((call) => call.callId),\n \"every call comes back, under the id the provider gave it — the id is what a result is paired with\");\n equals(reported.map((call) => call.name), asked.map((call) => call.name), \"and the tool it asked for\");\n for (const [at, call] of reported.entries()) {\n // Complete JSON, not the fragments it arrived as. A caller parses this to\n // decide whether a tool may run at all, so half of an object is worse than\n // none — it parses on a good day.\n equals(parsed(call.arguments, `call ${call.callId}`), parsed(asked[at]!.arguments, \"the script\"),\n \"the arguments parse, whole\");\n }\n equals(response.finishReason, \"tool-calls\", \"a turn holding calls says that is why it stopped\");\n });\n\n define(\"a turn cut off at the output ceiling says so\", async () => {\n // The reason the loop cannot read this from the absence of tool calls: a\n // truncated turn looks exactly like a finished one, and reporting it as an\n // answer hands the caller half a sentence dressed as a whole one.\n const streamed = await answering({ kind: \"truncated\", text: \"The balance is 12\" }, { messages: [user(\"go\")] });\n const response = got(streamed.result, \"generate\");\n equals(response.finishReason, \"length\", \"the ceiling, not a full stop\");\n equals(textOf(response.message.content), \"The balance is 12\", \"and what did arrive is kept\");\n });\n\n define(\"a turn cut off while it was asking for tools still says it was cut off\", async () => {\n // The precedence the loop's truncation guard rests on. A response holding\n // calls looks like a turn that asked for them, and half a request can parse\n // as whole JSON — so an adapter that lets the calls decide the reason hands\n // a batch built from a severed argument list to a tool that will run it.\n const streamed = await answering({ kind: \"truncated\", text: \"Looking\", calls: [asked[0]!] }, {\n messages: [user(\"go\")], tools,\n });\n const response = got(streamed.result, \"generate\");\n equals(response.finishReason, \"length\", \"the ceiling outranks the calls\");\n equals((response.message.calls ?? []).length, 1,\n \"and the calls that did arrive are still reported, so the model can be told why they did not run\");\n });\n\n define(\"a turn the provider declined says so\", async () => {\n const streamed = await answering({ kind: \"refused\" }, { messages: [user(\"go\")] });\n equals(got(streamed.result, \"generate\").finishReason, \"refusal\", \"a refusal is not a completed answer\");\n });\n\n define(\"the counts the provider reported reach the caller, and so does which model answered\", async () => {\n const counted: Usage = { inputTokens: 120, outputTokens: 6, cacheReadTokens: 80 };\n const streamed = await answering({ kind: \"usage\", usage: counted, model: \"acme/small\" }, {\n messages: [user(\"say ok\")],\n });\n const response = got(streamed.result, \"generate\");\n equals(response.usage, counted, \"the counts come back as they were reported\");\n // Not the id the model was built with: a provider may answer with a dated\n // variant, and an application pricing a run has to price what served it.\n equals(response.model, \"acme/small\", \"and the model that actually served the request\");\n });\n\n define(\"the input counts do not overlap, whichever wire answered\", async () => {\n // The wires disagree: Anthropic's `input_tokens` already excludes what was\n // cached, OpenAI's `prompt_tokens` includes it. `Usage` picks one meaning —\n // disjoint — so an application never has to ask which one it is holding.\n //\n // A caller sums. This is the case that lets it: the total below is only\n // right if no field is counted twice, and the one that used to subtract\n // instead priced a cached Anthropic turn's fresh tokens at zero.\n const split: Usage = { inputTokens: 40, outputTokens: 6, cacheReadTokens: 80 };\n const streamed = await answering({ kind: \"usage\", usage: split, model: \"acme/small\" }, {\n messages: [user(\"say ok\")],\n });\n const { usage } = got(streamed.result, \"generate\");\n equals(usage.inputTokens, 40, \"input excludes what was served from cache\");\n equals(usage.cacheReadTokens, 80, \"and the cached tokens are reported beside it, not inside it\");\n equals((usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0), 120, \"so the prompt's size is the sum\");\n });\n\n if (subject.cost === \"reported\") {\n define(\"a cost the provider states reaches the caller\", async () => {\n // Carried, never computed. An application that had to price this itself\n // was reconstructing, from a table it maintains by hand, a number the\n // wire had already given it — and for a router it could not: the upstream\n // provider is chosen per request.\n const charged: Usage = { inputTokens: 120, outputTokens: 6, costUsd: 0.0042 };\n const streamed = await answering({ kind: \"usage\", usage: charged, model: \"acme/small\" }, {\n messages: [user(\"say ok\")],\n });\n equals(got(streamed.result, \"generate\").usage.costUsd, 0.0042, \"the charge comes back as it was reported\");\n });\n } else {\n define(\"a wire that states no cost does not invent one\", async () => {\n const streamed = await answering(\n { kind: \"usage\", usage: { inputTokens: 120, outputTokens: 6 }, model: \"acme/small\" },\n { messages: [user(\"say ok\")] },\n );\n absent(got(streamed.result, \"generate\").usage.costUsd,\n \"usage.costUsd is absent on a wire that does not carry one\");\n });\n }\n\n define(\"what the provider did not report is absent, not zero\", async () => {\n const streamed = await answering({ kind: \"silent\" }, { messages: [user(\"say ok\")] });\n const response = got(streamed.result, \"generate\");\n for (const field of [\"inputTokens\", \"outputTokens\", \"cacheReadTokens\", \"cacheWriteTokens\", \"costUsd\"] as const) {\n // A zero is a count. An application summing them for a ceiling would be\n // told this generation was free, which is a different claim from silence.\n absent(response.usage[field], `usage.${field} is absent when the provider reported none`);\n }\n absent(response.model, \"and the model that answered is not invented\");\n });\n\n define(\"a model names itself\", async () => {\n const { model } = await subject.answering({ kind: \"text\", deltas: [\"hello\"] });\n holds(typeof model.id === \"string\" && model.id.length > 0, \"a model has an id, so a log can say which one ran\");\n });\n\n // ---- Giving up ----------------------------------------------------------\n\n define(\"a generation cancelled before it starts fails cancelled, and does not throw\", async () => {\n const streamed = await answering({ kind: \"text\", deltas: [\"never \", \"delivered\"] }, {\n messages: [user(\"go\")], signal: AbortSignal.abort(),\n });\n const error = failed(streamed.result, \"cancelled\", \"an already-cancelled generation reports cancelled\");\n equals(error.retryable, false, \"a caller that gave up is not told to try again\");\n equals(streamed.deltas, [], \"and nothing was streamed to it\");\n });\n\n // ---- What differs, as the subject declares it ---------------------------\n\n if (subject.reasoning === \"streamed\") {\n define(\"reasoning reaches the caller as deltas, and never as something the model said\", async () => {\n const streamed = await answering({ kind: \"reasoning\", thoughts: [\"Check \", \"the ledger.\"], text: \"1250\" }, {\n messages: [user(\"what is the balance?\")], effort: \"high\",\n });\n const response = got(streamed.result, \"generate\");\n equals(joined(streamed.deltas, \"reasoning.delta\"), \"Check the ledger.\", \"the caller saw it being thought\");\n // Reasoning is not speech. Folded into the message it would be committed\n // as the assistant's words and replayed to the provider next turn, as if\n // the model had said aloud what it only thought.\n equals(textOf(response.message.content), \"1250\", \"and the message holds only what was said\");\n });\n } else {\n define(\"an implementation that carries no reasoning emits none\", async () => {\n const streamed = await answering({ kind: \"text\", deltas: [\"hello\"] }, { messages: [user(\"go\")] });\n holds(!streamed.deltas.some((delta) => delta.type === \"reasoning.delta\"),\n \"a subject declaring no reasoning must not emit a delta the suite would then not check\");\n });\n }\n\n if (subject.toolArguments === \"streamed\") {\n define(\"a tool call's arguments reach the caller as they are produced\", async () => {\n const call = asked[0]!;\n const streamed = await answering({ kind: \"tool-calls\", calls: [call] }, {\n messages: [user(\"look it up\")], tools,\n });\n const [reported] = got(streamed.result, \"generate\").message.calls ?? [];\n holds(reported !== undefined, \"the call came back\");\n\n const fragments = streamed.deltas\n .filter((delta): delta is Extract<ModelDelta, { type: \"tool-call.delta\" }> => delta.type === \"tool-call.delta\");\n holds(fragments.length > 0, \"the arguments were streamed at all\");\n equals([...new Set(fragments.map((delta) => delta.callId))], [reported.callId],\n \"every fragment names the call it belongs to — an application renders them per call\");\n equals(fragments.map((delta) => delta.arguments).join(\"\"), reported.arguments,\n \"and they reassemble into exactly what the call ended up holding\");\n });\n } else {\n define(\"an implementation that does not stream arguments emits no tool-call deltas\", async () => {\n const streamed = await answering({ kind: \"tool-calls\", calls: asked }, {\n messages: [user(\"look it up\")], tools,\n });\n holds(!streamed.deltas.some((delta) => delta.type === \"tool-call.delta\"),\n \"a subject declaring `whole` must not emit a delta the suite would then not check\");\n });\n }\n\n if (subject.wire === \"none\") {\n define(\"an implementation with no wire under it says so by not offering one\", async () => {\n const primed = await subject.answering({ kind: \"text\", deltas: [\"hello\"] });\n holds(primed.sent === undefined,\n \"a subject that can report what it sent declares a wire, rather than offering a report nothing reads\");\n });\n return cases;\n }\n\n const wire = subject.wire;\n\n // ---- What the provider refused ------------------------------------------\n\n const refusals = [\n { status: 401, body: \"{\\\"error\\\":{\\\"message\\\":\\\"invalid api key\\\"}}\", code: \"auth\", retryable: false },\n { status: 429, body: \"{\\\"error\\\":{\\\"message\\\":\\\"rate limit exceeded\\\"}}\", code: \"rate-limit\", retryable: true },\n {\n status: 400,\n body: \"{\\\"error\\\":{\\\"message\\\":\\\"prompt is too long: 300000 tokens > 200000 maximum context length\\\"}}\",\n code: \"context-length\", retryable: false,\n },\n { status: 500, body: \"upstream is unwell\", code: \"provider\", retryable: true },\n { status: 404, body: \"{\\\"error\\\":{\\\"message\\\":\\\"no such model\\\"}}\", code: \"failed\", retryable: false },\n ] as const;\n\n for (const refusal of refusals) {\n define(`a ${refusal.status} from the provider is a ${refusal.code} failure a caller can act on`, async () => {\n const streamed = await answering({ kind: \"status\", status: refusal.status, body: refusal.body }, {\n messages: [user(\"go\")],\n });\n const error = failed(streamed.result, refusal.code, `${refusal.status} is ${refusal.code}`);\n // The whole of what a backoff loop reads. Getting it wrong costs either a\n // run that gives up on a rate limit or one that hammers a bad credential.\n equals(error.retryable, refusal.retryable, `a ${refusal.code} failure says whether trying again is worth it`);\n holds(error.message.length > 0, \"and carries something a human can read\");\n equals(streamed.deltas, [], \"a refused request streamed nothing\");\n });\n }\n\n define(\"a body that dies part way through is a failure, not a thrown generator\", async () => {\n // Without this the generator throws, `run.result` rejects instead of\n // resolving, no `run.finished` is ever committed, and the activation stays\n // open until its claim expires.\n const streamed = await answering({ kind: \"cut\", text: \"The bal\" }, { messages: [user(\"go\")] });\n const error = failed(streamed.result, \"provider\", \"a dropped body is a provider failure\");\n equals(error.retryable, true, \"a connection that dropped is worth trying again\");\n holds(streamed.deltas.length > 0, \"and what did arrive had already reached the caller\");\n });\n\n define(\"a generation cancelled while it streams ends cancelled, not as a provider fault\", async () => {\n const primed = await subject.answering({ kind: \"text\", deltas: [\"one \", \"two \", \"three\"] });\n const controller = new AbortController();\n const generation = primed.model.generate({ messages: [user(\"count\")], signal: controller.signal });\n\n const first = await generation.next();\n holds(first.done === false, \"the first delta arrived\");\n // The moment that matters: a caller that has read something and then gives\n // up. A stream torn down under an adapter looks exactly like one the network\n // dropped, and only the signal tells them apart.\n controller.abort();\n\n let step = await generation.next();\n while (!step.done) step = await generation.next();\n equals(failed(step.value, \"cancelled\", \"a cancelled stream reports cancelled\").retryable, false,\n \"a caller that gave up is not told to try again\");\n });\n\n // ---- What went out ------------------------------------------------------\n\n /** One scripted generation, reported back as the request it put on the wire. */\n const sending = async (request: ModelRequest): Promise<SentRequest> => {\n const primed = await subject.answering({ kind: \"text\", deltas: [\"ok\"] });\n holds(primed.sent !== undefined, \"a subject declaring a wire owes a report of what it sent\");\n got((await drive(primed.model.generate(request))).result, \"generate\");\n return primed.sent();\n };\n\n define(\"everything the caller said reaches the provider, in the order it was said\", async () => {\n // Every role the port carries, in one turn. The wires disagree about where\n // each one goes — an instruction is hoisted out of the list on one and left\n // in it on the other, a tool result is a message here and a block inside the\n // previous user turn there — and none of that may lose a word or reorder one.\n const sent = await sending({ messages: conversation });\n equals(sent.text, [\"You are a bookkeeper.\", \"What is the balance?\", \"Looking that up.\", \"1250\", \"Thanks.\"],\n \"the instruction, the question, the reply, the result and the follow-up all arrive, in that order\");\n });\n\n define(\"a tool result reaches the provider paired with the call it answers\", async () => {\n // Unpaired, a provider rejects the turn outright: it has an answer and no\n // question. This is the one encoding mistake that makes a session unusable\n // rather than merely worse.\n const sent = await sending({ messages: conversation, tools });\n equals(sent.toolResults, [{ callId: \"call-1\", content: \"1250\" }], \"the result carries the id it answers\");\n equals(sent.toolCalls.map((call) => call.callId), [\"call-1\"], \"and the call it answers went back with it\");\n equals(parsed(sent.toolCalls[0]!.arguments, \"the call sent back\"), { account: \"main\" },\n \"still holding the arguments the model asked with\");\n });\n\n define(\"the tools the caller advertised reach the provider with their schemas\", async () => {\n const sent = await sending({ messages: [user(\"look it up\")], tools });\n equals([...sent.toolNames].sort(), tools.map((tool) => tool.name).sort(), \"every tool is advertised\");\n for (const tool of tools) {\n equals(sent.toolSchemas[tool.name], tool.parameters,\n `${tool.name} is advertised with the schema it declared — the model calls what it was shown`);\n }\n equals((await sending({ messages: [user(\"look it up\")] })).toolNames, [],\n \"and a request with no tools advertises none\");\n });\n\n define(\"an image reaches the provider as an image\", async () => {\n const sent = await sending({\n messages: [{\n role: \"user\",\n content: [\n { type: \"text\", text: \"what is this?\" },\n { type: \"image\", mediaType: \"image/png\", source: { kind: \"inline\", data: PIXEL } },\n ],\n }],\n });\n equals(sent.mediaTypes, [\"image/png\"], \"the picture is transmitted as a picture, not as prose about one\");\n holds(sent.text.includes(\"what is this?\"), \"and the text beside it is not lost carrying it\");\n });\n\n define(\"a block this wire cannot carry is dropped, not stringified into something the model reads\", async () => {\n // An opaque block belongs to the provider that made it and is valid on no\n // other wire. The tempting fix is to serialize what cannot be sent, which\n // puts another provider's internals — signatures and all — in front of the\n // model as if a person had typed them.\n const sent = await sending({\n messages: [{\n role: \"user\",\n content: [\n { type: \"text\", text: \"what is this?\" },\n { type: \"opaque\", provider: \"another-provider\", data: { signature: \"sig-9\" } },\n ],\n }],\n });\n equals(sent.text, [\"what is this?\"], \"the words go, the block this wire has no place for does not\");\n });\n\n define(\"the output ceiling the caller set reaches the provider\", async () => {\n equals((await sending({ messages: [user(\"go\")], maxOutputTokens: 64 })).maxOutputTokens, 64,\n \"a ceiling nothing transmits is a ceiling nothing enforces\");\n });\n\n define(`effort is ${wire.effort === \"sent\" ? \"sent as this provider's own depth control\" : \"dropped rather than sent\"}`,\n async () => {\n const withEffort = await sending({ messages: [user(\"think first\")], effort: \"high\" });\n absent((await sending({ messages: [user(\"think first\")] })).effort,\n \"a request that asked for no effort carries no depth control\");\n if (wire.effort === \"ignored\") {\n absent(withEffort.effort, \"a provider with no such control is given none, rather than a budget invented for it\");\n return;\n }\n holds(withEffort.effort !== undefined, \"the level the caller asked for reaches the provider\");\n });\n\n define(`temperature is ${wire.temperature === \"sent\" ? \"sent\" : \"dropped rather than sent to a provider that rejects it\"}`,\n async () => {\n const withTemperature = await sending({ messages: [user(\"go\")], temperature: 0.2 });\n absent((await sending({ messages: [user(\"go\")] })).temperature, \"a request that set none carries none\");\n if (wire.temperature === \"ignored\") {\n // Not an oversight: the current Anthropic models reject sampling\n // controls, so forwarding one turns every request into a 400.\n absent(withTemperature.temperature, \"a provider that rejects sampling controls is sent none\");\n return;\n }\n equals(withTemperature.temperature, 0.2, \"the value the caller set reaches the provider\");\n });\n\n define(`cacheAfter is ${wire.cache === \"sent\" ? \"marked on the wire\" : \"dropped on a wire with no breakpoint\"}`,\n async () => {\n const marked = await sending({ messages: conversation, cacheAfter: 1 });\n equals((await sending({ messages: conversation })).cacheMarks, 0, \"a request that asked for no breakpoint marks none\");\n if (wire.cache === \"ignored\") {\n equals(marked.cacheMarks, 0, \"a wire that caches by itself is not sent a mark it has no field for\");\n return;\n }\n holds(marked.cacheMarks > 0, \"the prefix the caller ended is marked, or nothing is cached and every turn pays\");\n });\n\n return cases;\n}\n"]}
@@ -1 +1 @@
1
- export type { Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ProviderState, ToolSpec, } from "./model.js";
1
+ export type { Message, Model, ModelDelta, ModelError, ModelGeneration, ModelRequest, ModelResponse, ModelSteerResult, ProviderState, ToolSpec, } from "./model.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/model/index.ts"],"names":[],"mappings":"","sourcesContent":["export type {\n Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ProviderState, ToolSpec,\n} from \"./model.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/model/index.ts"],"names":[],"mappings":"","sourcesContent":["export type {\n Message, Model, ModelDelta, ModelError, ModelGeneration, ModelRequest, ModelResponse,\n ModelSteerResult, ProviderState, ToolSpec,\n} from \"./model.js\";\n"]}
@@ -45,6 +45,7 @@ export interface ModelRequest {
45
45
  export type ModelDelta = {
46
46
  type: "text.delta";
47
47
  text: string;
48
+ phase?: "commentary" | "final_answer";
48
49
  } | {
49
50
  type: "reasoning.delta";
50
51
  text: string;
@@ -52,6 +53,11 @@ export type ModelDelta = {
52
53
  type: "tool-call.delta";
53
54
  callId: string;
54
55
  arguments: string;
56
+ }
57
+ /** A complete call may be executable before the response itself is done. */
58
+ | {
59
+ type: "tool-call.done";
60
+ call: ToolCall;
55
61
  };
56
62
  export interface ModelResponse {
57
63
  message: {
@@ -71,9 +77,22 @@ export interface ModelError extends Failure {
71
77
  * response drains the generator and takes its return value, so no adapter has
72
78
  * to implement the same normalization twice.
73
79
  */
80
+ export type ModelSteerResult = {
81
+ status: "accepted";
82
+ id: string;
83
+ } | {
84
+ status: "rejected";
85
+ error: ModelError;
86
+ };
87
+ export interface ModelGeneration extends AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {
88
+ /** Queue new user messages on this active generation, when its provider can. */
89
+ steer?(input: readonly Message[]): Promise<ModelSteerResult>;
90
+ }
74
91
  export interface Model {
75
92
  readonly id: string;
76
- generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>>;
93
+ /** This configured model accepts tools declared for asynchronous execution. */
94
+ readonly asyncTools?: true;
95
+ generate(request: ModelRequest): ModelGeneration;
77
96
  }
78
97
  /**
79
98
  * Drains a generation and returns only its outcome.
@@ -83,7 +102,7 @@ export interface Model {
83
102
  * consumed it. `Model`'s own contract above says what a caller who wants the
84
103
  * whole response does, and this is the four lines of doing it.
85
104
  */
86
- export declare function collect(generation: AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>>): Promise<Result<ModelResponse, ModelError>>;
105
+ export declare function collect(generation: ModelGeneration): Promise<Result<ModelResponse, ModelError>>;
87
106
  /**
88
107
  * The vocabulary an adapter needs, re-exported from the port it implements.
89
108
  * An adapter imports these from here rather than reaching into the modules that
@@ -1 +1 @@
1
- {"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/model/model.ts"],"names":[],"mappings":"AA0EA;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,UAAyE;IAEzE,IAAI,IAAI,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;IACnC,OAAO,CAAC,IAAI,CAAC,IAAI;QAAE,IAAI,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;IAClD,OAAO,IAAI,CAAC,KAAK,CAAC;AACpB,CAAC","sourcesContent":["import type { Content, ContentPart } from \"../content.js\";\nimport type { ProviderState, ToolCall, Usage } from \"../session/entry.js\";\nimport type { Message } from \"../session/messages.js\";\nimport type { ToolSpec } from \"../tools/tool.js\";\nimport type { Failure, Result } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/**\n * One provider call.\n *\n * There is no model *name* here, and that is the point: a model is a value.\n * `createAnthropicModel({ apiKey, model })` is the provider, the credential and\n * the model together, and choosing a different one is choosing a different\n * `Model` — which is already how the loop passes a cheaper one to compaction.\n *\n * A name would have to be resolved, and resolving is what goes wrong. The one\n * application that had a name field to use encoded provider and model into it\n * as `provider/model`, then had to split it back out — ambiguously, because a\n * provider's own ids contain slashes (`z-ai/glm-5.2`), so the split was\n * \"up to the first one\" with a comment apologising for it. One field, two facts.\n * Names leave this library as observations — `ModelResponse.model` says what\n * actually served — and never enter it as selections.\n */\nexport interface ModelRequest {\n messages: readonly Message[];\n tools?: readonly ToolSpec[];\n maxOutputTokens?: number;\n /**\n * Only for providers that still accept sampling controls. The current\n * Anthropic models reject it outright, so that adapter does not send it —\n * declaring the option here and dropping it there is the honest shape, since\n * the alternative is a request the provider 400s.\n */\n temperature?: number;\n /**\n * How much the model should think before answering, where it can. Named\n * levels rather than a token budget, because a budget is the one thing no\n * two providers agree on — and the providers that had one have since removed\n * it. Each adapter maps a level to its own control; one that has none\n * ignores it rather than failing.\n */\n effort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n /** End the cacheable prefix after this many messages. A decision about one request only. */\n cacheAfter?: number;\n signal?: AbortSignal;\n}\n\nexport type ModelDelta =\n | { type: \"text.delta\"; text: string }\n | { type: \"reasoning.delta\"; text: string }\n | { type: \"tool-call.delta\"; callId: string; arguments: string };\n\nexport interface ModelResponse {\n message: { content: Content; calls?: readonly ToolCall[] };\n finishReason: \"stop\" | \"tool-calls\" | \"length\" | \"refusal\";\n usage: Usage;\n model?: string;\n providerState?: ProviderState;\n}\n\nexport interface ModelError extends Failure {\n code: \"auth\" | \"rate-limit\" | \"context-length\" | \"cancelled\" | \"provider\" | \"failed\";\n}\n\n/**\n * One method. Streaming is not a second contract: a caller that wants the whole\n * response drains the generator and takes its return value, so no adapter has\n * to implement the same normalization twice.\n */\nexport interface Model {\n readonly id: string;\n generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>>;\n}\n\n/**\n * Drains a generation and returns only its outcome.\n *\n * Not on the `aglib/model` subpath. It was, for a recipe that turned a `Model`\n * into an Anthropic response; when that went, nothing outside the package\n * consumed it. `Model`'s own contract above says what a caller who wants the\n * whole response does, and this is the four lines of doing it.\n */\nexport async function collect(\n generation: AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>>,\n): Promise<Result<ModelResponse, ModelError>> {\n let step = await generation.next();\n while (!step.done) step = await generation.next();\n return step.value;\n}\n\n/**\n * The vocabulary an adapter needs, re-exported from the port it implements.\n * An adapter imports these from here rather than reaching into the modules that\n * own them, so the port is the whole of its surface — every one of them appears\n * in a type above, which is what makes this the place to get them.\n */\nexport type { ContentPart, Message, ProviderState, ToolCall, ToolSpec, Usage };\n"]}
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/model/model.ts"],"names":[],"mappings":"AAuFA;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,UAA2B;IAE3B,IAAI,IAAI,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;IACnC,OAAO,CAAC,IAAI,CAAC,IAAI;QAAE,IAAI,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;IAClD,OAAO,IAAI,CAAC,KAAK,CAAC;AACpB,CAAC","sourcesContent":["import type { Content, ContentPart } from \"../content.js\";\nimport type { ProviderState, ToolCall, Usage } from \"../session/entry.js\";\nimport type { Message } from \"../session/messages.js\";\nimport type { ToolSpec } from \"../tools/tool.js\";\nimport type { Failure, Result } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/**\n * One provider call.\n *\n * There is no model *name* here, and that is the point: a model is a value.\n * `createAnthropicModel({ apiKey, model })` is the provider, the credential and\n * the model together, and choosing a different one is choosing a different\n * `Model` — which is already how the loop passes a cheaper one to compaction.\n *\n * A name would have to be resolved, and resolving is what goes wrong. The one\n * application that had a name field to use encoded provider and model into it\n * as `provider/model`, then had to split it back out — ambiguously, because a\n * provider's own ids contain slashes (`z-ai/glm-5.2`), so the split was\n * \"up to the first one\" with a comment apologising for it. One field, two facts.\n * Names leave this library as observations — `ModelResponse.model` says what\n * actually served — and never enter it as selections.\n */\nexport interface ModelRequest {\n messages: readonly Message[];\n tools?: readonly ToolSpec[];\n maxOutputTokens?: number;\n /**\n * Only for providers that still accept sampling controls. The current\n * Anthropic models reject it outright, so that adapter does not send it —\n * declaring the option here and dropping it there is the honest shape, since\n * the alternative is a request the provider 400s.\n */\n temperature?: number;\n /**\n * How much the model should think before answering, where it can. Named\n * levels rather than a token budget, because a budget is the one thing no\n * two providers agree on — and the providers that had one have since removed\n * it. Each adapter maps a level to its own control; one that has none\n * ignores it rather than failing.\n */\n effort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n /** End the cacheable prefix after this many messages. A decision about one request only. */\n cacheAfter?: number;\n signal?: AbortSignal;\n}\n\nexport type ModelDelta =\n | { type: \"text.delta\"; text: string; phase?: \"commentary\" | \"final_answer\" }\n | { type: \"reasoning.delta\"; text: string }\n | { type: \"tool-call.delta\"; callId: string; arguments: string }\n /** A complete call may be executable before the response itself is done. */\n | { type: \"tool-call.done\"; call: ToolCall };\n\nexport interface ModelResponse {\n message: { content: Content; calls?: readonly ToolCall[] };\n finishReason: \"stop\" | \"tool-calls\" | \"length\" | \"refusal\";\n usage: Usage;\n model?: string;\n providerState?: ProviderState;\n}\n\nexport interface ModelError extends Failure {\n code: \"auth\" | \"rate-limit\" | \"context-length\" | \"cancelled\" | \"provider\" | \"failed\";\n}\n\n/**\n * One method. Streaming is not a second contract: a caller that wants the whole\n * response drains the generator and takes its return value, so no adapter has\n * to implement the same normalization twice.\n */\nexport type ModelSteerResult =\n | { status: \"accepted\"; id: string }\n | { status: \"rejected\"; error: ModelError };\n\nexport interface ModelGeneration extends AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n /** Queue new user messages on this active generation, when its provider can. */\n steer?(input: readonly Message[]): Promise<ModelSteerResult>;\n}\n\nexport interface Model {\n readonly id: string;\n /** This configured model accepts tools declared for asynchronous execution. */\n readonly asyncTools?: true;\n generate(request: ModelRequest): ModelGeneration;\n}\n\n/**\n * Drains a generation and returns only its outcome.\n *\n * Not on the `aglib/model` subpath. It was, for a recipe that turned a `Model`\n * into an Anthropic response; when that went, nothing outside the package\n * consumed it. `Model`'s own contract above says what a caller who wants the\n * whole response does, and this is the four lines of doing it.\n */\nexport async function collect(\n generation: ModelGeneration,\n): Promise<Result<ModelResponse, ModelError>> {\n let step = await generation.next();\n while (!step.done) step = await generation.next();\n return step.value;\n}\n\n/**\n * The vocabulary an adapter needs, re-exported from the port it implements.\n * An adapter imports these from here rather than reaching into the modules that\n * own them, so the port is the whole of its surface — every one of them appears\n * in a type above, which is what makes this the place to get them.\n */\nexport type { ContentPart, Message, ProviderState, ToolCall, ToolSpec, Usage };\n"]}