diff --git a/packages/factory/README.md b/packages/factory/README.md index 4f30a0b..67b290c 100644 --- a/packages/factory/README.md +++ b/packages/factory/README.md @@ -131,3 +131,20 @@ organization region and upstream API. Connectivity has been verified with Sonnet 4.6, Sonnet 5.5 and Opus 5.5. Two-turn Read tool calls with Claude Code's default tool set have been verified with Sonnet 4.6 and Sonnet 5.5, including Sonnet 5.5 selected through a routing group. + +## Tool schema compatibility + +Factory's Anthropic route rejects tool schemas with root-level `anyOf`, +`oneOf` or `allOf`. The plugin nests those schemas under an internal +`arguments` property instead of removing their branch constraints. It +wraps examples and previous tool inputs too, then unwraps tool replies +before returning them to OpenCode or magpie. Ordinary object schemas and +OpenAI routes keep their existing behavior. + +Local schema pointers are rebased to the nested schema; `$id` resources +and anchors retain their resolution scope, and literal data is unchanged. +Recursive schema resources +without `$id` fail explicitly because nesting would change their scope. +Affected streaming tool arguments are buffered until their content block +is complete. Other events, tool ids, usage and upstream errors pass through; +an incomplete or invalid argument envelope fails instead of being executed. diff --git a/packages/factory/anthropic-tools.mjs b/packages/factory/anthropic-tools.mjs new file mode 100644 index 0000000..b44168f --- /dev/null +++ b/packages/factory/anthropic-tools.mjs @@ -0,0 +1,181 @@ +// Factory rejects composition keywords at the tool schema's root. Keep the +// original schema under one argument, and hide that wire-only envelope from +// the caller in both replies and the next turn's history. +const argument = "arguments" +const compositions = ["anyOf", "oneOf", "allOf"] +const schemaMaps = ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"] +const schemaLists = ["anyOf", "oneOf", "allOf", "prefixItems"] +const schemaValues = ["additionalProperties", "unevaluatedProperties", "propertyNames", "contains", "items", "additionalItems", "unevaluatedItems", "not", "if", "then", "else", "contentSchema"] +const isObject = (v) => v != null && typeof v === "object" && !Array.isArray(v) + +export function parseToolJSON(text) { + return JSON.parse(text, (_key, value, context) => { + if (typeof value !== "number" || Number.isSafeInteger(value)) return value + if (context?.source && typeof JSON.rawJSON === "function") return JSON.rawJSON(context.source) + // Never round a tool's large integer into a different argument on an old + // runtime that cannot retain JSON number tokens. + if (!Number.isFinite(value) || Number.isInteger(value)) throw new Error("Factory: this runtime cannot preserve the tool's JSON number") + return value + }) +} + +function rebaseSchema(schema, rebase = true, legacy = false) { + if (!isObject(schema)) return + const id = schema.$id ?? (legacy ? schema.id : undefined) + if (typeof id === "string" && id.split("#")[0]) rebase = false + if (rebase) { + // Draft 2019-09's recursive anchor must remain a resource root. Refuse + // this unsupported relocation instead of changing its resolution scope. + if (schema.$recursiveAnchor === true || Object.hasOwn(schema, "$recursiveRef")) throw new Error("Factory: a recursive tool schema needs $id before it can be wrapped") + for (const key of ["$ref", "$dynamicRef"]) { + const ref = schema[key] + if (typeof ref !== "string" || !ref.startsWith("#")) continue + const pointer = decodeURIComponent(ref.slice(1)) + if (pointer === "" || pointer.startsWith("/")) schema[key] = "#/properties/" + argument + ref.slice(1) + } + } + // Visit schema positions only: const/default/examples may contain ordinary + // data named $ref, properties or anyOf and must not be rewritten. + for (const key of schemaMaps) { + if (isObject(schema[key])) for (const child of Object.values(schema[key])) rebaseSchema(child, rebase, legacy) + } + for (const key of schemaLists) { + if (Array.isArray(schema[key])) for (const child of schema[key]) rebaseSchema(child, rebase, legacy) + } + for (const key of schemaValues) { + if (Array.isArray(schema[key])) for (const child of schema[key]) rebaseSchema(child, rebase, legacy) + else rebaseSchema(schema[key], rebase, legacy) + } + if (isObject(schema.dependencies)) for (const child of Object.values(schema.dependencies)) rebaseSchema(child, rebase, legacy) +} + +export function wrapAnthropicTools(body) { + const names = new Set() + const text = typeof body === "string" ? body + : body instanceof ArrayBuffer ? Buffer.from(body).toString("utf8") + : ArrayBuffer.isView(body) ? Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("utf8") : "" + let request + try { request = parseToolJSON(text) } catch (e) { + if (!(e instanceof SyntaxError)) throw e + return { body, names } + } + if (!Array.isArray(request?.tools) || !Array.isArray(request.messages)) return { body, names } + for (const tool of request.tools) { + const schema = tool?.input_schema + if (typeof tool?.name !== "string" || !isObject(schema) || !compositions.some((key) => Object.hasOwn(schema, key))) continue + rebaseSchema(schema, true, /draft-0[34]/.test(schema.$schema ?? "")) + tool.input_schema = { type: "object", properties: { [argument]: schema }, required: [argument], additionalProperties: false } + if (schema.$schema) tool.input_schema.$schema = schema.$schema + if (Array.isArray(tool.input_examples)) tool.input_examples = tool.input_examples.map((input) => ({ [argument]: input })) + names.add(tool.name) + } + if (!names.size) return { body, names } + for (const message of request.messages) { + if (message?.role !== "assistant" || !Array.isArray(message.content)) continue + for (const block of message.content) { + if (block?.type === "tool_use" && names.has(block.name) && Object.hasOwn(block, "input")) block.input = { [argument]: block.input } + } + } + return { body: JSON.stringify(request), names } +} + +function unwrap(input, name) { + if (!isObject(input) || !Object.hasOwn(input, argument) || Object.keys(input).length !== 1) throw new Error(`Factory: tool ${name} returned invalid wrapped arguments`) + return input[argument] +} + +function responseHeaders(res) { + const headers = new Headers(res.headers) + headers.delete("content-length") + headers.delete("content-encoding") + return { status: res.status, statusText: res.statusText, headers } +} + +function toolStream(body, names) { + const reader = body.getReader() + const decoder = new TextDecoder("utf-8", { fatal: true }) + const encoder = new TextEncoder() + const blocks = new Map() + let pending = "", ended = false + const incomplete = () => { + if (blocks.size) throw new Error("Factory: incomplete wrapped tool arguments") + } + const frame = (raw, ending) => { + const lines = raw.split(/\r\n|\n|\r/) + const data = lines.filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join("\n") + if (!data) return [raw + ending] + if (data === "[DONE]") { incomplete(); return [raw + ending] } + const event = parseToolJSON(data) + const replace = (value) => { + let first = true + const next = [] + for (const line of lines) { + if (!line.startsWith("data:")) next.push(line) + else if (first) { next.push("data: " + JSON.stringify(value)); first = false } + } + return next.join(raw.includes("\r\n") ? "\r\n" : "\n") + ending + } + if (event.type === "content_block_start" && event.content_block?.type === "tool_use" && names.has(event.content_block.name)) { + if (blocks.has(event.index)) throw new Error("Factory: duplicate wrapped tool block") + blocks.set(event.index, { name: event.content_block.name, json: "", initial: event.content_block.input }) + event.content_block.input = {} + return [replace(event)] + } + const block = blocks.get(event.index) + if (block && event.type === "content_block_delta" && event.delta?.type === "input_json_delta") { + if (typeof event.delta.partial_json !== "string") throw new Error("Factory: invalid tool argument delta") + block.json += event.delta.partial_json + return [] + } + if (block && event.type === "content_block_stop") { + const input = unwrap(block.json ? parseToolJSON(block.json) : block.initial, block.name) + blocks.delete(event.index) + const delta = { type: "content_block_delta", index: event.index, delta: { type: "input_json_delta", partial_json: JSON.stringify(input) } } + return ["event: content_block_delta\ndata: " + JSON.stringify(delta) + "\n\n", raw + ending] + } + if (event.type === "error") blocks.clear() // preserve the upstream error + if (event.type === "message_stop") incomplete() + return [raw + ending] + } + return new ReadableStream({ + async pull(controller) { + try { + while (true) { + const boundary = /\r\n\r\n|\r\n\n|\n\r\n|\n\n|\r\r/.exec(pending) + if (boundary || (ended && pending)) { + const raw = boundary ? pending.slice(0, boundary.index) : pending + const ending = boundary?.[0] ?? "" + pending = boundary ? pending.slice(boundary.index + ending.length) : "" + const out = frame(raw, ending) + for (const value of out) controller.enqueue(encoder.encode(value)) + if (out.length) return + continue + } + if (ended) { incomplete(); controller.close(); return } + const chunk = await reader.read() + pending += decoder.decode(chunk.value, { stream: !chunk.done }) + ended = chunk.done + } + } catch (e) { + controller.error(e) + await reader.cancel(e).catch(() => {}) + } + }, + cancel(reason) { return reader.cancel(reason) }, + }) +} + +export async function unwrapAnthropicTools(res, names) { + if (!names.size || !res.ok || !res.body) return res + if ((res.headers.get("content-type") ?? "").includes("text/event-stream")) return new Response(toolStream(res.body, names), responseHeaders(res)) + if (!(res.headers.get("content-type") ?? "").includes("json")) return res + const text = await res.text() + const message = parseToolJSON(text) + let changed = false + for (const block of Array.isArray(message?.content) ? message.content : []) { + if (block?.type !== "tool_use" || !names.has(block.name)) continue + block.input = unwrap(block.input, block.name) + changed = true + } + return new Response(changed ? JSON.stringify(message) : text, responseHeaders(res)) +} diff --git a/packages/factory/index.mjs b/packages/factory/index.mjs index 1299d64..2d26c9e 100644 --- a/packages/factory/index.mjs +++ b/packages/factory/index.mjs @@ -4,6 +4,7 @@ // built-in Factory account (internal/provider/factory*.go). import { STATUS_CODES } from "node:http" +import { parseToolJSON, wrapAnthropicTools, unwrapAnthropicTools } from "./anthropic-tools.mjs" const PROVIDER = "factory" @@ -676,7 +677,7 @@ function anthropicBody(body) { const text = typeof body === "string" ? body : body instanceof ArrayBuffer ? Buffer.from(body).toString("utf8") : ArrayBuffer.isView(body) ? Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("utf8") : "" - request = JSON.parse(text) + request = parseToolJSON(text) } catch { return body } @@ -1095,10 +1096,12 @@ export const FactoryAuthPlugin = async ({ client }) => { // which Anthropic's SDK sends beside the bearer token if (path.includes("/llm/a/")) h.set("X-Api-Key", "placeholder") // another agent's request opens as droid's does (droidBody) - const out = path.includes("/llm/a/") && (path.endsWith("/messages") || path.endsWith("/messages/count_tokens")) - ? anthropicBody(body) : droidBody(path, body) + const anthropic = path.includes("/llm/a/") && (path.endsWith("/messages") || path.endsWith("/messages/count_tokens")) + const adapted = anthropic ? wrapAnthropicTools(anthropicBody(body)) : { body: droidBody(path, body), names: new Set() } + const out = adapted.body if (out !== body) h.delete("content-length") - return fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body: out }) + const res = await fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body: out }) + return path.endsWith("/messages") ? unwrapAnthropicTools(res, adapted.names) : res } return { diff --git a/packages/factory/package.json b/packages/factory/package.json index 21e1f80..e7ca628 100644 --- a/packages/factory/package.json +++ b/packages/factory/package.json @@ -4,7 +4,7 @@ "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie", "type": "module", "main": "./index.mjs", - "files": ["index.mjs", "README.md"], + "files": ["index.mjs", "anthropic-tools.mjs", "README.md"], "keywords": ["opencode", "opencode-plugin", "magpie", "factory", "droid"], "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/factory" } diff --git a/packages/factory/schema.test.mjs b/packages/factory/schema.test.mjs new file mode 100644 index 0000000..3dd5ede --- /dev/null +++ b/packages/factory/schema.test.mjs @@ -0,0 +1,256 @@ +import { afterEach, expect, test } from "bun:test" +import { FactoryAuthPlugin, _internal } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) +const url = "https://api.factory.ai/api/llm/a/v1/messages" +const object = { type: "object", properties: { mode: { const: "view" }, id: { type: "string" } }, required: ["mode", "id"], additionalProperties: false } +const input = { mode: "view", id: "task_1" } +const request = (schema, extra = {}) => ({ + model: "claude-opus-5-5", max_tokens: 64, system: [{ type: "text", text: _internal.DROID_LINE }], + messages: [{ role: "user", content: "Use the task tool." }], + tools: [{ name: "task", input_schema: schema }], ...extra, +}) + +async function loaded(serve) { + const seen = [] + globalThis.fetch = async (url, init) => { + seen.push({ url: String(url), ...init }) + return serve(JSON.parse(init.body), init) + } + const hooks = await FactoryAuthPlugin({ client: { auth: { set: async () => { throw new Error("unexpected auth write") } } } }) + const auth = { type: "oauth", access: "test-token", expires: Date.now() + 3_600_000, activeOrganizationId: "test-org" } + return { l: await hooks.auth.loader(async () => auth), seen } +} + +for (const keyword of ["anyOf", "oneOf", "allOf"]) { + test(`Factory accepts ${keyword} tools and the caller receives the original arguments`, async () => { + const create = { type: "object", properties: { mode: { const: "create" }, name: { type: "string" } }, required: ["mode", "name"], additionalProperties: false } + const schema = { [keyword]: keyword === "allOf" ? [object, { properties: { id: { pattern: "^task_" } } }] : [object, create] } + const { l, seen } = await loaded((body) => { + if (body.tools.some((t) => ["anyOf", "oneOf", "allOf"].some((k) => Object.hasOwn(t.input_schema, k)))) { + return Response.json({ type: "error", error: { type: "invalid_request_error", message: "tools.0.custom.input_schema: input_schema does not support oneOf, allOf, or anyOf at the top level" } }, { status: 400 }) + } + return Response.json({ id: "msg_1", type: "message", content: [{ type: "tool_use", id: "call_1", name: "task", input: { arguments: input } }], stop_reason: "tool_use", usage: { input_tokens: 7, output_tokens: 5 } }) + }) + const res = await l.fetch(url, { method: "POST", body: JSON.stringify(request(schema)) }) + expect(res.status).toBe(200) + expect(JSON.parse(seen[0].body).tools[0].input_schema).toEqual({ type: "object", properties: { arguments: schema }, required: ["arguments"], additionalProperties: false }) + const answer = await res.json() + expect(answer.content[0]).toEqual({ type: "tool_use", id: "call_1", name: "task", input }) + expect(answer.usage).toEqual({ input_tokens: 7, output_tokens: 5 }) + }) +} + +test("wraps previous tool inputs and examples, preserving ordinary tools and count_tokens replies", async () => { + const schema = { anyOf: [object] } + const ordinary = { name: "read", input_schema: { type: "object", properties: { path: { anyOf: [{ type: "string" }, { type: "null" }] } } } } + const body = request(schema, { + tools: [{ name: "task", input_schema: schema, input_examples: [input], cache_control: { type: "ephemeral" } }, ordinary], + messages: [{ role: "assistant", content: [{ type: "tool_use", id: "call_1", name: "task", input }, { type: "tool_use", id: "call_2", name: "read", input: { path: null } }] }, { role: "user", content: [{ type: "tool_result", tool_use_id: "call_1", content: "done" }] }], + }) + const { l, seen } = await loaded(() => Response.json({ input_tokens: 42 })) + const res = await l.fetch(url + "/count_tokens", { method: "POST", body: JSON.stringify(body) }) + const sent = JSON.parse(seen[0].body) + expect(sent.messages[0].content[0].input).toEqual({ arguments: input }) + expect(sent.messages[0].content[1]).toEqual(body.messages[0].content[1]) + expect(sent.messages[1]).toEqual(body.messages[1]) + expect(sent.tools[0].input_examples).toEqual([{ arguments: input }]) + expect(sent.tools[0].cache_control).toEqual(body.tools[0].cache_control) + expect(sent.tools[1]).toEqual(ordinary) + expect(await res.json()).toEqual({ input_tokens: 42 }) +}) + +test("rebases document pointers, respecting resource ids, anchors and literal data", async () => { + const schema = { + $schema: "https://json-schema.org/draft/2020-12/schema", type: "object", + anyOf: [{ $ref: "#/$defs/view" }, { $ref: "#%2F$defs%2Fview" }, { $ref: "#anchor" }, { $ref: "https://example.test/other.json" }], + $defs: { + view: { ...object, $anchor: "anchor", properties: { ...object.properties, nested: { $ref: "#" } } }, + resource: { $id: "child.json", $defs: { value: { type: "string" } }, anyOf: [{ $ref: "#/$defs/value" }] }, + }, + properties: { literal: { const: { $ref: "#/$defs/untouched", anyOf: [{ $ref: "literal" }] }, default: { $ref: "default" }, examples: [{ $ref: "example" }] } }, + } + const { l, seen } = await loaded(() => Response.json({ content: [] })) + await l.fetch(url, { method: "POST", body: JSON.stringify(request(schema)) }) + const wrapped = JSON.parse(seen[0].body).tools[0].input_schema + const original = wrapped.properties.arguments + expect(wrapped.$schema).toBe(schema.$schema) + expect(original.anyOf).toEqual([{ $ref: "#/properties/arguments/$defs/view" }, { $ref: "#/properties/arguments%2F$defs%2Fview" }, schema.anyOf[2], schema.anyOf[3]]) + expect(original.$defs.view.properties.nested.$ref).toBe("#/properties/arguments") + expect(original.$defs.resource).toEqual(schema.$defs.resource) + expect(original.properties.literal).toEqual(schema.properties.literal) + expect(schema.anyOf[0].$ref).toBe("#/$defs/view") +}) + +test("keeps a root $id resource and its references intact", async () => { + const schema = { $id: "https://example.test/tool.json", $defs: { view: object }, oneOf: [{ $ref: "#/$defs/view" }] } + const { l, seen } = await loaded(() => Response.json({ content: [] })) + await l.fetch(url, { method: "POST", body: JSON.stringify(request(schema)) }) + expect(JSON.parse(seen[0].body).tools[0].input_schema.properties.arguments).toEqual(schema) +}) + +test("does not silently relocate a recursive resource without $id", async () => { + const { l, seen } = await loaded(() => Response.json({ content: [] })) + const schema = { anyOf: [{ $recursiveRef: "#" }], $recursiveAnchor: true } + await expect(l.fetch(url, { method: "POST", body: JSON.stringify(request(schema)) })).rejects.toThrow("recursive tool schema needs $id") + expect(seen).toHaveLength(0) +}) + +test("ordinary tools, nested compositions and OpenAI routes retain their original bytes", async () => { + const response = '{ "content": [{"type":"tool_use","name":"task","input":{"arguments":"a real caller field"}}] }' + const { l, seen } = await loaded(() => new Response(response, { headers: { "content-type": "application/json" } })) + const body = JSON.stringify(request({ type: "object", properties: { value: { anyOf: [{ type: "string" }, { type: "null" }] } } })) + const res = await l.fetch(url, { method: "POST", body }) + expect(seen[0].body).toBe(body) + expect(await res.text()).toBe(response) + const openai = JSON.stringify({ model: "gpt-6-sol", instructions: _internal.DROID_LINE, input: "OK", tools: [{ type: "function", name: "task", parameters: { anyOf: [object] } }] }) + const other = await l.fetch("https://api.factory.ai/api/llm/o/v1/responses", { method: "POST", body: openai }) + expect(seen[1].body).toBe(openai) + expect(await other.text()).toBe(response) +}) + +test("drops stale lengths after changing a request or reply, preserving response metadata", async () => { + const reply = JSON.stringify({ content: [{ type: "tool_use", name: "task", id: "call_1", input: { arguments: input } }], usage: { output_tokens: 42 } }) + const { l, seen } = await loaded(() => new Response(reply, { headers: { "content-type": "application/json", "content-length": String(reply.length), "content-encoding": "identity", "x-request-id": "request_1" } })) + const res = await l.fetch(url, { method: "POST", headers: { "content-length": "1" }, body: JSON.stringify(request({ type: "object", anyOf: [object] })) }) + expect(seen[0].headers.get("content-length")).toBeNull() + expect(res.headers.get("content-length")).toBeNull() + expect(res.headers.get("content-encoding")).toBeNull() + expect(res.headers.get("x-request-id")).toBe("request_1") + expect(res.headers.get("x-magpie-sign-in")).toBe("kept") + expect((await res.json()).content[0].input).toEqual(input) +}) + +for (const input of [{ wrong: {} }, { arguments: {}, extra: true }]) { + test("invalid argument envelopes fail instead of reaching the caller", async () => { + const { l } = await loaded(() => Response.json({ content: [{ type: "tool_use", name: "task", input }] })) + await expect(l.fetch(url, { method: "POST", body: JSON.stringify(request({ anyOf: [object] })) })).rejects.toThrow("invalid wrapped arguments") + }) +} + +test("upstream errors pass through without attempting to unwrap them", async () => { + const error = '{"type":"error","error":{"type":"overloaded_error","message":"try later"}}' + const { l } = await loaded(() => new Response(error, { status: 529, headers: { "content-type": "application/json", "retry-after": "5" } })) + const res = await l.fetch(url, { method: "POST", body: JSON.stringify(request({ anyOf: [object] })) }) + expect(res.status).toBe(529) + expect(res.headers.get("retry-after")).toBe("5") + expect(await res.text()).toBe(error) +}) + +const event = (type, data, eol = "\n") => `event: ${type}${eol}data: ${JSON.stringify({ type, ...data })}${eol}${eol}` +function bytes(text, size = 1, cancel) { + const data = new TextEncoder().encode(text) + let offset = 0 + return new ReadableStream({ + pull(c) { + if (offset >= data.length) c.close() + else { c.enqueue(data.slice(offset, offset + size)); offset += size } + }, cancel, + }) +} +function events(text) { + return text.split(/\r\n\r\n|\n\n|\r\r/).flatMap((frame) => { + const data = frame.split(/\r\n|\n|\r/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n") + return data && data !== "[DONE]" ? [JSON.parse(data)] : [] + }) +} + +for (const eol of ["\n", "\r\n"]) { + test(`streaming tools survive ${JSON.stringify(eol)} frames, split UTF-8 and interleaved blocks`, async () => { + const wrapped = JSON.stringify({ arguments: { ...input, text: '汉字 😀 "arguments" { braces }' } }) + const ordinary = JSON.stringify({ arguments: "a caller-owned field" }) + let stream = ": keep-alive" + eol + eol + + event("message_start", { message: { id: "msg_1", usage: { input_tokens: 7 } } }, eol) + + event("content_block_start", { index: 0, content_block: { type: "text", text: "" } }, eol) + + event("content_block_delta", { index: 0, delta: { type: "text_delta", text: "先调用" } }, eol) + + "id: event_1" + eol + "retry: 1000" + eol + + event("content_block_start", { index: 1, content_block: { type: "tool_use", id: "call_1", name: "task", input: {} } }, eol) + + event("content_block_start", { index: 2, content_block: { type: "tool_use", id: "call_2", name: "read", input: {} } }, eol) + for (let i = 0; i < wrapped.length; i += 3) stream += event("content_block_delta", { index: 1, delta: { type: "input_json_delta", partial_json: wrapped.slice(i, i + 3) } }, eol) + stream += event("ping", {}, eol) + + event("content_block_delta", { index: 2, delta: { type: "input_json_delta", partial_json: ordinary } }, eol) + + event("content_block_stop", { index: 2 }, eol) + + event("content_block_stop", { index: 1 }, eol) + + event("content_block_stop", { index: 0 }, eol) + + event("message_delta", { delta: { stop_reason: "tool_use" }, usage: { output_tokens: 9 } }, eol) + + event("message_stop", {}, eol) + const { l } = await loaded(() => new Response(bytes(stream), { headers: { "content-type": "text/event-stream", "content-length": "1" } })) + const tools = [{ name: "task", input_schema: { anyOf: [object] } }, { name: "read", input_schema: { type: "object" } }] + const res = await l.fetch(url, { method: "POST", body: JSON.stringify(request({}, { tools, stream: true })) }) + const text = await res.text(), out = events(text) + expect(text).toContain(": keep-alive") + expect(text).toContain("id: event_1") + expect(text).toContain("retry: 1000") + expect(res.headers.get("content-length")).toBeNull() + const argumentsFor = (index) => out.filter((e) => e.type === "content_block_delta" && e.index === index && e.delta.type === "input_json_delta").map((e) => e.delta.partial_json).join("") + expect(JSON.parse(argumentsFor(1))).toEqual({ ...input, text: '汉字 😀 "arguments" { braces }' }) + expect(argumentsFor(2)).toBe(ordinary) + expect(out.filter((e) => e.type === "content_block_start").map((e) => e.content_block.id).filter(Boolean)).toEqual(["call_1", "call_2"]) + expect(out.find((e) => e.type === "message_delta").usage).toEqual({ output_tokens: 9 }) + expect(out.at(-1).type).toBe("message_stop") + }) +} + +test("preserves large integer arguments in JSON, history and streaming replies", async () => { + const number = "900719925474099312345" + const input = '{"number":' + number + '}' + const reply = '{"content":[{"type":"tool_use","name":"task","input":{"arguments":' + input + '}}]}' + const { l, seen } = await loaded(() => new Response(reply, { headers: { "content-type": "application/json" } })) + const body = JSON.stringify(request({ anyOf: [{ type: "object" }] }, { messages: [{ role: "assistant", content: [{ type: "tool_use", name: "task", id: "call_1", input: "RAW_INPUT" }] }, { role: "user", content: "continue" }] })).replace('"RAW_INPUT"', input) + const res = await l.fetch(url, { method: "POST", body }) + expect(seen[0].body).toContain('"arguments":' + input) + expect(await res.text()).toContain('"input":' + input) + const stream = event("content_block_start", { index: 1, content_block: { type: "tool_use", name: "task", input: {} } }) + + event("content_block_delta", { index: 1, delta: { type: "input_json_delta", partial_json: '{"arguments":' + input + '}' } }) + + event("content_block_stop", { index: 1 }) + event("message_stop", {}) + globalThis.fetch = async () => new Response(bytes(stream, 5), { headers: { "content-type": "text/event-stream" } }) + const streamed = await l.fetch(url, { method: "POST", body: JSON.stringify(request({ anyOf: [{ type: "object" }] }, { stream: true })) }) + expect(events(await streamed.text()).find((e) => e.type === "content_block_delta").delta.partial_json).toBe(input) +}) + +test("streaming initial inputs are unwrapped when the upstream sends no argument deltas", async () => { + const stream = event("content_block_start", { index: 1, content_block: { type: "tool_use", name: "task", input: { arguments: input } } }) + event("content_block_stop", { index: 1 }) + event("message_stop", {}) + const { l } = await loaded(() => new Response(bytes(stream, 7), { headers: { "content-type": "text/event-stream" } })) + const res = await l.fetch(url, { method: "POST", body: JSON.stringify(request({ anyOf: [object] }, { stream: true })) }) + const out = events(await res.text()) + expect(out[0].content_block.input).toEqual({}) + expect(JSON.parse(out[1].delta.partial_json)).toEqual(input) +}) + +for (const end of ["", event("message_stop", {})]) { + test("an incomplete stream cannot deliver a completed tool call", async () => { + const stream = event("content_block_start", { index: 1, content_block: { type: "tool_use", name: "task", input: {} } }) + event("content_block_delta", { index: 1, delta: { type: "input_json_delta", partial_json: '{"arguments":{' } }) + end + const { l } = await loaded(() => new Response(bytes(stream), { headers: { "content-type": "text/event-stream" } })) + const res = await l.fetch(url, { method: "POST", body: JSON.stringify(request({ anyOf: [object] }, { stream: true })) }) + await expect(res.text()).rejects.toThrow("incomplete wrapped tool arguments") + }) +} + +test("upstream stream errors are preserved even during a partial tool call", async () => { + const error = event("error", { error: { type: "overloaded_error", message: "try later" } }) + const stream = event("content_block_start", { index: 1, content_block: { type: "tool_use", name: "task", input: {} } }) + error + const { l } = await loaded(() => new Response(bytes(stream), { headers: { "content-type": "text/event-stream" } })) + const res = await l.fetch(url, { method: "POST", body: JSON.stringify(request({ anyOf: [object] }, { stream: true })) }) + expect(await res.text()).toContain(error) +}) + +test("cancelling the adapted stream cancels the upstream reader", async () => { + let cancelled + const { l } = await loaded(() => new Response(new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode(event("message_start", { message: { id: "msg_1" } }))) }, cancel(reason) { cancelled = reason } }), { headers: { "content-type": "text/event-stream" } })) + const res = await l.fetch(url, { method: "POST", body: JSON.stringify(request({ anyOf: [object] }, { stream: true })) }) + const reader = res.body.getReader() + await reader.read() + await reader.cancel("caller stopped") + expect(cancelled).toBe("caller stopped") +}) + +test("concurrent requests do not share their wrapped tool names", async () => { + const { l } = await loaded((body) => Response.json({ content: [{ type: "tool_use", name: "task", input: Object.hasOwn(body.tools[0].input_schema.properties ?? {}, "arguments") ? { arguments: input } : { arguments: "ordinary" } }] })) + const [wrapped, ordinary] = await Promise.all([ + l.fetch(url, { method: "POST", body: JSON.stringify(request({ anyOf: [object] })) }), + l.fetch(url, { method: "POST", body: JSON.stringify(request({ type: "object", properties: {} })) }), + ]) + expect((await wrapped.json()).content[0].input).toEqual(input) + expect((await ordinary.json()).content[0].input).toEqual({ arguments: "ordinary" }) +})