@a-dray/aglib 0.3.3 → 0.3.4
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.
- package/dist/harness/adapters/native/loop.js +1 -0
- package/dist/harness/adapters/native/loop.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/dist/model/adapters/anthropic/index.js +49 -11
- package/dist/model/adapters/anthropic/index.js.map +1 -1
- package/dist/model/adapters/fake/index.d.ts +2 -1
- package/dist/model/adapters/fake/index.js +1 -0
- package/dist/model/adapters/fake/index.js.map +1 -1
- package/dist/model/adapters/openai-compatible/index.js +96 -7
- package/dist/model/adapters/openai-compatible/index.js.map +1 -1
- package/dist/model/index.d.ts +1 -1
- package/dist/model/index.js.map +1 -1
- package/dist/model/model.d.ts +3 -2
- package/dist/model/model.js.map +1 -1
- package/dist/session/entry.d.ts +7 -0
- package/dist/session/entry.js.map +1 -1
- package/dist/session/index.d.ts +1 -1
- package/dist/session/index.js.map +1 -1
- package/dist/session/messages.d.ts +2 -1
- package/dist/session/messages.js +1 -0
- package/dist/session/messages.js.map +1 -1
- package/dist/store/conformance.js +1 -0
- package/dist/store/conformance.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/openai-compatible/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAkB7C;;;GAGG;AACH,MAAM,UAAU,2BAA2B,CAAC,OAAgC;IAC1E,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC;IACpC,OAAO;QACL,EAAE,EAAE,qBAAqB,OAAO,CAAC,KAAK,EAAE;QAExC,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAqB;YACnC,IAAI,QAAkB,C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,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAChH,CAAC;AAED,+DAA+D;AAC/D,KAAK,SAAS,CAAC,CAAC,QAAQ,CAAC,IAAgC;IACvD,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,IAA4C,EAAE,CAAC;QACvE,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnC,OAAO,OAAO,IAAI,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;YAC7C,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;YACnC,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACzD,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n ContentPart, Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\nimport { textOf } from \"../../../content.js\";\n\nexport interface OpenAiCompatibleOptions {\n apiKey: string;\n baseUrl: string;\n model: string;\n headers?: Readonly<Record<string, string>>;\n /**\n * How this endpoint spells reasoning effort. OpenAI takes `reasoning_effort`;\n * OpenRouter takes `reasoning: { effort }` and forwards it to whoever is\n * serving the model. Sending both is not compatibility — OpenAI rejects the\n * request outright — so the dialect is declared rather than guessed.\n */\n effortParameter?: \"reasoning_effort\" | \"reasoning\" | \"none\";\n /** Injectable for tests; defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * The OpenAI chat-completions wire, which almost every provider now speaks —\n * OpenRouter, Together, Groq, vLLM, Ollama. One adapter, one base URL.\n */\nexport function createOpenAiCompatibleModel(options: OpenAiCompatibleOptions): Model {\n const call = options.fetch ?? fetch;\n return {\n id: `openai-compatible:${options.model}`,\n\n async *generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n let response: Response;\n try {\n response = await call(`${options.baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${options.apiKey}`,\n ...options.headers,\n },\n body: JSON.stringify({\n model: options.model,\n messages: encodeConversation(request.messages),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.maxOutputTokens !== undefined ? { max_tokens: request.maxOutputTokens } : {}),\n ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),\n ...encodeEffort(request.effort, options.effortParameter ?? \"reasoning_effort\"),\n stream: true,\n stream_options: { include_usage: true },\n }),\n ...(request.signal ? { signal: request.signal } : {}),\n });\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n if (!response.ok) return err(await httpError(response));\n if (!response.body) return err({ code: \"provider\", message: \"No response body\", retryable: true });\n\n const text: string[] = [];\n const calls = new Map<number, { callId: string; name: string; arguments: string }>();\n let finish: ModelResponse[\"finishReason\"] = \"stop\";\n let usage: Usage = {};\n let model: string | undefined;\n\n // A stream that dies mid-body — cancelled, dropped, truncated — must come\n // back as a typed failure like any other. Without this the generator throws,\n // `run.result` rejects instead of resolving `cancelled`, no `run.finished`\n // is ever committed, and the activation stays open until its claim expires.\n try {\n for await (const event of sseLines(response.body)) {\n if (event === \"[DONE]\") break;\n let frame: ChatFrame;\n try { frame = JSON.parse(event) as ChatFrame; } catch { continue; }\n model ??= frame.model;\n if (frame.usage) usage = decodeUsage(frame.usage);\n\n const choice = frame.choices?.[0];\n if (!choice) continue;\n if (choice.finish_reason) finish = decodeFinish(choice.finish_reason);\n\n const content = choice.delta?.content;\n if (content) { text.push(content); yield { type: \"text.delta\", text: content }; }\n\n const reasoning = choice.delta?.reasoning;\n if (reasoning) yield { type: \"reasoning.delta\", text: reasoning };\n\n for (const fragment of choice.delta?.tool_calls ?? []) {\n // Providers stream tool arguments in fragments, keyed by position;\n // only the first fragment carries the id and the name.\n const existing = calls.get(fragment.index) ?? {\n callId: fragment.id ?? `call_${fragment.index}`,\n name: fragment.function?.name ?? \"\",\n arguments: \"\",\n };\n if (fragment.id) existing.callId = fragment.id;\n if (fragment.function?.name) existing.name = fragment.function.name;\n if (fragment.function?.arguments) {\n existing.arguments += fragment.function.arguments;\n yield { type: \"tool-call.delta\", callId: existing.callId, arguments: fragment.function.arguments };\n }\n calls.set(fragment.index, existing);\n }\n }\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n const collected: ToolCall[] = [...calls.values()]\n .map((call) => ({ callId: call.callId, name: call.name, arguments: call.arguments || \"{}\" }));\n\n return ok({\n message: { content: text.join(\"\"), ...(collected.length ? { calls: collected } : {}) },\n finishReason: collected.length && finish === \"stop\" ? \"tool-calls\" : finish,\n usage,\n ...(model ? { model } : {}),\n });\n },\n };\n}\n\n/** OpenRouter is this wire with a fixed base URL and attribution headers. */\nexport function createOpenRouterModel(input: {\n apiKey: string; model: string; appUrl?: string; appName?: string; fetch?: typeof fetch;\n}): Model {\n return createOpenAiCompatibleModel({\n apiKey: input.apiKey,\n baseUrl: \"https://openrouter.ai/api/v1\",\n model: input.model,\n effortParameter: \"reasoning\",\n headers: {\n ...(input.appUrl ? { \"http-referer\": input.appUrl } : {}),\n ...(input.appName ? { \"x-title\": input.appName } : {}),\n },\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n}\n\nfunction encodeEffort(\n effort: ModelRequest[\"effort\"],\n parameter: \"reasoning_effort\" | \"reasoning\" | \"none\",\n): Record<string, unknown> {\n if (!effort || parameter === \"none\") return {};\n return parameter === \"reasoning\" ? { reasoning: { effort } } : { reasoning_effort: effort };\n}\n\nfunction encodeConversation(messages: readonly Message[]): Record<string, unknown>[] {\n const out: Record<string, unknown>[] = [];\n let images: ContentPart[] = [];\n const flush = () => {\n if (images.length) out.push({ role: \"user\", content: encodeContent(images) });\n images = [];\n };\n for (const message of messages) {\n // The wire accepts only text in tool replies. Keep every reply in a parallel\n // batch adjacent before supplying its images as associated user content.\n if (message.role !== \"tool\") flush();\n out.push(encodeMessage(message));\n if (message.role === \"tool\" && typeof message.content !== \"string\") {\n const media = message.content.filter((part) => part.type === \"image\");\n if (media.length) images.push({ type: \"text\", text: `Images from tool call ${message.callId}:` }, ...media);\n }\n }\n flush();\n return out;\n}\n\nfunction encodeMessage(message: Message): Record<string, unknown> {\n if (message.role === \"tool\") {\n return { role: \"tool\", tool_call_id: message.callId, content: textOf(message.content) };\n }\n if (message.role === \"assistant\") {\n return {\n role: \"assistant\",\n content: textOf(message.content) || null,\n ...(message.calls?.length\n ? {\n tool_calls: message.calls.map((call) => ({\n id: call.callId, type: \"function\",\n function: { name: call.name, arguments: call.arguments },\n })),\n }\n : {}),\n };\n }\n return { role: message.role, content: encodeContent(message.content) };\n}\n\nfunction encodeContent(content: Message[\"content\"]): unknown {\n if (typeof content === \"string\") return content;\n const parts: Record<string, unknown>[] = [];\n for (const part of content as readonly ContentPart[]) {\n if (part.type === \"text\") { parts.push({ type: \"text\", text: part.text }); continue; }\n if (part.type === \"image\") {\n const url = part.source.kind === \"url\" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`;\n parts.push({ type: \"image_url\", image_url: { url } });\n }\n // Files and opaque blocks have no place on this wire. Dropping them beats\n // stringifying them into something the model would read as prose.\n }\n const only = parts.length === 1 ? parts[0] : undefined;\n return only?.type === \"text\" ? only.text : parts;\n}\n\nconst encodeTool = (tool: ToolSpec) => ({\n type: \"function\",\n function: { name: tool.name, description: tool.description, parameters: tool.parameters, strict: false },\n});\n\nconst decodeFinish = (reason: string): ModelResponse[\"finishReason\"] =>\n reason === \"tool_calls\" ? \"tool-calls\"\n : reason === \"length\" ? \"length\"\n : reason === \"content_filter\" ? \"refusal\"\n : \"stop\";\n\nconst decodeUsage = (usage: ChatUsage): Usage => ({\n // Carried, not computed. A router picks an upstream provider per request and\n // adds its own margin, so what it charged is a thing only it can say — and\n // the frame carrying it is the one this adapter already reads.\n ...(typeof usage.cost === \"number\" ? { costUsd: usage.cost } : {}),\n // `prompt_tokens` is the whole prompt and `cached_tokens` is counted inside\n // it — \"cached tokens present in the prompt\". `Usage` keeps the three input\n // counts disjoint, so the cached part comes out here rather than every\n // caller having to know which wire produced the number it is holding.\n ...(usage.prompt_tokens !== undefined\n ? { inputTokens: Math.max(usage.prompt_tokens - (usage.prompt_tokens_details?.cached_tokens ?? 0), 0) } : {}),\n ...(usage.completion_tokens !== undefined ? { outputTokens: usage.completion_tokens } : {}),\n ...(usage.prompt_tokens_details?.cached_tokens !== undefined\n ? { cacheReadTokens: usage.prompt_tokens_details.cached_tokens } : {}),\n});\n\nasync function httpError(response: Response): Promise<ModelError> {\n const body = await response.text().catch(() => \"\");\n const code: ModelError[\"code\"] =\n response.status === 401 || response.status === 403 ? \"auth\"\n : response.status === 429 ? \"rate-limit\"\n : response.status === 400 && /context|token/i.test(body) ? \"context-length\"\n : response.status >= 500 ? \"provider\"\n : \"failed\";\n return {\n code,\n message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : \"\"}`,\n retryable: code === \"rate-limit\" || code === \"provider\",\n };\n}\n\nfunction transportError(error: unknown, signal?: AbortSignal): ModelError {\n if (signal?.aborted) return { code: \"cancelled\", message: \"Generation cancelled\", retryable: false };\n return { code: \"provider\", message: error instanceof Error ? error.message : String(error), retryable: true };\n}\n\n/** Server-sent events, reassembled across chunk boundaries. */\nasync function* sseLines(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(chunk, { stream: true });\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (line.startsWith(\"data:\")) yield line.slice(5).trim();\n newline = buffer.indexOf(\"\\n\");\n }\n }\n}\n\ninterface ChatUsage {\n prompt_tokens?: number;\n completion_tokens?: number;\n prompt_tokens_details?: { cached_tokens?: number };\n /**\n * What this generation was charged. OpenRouter sets it on every response and\n * calls it credits, whose base currency is US dollars; plain OpenAI and the\n * self-hosted endpoints on this wire do not send it at all, so it is absent\n * rather than zero there.\n */\n cost?: number;\n}\ninterface ChatFrame {\n model?: string;\n usage?: ChatUsage;\n choices?: readonly {\n finish_reason?: string | null;\n delta?: {\n content?: string;\n reasoning?: string;\n tool_calls?: readonly { index: number; id?: string; function?: { name?: string; arguments?: string } }[];\n };\n }[];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/openai-compatible/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAmB7C;;;GAGG;AACH,MAAM,UAAU,2BAA2B,CAAC,OAAgC;IAC1E,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC;IACpC,MAAM,QAAQ,GAAG,qBAAqB,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC;IAC5E,OAAO;QACL,EAAE,EAAE,qBAAqB,OAAO,CAAC,KAAK,EAAE;QAExC,KAAK,CAAC,CAAC,QAAQ,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I,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAChH,CAAC;AAED,+DAA+D;AAC/D,KAAK,SAAS,CAAC,CAAC,QAAQ,CAAC,IAAgC;IACvD,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,IAA4C,EAAE,CAAC;QACvE,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnC,OAAO,OAAO,IAAI,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;YAC7C,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;YACnC,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACzD,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n ContentPart, Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\nimport { textOf } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\n\nexport interface OpenAiCompatibleOptions {\n apiKey: string;\n baseUrl: string;\n model: string;\n headers?: Readonly<Record<string, string>>;\n /**\n * How this endpoint spells reasoning effort. OpenAI takes `reasoning_effort`;\n * OpenRouter takes `reasoning: { effort }` and forwards it to whoever is\n * serving the model. Sending both is not compatibility — OpenAI rejects the\n * request outright — so the dialect is declared rather than guessed.\n */\n effortParameter?: \"reasoning_effort\" | \"reasoning\" | \"none\";\n /** Injectable for tests; defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * The OpenAI chat-completions wire, which almost every provider now speaks —\n * OpenRouter, Together, Groq, vLLM, Ollama. One adapter, one base URL.\n */\nexport function createOpenAiCompatibleModel(options: OpenAiCompatibleOptions): Model {\n const call = options.fetch ?? fetch;\n const provider = `openai-compatible:${options.baseUrl.replace(/\\/+$/, \"\")}`;\n return {\n id: `openai-compatible:${options.model}`,\n\n async *generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n let response: Response;\n try {\n response = await call(`${options.baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${options.apiKey}`,\n ...options.headers,\n },\n body: JSON.stringify({\n model: options.model,\n messages: encodeConversation(request.messages, provider),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.maxOutputTokens !== undefined ? { max_tokens: request.maxOutputTokens } : {}),\n ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),\n ...encodeEffort(request.effort, options.effortParameter ?? \"reasoning_effort\"),\n stream: true,\n stream_options: { include_usage: true },\n }),\n ...(request.signal ? { signal: request.signal } : {}),\n });\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n if (!response.ok) return err(await httpError(response));\n if (!response.body) return err({ code: \"provider\", message: \"No response body\", retryable: true });\n\n const text: string[] = [];\n const calls = new Map<number, { callId: string; name: string; arguments: string }>();\n let finish: ModelResponse[\"finishReason\"] = \"stop\";\n let usage: Usage = {};\n let model: string | undefined;\n const reasoningDetails: JsonValue[] = [];\n let sawReasoningDetails = false;\n const reasoning: string[] = [];\n const reasoningContent: string[] = [];\n\n // A stream that dies mid-body — cancelled, dropped, truncated — must come\n // back as a typed failure like any other. Without this the generator throws,\n // `run.result` rejects instead of resolving `cancelled`, no `run.finished`\n // is ever committed, and the activation stays open until its claim expires.\n try {\n for await (const event of sseLines(response.body)) {\n if (event === \"[DONE]\") break;\n let frame: ChatFrame;\n try { frame = JSON.parse(event) as ChatFrame; } catch { continue; }\n model ??= frame.model;\n if (frame.usage) usage = decodeUsage(frame.usage);\n\n const choice = frame.choices?.[0];\n if (!choice) continue;\n if (choice.finish_reason) finish = decodeFinish(choice.finish_reason);\n\n const content = choice.delta?.content;\n if (content) { text.push(content); yield { type: \"text.delta\", text: content }; }\n\n const reasoningDelta = choice.delta?.reasoning;\n const reasoningContentDelta = choice.delta?.reasoning_content;\n if (reasoningDelta !== undefined) reasoning.push(reasoningDelta);\n if (reasoningContentDelta !== undefined) reasoningContent.push(reasoningContentDelta);\n const visibleReasoning = reasoningDelta ?? reasoningContentDelta;\n if (visibleReasoning) yield { type: \"reasoning.delta\", text: visibleReasoning };\n if (choice.delta?.reasoning_details !== undefined) {\n sawReasoningDetails = true;\n appendReasoningDetails(reasoningDetails, choice.delta.reasoning_details);\n }\n\n for (const fragment of choice.delta?.tool_calls ?? []) {\n // Providers stream tool arguments in fragments, keyed by position;\n // only the first fragment carries the id and the name.\n const existing = calls.get(fragment.index) ?? {\n callId: fragment.id ?? `call_${fragment.index}`,\n name: fragment.function?.name ?? \"\",\n arguments: \"\",\n };\n if (fragment.id) existing.callId = fragment.id;\n if (fragment.function?.name) existing.name = fragment.function.name;\n if (fragment.function?.arguments) {\n existing.arguments += fragment.function.arguments;\n yield { type: \"tool-call.delta\", callId: existing.callId, arguments: fragment.function.arguments };\n }\n calls.set(fragment.index, existing);\n }\n }\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n const collected: ToolCall[] = [...calls.values()]\n .map((call) => ({ callId: call.callId, name: call.name, arguments: call.arguments || \"{}\" }));\n\n const state = reasoningState(reasoningDetails, sawReasoningDetails, reasoning, reasoningContent);\n return ok({\n message: { content: text.join(\"\"), ...(collected.length ? { calls: collected } : {}) },\n finishReason: collected.length && finish === \"stop\" ? \"tool-calls\" : finish,\n usage,\n ...(model ? { model } : {}),\n ...(state.length ? { providerState: { provider, items: state } } : {}),\n });\n },\n };\n}\n\n/** OpenRouter is this wire with a fixed base URL and attribution headers. */\nexport function createOpenRouterModel(input: {\n apiKey: string; model: string; appUrl?: string; appName?: string; fetch?: typeof fetch;\n}): Model {\n return createOpenAiCompatibleModel({\n apiKey: input.apiKey,\n baseUrl: \"https://openrouter.ai/api/v1\",\n model: input.model,\n effortParameter: \"reasoning\",\n headers: {\n ...(input.appUrl ? { \"http-referer\": input.appUrl } : {}),\n ...(input.appName ? { \"x-title\": input.appName } : {}),\n },\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n}\n\nfunction encodeEffort(\n effort: ModelRequest[\"effort\"],\n parameter: \"reasoning_effort\" | \"reasoning\" | \"none\",\n): Record<string, unknown> {\n if (!effort || parameter === \"none\") return {};\n return parameter === \"reasoning\" ? { reasoning: { effort } } : { reasoning_effort: effort };\n}\n\nfunction encodeConversation(messages: readonly Message[], provider: string): Record<string, unknown>[] {\n const out: Record<string, unknown>[] = [];\n let images: ContentPart[] = [];\n const flush = () => {\n if (images.length) out.push({ role: \"user\", content: encodeContent(images) });\n images = [];\n };\n for (const message of messages) {\n // The wire accepts only text in tool replies. Keep every reply in a parallel\n // batch adjacent before supplying its images as associated user content.\n if (message.role !== \"tool\") flush();\n out.push(encodeMessage(message, provider));\n if (message.role === \"tool\" && typeof message.content !== \"string\") {\n const media = message.content.filter((part) => part.type === \"image\");\n if (media.length) images.push({ type: \"text\", text: `Images from tool call ${message.callId}:` }, ...media);\n }\n }\n flush();\n return out;\n}\n\nfunction encodeMessage(message: Message, provider: string): Record<string, unknown> {\n if (message.role === \"tool\") {\n return { role: \"tool\", tool_call_id: message.callId, content: textOf(message.content) };\n }\n if (message.role === \"assistant\") {\n return {\n role: \"assistant\",\n content: textOf(message.content) || null,\n ...decodeReasoningState(message, provider),\n ...(message.calls?.length\n ? {\n tool_calls: message.calls.map((call) => ({\n id: call.callId, type: \"function\",\n function: { name: call.name, arguments: call.arguments },\n })),\n }\n : {}),\n };\n }\n return { role: message.role, content: encodeContent(message.content) };\n}\n\nfunction encodeContent(content: Message[\"content\"]): unknown {\n if (typeof content === \"string\") return content;\n const parts: Record<string, unknown>[] = [];\n for (const part of content as readonly ContentPart[]) {\n if (part.type === \"text\") { parts.push({ type: \"text\", text: part.text }); continue; }\n if (part.type === \"image\") {\n const url = part.source.kind === \"url\" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`;\n parts.push({ type: \"image_url\", image_url: { url } });\n }\n // Files and opaque blocks have no place on this wire. Dropping them beats\n // stringifying them into something the model would read as prose.\n }\n const only = parts.length === 1 ? parts[0] : undefined;\n return only?.type === \"text\" ? only.text : parts;\n}\n\nfunction reasoningState(\n details: readonly JsonValue[],\n sawDetails: boolean,\n reasoning: readonly string[],\n reasoningContent: readonly string[],\n): JsonValue[] {\n const state: Record<string, JsonValue> = {};\n if (sawDetails) state[\"reasoning_details\"] = details;\n if (!sawDetails && reasoning.length) state[\"reasoning\"] = reasoning.join(\"\");\n if (!sawDetails && reasoningContent.length) state[\"reasoning_content\"] = reasoningContent.join(\"\");\n return Object.keys(state).length ? [state] : [];\n}\n\nfunction decodeReasoningState(message: Extract<Message, { role: \"assistant\" }>, provider: string) {\n if (message.providerState?.provider !== provider) return {};\n const state: Record<string, JsonValue> = {};\n for (const item of message.providerState.items) {\n const value = record(item);\n const details = value?.[\"reasoning_details\"];\n if (Array.isArray(details)) state[\"reasoning_details\"] = details;\n for (const field of [\"reasoning\", \"reasoning_content\"] as const) {\n if (typeof value?.[field] === \"string\") state[field] = value[field];\n }\n }\n return state;\n}\n\n/** Rebuild the complete blocks OpenRouter's chat stream fragments by type. */\nfunction appendReasoningDetails(target: JsonValue[], incoming: readonly JsonValue[]): void {\n for (const raw of incoming) {\n const detail = record(raw);\n if (!detail) {\n target.push(clone(raw));\n continue;\n }\n const field = detail?.[\"type\"] === \"reasoning.text\" ? \"text\"\n : detail?.[\"type\"] === \"reasoning.summary\" ? \"summary\"\n : undefined;\n const previous = record(target.at(-1));\n if (!field || !previous || previous[\"type\"] !== detail[\"type\"] || !compatible(previous, detail, field)) {\n target.push(clone(raw));\n continue;\n }\n\n const merged: Record<string, JsonValue> = { ...previous };\n for (const [key, value] of Object.entries(detail)) {\n if (key === field) continue;\n if (value !== null || merged[key] === undefined) merged[key] = value;\n }\n merged[field] = `${typeof previous[field] === \"string\" ? previous[field] : \"\"}${\n typeof detail[field] === \"string\" ? detail[field] : \"\"\n }`;\n target[target.length - 1] = merged;\n }\n}\n\nfunction compatible(\n left: Readonly<Record<string, JsonValue>>,\n right: Readonly<Record<string, JsonValue>>,\n payload: string,\n): boolean {\n const keys = new Set([...Object.keys(left), ...Object.keys(right)]);\n for (const key of keys) {\n if (key === payload) continue;\n const a = left[key];\n const b = right[key];\n if (a === undefined || a === null || b === undefined || b === null) continue;\n if (JSON.stringify(a) !== JSON.stringify(b)) return false;\n }\n return true;\n}\n\nconst record = (value: JsonValue | undefined): Readonly<Record<string, JsonValue>> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? value as Readonly<Record<string, JsonValue>>\n : undefined;\n\nconst clone = (value: JsonValue): JsonValue => JSON.parse(JSON.stringify(value)) as JsonValue;\n\nconst encodeTool = (tool: ToolSpec) => ({\n type: \"function\",\n function: { name: tool.name, description: tool.description, parameters: tool.parameters, strict: false },\n});\n\nconst decodeFinish = (reason: string): ModelResponse[\"finishReason\"] =>\n reason === \"tool_calls\" ? \"tool-calls\"\n : reason === \"length\" ? \"length\"\n : reason === \"content_filter\" ? \"refusal\"\n : \"stop\";\n\nconst decodeUsage = (usage: ChatUsage): Usage => ({\n // Carried, not computed. A router picks an upstream provider per request and\n // adds its own margin, so what it charged is a thing only it can say — and\n // the frame carrying it is the one this adapter already reads.\n ...(typeof usage.cost === \"number\" ? { costUsd: usage.cost } : {}),\n // `prompt_tokens` is the whole prompt and `cached_tokens` is counted inside\n // it — \"cached tokens present in the prompt\". `Usage` keeps the three input\n // counts disjoint, so the cached part comes out here rather than every\n // caller having to know which wire produced the number it is holding.\n ...(usage.prompt_tokens !== undefined\n ? { inputTokens: Math.max(usage.prompt_tokens - (usage.prompt_tokens_details?.cached_tokens ?? 0), 0) } : {}),\n ...(usage.completion_tokens !== undefined ? { outputTokens: usage.completion_tokens } : {}),\n ...(usage.prompt_tokens_details?.cached_tokens !== undefined\n ? { cacheReadTokens: usage.prompt_tokens_details.cached_tokens } : {}),\n});\n\nasync function httpError(response: Response): Promise<ModelError> {\n const body = await response.text().catch(() => \"\");\n const code: ModelError[\"code\"] =\n response.status === 401 || response.status === 403 ? \"auth\"\n : response.status === 429 ? \"rate-limit\"\n : response.status === 400 && /context|token/i.test(body) ? \"context-length\"\n : response.status >= 500 ? \"provider\"\n : \"failed\";\n return {\n code,\n message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : \"\"}`,\n retryable: code === \"rate-limit\" || code === \"provider\",\n };\n}\n\nfunction transportError(error: unknown, signal?: AbortSignal): ModelError {\n if (signal?.aborted) return { code: \"cancelled\", message: \"Generation cancelled\", retryable: false };\n return { code: \"provider\", message: error instanceof Error ? error.message : String(error), retryable: true };\n}\n\n/** Server-sent events, reassembled across chunk boundaries. */\nasync function* sseLines(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(chunk, { stream: true });\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (line.startsWith(\"data:\")) yield line.slice(5).trim();\n newline = buffer.indexOf(\"\\n\");\n }\n }\n}\n\ninterface ChatUsage {\n prompt_tokens?: number;\n completion_tokens?: number;\n prompt_tokens_details?: { cached_tokens?: number };\n /**\n * What this generation was charged. OpenRouter sets it on every response and\n * calls it credits, whose base currency is US dollars; plain OpenAI and the\n * self-hosted endpoints on this wire do not send it at all, so it is absent\n * rather than zero there.\n */\n cost?: number;\n}\ninterface ChatFrame {\n model?: string;\n usage?: ChatUsage;\n choices?: readonly {\n finish_reason?: string | null;\n delta?: {\n content?: string;\n reasoning?: string;\n reasoning_content?: string;\n reasoning_details?: readonly JsonValue[];\n tool_calls?: readonly { index: number; id?: string; function?: { name?: string; arguments?: string } }[];\n };\n }[];\n}\n"]}
|
package/dist/model/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export type { Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolSpec, } from "./model.js";
|
|
1
|
+
export type { Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ProviderState, ToolSpec, } from "./model.js";
|
package/dist/model/index.js.map
CHANGED
|
@@ -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, 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, ModelRequest, ModelResponse, ProviderState, ToolSpec,\n} from \"./model.js\";\n"]}
|
package/dist/model/model.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Content, ContentPart } from "../content.js";
|
|
2
|
-
import type { ToolCall, Usage } from "../session/entry.js";
|
|
2
|
+
import type { ProviderState, ToolCall, Usage } from "../session/entry.js";
|
|
3
3
|
import type { Message } from "../session/messages.js";
|
|
4
4
|
import type { ToolSpec } from "../tools/tool.js";
|
|
5
5
|
import type { Failure, Result } from "../result.js";
|
|
@@ -61,6 +61,7 @@ export interface ModelResponse {
|
|
|
61
61
|
finishReason: "stop" | "tool-calls" | "length" | "refusal";
|
|
62
62
|
usage: Usage;
|
|
63
63
|
model?: string;
|
|
64
|
+
providerState?: ProviderState;
|
|
64
65
|
}
|
|
65
66
|
export interface ModelError extends Failure {
|
|
66
67
|
code: "auth" | "rate-limit" | "context-length" | "cancelled" | "provider" | "failed";
|
|
@@ -89,4 +90,4 @@ export declare function collect(generation: AsyncGenerator<ModelDelta, Result<Mo
|
|
|
89
90
|
* own them, so the port is the whole of its surface — every one of them appears
|
|
90
91
|
* in a type above, which is what makes this the place to get them.
|
|
91
92
|
*/
|
|
92
|
-
export type { ContentPart, Message, ToolCall, ToolSpec, Usage };
|
|
93
|
+
export type { ContentPart, Message, ProviderState, ToolCall, ToolSpec, Usage };
|
package/dist/model/model.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/model/model.ts"],"names":[],"mappings":"
|
|
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"]}
|
package/dist/session/entry.d.ts
CHANGED
|
@@ -7,6 +7,12 @@ export interface ToolCall {
|
|
|
7
7
|
name: string;
|
|
8
8
|
arguments: string;
|
|
9
9
|
}
|
|
10
|
+
/** Provider-owned continuation data, retained verbatim beside the output that produced it. */
|
|
11
|
+
export interface ProviderState {
|
|
12
|
+
/** The provider wire allowed to replay these items. */
|
|
13
|
+
provider: string;
|
|
14
|
+
items: readonly JsonValue[];
|
|
15
|
+
}
|
|
10
16
|
export interface ToolResult {
|
|
11
17
|
content: Content;
|
|
12
18
|
/** Structured channel for the application and the UI. Never reaches the model. */
|
|
@@ -108,6 +114,7 @@ export type Entry = {
|
|
|
108
114
|
content: Content;
|
|
109
115
|
calls?: readonly ToolCall[];
|
|
110
116
|
usage?: Usage;
|
|
117
|
+
providerState?: ProviderState;
|
|
111
118
|
/**
|
|
112
119
|
* What produced this turn, when a model did: which model answered and the
|
|
113
120
|
* span it took. `Stored.at` is when the entry was committed, which is a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entry.js","sourceRoot":"","sources":["../../src/session/entry.ts"],"names":[],"mappings":"","sourcesContent":["import type { Content } from \"../content.js\";\nimport type { Failure } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/** A model's request to invoke a tool. `arguments` is unparsed JSON as the provider sent it. */\nexport interface ToolCall {\n callId: string;\n name: string;\n arguments: string;\n}\n\nexport interface ToolResult {\n content: Content;\n /** Structured channel for the application and the UI. Never reaches the model. */\n details?: JsonValue;\n isError?: boolean;\n}\n\n/**\n * What a generation consumed.\n *\n * Absent stays absent — a count nobody reported is not a zero. This package\n * holds no rates and computes no money from tokens. Where an adapter does\n * arithmetic it is reconciling its wire's encoding to the meanings below:\n * normalization, which is an adapter's job, and never a new fact.\n *\n * That is why `costUsd` belongs here and a rate table does not. A cost the\n * provider *states* is an observation like the counts beside it, and dropping\n * it was the same mistake as dropping the model that served the request: an\n * application was left reconstructing, from a table it maintains by hand, a\n * number the wire had already given it. For a router that is not even possible\n * — it picks an upstream provider per request and adds its own margin, so no\n * static table can say what was charged.\n */\nexport interface Usage {\n /**\n * Input tokens that were neither read from nor written to a cache.\n *\n * **The three input counts are disjoint.** The prompt's total size is\n * `inputTokens + cacheReadTokens + cacheWriteTokens`; no field here is a\n * subset of another, so a caller sums and never subtracts.\n *\n * The wires disagree about this and one of them has to be converted. What\n * Anthropic calls `input_tokens` is already this — \"tokens which were not\n * read from or used to create a cache\". What OpenAI calls `prompt_tokens` is\n * the whole prompt, with `cached_tokens` counted inside it, so that adapter\n * subtracts once and callers stop having to know which wire answered.\n *\n * Disjoint is the choice that survives absence, which is the rule the rest of\n * this type runs on. Summing the fields you were given is right whichever\n * ones are missing; subtracting a field you were not given is not. Under the\n * other convention a heavily cached Anthropic turn priced its fresh tokens at\n * zero — quietly, because the subtraction was clamped at zero rather than\n * being allowed to go negative where somebody would have seen it.\n */\n inputTokens?: number;\n outputTokens?: number;\n /** Input tokens served from a cache. Disjoint from `inputTokens`. */\n cacheReadTokens?: number;\n /** Input tokens written to a cache. Disjoint from `inputTokens`. */\n cacheWriteTokens?: number;\n /**\n * What the provider said this generation cost, in US dollars. Reported,\n * never derived: no adapter computes this from a rate, and one whose wire\n * does not carry a cost leaves it absent rather than estimating.\n */\n costUsd?: number;\n}\n\n/**\n * Who sent an arrival: what sort of sender, and which one.\n *\n * aglib mints exactly one kind — `\"session\"`, a delivery from another session —\n * and interprets no other. Every other kind is the application's word for one of\n * its own senders: a person, a channel, a schedule, a webhook. The vocabulary\n * belongs to whoever can close it, and that is never this package.\n *\n * Two fields because absence was carrying four facts. This used to be the\n * sending session's id alone, so an operator, a channel and a timer all said the\n * same thing by saying nothing, and a recipient could not tell a person typing\n * from a routine firing. Packing both into one string instead — `\"routine:x\"` —\n * would put the vocabulary in a convention nothing closes, which is how such a\n * field ends up with values that exist only by grep and a different reading on\n * every surface that renders it.\n */\nexport interface From {\n kind: string;\n id: string;\n}\n\n/**\n * The canonical vocabulary. This is the session's state, not a record of it:\n * the loop reads its context by projecting these and appends back to them, so\n * there is no second transcript that could disagree.\n *\n * `tool.started` carries only the call id — the assistant entry above it\n * already holds the call, and duplicating name and arguments would be a second\n * field for a value another field determines.\n */\nexport type Entry =\n | { type: \"hook.input\"; runId: string; hook: string; input: Content }\n | { type: \"run.started\"; runId: string; input: Content; from?: From }\n | {\n type: \"assistant\"; runId: string; content: Content;\n calls?: readonly ToolCall[]; usage?: Usage;\n /**\n * What produced this turn, when a model did: which model answered and the\n * span it took. `Stored.at` is when the entry was committed, which is a\n * different fact and not a substitute — anything projecting a generation\n * needs both ends of the call, and the commit is neither of them.\n */\n generation?: { model?: string; startedAt: string; endedAt: string };\n }\n | { type: \"tool.started\"; runId: string; callId: string }\n | { type: \"tool.finished\"; runId: string; callId: string; result: ToolResult }\n /** Compaction output. `replaces` is the seq up to which entries are folded; nothing is deleted. */\n | { type: \"summary\"; runId: string; content: string; replaces: number }\n | { type: \"run.finished\"; runId: string; outcome: \"completed\" | \"failed\" | \"cancelled\"; error?: Failure };\n\nexport type EntryType = Entry[\"type\"];\n\n/** An entry once the log has given it a position. */\nexport type Stored<T extends Entry = Entry> = T & { seq: number; at: string };\n\n/**\n * Input delivered to a session, committed with the sender's own entries.\n * Spawning a child, replying to a parent and messaging a peer are all this.\n */\nexport interface Delivery {\n /** The session it is delivered to. */\n sessionId: string;\n input: Content;\n /**\n * Who sent it. Absent means the application did not say — not that nobody\n * did. Recorded on the receiving `run.started`, so an application can tell a\n * peer's message from its user's, and can see that it already answered one\n * that arrives twice. It becomes text the model reads only where the\n * recipient's agent asks, with `attribution`.\n */\n from?: From;\n /**\n * Where in the recipient's loop this lands. Defaults to \"next\".\n *\n * Three places, and each is an outcome a sender can reason about rather than\n * a level of urgency a harness interprets:\n *\n * \"interrupt\" — the running activation ends, so the next one begins with\n * this. Its uncommitted work is lost; everything it had\n * already committed stays.\n * \"turn\" — folded into the activation already running, before its next\n * model call. Nothing in flight is lost. Immediately, if\n * nothing is running.\n * \"next\" — at the start of the recipient's next activation.\n *\n * This used to be `now | next | later`, and `now` meant either of the first\n * two depending on the harness — fold if it had a safe point, end the\n * activation if it did not. One word for \"your message arrives and the work\n * continues\" and \"your message arrives and a turn's work is destroyed\". The\n * doctrine was that a priority names the requirement and not the mechanism,\n * but those are not two mechanisms for one requirement: they are two\n * different things happening to somebody's work, and a runtime answer saying\n * which one you got was invented to paper over it. `later` named a fourth\n * thing that nothing implemented.\n *\n * **A harness that cannot honour one falls back to a later place, never an\n * earlier one.** A loop with no safe point cannot do \"turn\", so it does\n * \"next\" — the message waits. It does not end the activation instead, which\n * is what falling back through an ordered scale used to do: ask for the\n * gentlest useful thing and get the most destructive one.\n */\n priority?: \"interrupt\" | \"turn\" | \"next\";\n /**\n * The sender's key for this delivery. Two deliveries with the same id are the\n * same delivery, so a retried send does not arrive twice.\n */\n id?: string;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"entry.js","sourceRoot":"","sources":["../../src/session/entry.ts"],"names":[],"mappings":"","sourcesContent":["import type { Content } from \"../content.js\";\nimport type { Failure } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/** A model's request to invoke a tool. `arguments` is unparsed JSON as the provider sent it. */\nexport interface ToolCall {\n callId: string;\n name: string;\n arguments: string;\n}\n\n/** Provider-owned continuation data, retained verbatim beside the output that produced it. */\nexport interface ProviderState {\n /** The provider wire allowed to replay these items. */\n provider: string;\n items: readonly JsonValue[];\n}\n\nexport interface ToolResult {\n content: Content;\n /** Structured channel for the application and the UI. Never reaches the model. */\n details?: JsonValue;\n isError?: boolean;\n}\n\n/**\n * What a generation consumed.\n *\n * Absent stays absent — a count nobody reported is not a zero. This package\n * holds no rates and computes no money from tokens. Where an adapter does\n * arithmetic it is reconciling its wire's encoding to the meanings below:\n * normalization, which is an adapter's job, and never a new fact.\n *\n * That is why `costUsd` belongs here and a rate table does not. A cost the\n * provider *states* is an observation like the counts beside it, and dropping\n * it was the same mistake as dropping the model that served the request: an\n * application was left reconstructing, from a table it maintains by hand, a\n * number the wire had already given it. For a router that is not even possible\n * — it picks an upstream provider per request and adds its own margin, so no\n * static table can say what was charged.\n */\nexport interface Usage {\n /**\n * Input tokens that were neither read from nor written to a cache.\n *\n * **The three input counts are disjoint.** The prompt's total size is\n * `inputTokens + cacheReadTokens + cacheWriteTokens`; no field here is a\n * subset of another, so a caller sums and never subtracts.\n *\n * The wires disagree about this and one of them has to be converted. What\n * Anthropic calls `input_tokens` is already this — \"tokens which were not\n * read from or used to create a cache\". What OpenAI calls `prompt_tokens` is\n * the whole prompt, with `cached_tokens` counted inside it, so that adapter\n * subtracts once and callers stop having to know which wire answered.\n *\n * Disjoint is the choice that survives absence, which is the rule the rest of\n * this type runs on. Summing the fields you were given is right whichever\n * ones are missing; subtracting a field you were not given is not. Under the\n * other convention a heavily cached Anthropic turn priced its fresh tokens at\n * zero — quietly, because the subtraction was clamped at zero rather than\n * being allowed to go negative where somebody would have seen it.\n */\n inputTokens?: number;\n outputTokens?: number;\n /** Input tokens served from a cache. Disjoint from `inputTokens`. */\n cacheReadTokens?: number;\n /** Input tokens written to a cache. Disjoint from `inputTokens`. */\n cacheWriteTokens?: number;\n /**\n * What the provider said this generation cost, in US dollars. Reported,\n * never derived: no adapter computes this from a rate, and one whose wire\n * does not carry a cost leaves it absent rather than estimating.\n */\n costUsd?: number;\n}\n\n/**\n * Who sent an arrival: what sort of sender, and which one.\n *\n * aglib mints exactly one kind — `\"session\"`, a delivery from another session —\n * and interprets no other. Every other kind is the application's word for one of\n * its own senders: a person, a channel, a schedule, a webhook. The vocabulary\n * belongs to whoever can close it, and that is never this package.\n *\n * Two fields because absence was carrying four facts. This used to be the\n * sending session's id alone, so an operator, a channel and a timer all said the\n * same thing by saying nothing, and a recipient could not tell a person typing\n * from a routine firing. Packing both into one string instead — `\"routine:x\"` —\n * would put the vocabulary in a convention nothing closes, which is how such a\n * field ends up with values that exist only by grep and a different reading on\n * every surface that renders it.\n */\nexport interface From {\n kind: string;\n id: string;\n}\n\n/**\n * The canonical vocabulary. This is the session's state, not a record of it:\n * the loop reads its context by projecting these and appends back to them, so\n * there is no second transcript that could disagree.\n *\n * `tool.started` carries only the call id — the assistant entry above it\n * already holds the call, and duplicating name and arguments would be a second\n * field for a value another field determines.\n */\nexport type Entry =\n | { type: \"hook.input\"; runId: string; hook: string; input: Content }\n | { type: \"run.started\"; runId: string; input: Content; from?: From }\n | {\n type: \"assistant\"; runId: string; content: Content;\n calls?: readonly ToolCall[]; usage?: Usage; providerState?: ProviderState;\n /**\n * What produced this turn, when a model did: which model answered and the\n * span it took. `Stored.at` is when the entry was committed, which is a\n * different fact and not a substitute — anything projecting a generation\n * needs both ends of the call, and the commit is neither of them.\n */\n generation?: { model?: string; startedAt: string; endedAt: string };\n }\n | { type: \"tool.started\"; runId: string; callId: string }\n | { type: \"tool.finished\"; runId: string; callId: string; result: ToolResult }\n /** Compaction output. `replaces` is the seq up to which entries are folded; nothing is deleted. */\n | { type: \"summary\"; runId: string; content: string; replaces: number }\n | { type: \"run.finished\"; runId: string; outcome: \"completed\" | \"failed\" | \"cancelled\"; error?: Failure };\n\nexport type EntryType = Entry[\"type\"];\n\n/** An entry once the log has given it a position. */\nexport type Stored<T extends Entry = Entry> = T & { seq: number; at: string };\n\n/**\n * Input delivered to a session, committed with the sender's own entries.\n * Spawning a child, replying to a parent and messaging a peer are all this.\n */\nexport interface Delivery {\n /** The session it is delivered to. */\n sessionId: string;\n input: Content;\n /**\n * Who sent it. Absent means the application did not say — not that nobody\n * did. Recorded on the receiving `run.started`, so an application can tell a\n * peer's message from its user's, and can see that it already answered one\n * that arrives twice. It becomes text the model reads only where the\n * recipient's agent asks, with `attribution`.\n */\n from?: From;\n /**\n * Where in the recipient's loop this lands. Defaults to \"next\".\n *\n * Three places, and each is an outcome a sender can reason about rather than\n * a level of urgency a harness interprets:\n *\n * \"interrupt\" — the running activation ends, so the next one begins with\n * this. Its uncommitted work is lost; everything it had\n * already committed stays.\n * \"turn\" — folded into the activation already running, before its next\n * model call. Nothing in flight is lost. Immediately, if\n * nothing is running.\n * \"next\" — at the start of the recipient's next activation.\n *\n * This used to be `now | next | later`, and `now` meant either of the first\n * two depending on the harness — fold if it had a safe point, end the\n * activation if it did not. One word for \"your message arrives and the work\n * continues\" and \"your message arrives and a turn's work is destroyed\". The\n * doctrine was that a priority names the requirement and not the mechanism,\n * but those are not two mechanisms for one requirement: they are two\n * different things happening to somebody's work, and a runtime answer saying\n * which one you got was invented to paper over it. `later` named a fourth\n * thing that nothing implemented.\n *\n * **A harness that cannot honour one falls back to a later place, never an\n * earlier one.** A loop with no safe point cannot do \"turn\", so it does\n * \"next\" — the message waits. It does not end the activation instead, which\n * is what falling back through an ordered scale used to do: ask for the\n * gentlest useful thing and get the most destructive one.\n */\n priority?: \"interrupt\" | \"turn\" | \"next\";\n /**\n * The sender's key for this delivery. Two deliveries with the same id are the\n * same delivery, so a retried send does not arrive twice.\n */\n id?: string;\n}\n"]}
|
package/dist/session/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export type { Delivery, Entry, EntryType, From, Stored, ToolCall, ToolResult, Usage } from "./entry.js";
|
|
1
|
+
export type { Delivery, Entry, EntryType, From, ProviderState, Stored, ToolCall, ToolResult, Usage } from "./entry.js";
|
|
2
2
|
export type { Message } from "./messages.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/session/index.ts"],"names":[],"mappings":"","sourcesContent":["export type { Delivery, Entry, EntryType, From, Stored, ToolCall, ToolResult, Usage } from \"./entry.js\";\nexport type { Message } from \"./messages.js\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/session/index.ts"],"names":[],"mappings":"","sourcesContent":["export type { Delivery, Entry, EntryType, From, ProviderState, Stored, ToolCall, ToolResult, Usage } from \"./entry.js\";\nexport type { Message } from \"./messages.js\";\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Content } from "../content.js";
|
|
2
|
-
import type { Stored, ToolCall } from "./entry.js";
|
|
2
|
+
import type { ProviderState, Stored, ToolCall } from "./entry.js";
|
|
3
3
|
/** A message as a provider takes it: built per turn from the log, never held. */
|
|
4
4
|
export type Message = {
|
|
5
5
|
role: "system";
|
|
@@ -11,6 +11,7 @@ export type Message = {
|
|
|
11
11
|
role: "assistant";
|
|
12
12
|
content: Content;
|
|
13
13
|
calls?: readonly ToolCall[];
|
|
14
|
+
providerState?: ProviderState;
|
|
14
15
|
} | {
|
|
15
16
|
role: "tool";
|
|
16
17
|
callId: string;
|
package/dist/session/messages.js
CHANGED
|
@@ -64,6 +64,7 @@ export function toMessages(input) {
|
|
|
64
64
|
role: "assistant",
|
|
65
65
|
content: entry.content,
|
|
66
66
|
...(entry.calls?.length ? { calls: entry.calls } : {}),
|
|
67
|
+
...(entry.providerState ? { providerState: entry.providerState } : {}),
|
|
67
68
|
});
|
|
68
69
|
for (const call of entry.calls ?? []) {
|
|
69
70
|
if (answered.has(call.callId))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/session/messages.ts"],"names":[],"mappings":"AAUA;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAAC,O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CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBACnD,CAAC,CAAC;gBACH,MAAM;YACR,uEAAuE;YACvE,YAAY;YACZ,KAAK,cAAc,CAAC;YACpB,KAAK,cAAc;gBACjB,MAAM;QACV,CAAC;IACH,CAAC;IAED,6EAA6E;IAC7E,oEAAoE;IACpE,IAAI,KAAK,CAAC,OAAO,EAAE,IAAI;QAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IACxF,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import type { Content } from \"../content.js\";\nimport type { From, ProviderState, Stored, ToolCall } from \"./entry.js\";\n\n/** A message as a provider takes it: built per turn from the log, never held. */\nexport type Message =\n | { role: \"system\"; content: Content }\n | { role: \"user\"; content: Content }\n | { role: \"assistant\"; content: Content; calls?: readonly ToolCall[]; providerState?: ProviderState }\n | { role: \"tool\"; callId: string; content: Content; isError?: boolean };\n\n/**\n * The position everything up to has been folded into a summary.\n *\n * One answer, because two callers need it: the projection skips what is folded,\n * and the loop refuses to cut at or behind it. They were the same reduce written\n * out twice.\n */\nexport function foldedThrough(entries: readonly Stored[]): number {\n return entries.reduce((at, entry) => entry.type === \"summary\" ? Math.max(at, entry.replaces) : at, 0);\n}\n\n/** Names the sender in the turn itself, since only text reaches the model. */\nfunction labelled(input: Content, from: From | undefined): Content {\n if (!from) return input;\n const label = `[from ${from.kind} ${from.id}]`;\n return typeof input === \"string\"\n ? `${label}\\n${input}`\n : [{ type: \"text\" as const, text: label }, ...input];\n}\n\n/**\n * The log projected into what a provider takes.\n *\n * Built fresh for every request and never held. That is the whole reason there\n * is no second transcript to drift from the log, and why nothing needs a test\n * proving two representations agree.\n */\nexport function toMessages(input: {\n instructions: Content;\n entries: readonly Stored[];\n context?: { run?: string; turn?: string };\n /**\n * Name each arrival's sender in the turn text, as `[from kind id]`.\n *\n * Off by default. `from` is provenance the log keeps whatever this says; an\n * application that renders its own attribution into the input it delivers\n * would otherwise hand the model two names for one sender, one of them a\n * session id that means nothing to it.\n */\n attribution?: boolean;\n}): readonly Message[] {\n const messages: Message[] = [{ role: \"system\", content: input.instructions }];\n\n // Run-scoped context sits immediately after the instructions, inside the\n // cacheable prefix, because it does not change for the life of the run.\n if (input.context?.run) messages.push({ role: \"system\", content: input.context.run });\n\n // A summary folds everything up to `replaces`. The source entries stay in the\n // log — compaction changes what the model sees, never what happened.\n const cut = foldedThrough(input.entries);\n const summary = input.entries.findLast((entry) => entry.type === \"summary\" && entry.replaces === cut);\n if (summary?.type === \"summary\") {\n messages.push({ role: \"user\", content: `<summary>\\n${summary.content}\\n</summary>` });\n }\n\n // A call whose result never committed. It happens when an activation ends\n // between asking and answering — cancelled, interrupted, or beaten to the\n // commit by another worker. The projection has to close it: a provider\n // rejects an assistant turn holding a call with no result, so leaving the gap\n // would make the session permanently unusable. What is said is what is known\n // — the call did not report back — and never an invented result.\n const answered = new Set(\n input.entries.filter((entry) => entry.type === \"tool.finished\").map((entry) => entry.callId),\n );\n\n for (const entry of input.entries) {\n // The checkpoint describes the replaced prefix, not the moment it was\n // written. Newer instructions must follow it, including after another fold.\n if (entry.seq <= cut || entry.type === \"summary\") continue;\n switch (entry.type) {\n case \"hook.input\":\n messages.push({ role: \"user\", content: entry.input });\n break;\n case \"run.started\":\n messages.push({\n role: \"user\",\n content: input.attribution ? labelled(entry.input, entry.from) : entry.input,\n });\n break;\n case \"assistant\": {\n messages.push({\n role: \"assistant\",\n content: entry.content,\n ...(entry.calls?.length ? { calls: entry.calls } : {}),\n ...(entry.providerState ? { providerState: entry.providerState } : {}),\n });\n for (const call of entry.calls ?? []) {\n if (answered.has(call.callId)) continue;\n messages.push({\n role: \"tool\", callId: call.callId, isError: true,\n content: \"This call did not report back: the activation ended before its result was committed.\",\n });\n }\n break;\n }\n case \"tool.finished\":\n messages.push({\n role: \"tool\",\n callId: entry.callId,\n content: entry.result.content,\n ...(entry.result.isError ? { isError: true } : {}),\n });\n break;\n // Not model-visible: tool.started is bookkeeping and run.finished is a\n // boundary.\n case \"tool.started\":\n case \"run.finished\":\n break;\n }\n }\n\n // Turn-scoped context sits last, after the cache boundary, because it is for\n // this request only and must not be written into the cached prefix.\n if (input.context?.turn) messages.push({ role: \"system\", content: input.context.turn });\n return messages;\n}\n"]}
|
|
@@ -107,6 +107,7 @@ export function defineStoreConformance(subject) {
|
|
|
107
107
|
content: [{ type: "text", text: "here" }, { type: "opaque", provider: "acme", data: { keep: [1, null, "x"] } }],
|
|
108
108
|
calls: [{ callId: "c1", name: "look", arguments: "{\"at\":1}" }],
|
|
109
109
|
usage: { inputTokens: 10, outputTokens: 2 },
|
|
110
|
+
providerState: { provider: "acme-wire", items: [{ signature: "sig-9" }, "opaque"] },
|
|
110
111
|
generation: { model: "m", startedAt: "2026-01-01T00:00:00.000Z", endedAt: "2026-01-01T00:00:01.000Z" },
|
|
111
112
|
};
|
|
112
113
|
got(await store.append({ sessionId: id("s"), expectedSeq: 0, entries: [rich] }), "append");
|