@a-dray/aglib 0.1.0 → 0.2.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.
- package/README.md +55 -136
- package/dist/agent.d.ts +12 -0
- package/dist/agent.js.map +1 -1
- package/dist/harness/adapters/acp/index.d.ts +27 -11
- package/dist/harness/adapters/acp/index.js +58 -24
- package/dist/harness/adapters/acp/index.js.map +1 -1
- package/dist/harness/adapters/native/compaction.d.ts +15 -0
- package/dist/harness/adapters/native/compaction.js +23 -8
- package/dist/harness/adapters/native/compaction.js.map +1 -1
- package/dist/harness/adapters/native/loop.d.ts +18 -1
- package/dist/harness/adapters/native/loop.js +0 -1
- package/dist/harness/adapters/native/loop.js.map +1 -1
- package/dist/harness/harness.d.ts +17 -6
- package/dist/harness/harness.js.map +1 -1
- package/dist/model/adapters/anthropic/index.js +21 -4
- package/dist/model/adapters/anthropic/index.js.map +1 -1
- package/dist/model/index.d.ts +0 -1
- package/dist/model/index.js +1 -1
- package/dist/model/index.js.map +1 -1
- package/dist/model/model.d.ts +8 -1
- package/dist/model/model.js +8 -1
- package/dist/model/model.js.map +1 -1
- package/dist/render.d.ts +100 -0
- package/dist/render.js +370 -0
- package/dist/render.js.map +1 -0
- package/dist/run.js +1 -0
- package/dist/run.js.map +1 -1
- package/dist/session/entry.d.ts +3 -2
- package/dist/session/entry.js.map +1 -1
- package/dist/session/messages.d.ts +9 -0
- package/dist/session/messages.js +5 -5
- package/dist/session/messages.js.map +1 -1
- package/dist/store/adapters/sqlite.js +25 -2
- package/dist/store/adapters/sqlite.js.map +1 -1
- package/dist/terminal.d.ts +23 -0
- package/dist/terminal.js +90 -0
- package/dist/terminal.js.map +1 -0
- package/dist/tools/execute.js +3 -1
- package/dist/tools/execute.js.map +1 -1
- package/dist/tools/tool.d.ts +8 -1
- package/dist/tools/tool.js.map +1 -1
- package/package.json +10 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":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AAE,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 AnthropicOptions {\n apiKey: string;\n model: string;\n baseUrl?: string;\n version?: string;\n fetch?: typeof fetch;\n}\n\n/**\n * The Anthropic Messages wire.\n *\n * A genuinely different shape from OpenAI's — the leading system prompt hoisted\n * out of the message list, tool results carried as user content blocks, cache\n * breakpoints marked inline — which is the point of it being here: a port\n * proved against one wire format has not been proved.\n *\n * Three things this wire will refuse, and what we send instead:\n *\n * - **Thinking budgets.** `thinking: { type: \"enabled\", budget_tokens }` is\n * removed on the current models and returns 400. Depth is `output_config.effort`\n * over adaptive thinking, so `effort` maps there and nothing computes a budget.\n * - **Sampling controls.** `temperature`, `top_p` and `top_k` are removed on the\n * same models. `ModelRequest.temperature` is therefore dropped here rather\n * than forwarded into a request the provider rejects.\n * - **A system message in the middle of a turn.** Only the *leading* run of\n * system messages becomes the `system` field. One arriving after the\n * conversation has started is turn-scoped context, which the projection\n * deliberately places after the cache boundary, so it stays in `messages` as\n * a mid-conversation system message. Hoisting it would put the one thing that\n * changes every turn at the front of the prefix that must not change.\n * Supported on Opus 5, Opus 4.8 and Fable 5; a model without it fails the\n * request rather than silently having its cache invalidated every turn.\n */\nexport function createAnthropicModel(options: AnthropicOptions): Model {\n const call = options.fetch ?? fetch;\n const baseUrl = options.baseUrl ?? \"https://api.anthropic.com/v1\";\n\n return {\n id: `anthropic:${options.model}`,\n\n async *generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n // Only the leading run of system messages is the system prompt. Anything\n // after it belongs where the projection put it — see the header.\n let lead = 0;\n while (lead < request.messages.length && request.messages[lead]!.role === \"system\") lead += 1;\n const system = request.messages.slice(0, lead).map((message) => textOf(message.content));\n const conversation = request.messages.slice(lead);\n\n // The prefix ends where the caller says it does. In practice that is the\n // end of the system prompt, which is the one span fixed for the whole\n // run; a mark past it is honoured too rather than quietly ignored.\n const boundary = request.cacheAfter;\n const cacheSystem = boundary !== undefined && boundary >= lead && system.length > 0;\n const cacheAt = boundary !== undefined && boundary > lead ? boundary - lead - 1 : -1;\n\n const maxOutputTokens = request.maxOutputTokens ?? 32_000;\n\n let response: Response;\n try {\n response = await call(`${baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-api-key\": options.apiKey,\n \"anthropic-version\": options.version ?? \"2023-06-01\",\n },\n body: JSON.stringify({\n model: options.model,\n max_tokens: maxOutputTokens,\n ...(system.length ? { system: encodeSystem(system, cacheSystem) } : {}),\n messages: encodeConversation(conversation, cacheAt),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.effort\n ? { thinking: { type: \"adaptive\" }, output_config: { effort: request.effort } }\n : {}),\n stream: true,\n }),\n ...(request.signal ? { signal: request.signal } : {}),\n });\n } catch (error) {\n return err(transportError(error, request.signal));\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: ToolCall[] = [];\n let partial = \"\";\n let stop: string | undefined;\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 sseData(response.body)) {\n let frame: AnthropicFrame;\n try { frame = JSON.parse(event) as AnthropicFrame; } catch { continue; }\n\n if (frame.type === \"message_start\" && frame.message) {\n model = frame.message.model;\n usage = { ...usage, ...decodeUsage(frame.message.usage) };\n }\n if (frame.type === \"content_block_start\" && frame.content_block?.type === \"tool_use\") {\n calls.push({ callId: frame.content_block.id!, name: frame.content_block.name!, arguments: \"\" });\n partial = \"\";\n }\n if (frame.type === \"content_block_delta\") {\n const delta = frame.delta!;\n if (delta.type === \"text_delta\" && delta.text) { text.push(delta.text); yield { type: \"text.delta\", text: delta.text }; }\n if (delta.type === \"thinking_delta\" && delta.thinking) yield { type: \"reasoning.delta\", text: delta.thinking };\n if (delta.type === \"input_json_delta\" && delta.partial_json !== undefined) {\n partial += delta.partial_json;\n const current = calls.at(-1);\n if (current) yield { type: \"tool-call.delta\", callId: current.callId, arguments: delta.partial_json };\n }\n }\n if (frame.type === \"content_block_stop\" && calls.length) {\n const current = calls.at(-1)!;\n if (!current.arguments) current.arguments = partial || \"{}\";\n }\n if (frame.type === \"message_delta\") {\n stop = frame.delta?.stop_reason ?? stop;\n usage = { ...usage, ...decodeUsage(frame.usage) };\n }\n if (frame.type === \"error\") {\n return err({ code: \"provider\", message: frame.error?.message ?? \"Provider error\", retryable: true });\n }\n }\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n return ok({\n message: { content: text.join(\"\"), ...(calls.length ? { calls } : {}) },\n finishReason: stop === \"max_tokens\" ? \"length\" : stop === \"refusal\" ? \"refusal\" : calls.length ? \"tool-calls\" : \"stop\",\n usage,\n ...(model ? { model } : {}),\n });\n },\n };\n}\n\n/**\n * Text blocks rather than one joined string, so the end of the prefix can carry\n * a breakpoint. Only the last block is marked: a breakpoint caches everything\n * before it, so marking each one would buy nothing and spend the budget of four.\n */\nfunction encodeSystem(blocks: readonly string[], cache: boolean): unknown[] {\n return blocks.map((text, index) => ({\n type: \"text\",\n text,\n ...(cache && index === blocks.length - 1 ? { cache_control: { type: \"ephemeral\" } } : {}),\n }));\n}\n\n/**\n * Tool results are user-role content blocks here, not a role of their own.\n *\n * `cacheAt` is an index into `messages`; the breakpoint lands on the last\n * content block that message produced. Tool results merge into a preceding user\n * block, so the mapping from message to block is not one to one and the mark is\n * placed as each message is encoded rather than computed afterwards.\n */\nfunction encodeConversation(messages: readonly Message[], cacheAt = -1): unknown[] {\n const out: { role: string; content: unknown[] }[] = [];\n let mark: unknown[] | undefined;\n\n messages.forEach((message, index) => {\n if (message.role === \"tool\") {\n const block = {\n type: \"tool_result\", tool_use_id: message.callId, content: textOf(message.content),\n ...(message.isError ? { is_error: true } : {}),\n };\n const last = out.at(-1);\n if (last?.role === \"user\") last.content.push(block);\n else out.push({ role: \"user\", content: [block] });\n } else if (message.role === \"assistant\") {\n const content: unknown[] = [];\n const spoken = textOf(message.content);\n if (spoken) content.push({ type: \"text\", text: spoken });\n for (const call of message.calls ?? []) {\n content.push({ type: \"tool_use\", id: call.callId, name: call.name, input: safeJson(call.arguments) });\n }\n out.push({ role: \"assistant\", content });\n } else if (message.role === \"system\") {\n // Turn-scoped context, kept where the projection put it: an operator\n // instruction inside the conversation leaves the cached prefix intact,\n // where rewriting the front of it would invalidate every following turn.\n out.push({ role: \"system\", content: encodeContent(message.content) });\n } else {\n out.push({ role: \"user\", content: encodeContent(message.content) });\n }\n if (index === cacheAt) mark = out.at(-1)?.content;\n });\n\n const block = mark?.at(-1) as Record<string, unknown> | undefined;\n if (block) block[\"cache_control\"] = { type: \"ephemeral\" };\n return out;\n}\n\nfunction encodeContent(content: Message[\"content\"]): unknown[] {\n if (typeof content === \"string\") return [{ type: \"text\", text: content }];\n const parts: unknown[] = [];\n for (const part of content as readonly ContentPart[]) {\n if (part.type === \"text\") parts.push({ type: \"text\", text: part.text });\n if (part.type === \"image\") {\n parts.push(part.source.kind === \"url\"\n ? { type: \"image\", source: { type: \"url\", url: part.source.url } }\n : { type: \"image\", source: { type: \"base64\", media_type: part.mediaType, data: part.source.data } });\n }\n }\n return parts;\n}\n\nconst encodeTool = (tool: ToolSpec) => ({\n name: tool.name, description: tool.description, input_schema: tool.parameters,\n});\n\nconst safeJson = (raw: string): unknown => { try { return JSON.parse(raw); } catch { return {}; } };\n\nconst decodeUsage = (usage: AnthropicUsage | undefined): Usage => usage ? {\n ...(usage.input_tokens !== undefined ? { inputTokens: usage.input_tokens } : {}),\n ...(usage.output_tokens !== undefined ? { outputTokens: usage.output_tokens } : {}),\n ...(usage.cache_read_input_tokens !== undefined ? { cacheReadTokens: usage.cache_read_input_tokens } : {}),\n ...(usage.cache_creation_input_tokens !== undefined ? { cacheWriteTokens: usage.cache_creation_input_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 && /prompt is too long|context/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\nasync function* sseData(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 AnthropicUsage {\n input_tokens?: number; output_tokens?: number;\n cache_read_input_tokens?: number; cache_creation_input_tokens?: number;\n}\ninterface AnthropicFrame {\n type: string;\n message?: { model?: string; usage?: AnthropicUsage };\n content_block?: { type: string; id?: string; name?: string };\n delta?: { type?: string; text?: string; thinking?: string; partial_json?: string; stop_reason?: string };\n usage?: AnthropicUsage;\n error?: { message?: string };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/anthropic/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAU7C;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAAyB;IAC5D,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC;IACpC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,8BAA8B,CAAC;IAElE,OAAO;QACL,EAAE,EAAE,aAAa,OAAO,CAAC,KAAK,EAAE;QAEhC,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAqB;YACnC,yEAAyE;YACzE,iEAAiE;YACjE,IAAI,IAAI,GAAG,CAAC,CAAC;YACb,OAAO,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC,MAAM,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAE,CAAC,IAAI,K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ACnC,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 AnthropicOptions {\n apiKey: string;\n model: string;\n baseUrl?: string;\n version?: string;\n fetch?: typeof fetch;\n}\n\n/**\n * The Anthropic Messages wire.\n *\n * A genuinely different shape from OpenAI's — the leading system prompt hoisted\n * out of the message list, tool results carried as user content blocks, cache\n * breakpoints marked inline — which is the point of it being here: a port\n * proved against one wire format has not been proved.\n *\n * Three things this wire will refuse, and what we send instead:\n *\n * - **Thinking budgets.** `thinking: { type: \"enabled\", budget_tokens }` is\n * removed on the current models and returns 400. Depth is `output_config.effort`\n * over adaptive thinking, so `effort` maps there and nothing computes a budget.\n * - **Sampling controls.** `temperature`, `top_p` and `top_k` are removed on the\n * same models. `ModelRequest.temperature` is therefore dropped here rather\n * than forwarded into a request the provider rejects.\n * - **A system message in the middle of a turn.** Only the *leading* run of\n * system messages becomes the `system` field. One arriving after the\n * conversation has started is turn-scoped context, which the projection\n * deliberately places after the cache boundary, so it stays in `messages` as\n * a mid-conversation system message. Hoisting it would put the one thing that\n * changes every turn at the front of the prefix that must not change.\n * Supported on Opus 5, Opus 4.8 and Fable 5; a model without it fails the\n * request rather than silently having its cache invalidated every turn.\n */\nexport function createAnthropicModel(options: AnthropicOptions): Model {\n const call = options.fetch ?? fetch;\n const baseUrl = options.baseUrl ?? \"https://api.anthropic.com/v1\";\n\n return {\n id: `anthropic:${options.model}`,\n\n async *generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n // Only the leading run of system messages is the system prompt. Anything\n // after it belongs where the projection put it — see the header.\n let lead = 0;\n while (lead < request.messages.length && request.messages[lead]!.role === \"system\") lead += 1;\n const system = request.messages.slice(0, lead).map((message) => textOf(message.content));\n const conversation = request.messages.slice(lead);\n\n // The prefix ends where the caller says it does. In practice that is the\n // end of the system prompt, which is the one span fixed for the whole\n // run; a mark past it is honoured too rather than quietly ignored.\n const boundary = request.cacheAfter;\n const cacheSystem = boundary !== undefined && boundary >= lead && system.length > 0;\n const cacheAt = boundary !== undefined && boundary > lead ? boundary - lead - 1 : -1;\n\n const maxOutputTokens = request.maxOutputTokens ?? 32_000;\n\n let response: Response;\n try {\n response = await call(`${baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-api-key\": options.apiKey,\n \"anthropic-version\": options.version ?? \"2023-06-01\",\n },\n body: JSON.stringify({\n model: options.model,\n max_tokens: maxOutputTokens,\n ...(system.length ? { system: encodeSystem(system, cacheSystem) } : {}),\n messages: encodeConversation(conversation, cacheAt),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.effort\n ? { thinking: { type: \"adaptive\" }, output_config: { effort: request.effort } }\n : {}),\n stream: true,\n }),\n ...(request.signal ? { signal: request.signal } : {}),\n });\n } catch (error) {\n return err(transportError(error, request.signal));\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: ToolCall[] = [];\n let partial = \"\";\n let stop: string | undefined;\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 sseData(response.body)) {\n let frame: AnthropicFrame;\n try { frame = JSON.parse(event) as AnthropicFrame; } catch { continue; }\n\n if (frame.type === \"message_start\" && frame.message) {\n model = frame.message.model;\n usage = { ...usage, ...decodeUsage(frame.message.usage) };\n }\n if (frame.type === \"content_block_start\" && frame.content_block?.type === \"tool_use\") {\n calls.push({ callId: frame.content_block.id!, name: frame.content_block.name!, arguments: \"\" });\n partial = \"\";\n }\n if (frame.type === \"content_block_delta\") {\n const delta = frame.delta!;\n if (delta.type === \"text_delta\" && delta.text) { text.push(delta.text); yield { type: \"text.delta\", text: delta.text }; }\n if (delta.type === \"thinking_delta\" && delta.thinking) yield { type: \"reasoning.delta\", text: delta.thinking };\n if (delta.type === \"input_json_delta\" && delta.partial_json !== undefined) {\n partial += delta.partial_json;\n const current = calls.at(-1);\n if (current) yield { type: \"tool-call.delta\", callId: current.callId, arguments: delta.partial_json };\n }\n }\n if (frame.type === \"content_block_stop\" && calls.length) {\n const current = calls.at(-1)!;\n if (!current.arguments) current.arguments = partial || \"{}\";\n }\n if (frame.type === \"message_delta\") {\n stop = frame.delta?.stop_reason ?? stop;\n usage = { ...usage, ...decodeUsage(frame.usage) };\n }\n if (frame.type === \"error\") {\n return err({ code: \"provider\", message: frame.error?.message ?? \"Provider error\", retryable: true });\n }\n }\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n return ok({\n message: { content: text.join(\"\"), ...(calls.length ? { calls } : {}) },\n finishReason: stop === \"max_tokens\" ? \"length\" : stop === \"refusal\" ? \"refusal\" : calls.length ? \"tool-calls\" : \"stop\",\n usage,\n ...(model ? { model } : {}),\n });\n },\n };\n}\n\n/**\n * Text blocks rather than one joined string, so the prefix can carry\n * breakpoints.\n *\n * Two are marked: the **first** block and the **last**. A breakpoint caches\n * everything before it, so the last one is what makes the whole prefix\n * reusable across a conversation's turns — and marking every block between\n * would buy nothing while spending a budget of four.\n *\n * The first earns its own for a different reason. The first block is an agent's\n * standing instructions, which are identical for every conversation it serves;\n * everything after it is composed per conversation and changes with it. With\n * one breakpoint at the end, a new conversation shares nothing: its prefix\n * differs from the last one somewhere in the middle, so the whole of it is\n * written again, instructions included. With one at the head, the instructions\n * are read from cache by every conversation and only what actually differs is\n * paid for — which is the common case for an agent serving many callers at\n * once, and free where there is only one.\n *\n * Skipped when there is a single block: the two marks would be the same one.\n */\nfunction encodeSystem(blocks: readonly string[], cache: boolean): unknown[] {\n const marked = new Set(blocks.length > 1 ? [0, blocks.length - 1] : [blocks.length - 1]);\n return blocks.map((text, index) => ({\n type: \"text\",\n text,\n ...(cache && marked.has(index) ? { cache_control: { type: \"ephemeral\" } } : {}),\n }));\n}\n\n/**\n * Tool results are user-role content blocks here, not a role of their own.\n *\n * `cacheAt` is an index into `messages`; the breakpoint lands on the last\n * content block that message produced. Tool results merge into a preceding user\n * block, so the mapping from message to block is not one to one and the mark is\n * placed as each message is encoded rather than computed afterwards.\n */\nfunction encodeConversation(messages: readonly Message[], cacheAt = -1): unknown[] {\n const out: { role: string; content: unknown[] }[] = [];\n let mark: unknown[] | undefined;\n\n messages.forEach((message, index) => {\n if (message.role === \"tool\") {\n const block = {\n type: \"tool_result\", tool_use_id: message.callId, content: textOf(message.content),\n ...(message.isError ? { is_error: true } : {}),\n };\n const last = out.at(-1);\n if (last?.role === \"user\") last.content.push(block);\n else out.push({ role: \"user\", content: [block] });\n } else if (message.role === \"assistant\") {\n const content: unknown[] = [];\n const spoken = textOf(message.content);\n if (spoken) content.push({ type: \"text\", text: spoken });\n for (const call of message.calls ?? []) {\n content.push({ type: \"tool_use\", id: call.callId, name: call.name, input: safeJson(call.arguments) });\n }\n out.push({ role: \"assistant\", content });\n } else if (message.role === \"system\") {\n // Turn-scoped context, kept where the projection put it: an operator\n // instruction inside the conversation leaves the cached prefix intact,\n // where rewriting the front of it would invalidate every following turn.\n out.push({ role: \"system\", content: encodeContent(message.content) });\n } else {\n out.push({ role: \"user\", content: encodeContent(message.content) });\n }\n if (index === cacheAt) mark = out.at(-1)?.content;\n });\n\n const block = mark?.at(-1) as Record<string, unknown> | undefined;\n if (block) block[\"cache_control\"] = { type: \"ephemeral\" };\n return out;\n}\n\nfunction encodeContent(content: Message[\"content\"]): unknown[] {\n if (typeof content === \"string\") return [{ type: \"text\", text: content }];\n const parts: unknown[] = [];\n for (const part of content as readonly ContentPart[]) {\n if (part.type === \"text\") parts.push({ type: \"text\", text: part.text });\n if (part.type === \"image\") {\n parts.push(part.source.kind === \"url\"\n ? { type: \"image\", source: { type: \"url\", url: part.source.url } }\n : { type: \"image\", source: { type: \"base64\", media_type: part.mediaType, data: part.source.data } });\n }\n }\n return parts;\n}\n\nconst encodeTool = (tool: ToolSpec) => ({\n name: tool.name, description: tool.description, input_schema: tool.parameters,\n});\n\nconst safeJson = (raw: string): unknown => { try { return JSON.parse(raw); } catch { return {}; } };\n\nconst decodeUsage = (usage: AnthropicUsage | undefined): Usage => usage ? {\n ...(usage.input_tokens !== undefined ? { inputTokens: usage.input_tokens } : {}),\n ...(usage.output_tokens !== undefined ? { outputTokens: usage.output_tokens } : {}),\n ...(usage.cache_read_input_tokens !== undefined ? { cacheReadTokens: usage.cache_read_input_tokens } : {}),\n ...(usage.cache_creation_input_tokens !== undefined ? { cacheWriteTokens: usage.cache_creation_input_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 && /prompt is too long|context/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\nasync function* sseData(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 AnthropicUsage {\n input_tokens?: number; output_tokens?: number;\n cache_read_input_tokens?: number; cache_creation_input_tokens?: number;\n}\ninterface AnthropicFrame {\n type: string;\n message?: { model?: string; usage?: AnthropicUsage };\n content_block?: { type: string; id?: string; name?: string };\n delta?: { type?: string; text?: string; thinking?: string; partial_json?: string; stop_reason?: string };\n usage?: AnthropicUsage;\n error?: { message?: string };\n}\n"]}
|
package/dist/model/index.d.ts
CHANGED
package/dist/model/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export {};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/model/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/model/index.ts"],"names":[],"mappings":"
|
|
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"]}
|
package/dist/model/model.d.ts
CHANGED
|
@@ -74,7 +74,14 @@ export interface Model {
|
|
|
74
74
|
readonly id: string;
|
|
75
75
|
generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>>;
|
|
76
76
|
}
|
|
77
|
-
/**
|
|
77
|
+
/**
|
|
78
|
+
* Drains a generation and returns only its outcome.
|
|
79
|
+
*
|
|
80
|
+
* Not on the `aglib/model` subpath. It was, for a recipe that turned a `Model`
|
|
81
|
+
* into an Anthropic response; when that went, nothing outside the package
|
|
82
|
+
* consumed it. `Model`'s own contract above says what a caller who wants the
|
|
83
|
+
* whole response does, and this is the four lines of doing it.
|
|
84
|
+
*/
|
|
78
85
|
export declare function collect(generation: AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>>): Promise<Result<ModelResponse, ModelError>>;
|
|
79
86
|
/**
|
|
80
87
|
* The vocabulary an adapter needs, re-exported from the port it implements.
|
package/dist/model/model.js
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* Drains a generation and returns only its outcome.
|
|
3
|
+
*
|
|
4
|
+
* Not on the `aglib/model` subpath. It was, for a recipe that turned a `Model`
|
|
5
|
+
* into an Anthropic response; when that went, nothing outside the package
|
|
6
|
+
* consumed it. `Model`'s own contract above says what a caller who wants the
|
|
7
|
+
* whole response does, and this is the four lines of doing it.
|
|
8
|
+
*/
|
|
2
9
|
export async function collect(generation) {
|
|
3
10
|
let step = await generation.next();
|
|
4
11
|
while (!step.done)
|
package/dist/model/model.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/model/model.ts"],"names":[],"mappings":"AAyEA
|
|
1
|
+
{"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/model/model.ts"],"names":[],"mappings":"AAyEA;;;;;;;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 { 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}\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, ToolCall, ToolSpec, Usage };\n"]}
|
package/dist/render.d.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A run, as lines someone can read.
|
|
3
|
+
*
|
|
4
|
+
* A root file rather than a module, and a projection rather than a port: this
|
|
5
|
+
* is `textOf` one level out. `toMessages` folds committed entries into what a
|
|
6
|
+
* model is shown; this folds the update stream into what a person is shown. No
|
|
7
|
+
* adapter has to prove anything about it, so there is nothing here for a
|
|
8
|
+
* conformance suite to hold, and nothing below it to rank against.
|
|
9
|
+
*
|
|
10
|
+
* **It is not a channel, and the difference is worth stating because it is
|
|
11
|
+
* subtle.** A channel does three jobs: decide which session a person is talking
|
|
12
|
+
* to, deliver a message exactly once, and put the result in a medium's own
|
|
13
|
+
* shape. The first two are an application's — a mail thread maps to a session,
|
|
14
|
+
* a webhook may arrive twice. Only the third is the same work for every medium,
|
|
15
|
+
* and only the third is here. Email is a channel with no projection at all: it
|
|
16
|
+
* sends `RunResult.output` and never looks at the stream. A terminal is the
|
|
17
|
+
* other extreme — its identity is "the one session" and its delivery is a pipe
|
|
18
|
+
* that cannot fail, so a terminal channel is *nothing but* this projection.
|
|
19
|
+
*
|
|
20
|
+
* **The answer and the stream are different things, and only one is a message.**
|
|
21
|
+
* `RunResult.output` is what `finished` hands to `Delivery.input`: the same
|
|
22
|
+
* `Content`, whether the recipient is a person or another session. The stream
|
|
23
|
+
* is not a message and never becomes one — a `cancelled` or `failed` result has
|
|
24
|
+
* no `output` field at all, so a run can stream a paragraph and produce nothing
|
|
25
|
+
* that could be delivered.
|
|
26
|
+
*
|
|
27
|
+
* Showing that paragraph is not a mistake. Watching what an agent was saying
|
|
28
|
+
* when it was cancelled is most of what debugging one is. What would be a
|
|
29
|
+
* mistake is leaving the outcome implicit, so the text reads as an answer that
|
|
30
|
+
* was never given — which is why `finish` always states it, and takes it from
|
|
31
|
+
* the result rather than from whatever happened to stream.
|
|
32
|
+
*
|
|
33
|
+
* **`detail` is the knob that makes one projection serve every medium.** Three
|
|
34
|
+
* levels, because what the knob is graduated in is the *internal stream* and
|
|
35
|
+
* not the conversation: a tool call is the agent talking to itself, while a
|
|
36
|
+
* message arriving from a subagent, a peer or a person is the conversation
|
|
37
|
+
* happening. The log keeps those apart — one is an entry the loop wrote, the
|
|
38
|
+
* other came through `enqueue` — so the projection does too.
|
|
39
|
+
*
|
|
40
|
+
* There is no level below `"minimal"`, and there was one. A medium with no
|
|
41
|
+
* second channel says so by having no `status`, which drops the account
|
|
42
|
+
* entirely; a `detail` that meant the same thing was a second way to state a
|
|
43
|
+
* fact the `Sink` already stated. Failures are not behind a level either — an
|
|
44
|
+
* agent that silently did nothing is the one outcome a reader cannot diagnose
|
|
45
|
+
* from what they were shown.
|
|
46
|
+
*
|
|
47
|
+
* Two channels out, because they answer different questions. `write` carries
|
|
48
|
+
* the answer, so redirecting it captures the answer and nothing else. `status`
|
|
49
|
+
* carries what the agent did on the way — tools, provenance, what it spent.
|
|
50
|
+
*/
|
|
51
|
+
import type { AgentRun, RunResult } from "./agent.js";
|
|
52
|
+
import type { Update } from "./harness/harness.js";
|
|
53
|
+
import type { ToolCall, Usage } from "./session/entry.js";
|
|
54
|
+
export interface Sink {
|
|
55
|
+
/** The answer: assistant text, exactly as it streamed. */
|
|
56
|
+
write(text: string): void;
|
|
57
|
+
/**
|
|
58
|
+
* Everything else: tools, provenance, what the run spent.
|
|
59
|
+
*
|
|
60
|
+
* Omit it and that account is **dropped**, not folded into `write`. Falling
|
|
61
|
+
* back would break the one promise `write` makes — that it holds the answer
|
|
62
|
+
* and nothing else — for every caller who only wanted the answer and did not
|
|
63
|
+
* think to say so.
|
|
64
|
+
*/
|
|
65
|
+
status?(line: string): void;
|
|
66
|
+
/** Enables colour and the elapsed-time ticker. A caller without a terminal leaves it off. */
|
|
67
|
+
tty?: boolean;
|
|
68
|
+
/**
|
|
69
|
+
* How much of the run to show.
|
|
70
|
+
*
|
|
71
|
+
* `"minimal"` is the conversation: the answer, input that arrived from
|
|
72
|
+
* somewhere else, and anything that failed. `"standard"` adds the internal
|
|
73
|
+
* stream — tool calls, their results, and what the run spent. `"detailed"`
|
|
74
|
+
* adds what it was thinking, arguments as they form, and the structured
|
|
75
|
+
* `details` a tool returned.
|
|
76
|
+
*
|
|
77
|
+
* For the answer and nothing whatever beside it, give a sink with no
|
|
78
|
+
* `status`.
|
|
79
|
+
*/
|
|
80
|
+
detail?: "minimal" | "standard" | "detailed";
|
|
81
|
+
/**
|
|
82
|
+
* Marks a run being watched rather than driven — a subagent taken off the
|
|
83
|
+
* queue, most often. A labelled run has no answer channel: nobody asked it
|
|
84
|
+
* anything, so everything it says is an account of what the run it belongs
|
|
85
|
+
* to is doing, and all of it is prefixed and sent to `status`.
|
|
86
|
+
*/
|
|
87
|
+
label?: string;
|
|
88
|
+
/** Milliseconds, for durations. Supplied by a test so its output is exact. */
|
|
89
|
+
now?(): number;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Render a run to its end, and answer what it did.
|
|
93
|
+
*
|
|
94
|
+
* The loop every application writes by hand, with the two things a hand-written
|
|
95
|
+
* one keeps getting wrong: everything the stream carries besides text, and an
|
|
96
|
+
* outcome taken from the result rather than from whatever happened to stream.
|
|
97
|
+
*/
|
|
98
|
+
export declare function renderRun(run: AgentRun, sink: Sink): Promise<RunResult>;
|
|
99
|
+
/** Re-exported so a caller composing a sink imports one thing. */
|
|
100
|
+
export type { Update, RunResult, Usage, ToolCall };
|