diff --git a/README.md b/README.md index ba76b61..ae9aba5 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ subscription and makes its requests. The packages work in OpenCode and in | [workbuddy](packages/workbuddy) | WorkBuddy (international build) | `workbuddy-ai` | | [zcode](packages/zcode) | ZCode: Z.ai / BigModel (智谱) GLM Coding Plan, team seats, Start Plan | `zcode` | | [zed](packages/zed) | Zed (Pro, Pro Trial, Student, Business): Anthropic, OpenAI, Google and xAI models hosted by Zed | `zed` | +| [zen-free](packages/zen-free) | OpenCode Zen free models with the public credential | `opencode-zen-free` | ## Gateway middleware diff --git a/packages/zen-free/LICENSE b/packages/zen-free/LICENSE new file mode 100644 index 0000000..85e65f8 --- /dev/null +++ b/packages/zen-free/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 xiaozhou26 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/zen-free/README.md b/packages/zen-free/README.md new file mode 100644 index 0000000..fca3fa5 --- /dev/null +++ b/packages/zen-free/README.md @@ -0,0 +1,36 @@ +# OpenCode Zen Free + +OpenCode Zen's free models in magpie and OpenCode. Provider id: +`opencode-zen-free`. + +## Install + +```sh +magpie plugin add @magpie-community/opencode-zen-free-auth +magpie plugin login opencode-zen-free +``` + +## Sign in + +Enter `public` in the key field. No personal API key is needed. +The credential is kept in OpenCode's `auth.json` or magpie's +`plugin-auth.json`. + +## Models + +The plugin discovers Zen's current free models, including their context +windows and reasoning levels. Use `opencode-zen-free/`, for example +`opencode-zen-free/big-pickle`. + +Retired models and SystemOne models are excluded. Availability and rate +limits are set by Zen; the plugin has no remaining-quota data. + +## Requests + +Requests go to `https://opencode.ai/zen/v1` using each model's native +Chat Completions, Responses or Anthropic Messages API. Streaming and +ordinary JSON replies are supported. + +The agent's tools are preserved. If Zen calls an added tool, its name is +mapped to the agent's unique case-insensitive match (`bash` to `Bash`). +A call with no matching tool returns an error. Tools run in the agent. diff --git a/packages/zen-free/index.mjs b/packages/zen-free/index.mjs new file mode 100644 index 0000000..3e8bce7 --- /dev/null +++ b/packages/zen-free/index.mjs @@ -0,0 +1,3 @@ +import plugin from "./provider.mjs" + +export const ZenFreePlugin = plugin.server diff --git a/packages/zen-free/index.test.mjs b/packages/zen-free/index.test.mjs new file mode 100644 index 0000000..2e96f1b --- /dev/null +++ b/packages/zen-free/index.test.mjs @@ -0,0 +1,382 @@ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { once } from "node:events"; +import test from "node:test"; +import { protocols, declaredTools, toolReply } from "./tool-fixtures.mjs"; + +const subject = import("./index.mjs").then((module) => ({ + default: { server: module.ZenFreePlugin }, +})); + +async function fixture(t, input = {}) { + const state = { calls: [], status: 200, modelsStatus: 200, docsStatus: 200, catalogStatus: 200 }; + const server = createServer(async (req, res) => { + let text = ""; + for await (const chunk of req) text += chunk; + state.calls.push({ url: req.url, headers: req.headers, body: text && JSON.parse(text) }); + if (state.discoveryHang) { + state.onDiscovery?.(); + return; + } + if (req.url === "/v1/models") { + res.writeHead(state.modelsStatus, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + data: [ + { id: "chat-free" }, + { id: "responses-free" }, + { id: "messages-free" }, + { id: "paid" }, + ], + }), + ); + } else if (req.url === "/catalog") { + res.writeHead(state.catalogStatus, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + opencode: { + npm: "@ai-sdk/openai-compatible", + models: { + ...(state.omitChat + ? {} + : { "chat-free": { name: "Chat Free", limit: { context: 200000, output: 8192 } } }), + "responses-free": { provider: { npm: "@ai-sdk/openai" } }, + "messages-free": { provider: { npm: "@ai-sdk/anthropic" } }, + paid: { cost: { input: 3, output: 10 } }, + }, + }, + }), + ); + } else if (req.url === "/docs") { + res.writeHead(state.docsStatus); + res.end( + `| Model | chat-free | \`https://opencode.ai/zen/v1/${state.chatProtocol ?? "chat/completions"}\` | sdk |`, + ); + } else if (state.reply) { + res.writeHead(200, { "content-type": state.contentType ?? "text/event-stream" }); + res.end(state.reply); + } else if (state.hang) { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.write(": heartbeat\n\n"); + } else if (state.status !== 200) { + res.writeHead(state.status, { "content-type": "application/json", "retry-after": "30" }); + res.end('{"error":{"message":"limited","type":"rate_limit_error"}}'); + } else { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end( + 'data: {"id":"chat-1","model":"chat-free","choices":[{"index":0,"delta":{"role":"assistant","content":"hello"},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n', + ); + } + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + t.after(() => { + server.closeAllConnections(); + server.close(); + }); + const origin = `http://127.0.0.1:${server.address().port}`; + const module = await subject; + assert.equal(typeof module.default?.server, "function", "plugin hooks must be implemented"); + const plugin = await module.default.server(input, { + baseURL: `${origin}/v1`, + catalogURL: `${origin}/catalog`, + docsURL: `${origin}/docs`, + }); + return { plugin, state, origin }; +} + +const publicAuth = async () => ({ type: "api", key: "public" }); + +for (const { protocol, path, model } of protocols) { + for (const stream of [true, false]) { + for (const upstreamSSE of [true, false]) { + test(`${protocol}: guards tool names with client stream=${stream}, upstream SSE=${upstreamSSE}`, async (t) => { + const { plugin, state, origin } = await fixture(t); + await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); + const loader = await plugin.auth.loader(publicAuth); + const tools = declaredTools(protocol); + state.contentType = upstreamSSE ? "text/event-stream" : "application/json"; + const send = () => + loader.fetch(`${origin}/v1/${path}`, { + method: "POST", + body: JSON.stringify({ model, stream, tools }), + }); + for (const [upstream, expected] of [ + ["bash", "Bash"], + ["read", "Read"], + ["Bash", "Bash"], + ]) { + state.reply = toolReply(protocol, upstream, upstreamSSE); + const response = await send(); + assert.equal(response.status, 200); + const text = await response.text(); + assert.match(text, new RegExp(`"name"\\s*:\\s*"${expected}"`)); + assert.doesNotMatch(text, /"name"\s*:\s*"(?:bash|read)"/); + } + const outbound = state.calls.at(-1).body.tools; + assert.deepEqual(outbound.slice(0, tools.length), tools); + for (const raw of outbound.slice(tools.length)) { + const tool = protocol === "chat" ? raw.function : raw; + assert.match(tool.description, /Not available\. Never call this tool\./); + assert.equal((tool.parameters ?? tool.input_schema).additionalProperties, false); + assert.deepEqual((tool.parameters ?? tool.input_schema).properties, {}); + } + state.reply = toolReply(protocol, "edit", upstreamSSE); + const error = await send(); + if (!stream || !upstreamSSE) assert.equal(error.status, 502); + const rejected = await error.text(); + assert.match(rejected, /error/); + assert.doesNotMatch(rejected, /"name"\s*:\s*"edit"/); + }); + } + } +} + +test("keeps declared tools isolated between requests using the same loader", async (t) => { + const { plugin, state, origin } = await fixture(t); + await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); + const loader = await plugin.auth.loader(publicAuth); + state.reply = toolReply("chat", "bash"); + const send = (tools) => + loader.fetch(`${origin}/v1/chat/completions`, { + method: "POST", + body: JSON.stringify({ model: "chat-free", stream: false, tools }), + }); + assert.equal((await send(declaredTools("chat"))).status, 200); + const blocked = await send([]); + assert.equal(blocked.status, 502); + assert.doesNotMatch(await blocked.text(), /"name"\s*:\s*"Bash"/); +}); + +for (const [input, supplied, expected] of [ + [{}, undefined, "global"], + [{ project: { id: "magpie" } }, undefined, "global"], + [{ project: { id: "abc123", vcs: "git" } }, undefined, "abc123"], + [{}, "client-project", "client-project"], +]) { + test(`uses OpenCode project identity ${expected}`, async (t) => { + const { plugin, state, origin } = await fixture(t, input); + await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); + const loader = await plugin.auth.loader(publicAuth); + const response = await loader.fetch(`${origin}/v1/chat/completions`, { + method: "POST", + headers: supplied ? { "x-opencode-project": supplied } : {}, + body: JSON.stringify({ model: "chat-free", stream: true }), + }); + await response.text(); + assert.equal(state.calls.at(-1).headers["x-opencode-project"], expected); + assert.equal(state.calls.at(-1).headers["user-agent"], "opencode/1.18.34"); + }); +} + +test("aborts discovery immediately when the inference caller cancels", async (t) => { + const { plugin, state, origin } = await fixture(t); + const loader = await plugin.auth.loader(publicAuth); + const controller = new AbortController(); + state.discoveryHang = true; + const started = new Promise((resolve) => { + state.onDiscovery = resolve; + }); + const request = loader.fetch(`${origin}/v1/chat/completions`, { + method: "POST", + signal: controller.signal, + body: JSON.stringify({ model: "chat-free", stream: true }), + }); + const rejected = assert.rejects(request, /abort/i); + await started; + controller.abort(); + let timer; + try { + await Promise.race([ + rejected, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error("discovery ignored caller cancellation")), 500); + }), + ]); + } finally { + clearTimeout(timer); + } +}); + +test("partial discovery never restores a model explicitly changed to SystemOne", async (t) => { + const { plugin, state } = await fixture(t); + state.omitChat = true; + const before = await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); + assert.ok(before["chat-free"]); + state.catalogStatus = 503; + state.chatProtocol = "systemone"; + const after = await plugin.provider.models({ models: before }, { auth: await publicAuth() }); + assert.equal(after["chat-free"], undefined); +}); + +test("registers without overwriting user config and enables public access without a secret", async (t) => { + const { plugin } = await fixture(t); + const cfg = {}; + await plugin.config(cfg); + assert.equal(cfg.provider["opencode-zen-free"].name, "OpenCode Zen Free"); + cfg.provider["opencode-zen-free"].name = "My name"; + await plugin.config(cfg); + assert.equal(cfg.provider["opencode-zen-free"].name, "My name"); + assert.deepEqual(await plugin.auth.methods[0].authorize(), { type: "success", key: "public" }); + assert.deepEqual(await plugin.auth.loader(async () => undefined), {}); + await assert.rejects( + plugin.auth.loader(async () => ({ type: "api", key: "paid-secret" })), + /public/i, + ); + assert.deepEqual((await plugin.auth.usage(publicAuth)).windows, []); +}); + +test("discovers protocols and free models, caches success, marks failed refresh as fallback", async (t) => { + const { plugin, state, origin } = await fixture(t); + const provider = { models: {} }; + const models = await plugin.provider.models(provider, { auth: await publicAuth() }); + assert.deepEqual(Object.keys(models).sort(), ["chat-free", "messages-free", "responses-free"]); + assert.equal(models["responses-free"].api.npm, "@ai-sdk/openai"); + assert.equal(models["messages-free"].api.npm, "@ai-sdk/anthropic"); + assert.equal(models["chat-free"].api.url, `${origin}/v1`); + state.modelsStatus = 503; + const fallback = await plugin.provider.models({ models }, { auth: await publicAuth() }); + assert.equal(fallback[Symbol.for("magpie.fellBack")], true); + assert.deepEqual(Object.keys(fallback), Object.keys(models)); +}); + +test("partial catalog failure retains previously verified models rather than dropping them", async (t) => { + const { plugin, state } = await fixture(t); + const models = await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); + state.catalogStatus = 503; + state.docsStatus = 503; + const fallback = await plugin.provider.models({ models }, { auth: await publicAuth() }); + assert.deepEqual(Object.keys(fallback).sort(), ["chat-free", "messages-free", "responses-free"]); + assert.equal(fallback[Symbol.for("magpie.fellBack")], true); +}); + +test("forces upstream streaming, preserves existing tools and returns the SSE body unbuffered", async (t) => { + const { plugin, state, origin } = await fixture(t); + await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); + const loader = await plugin.auth.loader(publicAuth); + const bash = { + type: "function", + function: { + name: "bash", + description: "real bash", + parameters: { type: "object", properties: { command: { type: "string" } } }, + }, + }; + const response = await loader.fetch(`${origin}/v1/chat/completions`, { + method: "POST", + headers: { + authorization: "Bearer client-key", + "x-session-id": "session_123", + "content-length": "1", + }, + body: JSON.stringify({ + model: "chat-free", + stream: true, + messages: [{ role: "user", content: "hello" }], + tools: [bash], + }), + }); + assert.match(response.headers.get("content-type"), /text\/event-stream/); + assert.match(await response.text(), /\[DONE\]/); + const sent = state.calls.at(-1); + assert.equal(sent.headers.authorization, "Bearer public"); + assert.match(sent.headers["x-opencode-session"], /^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/); + assert.equal(sent.headers["x-session-affinity"], sent.headers["x-opencode-session"]); + assert.equal(sent.headers["x-session-id"], sent.headers["x-opencode-session"]); + assert.ok(sent.headers["x-opencode-request"]); + assert.equal(sent.body.stream, true); + assert.equal(sent.body.stream_options.include_usage, true); + assert.deepEqual(sent.body.tools[0], bash); + assert.deepEqual( + sent.body.tools.map((tool) => tool.function.name), + ["bash", "edit", "glob", "grep", "read"], + ); +}); + +test("collapses SSE for a non-streaming client and preserves upstream HTTP errors", async (t) => { + const { plugin, state, origin } = await fixture(t); + await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); + const loader = await plugin.auth.loader(publicAuth); + const send = () => + loader.fetch(`${origin}/v1/chat/completions`, { + method: "POST", + body: JSON.stringify({ model: "chat-free", messages: [{ role: "user", content: "hello" }] }), + }); + const response = await send(); + assert.equal((await response.json()).choices[0].message.content, "hello"); + state.status = 429; + const error = await send(); + assert.equal(error.status, 429); + assert.equal(error.headers.get("retry-after"), "30"); + assert.equal((await error.json()).error.message, "limited"); +}); + +for (const [path, model, key] of [ + ["responses", "responses-free", "parameters"], + ["messages", "messages-free", "input_schema"], +]) { + test(`normalizes ${path} tools and authentication using native protocol`, async (t) => { + const { plugin, state, origin } = await fixture(t); + await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); + const loader = await plugin.auth.loader(publicAuth); + const response = await loader.fetch(`${origin}/v1/${path}`, { + method: "POST", + body: JSON.stringify({ model, stream: true }), + }); + await response.text(); + const sent = state.calls.at(-1); + assert.equal(sent.body.tools[0].name, "bash"); + assert.equal(sent.body.tools[0][key].type, "object"); + if (path === "messages") { + assert.equal(sent.headers["x-api-key"], "public"); + assert.equal(sent.headers["anthropic-version"], "2023-06-01"); + assert.equal(sent.headers.authorization, undefined); + } + }); +} + +test("rejects paid models, wrong protocol and foreign URLs before sending inference", async (t) => { + const { plugin, state, origin } = await fixture(t); + await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); + const loader = await plugin.auth.loader(publicAuth); + const before = state.calls.length; + for (const [url, model] of [ + [`${origin}/v1/chat/completions`, "paid"], + [`${origin}/v1/responses`, "chat-free"], + ["https://other.example/v1/chat/completions", "chat-free"], + ]) { + await assert.rejects( + loader.fetch(url, { method: "POST", body: JSON.stringify({ model, stream: true }) }), + ); + } + assert.equal(state.calls.length, before); +}); + +test("accepts Request input and aborts a streaming request", async (t) => { + const { plugin, state, origin } = await fixture(t); + await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); + const loader = await plugin.auth.loader(publicAuth); + state.hang = true; + const controller = new AbortController(); + const req = new Request(`${origin}/v1/chat/completions`, { + method: "POST", + signal: controller.signal, + body: JSON.stringify({ model: "chat-free", stream: true }), + }); + const response = await loader.fetch(req); + const body = response.text(); + controller.abort(); + await assert.rejects(body, /abort/i); +}); + +test("chat headers are scoped to this provider and retain the conversation session", async (t) => { + const { plugin } = await fixture(t); + const out = { headers: {} }; + await plugin["chat.headers"]({ model: { providerID: "other" }, sessionID: "s1" }, out); + assert.deepEqual(out.headers, {}); + await plugin["chat.headers"]( + { model: { providerID: "opencode-zen-free" }, sessionID: "s1" }, + out, + ); + assert.equal(out.headers["x-session-id"], "s1"); +}); diff --git a/packages/zen-free/models.mjs b/packages/zen-free/models.mjs new file mode 100644 index 0000000..0b2a904 --- /dev/null +++ b/packages/zen-free/models.mjs @@ -0,0 +1,148 @@ +export const PROVIDER = "opencode-zen-free"; +export const SDK = { + chat: "@ai-sdk/openai-compatible", + responses: "@ai-sdk/openai", + anthropic: "@ai-sdk/anthropic", +}; + +export function parseProtocolDocs(text) { + const protocols = {}; + const pattern = + /\|[^|]+\|\s*`?([^|`\s]+)`?\s*\|\s*`[^`]+\/v1\/(chat\/completions|responses|messages|systemone)`/g; + for (const match of text.matchAll(pattern)) { + protocols[match[1]] = { + "chat/completions": "chat", + responses: "responses", + messages: "anthropic", + systemone: "systemone", + }[match[2]]; + } + return protocols; +} + +function sdkProtocol(npm) { + if (npm?.includes("anthropic")) return "anthropic"; + if (npm === SDK.responses) return "responses"; + if (npm?.includes("openai-compatible")) return "chat"; +} + +function isRetired(model) { + return ( + model.deprecated === true || + ["deprecated", "retired", "disabled"].includes(model.status ?? model.lifecycle) || + model.deprecated_at != null || + model.retirement_date != null + ); +} + +export function isFree(id, model = {}) { + return ( + !isRetired(model) && (/free/i.test(id) || (model.cost?.input === 0 && model.cost?.output === 0)) + ); +} + +export function buildModels(ids, provider, protocols, baseURL) { + const result = {}; + for (const id of ids) { + if (typeof id !== "string" || !id || id === "__proto__") continue; + const raw = provider.models?.[id]; + const model = raw ?? {}; + const protocol = protocols[id] ?? (raw && sdkProtocol(model.provider?.npm ?? provider.npm)); + if (!isFree(id, model) || !Object.hasOwn(SDK, protocol)) continue; + const input = model.modalities?.input ?? ["text"]; + const output = model.modalities?.output ?? ["text"]; + const modalities = (values) => + Object.fromEntries( + ["text", "image", "audio", "video", "pdf"].map((name) => [name, values.includes(name)]), + ); + const efforts = (model.reasoning_options ?? []) + .filter((option) => option.type === "effort") + .flatMap((option) => option.values ?? []); + result[id] = { + id, + providerID: PROVIDER, + name: model.name ?? id, + api: { id, url: baseURL, npm: SDK[protocol] }, + limit: { context: 32768, output: 4096, ...model.limit }, + capabilities: { + temperature: model.temperature ?? true, + reasoning: model.reasoning ?? false, + attachment: model.attachment ?? input.some((name) => name !== "text"), + toolcall: model.tool_call ?? true, + input: modalities(input), + output: modalities(output), + interleaved: model.interleaved ?? false, + }, + cost: { input: 0, output: 0, cache: { read: 0, write: 0 } }, + variants: Object.fromEntries(efforts.map((effort) => [effort, { reasoningEffort: effort }])), + options: {}, + headers: {}, + status: model.status ?? "active", + release_date: model.release_date ?? "", + free: true, + }; + } + return result; +} + +// Offline bootstrap metadata from the OpenCode catalog, 2026-10-06. +export const bootstrapProvider = { + npm: SDK.chat, + models: { + "big-pickle": { + name: "Big Pickle", + cost: { input: 0, output: 0 }, + limit: { context: 200000, input: 160000, output: 32000 }, + reasoning: true, + tool_call: true, + interleaved: { field: "reasoning_content" }, + }, + "space-bunny-free": { + name: "Space Bunny Free", + cost: { input: 0, output: 0 }, + limit: { context: 1048576, input: 524288, output: 524288 }, + reasoning: true, + tool_call: true, + }, + "muse-spark-1.3-contributor-free": { + name: "Muse Spark 1.3 Free", + cost: { input: 0, output: 0 }, + provider: { npm: SDK.responses }, + limit: { context: 1048576, output: 131072 }, + reasoning: true, + tool_call: true, + modalities: { input: ["text", "image", "video", "pdf", "audio"], output: ["text"] }, + reasoning_options: [ + { type: "effort", values: ["minimal", "low", "medium", "high", "xhigh"] }, + ], + }, + }, +}; + +export function configModels(models) { + return Object.fromEntries( + Object.entries(models).map(([id, model]) => [ + id, + { + id, + name: model.name, + provider: { npm: model.api.npm, api: model.api.url }, + limit: model.limit, + reasoning: model.capabilities.reasoning, + tool_call: model.capabilities.toolcall, + attachment: model.capabilities.attachment, + modalities: { + input: Object.keys(model.capabilities.input).filter( + (key) => model.capabilities.input[key], + ), + output: Object.keys(model.capabilities.output).filter( + (key) => model.capabilities.output[key], + ), + }, + cost: { input: 0, output: 0 }, + variants: model.variants, + free: true, + }, + ]), + ); +} diff --git a/packages/zen-free/models.test.mjs b/packages/zen-free/models.test.mjs new file mode 100644 index 0000000..ece1688 --- /dev/null +++ b/packages/zen-free/models.test.mjs @@ -0,0 +1,70 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +const subject = import("./models.mjs").catch(() => ({})); +const provider = { + npm: "@ai-sdk/openai-compatible", + models: { + "coder-free": { + name: "Coder Free", + cost: { input: 0, output: 0 }, + limit: { context: 200000, input: 160000, output: 32000 }, + reasoning: true, + tool_call: true, + modalities: { input: ["text", "image"], output: ["text"] }, + reasoning_options: [{ type: "effort", values: ["low", "high"] }], + }, + "zero-cost": { cost: { input: 0, output: 0 } }, + paid: { cost: { input: 1, output: 3 } }, + "old-free": { status: "deprecated", cost: { input: 0, output: 0 } }, + "decision-free": { provider: { npm: "@vendor/systemone" } }, + "responses-free": { provider: { npm: "@ai-sdk/openai" } }, + "messages-free": { provider: { npm: "@ai-sdk/anthropic" } }, + "gone-free": {}, + }, +}; +const ids = Object.keys(provider.models).filter((id) => id !== "gone-free"); +const baseURL = "https://opencode.ai/zen/v1"; + +test("lists only live free models with supported protocols and excludes retired models", async () => { + const { buildModels } = await subject; + assert.equal(typeof buildModels, "function", "model discovery must be implemented"); + const models = buildModels(ids, provider, {}, baseURL); + assert.deepEqual(Object.keys(models).sort(), [ + "coder-free", + "messages-free", + "responses-free", + "zero-cost", + ]); + assert.equal(models["coder-free"].free, true); + assert.equal(models["coder-free"].providerID, "opencode-zen-free"); + assert.deepEqual(models["coder-free"].limit, { context: 200000, input: 160000, output: 32000 }); + assert.equal(models["coder-free"].capabilities.input.image, true); + assert.equal(models["coder-free"].capabilities.toolcall, true); + assert.deepEqual(Object.keys(models["coder-free"].variants), ["low", "high"]); + assert.equal(models["responses-free"].api.npm, "@ai-sdk/openai"); + assert.equal(models["messages-free"].api.npm, "@ai-sdk/anthropic"); +}); + +test("endpoint documentation overrides inherited SDK and excludes SystemOne", async () => { + const { buildModels, parseProtocolDocs } = await subject; + assert.equal(typeof parseProtocolDocs, "function", "protocol parsing must be implemented"); + const protocols = parseProtocolDocs( + [ + "| Coder | coder-free | `https://opencode.ai/zen/v1/messages` | sdk |", + "| Decision | decision-free | `https://opencode.ai/zen/v1/systemone` | - |", + ].join("\n"), + ); + const models = buildModels(ids, provider, protocols, baseURL); + assert.equal(models["coder-free"].api.npm, "@ai-sdk/anthropic"); + assert.equal(models["decision-free"], undefined); +}); + +test("unknown models require a known protocol rather than a guessed chat endpoint", async () => { + const { buildModels } = await subject; + assert.equal(typeof buildModels, "function", "model discovery must be implemented"); + assert.deepEqual(Object.keys(buildModels(["new-free", "unknown-paid"], {}, {}, baseURL)), []); + const models = buildModels(["new-free"], {}, { "new-free": "chat" }, baseURL); + assert.equal(models["new-free"].api.url, baseURL); + assert.equal(models["new-free"].cost.input, 0); +}); diff --git a/packages/zen-free/package.json b/packages/zen-free/package.json new file mode 100644 index 0000000..487d180 --- /dev/null +++ b/packages/zen-free/package.json @@ -0,0 +1,13 @@ +{ + "name": "@magpie-community/opencode-zen-free-auth", + "version": "0.1.0", + "description": "OpenCode Zen free models through the public credential, with native streaming protocols", + "type": "module", + "main": "./index.mjs", + "files": ["index.mjs", "provider.mjs", "models.mjs", "stream.mjs", "tool-response.mjs", "README.md", "LICENSE"], + "keywords": ["opencode", "opencode-plugin", "zen", "free", "magpie"], + "license": "MIT", + "repository": { "type": "git", "url": "https://github.com/magpie-community/plugins", "directory": "packages/zen-free" }, + "scripts": { "test": "bun test" }, + "magpie": { "icon": "https://opencode.ai/favicon-v3.ico", "maxConcurrency": 2 } +} diff --git a/packages/zen-free/provider.mjs b/packages/zen-free/provider.mjs new file mode 100644 index 0000000..0864b09 --- /dev/null +++ b/packages/zen-free/provider.mjs @@ -0,0 +1,290 @@ +import { createHash, randomUUID } from "node:crypto"; +import { + PROVIDER, + SDK, + bootstrapProvider, + buildModels, + configModels, + parseProtocolDocs, +} from "./models.mjs"; +import { collapseResponse } from "./stream.mjs"; +import { guardToolResponse } from "./tool-response.mjs"; + +const DEFAULT_BASE = "https://opencode.ai/zen/v1"; +const CATALOG = "https://models.opencode.ai/api.json"; +const DOCS = + "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/zen.mdx"; +const PATHS = { chat: "/chat/completions", responses: "/responses", anthropic: "/messages" }; +const CORE_TOOLS = ["bash", "edit", "glob", "grep", "read"]; +const OPENCODE_VERSION = "1.18.34"; + +function httpURL(value) { + const url = new URL(value); + if ( + !["http:", "https:"].includes(url.protocol) || + url.username || + url.password || + url.search || + url.hash + ) { + throw new Error("Expected an HTTP(S) URL without credentials, query or fragment"); + } + return url.href.replace(/\/+$/, ""); +} + +function requirePublic(auth) { + if (auth?.type !== "api" || auth.key !== "public") { + throw new Error( + "OpenCode Zen Free uses the public credential. Enable its free access login method.", + ); + } +} + +async function readRemote(url, json, headers, callerSignal) { + const timeout = AbortSignal.timeout(15000); + const signal = callerSignal ? AbortSignal.any([callerSignal, timeout]) : timeout; + const response = await fetch(url, { headers, signal }); + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`Model discovery returned HTTP ${response.status}`); + } + return json ? response.json() : response.text(); +} + +function normalizeTools(body, protocol) { + if (body.tools !== undefined && !Array.isArray(body.tools)) { + throw new Error("tools must be an array"); + } + body.tools ??= []; + const present = new Set( + body.tools.map((tool) => (protocol === "chat" ? tool?.function?.name : tool?.name)), + ); + const declared = new Set([...present].filter((name) => typeof name === "string")); + if (protocol === "chat" && Array.isArray(body.functions)) { + for (const tool of body.functions) if (typeof tool?.name === "string") declared.add(tool.name); + } + const injected = new Set(); + for (const name of CORE_TOOLS) { + if (present.has(name)) continue; + injected.add(name); + const parameters = { type: "object", properties: {}, additionalProperties: false }; + const definition = { name, description: "Not available. Never call this tool." }; + body.tools.push( + protocol === "chat" + ? { type: "function", function: { ...definition, parameters } } + : protocol === "anthropic" + ? { ...definition, input_schema: parameters } + : { type: "function", ...definition, parameters }, + ); + } + return { declared, injected }; +} + +function sessionID(headers, body) { + let signal; + for (const name of [ + "x-opencode-session", + "x-session-affinity", + "x-session-id", + "conversation-id", + ]) { + if (headers.get(name)) { + signal = headers.get(name); + break; + } + } + if (!signal && typeof body.metadata?.session_id === "string") signal = body.metadata.session_id; + if (!signal) { + const messages = body.messages ?? body.input; + const first = Array.isArray(messages) + ? messages.find((message) => message.role === "user")?.content + : messages; + signal = first ? JSON.stringify(first) : randomUUID(); + } + if (/^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/.test(signal)) return signal; + // Keep conversation affinity using OpenCode's canonical session format. + const hash = createHash("sha256").update(`ses\0${signal}`).digest("hex"); + let value = BigInt(`0x${hash.slice(12, 32)}`); + let suffix = ""; + const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + for (let i = 0; i < 14; i++) { + suffix = alphabet[Number(value % 62n)] + suffix; + value /= 62n; + } + return `ses_${hash.slice(0, 12)}${suffix}`; +} + +async function server(_input, options = {}) { + const baseURL = httpURL(options.baseURL ?? DEFAULT_BASE); + const catalogURL = httpURL(options.catalogURL ?? CATALOG); + const docsURL = httpURL(options.docsURL ?? DOCS); + let known = buildModels(Object.keys(bootstrapProvider.models), bootstrapProvider, {}, baseURL); + let metadata = bootstrapProvider; + let protocols = {}; + let listed = false; + + async function discover(signal) { + const headers = { authorization: "Bearer public", "x-opencode-client": "cli" }; + const [listing, catalog, docs] = await Promise.allSettled([ + readRemote(`${baseURL}/models`, true, headers, signal), + readRemote(catalogURL, true, undefined, signal), + readRemote(docsURL, false, undefined, signal), + ]); + signal?.throwIfAborted(); + let partial = false; + if (catalog.status === "fulfilled" && catalog.value?.opencode?.models) { + metadata = catalog.value.opencode; + } else { + partial = true; + } + if (docs.status === "fulfilled" && Object.keys(parseProtocolDocs(docs.value)).length) { + protocols = parseProtocolDocs(docs.value); + } else { + partial = true; + } + if (listing.status !== "fulfilled" || !Array.isArray(listing.value?.data)) { + const fallback = { ...known }; + fallback[Symbol.for("magpie.fellBack")] = true; + return fallback; + } + const ids = listing.value.data.map((item) => item.id); + const discovered = buildModels(ids, metadata, protocols, baseURL); + if (partial) { + // Preserve previously verified models only while they remain in the live catalog. + for (const id of ids) { + if (!discovered[id] && !metadata.models?.[id] && !protocols[id] && known[id]) { + discovered[id] = known[id]; + } + } + discovered[Symbol.for("magpie.fellBack")] = true; + } + known = discovered; + listed = true; + return discovered; + } + + return { + async config(cfg) { + cfg.provider ??= {}; + cfg.provider[PROVIDER] ??= { + name: "OpenCode Zen Free", + npm: SDK.chat, + api: baseURL, + models: configModels(known), + }; + }, + auth: { + provider: PROVIDER, + icon: "https://opencode.ai/favicon-v3.ico", + maxConcurrency: 2, + methods: [ + { + type: "api", + label: "Zen 免费访问(密钥填写 public)", + placeholder: "public", + async authorize() { + return { type: "success", key: "public" }; + }, + }, + ], + async loader(getAuth) { + const auth = await getAuth(); + if (!auth) return {}; + requirePublic(auth); + return { + baseURL, + apiKey: "public", + async fetch(input, init) { + requirePublic(await getAuth()); + const request = new Request(input, init); + const protocol = Object.keys(PATHS).find( + (key) => request.url === `${baseURL}${PATHS[key]}`, + ); + if (!protocol || request.method !== "POST") + throw new Error("Unsupported Zen endpoint or method"); + request.signal.throwIfAborted(); + const body = await request.json(); + if (!body || typeof body !== "object" || Array.isArray(body)) + throw new Error("Expected a JSON request object"); + if (!listed && !Object.hasOwn(known, body.model)) { + await discover(request.signal); + } + const model = known[body.model]; + if (!model || model.api.npm !== SDK[protocol]) { + throw new Error( + "Model is not an available free model for this protocol. Refresh the model list.", + ); + } + const streaming = body.stream === true; + body.stream = true; + const toolPolicy = normalizeTools(body, protocol); + if (protocol === "chat") + body.stream_options = { ...body.stream_options, include_usage: true }; + const headers = new Headers(request.headers); + for (const name of [ + "authorization", + "x-api-key", + "x-goog-api-key", + "content-length", + "content-encoding", + "host", + "cookie", + ]) { + headers.delete(name); + } + headers.set("content-type", "application/json"); + headers.set("accept", "text/event-stream"); + headers.set("user-agent", `opencode/${OPENCODE_VERSION}`); + headers.set("x-opencode-client", "cli"); + headers.set("x-opencode-request", `req_${randomUUID().replaceAll("-", "")}`); + if (!headers.has("x-opencode-project")) { + const project = _input?.project; + headers.set( + "x-opencode-project", + project?.vcs === "git" && project.id ? project.id : "global", + ); + } + const session = sessionID(headers, body); + for (const name of ["x-session-id", "x-opencode-session", "x-session-affinity"]) + headers.set(name, session); + if (protocol === "anthropic") { + headers.set("x-api-key", "public"); + if (!headers.has("anthropic-version")) headers.set("anthropic-version", "2023-06-01"); + } else { + headers.set("authorization", "Bearer public"); + } + const response = await fetch(request.url, { + method: "POST", + headers, + body: JSON.stringify(body), + signal: request.signal, + redirect: "error", + }); + const guarded = await guardToolResponse(response, protocol, toolPolicy); + return streaming ? guarded : collapseResponse(guarded, protocol); + }, + }; + }, + async usage() { + return { plan: "OpenCode Zen Free", windows: [] }; + }, + }, + provider: { + id: PROVIDER, + async models(provider, { auth } = {}) { + if (!auth) return provider.models; + requirePublic(auth); + return discover(); + }, + }, + async "chat.headers"(input, output) { + if (![PROVIDER, `${PROVIDER}-plugin`].includes(input.model?.providerID) || !input.sessionID) + return; + output.headers["x-session-id"] = input.sessionID; + output.headers["x-opencode-session"] = input.sessionID; + output.headers["x-session-affinity"] = input.sessionID; + }, + }; +} + +export default { id: PROVIDER, server }; diff --git a/packages/zen-free/stream.mjs b/packages/zen-free/stream.mjs new file mode 100644 index 0000000..717071b --- /dev/null +++ b/packages/zen-free/stream.mjs @@ -0,0 +1,398 @@ +const MAX_BYTES = 32 * 1024 * 1024; + +function jsonResponse(source, protocol, value, error) { + const headers = new Headers(source.headers); + headers.delete("content-length"); + headers.delete("content-encoding"); + headers.set("content-type", "application/json"); + if (error) { + const detail = { type: "upstream_error", message: error }; + value = + protocol === "anthropic" + ? { type: "error", error: detail } + : { error: { ...detail, param: null, code: null } }; + } + return new Response(JSON.stringify(value), { + status: error ? 502 : source.status, + headers, + }); +} + +function errorMessage(value, fallback = "Upstream stream failed") { + if (typeof value === "string" && value) return value; + return value?.message || value?.error?.message || fallback; +} + +function index(value) { + const result = value ?? 0; + if (!Number.isInteger(result) || result < 0 || result > 65535) { + throw new Error("Invalid stream item index"); + } + return result; +} + +function sorted(map) { + return [...map].sort(([a], [b]) => a - b).map(([, value]) => value); +} + +function appendFunction(target, delta) { + for (const key of ["name", "arguments"]) { + if (typeof delta[key] === "string") target[key] = (target[key] ?? "") + delta[key]; + } +} + +function chatAccumulator() { + const body = { object: "chat.completion", choices: [] }; + const choices = new Map(); + const tools = new Map(); + return { + apply(data) { + for (const key of ["id", "created", "model", "system_fingerprint", "service_tier"]) { + if (data[key] !== undefined) body[key] = data[key]; + } + if (data.usage) body.usage = { ...body.usage, ...data.usage }; + for (const part of data.choices ?? []) { + const position = index(part.index); + if (!choices.has(position)) { + choices.set(position, { + index: position, + message: { role: "assistant", content: null }, + finish_reason: null, + }); + tools.set(position, new Map()); + } + const choice = choices.get(position); + const message = choice.message; + const delta = part.delta ?? {}; + if (delta.role) message.role = delta.role; + for (const key of ["content", "reasoning_content", "reasoning", "refusal"]) { + if (typeof delta[key] === "string") message[key] = (message[key] ?? "") + delta[key]; + } + if (delta.function_call) { + message.function_call ??= { name: "", arguments: "" }; + appendFunction(message.function_call, delta.function_call); + } + for (const fragment of delta.tool_calls ?? []) { + const toolIndex = index(fragment.index); + const calls = tools.get(position); + if (!calls.has(toolIndex)) + calls.set(toolIndex, { type: "function", function: { name: "", arguments: "" } }); + const call = calls.get(toolIndex); + for (const key of ["id", "type"]) { + if (fragment[key] !== undefined) call[key] = fragment[key]; + } + if (fragment.function) appendFunction(call.function, fragment.function); + } + if (part.finish_reason != null) choice.finish_reason = part.finish_reason; + if (part.logprobs) { + choice.logprobs ??= {}; + for (const [key, value] of Object.entries(part.logprobs)) { + if (Array.isArray(value)) + choice.logprobs[key] = [...(choice.logprobs[key] ?? []), ...value]; + else choice.logprobs[key] = value; + } + } + } + }, + finish() { + for (const [position, choice] of choices) { + if (tools.get(position).size) choice.message.tool_calls = sorted(tools.get(position)); + } + body.choices = sorted(choices); + return body; + }, + }; +} + +function responsesAccumulator() { + let body = { object: "response", output: [] }; + let final; + const output = new Map(); + function item(data, type = "message") { + let position = data.output_index; + if (position === undefined && data.item_id) { + position = [...output].find(([, value]) => value.id === data.item_id)?.[0]; + } + position = index(position); + if (!output.has(position)) { + const value = { type }; + if (data.item_id) value.id = data.item_id; + if (type === "message") Object.assign(value, { role: "assistant", content: [] }); + if (type === "function_call") value.arguments = ""; + if (type === "reasoning") value.summary = []; + output.set(position, value); + } + return output.get(position); + } + return { + apply(data, type) { + if (type === "response.created" || type === "response.in_progress") { + if (data.response) { + body = { ...body, ...data.response }; + for (const [position, value] of (data.response.output ?? []).entries()) + output.set(position, value); + } + } else if (type === "response.output_item.added" || type === "response.output_item.done") { + if (data.item) output.set(index(data.output_index), data.item); + } else if (type === "response.content_part.added" || type === "response.content_part.done") { + const value = item(data); + value.content ??= []; + value.content[index(data.content_index)] = data.part; + } else if ( + type === "response.output_text.delta" || + type === "response.output_text.done" || + type === "response.refusal.delta" || + type === "response.refusal.done" + ) { + const value = item(data); + value.content ??= []; + const refusal = type.startsWith("response.refusal."); + const field = refusal ? "refusal" : "text"; + const part = (value.content[index(data.content_index)] ??= refusal + ? { type: "refusal", refusal: "" } + : { type: "output_text", text: "", annotations: [] }); + if (type.endsWith(".delta")) part[field] = (part[field] ?? "") + (data.delta ?? ""); + else if (data[field] !== undefined) part[field] = data[field]; + } else if ( + type === "response.function_call_arguments.delta" || + type === "response.function_call_arguments.done" + ) { + const value = item(data, "function_call"); + if (type.endsWith(".delta")) value.arguments = (value.arguments ?? "") + (data.delta ?? ""); + else if (data.arguments !== undefined) value.arguments = data.arguments; + } else if ( + type === "response.reasoning_summary_part.added" || + type === "response.reasoning_summary_part.done" + ) { + const value = item(data, "reasoning"); + value.summary ??= []; + value.summary[index(data.summary_index)] = data.part; + } else if (/^response\.reasoning_(summary_)?text\.(delta|done)$/.test(type)) { + const value = item(data, "reasoning"); + const summary = type.includes("summary"); + const field = summary ? "summary" : "content"; + value[field] ??= []; + const part = (value[field][index(summary ? data.summary_index : data.content_index)] ??= { + type: summary ? "summary_text" : "reasoning_text", + text: "", + }); + if (type.endsWith(".delta")) part.text += data.delta ?? ""; + else if (data.text !== undefined) part.text = data.text; + } else if (type === "response.reasoning_content.delta") { + body.reasoning_content = (body.reasoning_content ?? "") + (data.delta ?? ""); + } else if (type === "response.completed" || type === "response.incomplete") { + if (data.response && typeof data.response === "object") final = data.response; + body.status = type === "response.completed" ? "completed" : "incomplete"; + for (const key of ["incomplete_details", "finish_reason"]) { + if (data[key] !== undefined) body[key] = data[key]; + } + } + if (data.usage) body.usage = { ...body.usage, ...data.usage }; + }, + finish() { + if (final) return final; + body.output = sorted(output); + return body; + }, + }; +} + +function anthropicAccumulator() { + let body = { + type: "message", + role: "assistant", + content: [], + stop_reason: null, + stop_sequence: null, + }; + const blocks = new Map(); + const argumentsJSON = new Map(); + return { + apply(data, type) { + if (type === "message_start") { + body = { ...body, ...data.message }; + for (const [position, block] of (data.message?.content ?? []).entries()) + blocks.set(position, block); + } else if (type === "content_block_start") { + blocks.set(index(data.index), data.content_block); + } else if (type === "content_block_delta") { + const position = index(data.index); + const block = blocks.get(position); + if (!block) throw new Error("Content delta without a content block"); + const delta = data.delta ?? {}; + const field = { + text_delta: "text", + thinking_delta: "thinking", + signature_delta: "signature", + }[delta.type]; + if (field) block[field] = (block[field] ?? "") + (delta[field] ?? ""); + if (delta.type === "input_json_delta") { + argumentsJSON.set( + position, + (argumentsJSON.get(position) ?? "") + (delta.partial_json ?? ""), + ); + } + } else if (type === "message_delta") { + Object.assign(body, data.delta); + if (data.usage) body.usage = { ...body.usage, ...data.usage }; + } + }, + finish() { + for (const [position, value] of argumentsJSON) { + try { + blocks.get(position).input = JSON.parse(value); + } catch { + throw new Error("Invalid tool input JSON in upstream stream"); + } + } + body.content = sorted(blocks); + return body; + }, + }; +} + +export async function collapseResponse(response, protocol) { + if (!response.ok) return response; + const contentType = response.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase(); + if (contentType !== "text/event-stream") return response; + const factories = { + chat: chatAccumulator, + responses: responsesAccumulator, + anthropic: anthropicAccumulator, + }; + if (!Object.hasOwn(factories, protocol)) throw new TypeError(`Unsupported protocol: ${protocol}`); + const accumulator = factories[protocol](); + let completed = false; + let failure; + let eventName = ""; + let dataLines = []; + let lineParts = []; + let skipLF = false; + + function dispatch() { + const name = eventName; + const text = dataLines.join("\n"); + eventName = ""; + dataLines = []; + if (failure) return; + if (name === "error") { + let value = text; + try { + value = JSON.parse(text); + } catch { + /* Error events may contain plain text. */ + } + failure = errorMessage(value); + return; + } + if (!text.trim()) return; + if (text.trim() === "[DONE]") { + if (protocol === "chat") completed = true; + return; + } + let data; + try { + data = JSON.parse(text); + } catch { + failure = "Invalid JSON in upstream SSE event"; + return; + } + if (!data || typeof data !== "object" || Array.isArray(data)) { + failure = "Invalid JSON object in upstream SSE event"; + return; + } + const type = data.type ?? name; + if ( + data.error || + type === "error" || + type === "response.failed" || + data.response?.status === "failed" + ) { + failure = errorMessage(data.error ?? data.response?.error ?? data); + return; + } + if (completed) return; + try { + accumulator.apply(data, type); + } catch (error) { + failure = errorMessage(error, "Invalid upstream SSE event"); + return; + } + if ( + (protocol === "responses" && + (type === "response.completed" || type === "response.incomplete")) || + (protocol === "anthropic" && type === "message_stop") + ) + completed = true; + } + + function line(value) { + if (value === "") return dispatch(); + if (value.startsWith(":")) return; + const colon = value.indexOf(":"); + const field = colon < 0 ? value : value.slice(0, colon); + let content = colon < 0 ? "" : value.slice(colon + 1); + if (content.startsWith(" ")) content = content.slice(1); + if (field === "data") dataLines.push(content); + if (field === "event") eventName = content; + } + + function feed(text) { + let start = 0; + if (skipLF && text.length) { + if (text[0] === "\n") start = 1; + skipLF = false; + } + const endings = /[\r\n]/g; + endings.lastIndex = start; + let match; + while ((match = endings.exec(text))) { + lineParts.push(text.slice(start, match.index)); + line(lineParts.join("")); + lineParts = []; + start = match.index + 1; + if (match[0] === "\r") { + if (text[start] === "\n") start++; + else if (start === text.length) skipLF = true; + } + endings.lastIndex = start; + } + if (start < text.length) lineParts.push(text.slice(start)); + } + + if (response.body) { + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let bytes = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + bytes += value.byteLength; + if (bytes > MAX_BYTES) { + failure = "Upstream SSE exceeds the 32 MiB buffer limit"; + await reader.cancel(); + break; + } + feed(decoder.decode(value, { stream: true })); + if (failure) { + await reader.cancel(); + break; + } + } + feed(decoder.decode()); + } finally { + reader.releaseLock(); + } + } + if (!failure && !completed) failure = "Upstream SSE ended without a completion marker"; + let body; + if (!failure) { + try { + body = accumulator.finish(); + } catch (error) { + failure = errorMessage(error); + } + } + return jsonResponse(response, protocol, body, failure); +} diff --git a/packages/zen-free/stream.test.mjs b/packages/zen-free/stream.test.mjs new file mode 100644 index 0000000..e35d919 --- /dev/null +++ b/packages/zen-free/stream.test.mjs @@ -0,0 +1,693 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { collapseResponse } from "./stream.mjs"; + +const encoder = new TextEncoder(); +const event = (data, name) => + `${name ? `event: ${name}\n` : ""}data: ${typeof data === "string" ? data : JSON.stringify(data)}\n\n`; + +function sse(text, { chunkSize = 23, headers = {}, status = 200 } = {}) { + const bytes = encoder.encode(text); + let offset = 0; + return new Response( + new ReadableStream({ + pull(controller) { + if (offset === bytes.length) return controller.close(); + const end = Math.min(offset + chunkSize, bytes.length); + controller.enqueue(bytes.slice(offset, end)); + offset = end; + }, + }), + { status, headers: { "content-type": "text/event-stream; charset=utf-8", ...headers } }, + ); +} + +async function collapseOpenStream(text, protocol, cancel = () => {}) { + let controller; + let cancelled = false; + let timer; + const bytes = encoder.encode(text); + const response = new Response( + new ReadableStream({ + start(source) { + controller = source; + source.enqueue(bytes.slice(0, -1)); + source.enqueue(bytes.slice(-1)); + }, + cancel() { + cancelled = true; + return cancel(); + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); + try { + const result = await Promise.race([ + collapseResponse(response, protocol), + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error("SSE error waited for EOF")), 500); + }), + ]); + assert.equal(cancelled, true); + assert.equal(response.body.locked, false); + return result; + } finally { + clearTimeout(timer); + if (!cancelled) controller.close(); + } +} + +async function json(text, protocol, options) { + const response = await collapseResponse(sse(text, options), protocol); + assert.equal(response.status, 200); + assert.equal(response.headers.get("content-type"), "application/json"); + return response.json(); +} + +async function failure(text, protocol, pattern = /./) { + const response = await collapseResponse(sse(text), protocol); + assert.equal(response.status, 502); + const body = await response.json(); + assert.equal(body.error.type, "upstream_error"); + assert.match(body.error.message, pattern); + if (protocol === "anthropic") assert.equal(body.type, "error"); + else { + assert.equal(body.error.param, null); + assert.equal(body.error.code, null); + } +} + +test("chat preserves text, reasoning, indexed choices, tool arguments, usage and finish reasons", async () => { + const text = + [ + { + id: "chat-1", + object: "chat.completion.chunk", + created: 123, + model: "zen", + system_fingerprint: "fp", + choices: [ + { + index: 0, + delta: { + role: "assistant", + content: "你", + reasoning_content: "想", + tool_calls: [ + { + index: 1, + id: "call-b", + type: "function", + function: { name: "second", arguments: '{"b":' }, + }, + { + index: 0, + id: "call-a", + type: "function", + function: { name: "first", arguments: '{"a":' }, + }, + ], + }, + }, + ], + }, + { + choices: [ + { index: 1, delta: { content: "other" }, finish_reason: "stop" }, + { + index: 0, + delta: { + content: "好🙂", + reasoning_content: "法", + tool_calls: [ + { index: 0, function: { arguments: "1}" } }, + { index: 1, function: { arguments: "2}" } }, + ], + }, + finish_reason: "tool_calls", + }, + ], + }, + { + choices: [], + usage: { + prompt_tokens: 10, + completion_tokens: 7, + total_tokens: 17, + completion_tokens_details: { reasoning_tokens: 3 }, + }, + }, + ] + .map((value) => event(value)) + .join("") + event("[DONE]"); + const body = await json(text, "chat", { chunkSize: 1 }); + assert.equal(body.id, "chat-1"); + assert.equal(body.object, "chat.completion"); + assert.equal(body.created, 123); + assert.equal(body.model, "zen"); + assert.equal(body.system_fingerprint, "fp"); + assert.equal(body.choices[0].message.role, "assistant"); + assert.equal(body.choices[0].message.content, "你好🙂"); + assert.equal(body.choices[0].message.reasoning_content, "想法"); + assert.deepEqual(body.choices[0].message.tool_calls, [ + { id: "call-a", type: "function", function: { name: "first", arguments: '{"a":1}' } }, + { id: "call-b", type: "function", function: { name: "second", arguments: '{"b":2}' } }, + ]); + assert.equal(body.choices[0].finish_reason, "tool_calls"); + assert.equal(body.choices[1].message.content, "other"); + assert.equal(body.choices[1].finish_reason, "stop"); + assert.deepEqual(body.usage, { + prompt_tokens: 10, + completion_tokens: 7, + total_tokens: 17, + completion_tokens_details: { reasoning_tokens: 3 }, + }); +}); + +test("chat retains null content for tool-only replies and legacy function_call fragments", async () => { + const body = await json( + event({ + choices: [ + { + index: 0, + delta: { content: null, function_call: { name: "lookup", arguments: '{"x":' } }, + }, + ], + }) + + event({ + choices: [ + { + index: 0, + delta: { function_call: { arguments: "1}" } }, + finish_reason: "function_call", + }, + ], + }) + + event("[DONE]"), + "chat", + ); + assert.equal(body.choices[0].message.content, null); + assert.deepEqual(body.choices[0].message.function_call, { name: "lookup", arguments: '{"x":1}' }); +}); + +test("SSE supports BOM, comments, CRLF, multiple data lines and arbitrary byte boundaries", async () => { + const text = + '\uFEFF: keepalive\r\nid: 3\r\nevent: message\r\ndata: {"choices":\r\ndata: [{"index":0,"delta":{"content":"中文🙂"},"finish_reason":"stop"}]}\r\n\r\ndata: [DONE]\r\n\r\n'; + for (const chunkSize of [1, 2, 3, 7, 64, 1024]) { + const body = await json(text, "chat", { chunkSize }); + assert.equal(body.choices[0].message.content, "中文🙂"); + } +}); + +test("SSE supports CR-only line endings", async () => { + const body = await json( + ( + event({ choices: [{ index: 0, delta: { content: "ok" }, finish_reason: "stop" }] }) + + event("[DONE]") + ).replaceAll("\n", "\r"), + "chat", + { chunkSize: 1 }, + ); + assert.equal(body.choices[0].message.content, "ok"); +}); + +test("Responses uses the complete final response without replacing authoritative fields", async () => { + const final = { + id: "resp-1", + object: "response", + status: "completed", + model: "zen", + output: [ + { + type: "message", + id: "msg", + role: "assistant", + content: [{ type: "output_text", text: "final", annotations: [] }], + }, + { type: "reasoning", summary: [{ type: "summary_text", text: "thought" }] }, + { type: "function_call", call_id: "call", name: "f", arguments: '{"a":1}' }, + ], + usage: { input_tokens: 4, output_tokens: 6, total_tokens: 10 }, + metadata: { retained: true }, + }; + const body = await json( + event({ + type: "response.output_text.delta", + output_index: 0, + content_index: 0, + delta: "not final", + }) + event({ type: "response.completed", response: final }, "response.completed"), + "responses", + ); + assert.deepEqual(body, final); +}); + +test("Responses incomplete keeps the original response and its usage", async () => { + const final = { + id: "resp-limit", + object: "response", + status: "incomplete", + incomplete_details: { reason: "max_output_tokens" }, + output: [], + usage: { output_tokens: 20 }, + }; + assert.deepEqual( + await json(event({ response: final }, "response.incomplete"), "responses"), + final, + ); +}); + +test("Responses aggregates fallback text, reasoning, function arguments and usage", async () => { + const events = [ + { + type: "response.created", + response: { + id: "resp-2", + object: "response", + model: "zen", + status: "in_progress", + output: [], + }, + }, + { + type: "response.output_item.added", + output_index: 0, + item: { id: "m", type: "message", role: "assistant", content: [] }, + }, + { + type: "response.content_part.added", + output_index: 0, + content_index: 0, + part: { type: "output_text", text: "", annotations: [] }, + }, + { type: "response.output_text.delta", output_index: 0, content_index: 0, delta: "hello" }, + { type: "response.output_text.delta", output_index: 0, content_index: 0, delta: " world" }, + { + type: "response.output_item.added", + output_index: 1, + item: { id: "r", type: "reasoning", summary: [] }, + }, + { + type: "response.reasoning_summary_part.added", + output_index: 1, + summary_index: 0, + part: { type: "summary_text", text: "" }, + }, + { + type: "response.reasoning_summary_text.delta", + output_index: 1, + summary_index: 0, + delta: "think", + }, + { + type: "response.output_item.added", + output_index: 2, + item: { id: "f", type: "function_call", call_id: "call", name: "lookup", arguments: "" }, + }, + { type: "response.function_call_arguments.delta", output_index: 2, delta: '{"q":' }, + { type: "response.function_call_arguments.delta", output_index: 2, delta: '"x"}' }, + { type: "response.completed", usage: { input_tokens: 2, output_tokens: 4, total_tokens: 6 } }, + ]; + const body = await json(events.map((value) => event(value)).join(""), "responses"); + assert.equal(body.id, "resp-2"); + assert.equal(body.status, "completed"); + assert.equal(body.output[0].content[0].text, "hello world"); + assert.equal(body.output[1].summary[0].text, "think"); + assert.equal(body.output[2].arguments, '{"q":"x"}'); + assert.deepEqual(body.usage, { input_tokens: 2, output_tokens: 4, total_tokens: 6 }); +}); + +test("Responses done snapshots do not duplicate accumulated deltas", async () => { + const item = { + id: "f", + type: "function_call", + call_id: "call", + name: "lookup", + arguments: '{"a":1}', + status: "completed", + }; + const body = await json( + event({ + type: "response.output_item.added", + output_index: 0, + item: { ...item, arguments: "" }, + }) + + event({ type: "response.function_call_arguments.delta", output_index: 0, delta: '{"a":1}' }) + + event({ + type: "response.function_call_arguments.done", + output_index: 0, + arguments: '{"a":1}', + }) + + event({ type: "response.output_item.done", output_index: 0, item }) + + event({ type: "response.completed" }), + "responses", + ); + assert.deepEqual(body.output, [item]); +}); + +test("Anthropic preserves initial content, thinking, signatures, tool JSON, usage and stop reason", async () => { + const events = [ + { + type: "message_start", + message: { + id: "msg-1", + type: "message", + role: "assistant", + model: "zen", + content: [], + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: 11, output_tokens: 0, cache_read_input_tokens: 4 }, + }, + }, + { + type: "content_block_start", + index: 0, + content_block: { type: "thinking", thinking: "先", signature: "sig" }, + }, + { type: "content_block_delta", index: 0, delta: { type: "thinking_delta", thinking: "想" } }, + { + type: "content_block_delta", + index: 0, + delta: { type: "signature_delta", signature: "nature" }, + }, + { type: "content_block_stop", index: 0 }, + { type: "content_block_start", index: 1, content_block: { type: "text", text: "你" } }, + { type: "content_block_delta", index: 1, delta: { type: "text_delta", text: "好🙂" } }, + { + type: "content_block_start", + index: 2, + content_block: { type: "tool_use", id: "tool", name: "lookup", input: {} }, + }, + { + type: "content_block_delta", + index: 2, + delta: { type: "input_json_delta", partial_json: '{"q":' }, + }, + { + type: "content_block_delta", + index: 2, + delta: { type: "input_json_delta", partial_json: '"中文"}' }, + }, + { type: "content_block_stop", index: 2 }, + { + type: "content_block_start", + index: 3, + content_block: { type: "redacted_thinking", data: "opaque" }, + }, + { + type: "message_delta", + delta: { stop_reason: "tool_use", stop_sequence: "END" }, + usage: { output_tokens: 9 }, + }, + { type: "message_stop" }, + ]; + const body = await json(events.map((value) => event(value, value.type)).join(""), "anthropic", { + chunkSize: 1, + }); + assert.equal(body.id, "msg-1"); + assert.deepEqual(body.content, [ + { type: "thinking", thinking: "先想", signature: "signature" }, + { type: "text", text: "你好🙂" }, + { type: "tool_use", id: "tool", name: "lookup", input: { q: "中文" } }, + { type: "redacted_thinking", data: "opaque" }, + ]); + assert.deepEqual(body.usage, { input_tokens: 11, output_tokens: 9, cache_read_input_tokens: 4 }); + assert.equal(body.stop_reason, "tool_use"); + assert.equal(body.stop_sequence, "END"); +}); + +test("Anthropic retains complete tool input when there are no JSON deltas", async () => { + const body = await json( + event({ + type: "message_start", + message: { id: "m", content: [{ type: "text", text: "initial" }] }, + }) + + event({ + type: "content_block_start", + index: 1, + content_block: { type: "tool_use", id: "t", name: "f", input: { a: 1 } }, + }) + + event({ type: "message_stop" }), + "anthropic", + ); + assert.deepEqual(body.content[1].input, { a: 1 }); + assert.equal(body.content[0].text, "initial"); +}); + +for (const protocol of ["chat", "responses", "anthropic"]) { + test(`${protocol}: HTTP failures and non-SSE JSON return the same unread Response`, async () => { + const httpError = sse(event({ error: { message: "quota" } }), { status: 429 }); + assert.equal(await collapseResponse(httpError, protocol), httpError); + assert.equal(httpError.bodyUsed, false); + const plain = new Response('{"unchanged": true}', { + headers: { "content-type": "application/json", "content-length": "19" }, + }); + assert.equal(await collapseResponse(plain, protocol), plain); + assert.equal(plain.bodyUsed, false); + assert.equal(await plain.text(), '{"unchanged": true}'); + }); + + test(`${protocol}: empty and truncated SSE are 502 errors`, async () => { + await failure("", protocol, /complet|end|terminat/i); + await failure( + event({ choices: [{ index: 0, delta: { content: "partial" }, finish_reason: "stop" }] }), + protocol, + ); + if (protocol !== "chat") await failure(event("[DONE]"), protocol); + }); + + test(`${protocol}: error events and JSON errors are 502 errors`, async () => { + await failure(event({ error: { message: "quota exhausted" } }), protocol, /quota exhausted/); + await failure(event({ message: "upstream exploded" }, "error"), protocol, /upstream exploded/); + await failure(event("plain failure", "error"), protocol, /plain failure/); + await failure( + event({ type: "error", error: { type: "overloaded_error", message: "busy" } }), + protocol, + /busy/, + ); + await failure(event("{invalid json"), protocol, /JSON|invalid|malformed/i); + }); + + test(`${protocol}: open SSE errors cancel promptly and return 502`, async () => { + for (const text of [ + event({ message: "upstream exploded" }, "error"), + event("upstream exploded", "error"), + event({ error: { message: "upstream exploded" } }), + event({ type: "error", error: { message: "upstream exploded" } }), + ]) { + const response = await collapseOpenStream(text, protocol); + assert.equal(response.status, 502); + const body = await response.json(); + assert.equal(body.error.type, "upstream_error"); + assert.equal(body.error.message, "upstream exploded"); + if (protocol === "anthropic") assert.equal(body.type, "error"); + else { + assert.equal(body.error.param, null); + assert.equal(body.error.code, null); + } + } + }); + + test(`${protocol}: open SSE errors propagate cancellation failures`, async () => { + for (const asynchronous of [false, true]) { + const cause = new DOMException("cancel failed", "AbortError"); + let cancelled = false; + await assert.rejects( + collapseOpenStream(event("upstream exploded", "error"), protocol, () => { + cancelled = true; + if (asynchronous) return Promise.reject(cause); + throw cause; + }), + (error) => error === cause, + ); + assert.equal(cancelled, true); + } + }); + + test(`${protocol}: body read errors and aborts reject with the original exception`, async () => { + for (const cause of [new Error("read failed"), new DOMException("cancelled", "AbortError")]) { + let pulled = false; + const response = new Response( + new ReadableStream({ + pull(controller) { + if (pulled) return controller.error(cause); + pulled = true; + controller.enqueue(encoder.encode(": keepalive\n\n")); + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); + await assert.rejects(collapseResponse(response, protocol), (error) => error === cause); + } + }); +} + +test("protocol-specific finish reasons without terminal events remain truncated", async () => { + await failure( + event({ type: "response.created", response: { id: "r", output: [] } }) + + event({ type: "response.output_text.delta", output_index: 0, delta: "partial" }), + "responses", + /completion/, + ); + await failure( + event({ type: "message_start", message: { id: "m", content: [] } }) + + event({ type: "message_delta", delta: { stop_reason: "end_turn" } }), + "anthropic", + /completion/, + ); + await failure("data: [DONE]\n", "chat", /completion/); +}); + +test("upstream errors after terminal events are not successful responses", async () => { + for (const [protocol, terminal] of [ + ["chat", "[DONE]"], + ["responses", { type: "response.completed", response: { output: [] } }], + ["anthropic", { type: "message_stop" }], + ]) { + await failure( + event(terminal) + event({ error: { message: "late error" } }), + protocol, + /late error/, + ); + } +}); + +test("buffer-limit cancellation failures propagate instead of becoming JSON", async () => { + const cause = new DOMException("cancel failed", "AbortError"); + const chunk = new Uint8Array(1024 * 1024); + const response = new Response( + new ReadableStream({ + pull(controller) { + controller.enqueue(chunk); + }, + cancel() { + throw cause; + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); + await assert.rejects(collapseResponse(response, "chat"), (error) => error === cause); +}); + +test("Responses open SSE failed events cancel promptly and return 502", async () => { + const response = await collapseOpenStream( + event({ + type: "response.failed", + response: { status: "failed", error: { message: "model failed" } }, + }), + "responses", + ); + assert.equal(response.status, 502); + assert.equal((await response.json()).error.message, "model failed"); +}); + +test("Responses failed is an error even when a response object is present", async () => { + await failure( + event({ + type: "response.failed", + response: { id: "r", status: "failed", error: { message: "model failed" }, output: [] }, + }), + "responses", + /model failed/, + ); +}); + +test("Anthropic rejects malformed accumulated tool JSON", async () => { + await failure( + event({ + type: "content_block_start", + index: 0, + content_block: { type: "tool_use", input: {} }, + }) + + event({ + type: "content_block_delta", + index: 0, + delta: { type: "input_json_delta", partial_json: '{"unfinished":' }, + }) + + event({ type: "message_stop" }), + "anthropic", + /JSON|argument|input/i, + ); +}); + +test("success and error JSON remove stale entity headers and preserve retry metadata", async () => { + for (const text of [event("[DONE]"), event({ error: { message: "fail" } })]) { + const response = await collapseResponse( + sse(text, { + headers: { + "content-length": "999", + "content-encoding": "gzip", + "retry-after": "12", + "x-request-id": "req-1", + }, + }), + "chat", + ); + assert.equal(response.headers.get("content-type"), "application/json"); + assert.equal(response.headers.get("content-length"), null); + assert.equal(response.headers.get("content-encoding"), null); + assert.equal(response.headers.get("retry-after"), "12"); + assert.equal(response.headers.get("x-request-id"), "req-1"); + } +}); + +test("bounded buffering rejects oversized unterminated events and cancels the source", async () => { + let cancelled = false; + let pulls = 0; + const chunk = encoder.encode("x".repeat(1024 * 1024)); + const response = new Response( + new ReadableStream({ + pull(controller) { + pulls++; + controller.enqueue(chunk); + }, + cancel() { + cancelled = true; + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); + const result = await collapseResponse(response, "chat"); + assert.equal(result.status, 502); + assert.match((await result.json()).error.message, /limit|large|buffer/i); + assert.ok(pulls <= 35); + assert.equal(cancelled, true); +}); + +test("bounded buffering also counts many small completed events", async () => { + const chunk = encoder.encode( + event({ choices: [{ index: 0, delta: { content: "x".repeat(65536) } }] }), + ); + let cancelled = false; + const response = new Response( + new ReadableStream({ + pull(controller) { + controller.enqueue(chunk); + }, + cancel() { + cancelled = true; + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); + const result = await collapseResponse(response, "chat"); + assert.equal(result.status, 502); + assert.equal(cancelled, true); +}); + +test("read failures after a completion marker are not swallowed", async () => { + const cause = new Error("late transport failure"); + let sent = false; + const response = new Response( + new ReadableStream({ + pull(controller) { + if (sent) return controller.error(cause); + sent = true; + controller.enqueue(encoder.encode(event("[DONE]"))); + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); + await assert.rejects(collapseResponse(response, "chat"), (error) => error === cause); +}); diff --git a/packages/zen-free/tool-fixtures.mjs b/packages/zen-free/tool-fixtures.mjs new file mode 100644 index 0000000..10f2719 --- /dev/null +++ b/packages/zen-free/tool-fixtures.mjs @@ -0,0 +1,81 @@ +export const protocols = [ + { protocol: "chat", path: "chat/completions", model: "chat-free" }, + { protocol: "responses", path: "responses", model: "responses-free" }, + { protocol: "anthropic", path: "messages", model: "messages-free" }, +]; + +export function declaredTools(protocol) { + return ["Bash", "Read"].map((name) => { + const schema = { type: "object", properties: { command: { type: "string" } } }; + const tool = { name, description: `Client ${name}` }; + if (protocol === "chat") return { type: "function", function: { ...tool, parameters: schema } }; + if (protocol === "anthropic") return { ...tool, input_schema: schema }; + return { type: "function", ...tool, parameters: schema }; + }); +} + +export function toolReply(protocol, name, sse = true) { + const args = JSON.stringify({ command: "ls -la" }); + const event = (value) => `data: ${JSON.stringify(value)}\n\n`; + if (protocol === "chat") { + const tool = { id: "call_1", type: "function", function: { name, arguments: args } }; + if (!sse) + return JSON.stringify({ + choices: [ + { + index: 0, + message: { role: "assistant", content: null, tool_calls: [tool] }, + finish_reason: "tool_calls", + }, + ], + }); + return ( + event({ + id: "c1", + choices: [ + { index: 0, delta: { tool_calls: [{ index: 0, ...tool }] }, finish_reason: null }, + ], + }) + + event({ id: "c1", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] }) + + "data: [DONE]\n\n" + ); + } + if (protocol === "responses") { + const item = { + id: "fc1", + type: "function_call", + call_id: "call_1", + name, + arguments: args, + status: "completed", + }; + const response = { id: "r1", object: "response", status: "completed", output: [item] }; + if (!sse) return JSON.stringify(response); + return ( + event({ + type: "response.output_item.added", + output_index: 0, + item: { ...item, arguments: "", status: "in_progress" }, + }) + + event({ type: "response.output_item.done", output_index: 0, item }) + + event({ type: "response.completed", response }) + ); + } + const block = { type: "tool_use", id: "call_1", name, input: JSON.parse(args) }; + const message = { + id: "m1", + type: "message", + role: "assistant", + content: [block], + stop_reason: "tool_use", + usage: { input_tokens: 1, output_tokens: 2 }, + }; + if (!sse) return JSON.stringify(message); + return ( + event({ type: "message_start", message: { ...message, content: [], stop_reason: null } }) + + event({ type: "content_block_start", index: 0, content_block: block }) + + event({ type: "content_block_stop", index: 0 }) + + event({ type: "message_delta", delta: { stop_reason: "tool_use" } }) + + event({ type: "message_stop" }) + ); +} diff --git a/packages/zen-free/tool-response.mjs b/packages/zen-free/tool-response.mjs new file mode 100644 index 0000000..1a8c37d --- /dev/null +++ b/packages/zen-free/tool-response.mjs @@ -0,0 +1,542 @@ +const MAX_BYTES = 32 * 1024 * 1024; +const encoder = new TextEncoder(); + +class GuardError extends Error {} + +function headersFor(response) { + const headers = new Headers(response.headers); + headers.delete("content-length"); + headers.delete("content-encoding"); + return headers; +} + +function failure(protocol, message, stream = false) { + if (protocol === "anthropic") return { type: "error", error: { type: "api_error", message } }; + if (protocol === "responses") { + return stream + ? { type: "error", code: "undeclared_tool", message } + : { error: { type: "upstream_error", code: "undeclared_tool", message } }; + } + return { error: { message, type: "upstream_error" } }; +} + +function object(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function list(value) { + if (value == null) return []; + if (!Array.isArray(value)) throw new GuardError("Invalid upstream tool snapshot"); + return value; +} + +function nameGuard(policy) { + const declared = new Set(policy.declared); + const injected = new Set(policy.injected); + const folded = new Map(); + for (const name of declared) { + const key = name.toLowerCase(); + folded.set(key, folded.has(key) ? null : name); + } + return (name) => { + if (typeof name !== "string" || !name) throw new GuardError("Missing upstream tool name"); + if (declared.has(name)) return name; + const match = injected.has(name) && folded.get(name.toLowerCase()); + if (match) return match; + throw new GuardError("Upstream called a tool not declared by the client"); + }; +} + +function checkFunction(value, checkName) { + if (!object(value)) throw new GuardError("Invalid upstream function call"); + const name = checkName(value.name); + const changed = name !== value.name; + value.name = name; + return changed; +} + +function checkChatMessage(message, checkName) { + if (!object(message)) return false; + let changed = false; + if (message.function_call != null) changed = checkFunction(message.function_call, checkName); + for (const call of list(message.tool_calls)) { + if (!object(call) || (call.type != null && call.type !== "function")) { + throw new GuardError("Unsupported upstream tool call"); + } + changed = checkFunction(call.function, checkName) || changed; + } + return changed; +} + +function checkSnapshots(data, protocol, checkName) { + let changed = false; + if (protocol === "chat") { + for (const choice of list(data.choices)) { + if (!object(choice)) throw new GuardError("Invalid upstream choice"); + changed = checkChatMessage(choice.message, checkName) || changed; + } + return changed; + } + const stack = [data]; + while (stack.length) { + const value = stack.pop(); + if (!object(value)) throw new GuardError("Invalid upstream tool snapshot"); + if ( + protocol === "responses" && + typeof value.type === "string" && + value.type.endsWith("_call") && + value.type !== "function_call" + ) { + throw new GuardError("Unsupported upstream tool call type"); + } + if ( + (protocol === "responses" && value.type === "function_call") || + (protocol === "anthropic" && ["tool_use", "server_tool_use"].includes(value.type)) + ) { + changed = checkFunction(value, checkName) || changed; + } + const arrays = protocol === "responses" ? ["output", "content"] : ["content"]; + const objects = + protocol === "responses" ? ["response", "item", "part"] : ["message", "content_block"]; + for (const key of arrays) { + // Text content is not a snapshot container. + if (typeof value[key] === "string") continue; + for (const item of list(value[key])) stack.push(item); + } + for (const key of objects) { + if (value[key] != null) stack.push(value[key]); + } + } + return changed; +} + +function position(value) { + const result = value ?? 0; + if (!Number.isSafeInteger(result) || result < 0) + throw new GuardError("Invalid upstream tool index"); + return result; +} + +function appendFunction(target, fragment) { + if (!object(fragment)) throw new GuardError("Invalid upstream function delta"); + for (const [key, value] of Object.entries(fragment)) { + if (key === "name" || key === "arguments") { + if (typeof value !== "string") throw new GuardError("Invalid upstream function delta"); + target[key] = (target[key] ?? "") + value; + } else { + Object.defineProperty(target, key, { + value, + writable: true, + enumerable: true, + configurable: true, + }); + } + } +} + +function chatBuffer(checkName) { + const pending = new Map(); + let bytes = 0; + function charge(state, value) { + const size = encoder.encode(JSON.stringify(value)).byteLength; + bytes += size; + state.bytes += size; + if (bytes > MAX_BYTES) + throw new GuardError("Pending upstream tools exceed the 32 MiB buffer limit"); + } + function stateFor(index, data) { + if (!pending.has(index)) { + const metadata = {}; + for (const key of [ + "id", + "object", + "created", + "model", + "system_fingerprint", + "service_tier", + ]) { + if (data[key] !== undefined) metadata[key] = data[key]; + } + const state = { calls: new Map(), legacy: null, metadata, bytes: 0 }; + pending.set(index, state); + charge(state, metadata); + } + return pending.get(index); + } + function complete(state) { + const delta = {}; + if (state.calls.size) { + delta.tool_calls = [...state.calls].sort(([a], [b]) => a - b).map(([, value]) => value); + } + if (state.legacy) delta.function_call = state.legacy; + checkChatMessage(delta, checkName); + return delta; + } + function remove(index) { + const state = pending.get(index); + if (state) bytes -= state.bytes; + pending.delete(index); + } + return { + get size() { + return pending.size; + }, + clear() { + pending.clear(); + bytes = 0; + }, + apply(data) { + let changed = checkSnapshots(data, "chat", checkName); + const choices = list(data.choices); + for (const choice of choices) { + const delta = choice.delta; + if (!object(delta)) continue; + if (delta.tool_calls == null && delta.function_call == null) continue; + changed = true; + const state = stateFor(position(choice.index), data); + for (const fragment of list(delta.tool_calls)) { + if (!object(fragment) || (fragment.type != null && fragment.type !== "function")) { + throw new GuardError("Unsupported upstream tool delta"); + } + charge(state, fragment); + const index = position(fragment.index); + const previous = state.calls.get(index) ?? { index, function: {} }; + const value = { ...previous, ...fragment, index, function: previous.function }; + if (fragment.function != null) appendFunction(value.function, fragment.function); + state.calls.set(index, value); + } + if (delta.function_call != null) { + charge(state, delta.function_call); + state.legacy ??= {}; + appendFunction(state.legacy, delta.function_call); + } + delete delta.tool_calls; + delete delta.function_call; + } + // Validate every finishing choice before publishing any part of this event. + for (const choice of choices) { + if (choice.finish_reason == null) continue; + const index = position(choice.index); + const state = pending.get(index); + if (!state) continue; + choice.delta = { ...choice.delta, ...complete(state) }; + remove(index); + changed = true; + } + if (!changed) return { data, changed: false }; + data.choices = choices.filter( + (choice) => + choice.finish_reason != null || + Object.keys(choice.delta ?? {}).length || + Object.keys(choice).some((key) => !["index", "delta", "finish_reason"].includes(key)), + ); + return { data: data.choices.length || data.usage != null ? data : null, changed: true }; + }, + finish() { + if (!pending.size) return null; + const choices = [...pending] + .sort(([a], [b]) => a - b) + .map(([index, state]) => ({ index, delta: complete(state), finish_reason: null })); + const metadata = pending.values().next().value.metadata; + pending.clear(); + bytes = 0; + return { ...metadata, choices }; + }, + }; +} + +function parseJSON(text) { + let value; + try { + value = JSON.parse(text); + } catch { + throw new GuardError("Invalid JSON in upstream response"); + } + if (!object(value)) throw new GuardError("Invalid JSON object in upstream response"); + return value; +} + +function encodeEvent(data, name = "") { + return `${name ? `event: ${name}\n` : ""}data: ${JSON.stringify(data)}\n\n`; +} + +function rewrite(frame, data) { + const lines = frame.lines.filter((line) => line !== "data" && !line.startsWith("data:")); + lines.push(`data: ${JSON.stringify(data)}`); + return `${lines.join("\n")}\n\n`; +} + +async function* framesFrom(reader) { + let parts = []; + let lineBytes = 0; + let eventBytes = 0; + let lines = []; + let rawLines = []; + let skipLF = false; + let pendingFrame; + let firstLine = true; + const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + function append(value) { + eventBytes += value.byteLength; + if (eventBytes > MAX_BYTES) + throw new GuardError("Upstream SSE event exceeds the 32 MiB buffer limit"); + if (value.byteLength) { + parts.push(value); + lineBytes += value.byteLength; + } + } + while (true) { + const { done, value } = await reader.read(); + if (done) { + if (pendingFrame) { + yield pendingFrame; + pendingFrame = null; + eventBytes = 0; + } + if (eventBytes || lineBytes || lines.length) + throw new GuardError("Upstream SSE ended inside an event"); + return; + } + let start = 0; + if (skipLF && value.length) { + if (value[0] === 10) { + eventBytes++; + if (pendingFrame) pendingFrame.raw += "\n"; + else rawLines[rawLines.length - 1] += "\n"; + start = 1; + } + if (eventBytes > MAX_BYTES) + throw new GuardError("Upstream SSE event exceeds the 32 MiB buffer limit"); + skipLF = false; + if (pendingFrame) { + const frame = pendingFrame; + pendingFrame = null; + eventBytes = 0; + yield frame; + } + } + for (let offset = start; offset < value.length; offset++) { + if (value[offset] !== 10 && value[offset] !== 13) continue; + append(value.subarray(start, offset)); + if (++eventBytes > MAX_BYTES) + throw new GuardError("Upstream SSE event exceeds the 32 MiB buffer limit"); + const bytes = new Uint8Array(lineBytes); + let cursor = 0; + for (const part of parts) { + bytes.set(part, cursor); + cursor += part.length; + } + let line; + try { + line = decoder.decode(bytes); + } catch { + throw new GuardError("Invalid UTF-8 in upstream SSE event"); + } + parts = []; + lineBytes = 0; + let rawLine = line + String.fromCharCode(value[offset]); + if (firstLine) { + line = line.replace(/^\uFEFF/, ""); + firstLine = false; + } + if (value[offset] === 13) { + if (value[offset + 1] === 10) { + rawLine += "\n"; + offset++; + if (++eventBytes > MAX_BYTES) + throw new GuardError("Upstream SSE event exceeds the 32 MiB buffer limit"); + } else if (offset + 1 === value.length) skipLF = true; + } + start = offset + 1; + rawLines.push(rawLine); + if (line) { + lines.push(line); + } else { + const frameLines = lines; + lines = []; + let name = ""; + const data = []; + for (const item of frameLines) { + const colon = item.indexOf(":"); + const key = colon < 0 ? item : item.slice(0, colon); + let content = colon < 0 ? "" : item.slice(colon + 1); + if (content.startsWith(" ")) content = content.slice(1); + if (key === "event") name = content; + if (key === "data") data.push(content); + } + const frame = { + lines: frameLines, + name, + text: data.join("\n"), + raw: rawLines.join(""), + }; + rawLines = []; + if (skipLF) { + // Preserve a trailing CRLF even when its LF arrives in the next chunk. + pendingFrame = frame; + } else { + eventBytes = 0; + yield frame; + } + } + } + append(value.subarray(start)); + } +} + +function guardedStream(response, protocol, checkName) { + const reader = response.body?.getReader(); + const chat = protocol === "chat" ? chatBuffer(checkName) : null; + let frames = reader ? framesFrom(reader) : null; + let completed = false; + let stopped = false; + let released = false; + let cancellation; + function release() { + if (reader && !released) { + reader.releaseLock(); + released = true; + } + chat?.clear(); + frames = null; + } + function cancel(reason) { + cancellation ??= (async () => { + try { + await reader?.cancel(reason); + } finally { + release(); + } + })(); + return cancellation; + } + return new ReadableStream( + { + async pull(controller) { + try { + while (!stopped) { + const next = frames ? await frames.next() : { done: true }; + if (stopped) return; + if (next.done) { + if (!completed || chat?.size) + throw new GuardError("Upstream SSE ended without a completion marker"); + stopped = true; + release(); + controller.close(); + return; + } + const frame = next.value; + if (frame.name !== "error" && !frame.text.trim()) { + controller.enqueue(encoder.encode(frame.raw)); + return; + } + if (frame.name !== "error" && frame.text.trim() === "[DONE]") { + if (protocol !== "chat") + throw new GuardError("Unexpected upstream completion marker"); + const final = chat.finish(); + completed = true; + controller.enqueue(encoder.encode((final ? encodeEvent(final) : "") + frame.raw)); + return; + } + const data = frame.name === "error" ? null : parseJSON(frame.text); + const type = data?.type ?? frame.name; + if ( + frame.name === "error" || + type === "error" || + data?.error || + type === "response.failed" || + data?.response?.status === "failed" + ) { + stopped = true; + try { + await cancel(); + } catch (cause) { + controller.error(cause); + return; + } + controller.enqueue(encoder.encode(frame.raw)); + controller.close(); + return; + } + let changed; + let result = data; + if (chat) { + const checked = chat.apply(data); + changed = checked.changed; + result = checked.data; + } else { + changed = checkSnapshots(data, protocol, checkName); + } + if ( + (protocol === "responses" && + ["response.completed", "response.incomplete"].includes(type)) || + (protocol === "anthropic" && type === "message_stop") + ) + completed = true; + if (result) { + controller.enqueue(encoder.encode(changed ? rewrite(frame, result) : frame.raw)); + return; + } + } + } catch (error) { + if (stopped) return; + stopped = true; + if (error instanceof GuardError) { + try { + await cancel(error); + } catch (cause) { + controller.error(cause); + return; + } + controller.enqueue( + encoder.encode( + encodeEvent( + failure(protocol, error.message, true), + protocol === "chat" ? "" : "error", + ), + ), + ); + controller.close(); + } else { + release(); + controller.error(error); + } + } + }, + async cancel(reason) { + stopped = true; + await cancel(reason); + }, + }, + { highWaterMark: 0 }, + ); +} + +export async function guardToolResponse(response, protocol, policy) { + if (!response.ok) return response; + if (!["chat", "responses", "anthropic"].includes(protocol)) + throw new TypeError(`Unsupported protocol: ${protocol}`); + const checkName = nameGuard(policy); + const headers = headersFor(response); + const contentType = response.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase(); + if (contentType === "text/event-stream") { + return new Response(guardedStream(response, protocol, checkName), { + status: response.status, + statusText: response.statusText, + headers, + }); + } + const text = await response.text(); + let value; + let status = response.status; + try { + value = parseJSON(text); + checkSnapshots(value, protocol, checkName); + } catch (error) { + if (!(error instanceof GuardError)) throw error; + status = 502; + value = failure(protocol, error.message); + } + headers.set("content-type", "application/json"); + return new Response(JSON.stringify(value), { status, headers }); +} diff --git a/packages/zen-free/tool-response.test.mjs b/packages/zen-free/tool-response.test.mjs new file mode 100644 index 0000000..98e9457 --- /dev/null +++ b/packages/zen-free/tool-response.test.mjs @@ -0,0 +1,857 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { guardToolResponse } from "./tool-response.mjs"; + +const encoder = new TextEncoder(); + +for (const type of [ + "custom_tool_call", + "computer_call", + "local_shell_call", + "shell_call", + "mcp_call", + "apply_patch_call", +]) { + test(`Responses rejects unsupported ${type} in JSON and streaming snapshots`, async () => { + const item = { type, name: "undeclared_command", call_id: "call1", input: "run" }; + const json = await guardToolResponse(Response.json({ output: [item] }), "responses", policy); + assert.equal(json.status, 502); + assertError("responses", await json.json(), false); + for (const data of [ + { type: "response.output_item.added", item }, + { type: "response.output_item.done", item }, + { type: "response.completed", response: { output: [item] } }, + ]) { + const response = await guardToolResponse( + sse(event(data) + terminal("responses")), + "responses", + policy, + ); + const text = await response.text(); + assert.doesNotMatch(text, /undeclared_command/); + assertError("responses", parse(text)[0].data); + } + }); +} +const policy = { + declared: new Set(["Bash", "Read"]), + injected: new Set(["bash", "read", "shell"]), +}; +const protocols = ["chat", "responses", "anthropic"]; +const event = (data, name) => + `${name ? `event: ${name}\n` : ""}data: ${typeof data === "string" ? data : JSON.stringify(data)}\n\n`; +const terminal = (protocol) => + event( + protocol === "chat" + ? "[DONE]" + : { type: protocol === "responses" ? "response.completed" : "message_stop" }, + ); +const chat = (delta, finish_reason = null, index = 0) => ({ + choices: [{ index, delta, finish_reason }], +}); +const call = (name, index = 0, args = "{}") => ({ + index, + id: `call-${index}`, + type: "function", + function: { name, arguments: args }, +}); +const tool = (protocol, name) => + protocol === "chat" + ? call(name) + : protocol === "responses" + ? { type: "function_call", name, call_id: "call", arguments: "{}" } + : { type: "tool_use", name, id: "call", input: {} }; +function snapshot(protocol, names) { + const tools = names.map((name) => tool(protocol, name)); + if (protocol === "chat") + return { choices: [{ message: { role: "assistant", tool_calls: tools } }] }; + return protocol === "responses" ? { output: tools } : { type: "message", content: tools }; +} +function streamSnapshot(protocol, names) { + if (protocol === "chat") + return chat({ tool_calls: names.map((name, index) => call(name, index)) }, "tool_calls"); + if (protocol === "responses") + return { type: "response.completed", response: snapshot(protocol, names) }; + return { type: "message_start", message: snapshot(protocol, names) }; +} +function namesIn(protocol, data) { + if (protocol === "chat") + return data.choices + .flatMap((choice) => (choice.message ?? choice.delta)?.tool_calls ?? []) + .map((value) => value.function.name); + return ( + protocol === "responses" ? (data.response ?? data).output : (data.message ?? data).content + ).map((value) => value.name); +} +function sse(text, { chunkSize = 31, headers = {}, status = 200 } = {}) { + const bytes = encoder.encode(text); + let offset = 0; + return new Response( + new ReadableStream({ + pull(controller) { + if (offset === bytes.length) return controller.close(); + const end = Math.min(offset + chunkSize, bytes.length); + controller.enqueue(bytes.slice(offset, end)); + offset = end; + }, + }), + { status, headers: { "content-type": "text/event-stream", ...headers } }, + ); +} +function parse(text) { + return text + .replace(/^\uFEFF/, "") + .split(/\r\n\r\n|\n\n|\r\r/) + .filter(Boolean) + .map((frame) => { + const lines = frame.split(/\r\n|\r|\n/); + const data = lines + .filter((line) => line.startsWith("data:")) + .map((line) => line.slice(5).replace(/^ /, "")) + .join("\n"); + return { + name: lines + .find((line) => line.startsWith("event:")) + ?.slice(6) + .trim(), + data: !data || data === "[DONE]" ? data : JSON.parse(data), + }; + }); +} +function assertError(protocol, data, stream = true) { + if (protocol === "chat") assert.equal(data.error.type, "upstream_error"); + if (protocol === "responses") { + if (stream) { + assert.equal(data.type, "error"); + assert.equal(data.code, "undeclared_tool"); + } else { + assert.equal(data.error.type, "upstream_error"); + assert.equal(data.error.code, "undeclared_tool"); + } + } + if (protocol === "anthropic") { + assert.equal(data.type, "error"); + assert.equal(data.error.type, "api_error"); + } + assert.equal(typeof (data.message ?? data.error?.message), "string"); +} +async function withTimeout(promise) { + let timer; + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error("stream waited for EOF")), 1500); + }), + ]); + } finally { + clearTimeout(timer); + } +} +function openSource(text, cancel = () => {}) { + let controller; + let pulls = 0; + const response = new Response( + new ReadableStream( + { + start(value) { + controller = value; + }, + pull(value) { + pulls++; + if (pulls === 1) value.enqueue(encoder.encode(text)); + }, + cancel, + }, + { highWaterMark: 0 }, + ), + { headers: { "content-type": "text/event-stream" } }, + ); + return { + response, + push: (value) => controller.enqueue(encoder.encode(value)), + close: () => controller.close(), + pulls: () => pulls, + }; +} + +for (const protocol of protocols) { + test(`${protocol}: JSON maps injected casing and retains declared names`, async () => { + for (const names of [ + ["bash", "read"], + ["Bash", "Read"], + ]) { + const result = await guardToolResponse( + Response.json(snapshot(protocol, names)), + protocol, + policy, + ); + assert.equal(result.status, 200); + assert.deepEqual(namesIn(protocol, await result.json()), ["Bash", "Read"]); + } + }); + + test(`${protocol}: JSON refuses unknown, non-injected, ambiguous and semantic aliases atomically`, async () => { + for (const [name, rules] of [ + ["unknown", policy], + ["shell", policy], + ["BASH", policy], + ["bash", { declared: new Set(["Bash", "BASH"]), injected: new Set(["bash"]) }], + ["bash", { declared: new Set(), injected: new Set(["bash"]) }], + ]) { + const response = await guardToolResponse( + Response.json(snapshot(protocol, ["Read", name])), + protocol, + rules, + ); + assert.equal(response.status, 502); + const body = await response.json(); + assertError(protocol, body, false); + assert.equal(body.choices ?? body.output ?? body.content, undefined); + } + }); + + test(`${protocol}: exact matches win over ambiguous casing`, async () => { + const rules = { declared: new Set(["bash", "Bash"]), injected: new Set(["bash"]) }; + const result = await guardToolResponse( + Response.json(snapshot(protocol, ["bash"])), + protocol, + rules, + ); + assert.deepEqual(namesIn(protocol, await result.json()), ["bash"]); + }); + + test(`${protocol}: SSE maps injected casing and retains declared names`, async () => { + for (const names of [ + ["bash", "read"], + ["Bash", "Read"], + ]) { + const result = await guardToolResponse( + sse(event(streamSnapshot(protocol, names)) + terminal(protocol)), + protocol, + policy, + ); + assert.equal(result.status, 200); + const frames = parse(await result.text()).filter( + (frame) => frame.data && frame.data !== "[DONE]", + ); + const tools = frames.find( + (frame) => + protocol !== "chat" || frame.data.choices?.some((choice) => choice.delta?.tool_calls), + ); + assert.deepEqual(namesIn(protocol, tools.data), ["Bash", "Read"]); + assert.ok(!frames.some((frame) => frame.name === "error" || frame.data.error)); + } + }); + + test(`${protocol}: bad mixed SSE snapshot never leaks a tool and cancels immediately`, async () => { + for (const name of ["unknown", "shell", "BASH"]) { + let cancelled = false; + const source = openSource( + event(streamSnapshot(protocol, ["Read", name])) + event({ sentinel: "must not escape" }), + () => { + cancelled = true; + }, + ); + const result = await guardToolResponse(source.response, protocol, policy); + const frames = parse(await withTimeout(result.text())); + assert.equal(frames.length, 1); + assertError(protocol, frames[0].data); + if (protocol !== "chat") assert.equal(frames[0].name, "error"); + assert.equal(cancelled, true); + assert.equal(source.response.body.locked, false); + } + }); + + test(`${protocol}: upstream SSE errors pass through byte-for-byte and cancel open streams`, async () => { + const errors = + protocol === "responses" + ? [ + { + type: "response.failed", + response: { + status: "failed", + error: { code: "rate_limit_exceeded", message: "slow down 中文🙂" }, + }, + }, + { type: "error", code: "rate_limit_exceeded", message: "slow down 中文🙂" }, + { response: { status: "failed", error: { code: "server_error", message: "failed" } } }, + ] + : protocol === "anthropic" + ? [{ type: "error", error: { type: "overloaded_error", message: "busy 中文🙂" } }] + : [ + { + error: { + code: "rate_limit_exceeded", + type: "rate_limit_error", + message: "slow down 中文🙂", + param: null, + }, + }, + ]; + const rawFrames = errors.map( + (data) => + `\uFEFF: upstream\r\nid: err-7\r\nretry: 200\r\ndata: {\r\ndata: ${JSON.stringify(data).slice(1)}\r\n\r\n`, + ); + if (protocol === "responses") { + rawFrames.push( + event({ response: { error: { code: "rate_limit_exceeded" } } }, "response.failed"), + ); + } + rawFrames.push( + '\uFEFFevent:error\r\ndata: not JSON 中文🙂\r\ndata: second line\r\n\r\n', + 'event: error\ndata: {broken\n\n', + 'event: error\ndata: [DONE]\n\n', + 'event: error\n\n', + ); + for (const raw of rawFrames) { + for (const newline of ["\r\n", "\n", "\r"]) { + const text = raw.replace(/\r\n|\n/g, newline); + const bytes = encoder.encode(text); + for (const chunkSize of [1, 2, 7, bytes.length - 1, bytes.length + 1024]) { + let offset = 0; + let pulls = 0; + let cancellations = 0; + const trailing = encoder.encode(event(streamSnapshot(protocol, ["unknown"]))); + const all = new Uint8Array(bytes.length + trailing.length); + all.set(bytes); + all.set(trailing, bytes.length); + const source = new Response( + new ReadableStream( + { + pull(controller) { + pulls++; + if (offset === all.length) return; + const end = Math.min(offset + chunkSize, all.length); + controller.enqueue(all.slice(offset, end)); + offset = end; + }, + cancel() { + cancellations++; + }, + }, + { highWaterMark: 0 }, + ), + { headers: { "content-type": "text/event-stream" } }, + ); + const result = await guardToolResponse(source, protocol, policy); + const actual = new Uint8Array(await withTimeout(result.arrayBuffer())); + assert.deepEqual(actual, bytes); + assert.equal(cancellations, 1); + assert.equal(source.body.locked, false); + const lookahead = newline === "\r" && bytes.length % chunkSize === 0 ? 1 : 0; + assert.equal(pulls, Math.ceil(bytes.length / chunkSize) + lookahead); + } + if (newline === "\r") continue; + let cancelled = false; + const source = openSource(text, () => { + cancelled = true; + }); + const result = await guardToolResponse(source.response, protocol, policy); + assert.deepEqual(new Uint8Array(await withTimeout(result.arrayBuffer())), bytes); + assert.equal(cancelled, true); + assert.equal(source.pulls(), 1); + } + } + }); + + test(`${protocol}: upstream SSE errors preserve cancellation failures`, async () => { + for (const asynchronous of [false, true]) { + const cause = new DOMException("cancel failed", "AbortError"); + const source = openSource(event("not JSON", "error"), () => { + if (asynchronous) return Promise.reject(cause); + throw cause; + }); + const result = await guardToolResponse(source.response, protocol, policy); + await assert.rejects(withTimeout(result.arrayBuffer()), (error) => error === cause); + assert.equal(source.response.body.locked, false); + assert.equal(source.pulls(), 1); + } + }); + + test(`${protocol}: HTTP failures return the original unread response`, async () => { + const source = sse(event(streamSnapshot(protocol, ["unknown"])), { status: 429 }); + assert.equal(await guardToolResponse(source, protocol, policy), source); + assert.equal(source.bodyUsed, false); + }); + + test(`${protocol}: JSON and SSE remove stale entity headers, retain request metadata`, async () => { + const headers = { "content-length": "42", "content-encoding": "gzip", "x-request-id": "req" }; + for (const source of [ + Response.json(snapshot(protocol, ["bash"]), { headers }), + sse(event(streamSnapshot(protocol, ["bash"])) + terminal(protocol), { headers }), + ]) { + const result = await guardToolResponse(source, protocol, policy); + assert.equal(result.headers.get("content-length"), null); + assert.equal(result.headers.get("content-encoding"), null); + assert.equal(result.headers.get("x-request-id"), "req"); + await result.text(); + } + }); + + test(`${protocol}: truncated streams emit a protocol error`, async () => { + for (const text of ["", event({ harmless: true }), 'data: {"unfinished":']) { + const result = await guardToolResponse(sse(text), protocol, policy); + assertError(protocol, parse(await result.text()).at(-1).data); + } + }); + + test(`${protocol}: downstream cancellation propagates its reason without pre-reading`, async () => { + const reason = new Error("client stopped"); + let received; + const source = openSource(event({ harmless: true }), (value) => { + received = value; + }); + const result = await guardToolResponse(source.response, protocol, policy); + assert.equal(source.pulls(), 0); + await result.body.cancel(reason); + assert.equal(received, reason); + assert.equal(source.pulls(), 0); + assert.equal(source.response.body.locked, false); + }); + + test(`${protocol}: transport read failures preserve the original exception`, async () => { + const cause = new DOMException("upstream aborted", "AbortError"); + const source = new Response( + new ReadableStream({ + pull(controller) { + controller.error(cause); + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); + const result = await guardToolResponse(source, protocol, policy); + await assert.rejects(result.text(), (error) => error === cause); + assert.equal(source.body.locked, false); + }); + + test(`${protocol}: cancel failures propagate rather than being swallowed`, async () => { + const cause = new Error("cancel failed"); + for (const badTool of [false, true]) { + const source = openSource(event(streamSnapshot(protocol, ["unknown"])), () => { + throw cause; + }); + const result = await guardToolResponse(source.response, protocol, policy); + await assert.rejects( + badTool ? result.text() : result.body.cancel("stop"), + (error) => error === cause, + ); + assert.equal(source.response.body.locked, false); + } + }); + + test(`${protocol}: malformed JSON is a protocol-shaped 502`, async () => { + const result = await guardToolResponse( + new Response("{broken", { headers: { "content-type": "application/json" } }), + protocol, + policy, + ); + assert.equal(result.status, 502); + assertError(protocol, await result.json(), false); + }); +} + +test("chat: JSON checks every choice, legacy function_call and missing tool names", async () => { + const result = await guardToolResponse( + Response.json({ choices: [{ message: { function_call: { name: "read", arguments: "{}" } } }] }), + "chat", + policy, + ); + assert.equal((await result.json()).choices[0].message.function_call.name, "Read"); + for (const message of [ + { function_call: { name: "unknown" } }, + { tool_calls: [{ type: "function", function: {} }] }, + { tool_calls: [{ type: "custom", custom: { name: "unknown" } }] }, + ]) { + const source = Response.json({ choices: [{ message: { content: "ok" } }, { message }] }); + assert.equal((await guardToolResponse(source, "chat", policy)).status, 502); + } +}); + +test("Responses: nested JSON responses and all streaming snapshots are checked", async () => { + const nested = await guardToolResponse( + Response.json({ response: { response: snapshot("responses", ["bash"]) } }), + "responses", + policy, + ); + assert.equal((await nested.json()).response.response.output[0].name, "Bash"); + for (const type of [ + "response.output_item.added", + "response.output_item.done", + "response.created", + "response.in_progress", + "response.completed", + "response.incomplete", + "vendor.snapshot", + ]) { + for (const name of ["read", "unknown"]) { + const data = type.includes("output_item") + ? { type, item: tool("responses", name) } + : { type, response: snapshot("responses", [name]) }; + const result = await guardToolResponse( + sse(event(data, type) + terminal("responses")), + "responses", + policy, + ); + const frames = parse(await result.text()); + if (name === "unknown") { + assert.equal(frames.length, 1); + assertError("responses", frames[0].data); + } else + assert.equal(frames[0].data.item?.name ?? frames[0].data.response.output[0].name, "Read"); + } + } +}); + +test("Anthropic: content_block_start, message_start and server_tool_use are guarded", async () => { + for (const type of ["tool_use", "server_tool_use"]) { + for (const name of ["bash", "unknown"]) { + const block = { type, name, id: "t", input: {} }; + const json = await guardToolResponse( + Response.json({ content: [block] }), + "anthropic", + policy, + ); + assert.equal(json.status, name === "bash" ? 200 : 502); + for (const data of [ + { type: "content_block_start", index: 0, content_block: block }, + { type: "message_start", message: { content: [block] } }, + ]) { + const response = await guardToolResponse( + sse(event(data) + terminal("anthropic")), + "anthropic", + policy, + ); + const frames = parse(await response.text()); + if (name === "unknown") { + assert.equal(frames.length, 1); + assertError("anthropic", frames[0].data); + } else + assert.equal( + frames[0].data.content_block?.name ?? frames[0].data.message.content[0].name, + "Bash", + ); + } + } + } +}); + +test("chat: buffers names and arguments by choice/index, including arguments before name", async () => { + const values = [ + chat({ + tool_calls: [ + { index: 1, function: { arguments: '{"x":' } }, + { index: 0, id: "first", type: "function", function: { name: "ba", arguments: "{}" } }, + ], + }), + chat({ tool_calls: [{ index: 0, function: { name: "re", arguments: "{}" } }] }, null, 1), + chat({ + content: "你好", + tool_calls: [ + { index: 1, id: "second", type: "function", function: { name: "re", arguments: "1}" } }, + { index: 0, function: { name: "sh" } }, + ], + }), + chat({ tool_calls: [{ index: 0, function: { name: "ad" } }] }, "tool_calls", 1), + chat({ tool_calls: [{ index: 1, function: { name: "ad" } }] }, "tool_calls"), + ]; + const result = await guardToolResponse( + sse(values.map((value) => event(value)).join("") + terminal("chat"), { chunkSize: 1 }), + "chat", + policy, + ); + const choices = parse(await result.text()).flatMap((frame) => frame.data.choices ?? []); + const toolChoices = choices.filter((choice) => choice.delta?.tool_calls); + assert.equal(toolChoices.length, 2); + assert.deepEqual(toolChoices.find((choice) => choice.index === 0).delta.tool_calls, [ + { index: 0, id: "first", type: "function", function: { name: "Bash", arguments: "{}" } }, + { index: 1, id: "second", type: "function", function: { name: "Read", arguments: '{"x":1}' } }, + ]); + assert.equal( + toolChoices.find((choice) => choice.index === 1).delta.tool_calls[0].function.name, + "Read", + ); + assert.equal( + choices + .filter((choice) => choice.delta?.content) + .map((choice) => choice.delta.content) + .join(""), + "你好", + ); +}); + +test("chat: legacy fragments flush at DONE, but truncated pending calls never escape", async () => { + const prefix = + event(chat({ function_call: { arguments: "{}" } })) + + event(chat({ function_call: { name: "ba" } })) + + event(chat({ function_call: { name: "sh" } })); + const success = await guardToolResponse(sse(prefix + terminal("chat")), "chat", policy); + const frames = parse(await success.text()); + const calls = frames + .flatMap((frame) => frame.data.choices ?? []) + .filter((choice) => choice.delta?.function_call); + assert.deepEqual( + calls.map((choice) => choice.delta.function_call), + [{ name: "Bash", arguments: "{}" }], + ); + const failure = await guardToolResponse(sse(prefix), "chat", policy); + const failed = parse(await failure.text()); + assert.equal(failed.length, 1); + assertError("chat", failed[0].data); +}); + +test("chat: text and usage flow immediately while tools wait, without reading the conversation", async () => { + let cancelled = false; + const text = event(chat({ content: "first", tool_calls: [call("ba")] })); + const source = openSource(text, () => { + cancelled = true; + }); + const result = await guardToolResponse(source.response, "chat", policy); + const reader = result.body.getReader(); + const first = await withTimeout(reader.read()); + const firstData = parse(new TextDecoder().decode(first.value))[0].data; + assert.equal(firstData.choices[0].delta.content, "first"); + assert.equal(firstData.choices[0].delta.tool_calls, undefined); + assert.equal(source.pulls(), 1); + source.push(event({ choices: [], usage: { total_tokens: 12 } })); + const usage = await withTimeout(reader.read()); + assert.equal(parse(new TextDecoder().decode(usage.value))[0].data.usage.total_tokens, 12); + await reader.cancel("enough"); + assert.equal(cancelled, true); +}); + +test("chat: one chunk containing many text events still obeys downstream backpressure", async () => { + let cancelled = false; + const source = openSource( + event(chat({ content: "one" })) + + event(chat({ content: "two" })) + + event(chat({ tool_calls: [call("unknown")] }, "tool_calls")), + () => { + cancelled = true; + }, + ); + const result = await guardToolResponse(source.response, "chat", policy); + const reader = result.body.getReader(); + assert.equal( + parse(new TextDecoder().decode((await reader.read()).value))[0].data.choices[0].delta.content, + "one", + ); + assert.equal(cancelled, false); + assert.equal( + parse(new TextDecoder().decode((await reader.read()).value))[0].data.choices[0].delta.content, + "two", + ); + assert.equal(cancelled, false); + assertError("chat", parse(new TextDecoder().decode((await reader.read()).value))[0].data); + assert.equal(cancelled, true); +}); + +test("SSE handles UTF8, BOM, CRLF, CR-only, multiline data and arbitrary chunks", async () => { + const raw = + '\uFEFF: ping\r\nid: 7\r\nevent: message\r\ndata: {"choices":\r\ndata: [{"index":0,"delta":{"content":"中文🙂"},"finish_reason":"stop"}]}\r\n\r\ndata: [DONE]\r\n\r\n'; + for (const text of [raw, raw.replaceAll("\r\n", "\r"), raw.replaceAll("\r\n", "\n")]) { + for (const chunkSize of [1, 2, 3, 7, 1024]) { + const result = await guardToolResponse(sse(text, { chunkSize }), "chat", policy); + const frames = parse(await result.text()); + assert.equal(frames[0].data.choices[0].delta.content, "中文🙂"); + assert.equal(frames[1].data, "[DONE]"); + } + } +}); + +test("ordinary events retain SSE metadata without buffering", async () => { + for (const protocol of protocols) { + const text = ': keepalive\nid: 8\nretry: 200\nevent: vendor.text\ndata: {"text":"hello"}\n\n'; + const source = openSource(text); + const result = await guardToolResponse(source.response, protocol, policy); + const reader = result.body.getReader(); + assert.equal(new TextDecoder().decode((await withTimeout(reader.read())).value), text); + await reader.cancel(); + } +}); + +test("single SSE event limit is 32 MiB and cancels an unterminated upstream", async () => { + let cancelled = false; + let pulls = 0; + const bytes = encoder.encode("x".repeat(1024 * 1024)); + const source = new Response( + new ReadableStream( + { + pull(controller) { + pulls++; + controller.enqueue(bytes); + }, + cancel() { + cancelled = true; + }, + }, + { highWaterMark: 0 }, + ), + { headers: { "content-type": "text/event-stream" } }, + ); + const result = await guardToolResponse(source, "chat", policy); + const frames = parse(await result.text()); + assertError("chat", frames[0].data); + assert.match(frames[0].data.error.message, /32 MiB|limit/i); + assert.equal(cancelled, true); + assert.ok(pulls <= 33); +}); + +test("cumulative pending chat tools are limited across choices and calls", async () => { + let cancelled = false; + let pulls = 0; + const argumentsChunk = "x".repeat(1024 * 1024); + const source = new Response( + new ReadableStream( + { + pull(controller) { + controller.enqueue( + encoder.encode( + event(chat({ tool_calls: [call("bash", pulls, argumentsChunk)] }, null, pulls++ % 2)), + ), + ); + }, + cancel() { + cancelled = true; + }, + }, + { highWaterMark: 0 }, + ), + { headers: { "content-type": "text/event-stream" } }, + ); + const result = await guardToolResponse(source, "chat", policy); + const frames = parse(await result.text()); + assert.equal(frames.length, 1); + assertError("chat", frames[0].data); + assert.match(frames[0].data.error.message, /32 MiB|limit/i); + assert.equal(cancelled, true); + assert.ok(pulls <= 33); +}); + +test("chat: DONE validates all pending choices atomically and rejects missing final names", async () => { + for (const ending of [ + terminal("chat"), + event({ + choices: [ + { index: 0, delta: {}, finish_reason: "tool_calls" }, + { index: 1, delta: {}, finish_reason: "tool_calls" }, + ], + }), + ]) { + for (const name of ["unknown", ""]) { + const text = + event(chat({ tool_calls: [call("bash")] })) + + event(chat({ tool_calls: [call(name)] }, null, 1)) + + ending; + const response = await guardToolResponse(sse(text), "chat", policy); + const frames = parse(await response.text()); + assert.equal(frames.length, 1); + assertError("chat", frames[0].data); + } + } +}); + +test("SSE: ambiguous injected names fail in every protocol", async () => { + const rules = { declared: new Set(["Bash", "BASH"]), injected: new Set(["bash"]) }; + for (const protocol of protocols) { + const response = await guardToolResponse( + sse(event(streamSnapshot(protocol, ["bash"])) + terminal(protocol)), + protocol, + rules, + ); + const frames = parse(await response.text()); + assert.equal(frames.length, 1); + assertError(protocol, frames[0].data); + } +}); + +test("downstream cancellation interrupts a pending upstream read", async () => { + for (const protocol of protocols) { + let cancelReason; + const source = openSource(event({ harmless: true }), (reason) => { + cancelReason = reason; + }); + const response = await guardToolResponse(source.response, protocol, policy); + const reader = response.body.getReader(); + await reader.read(); + const waiting = reader.read(); + await Promise.resolve(); + await withTimeout(reader.cancel("abort now")); + assert.equal((await withTimeout(waiting)).done, true); + assert.equal(cancelReason, "abort now"); + assert.equal(source.response.body.locked, false); + } +}); + +test("chat: completed tool buffers release their cumulative budget", async () => { + let count = 0; + const bytes = encoder.encode( + event(chat({ tool_calls: [call("bash", 0, "x".repeat(1024 * 1024))] }, "tool_calls")), + ); + const source = new Response( + new ReadableStream({ + pull(controller) { + if (count < 34) { + count++; + return controller.enqueue(bytes); + } + if (count++ === 34) return controller.enqueue(encoder.encode(terminal("chat"))); + controller.close(); + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); + const response = await guardToolResponse(source, "chat", policy); + const reader = response.body.getReader(); + let tools = 0; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + const data = parse(new TextDecoder().decode(value))[0].data; + if (data === "[DONE]") continue; + assert.equal(data.choices[0].delta.tool_calls[0].function.name, "Bash"); + tools++; + } + assert.equal(tools, 34); +}); + +test("SSE event byte limit includes both bytes of CRLF even across chunks", async () => { + const prefix = 'data: {"text":"'; + const suffix = '"}\r\n\r\n'; + const text = prefix + "x".repeat(32 * 1024 * 1024 + 1 - prefix.length - suffix.length) + suffix; + for (const chunkSize of [1024 * 1024, text.length - 1]) { + const result = await guardToolResponse(sse(text, { chunkSize }), "chat", policy); + const frames = parse(await result.text()); + assert.equal(frames.length, 1); + assertError("chat", frames[0].data); + assert.match(frames[0].data.error.message, /32 MiB|limit/i); + } +}); + +test("text streams larger than 32 MiB are not subject to the pending-tool limit", async () => { + let count = 0; + const bytes = encoder.encode(event(chat({ content: "x".repeat(1024 * 1024) }))); + const source = new Response( + new ReadableStream({ + pull(controller) { + if (count < 34) { + count++; + return controller.enqueue(bytes); + } + if (count++ === 34) return controller.enqueue(encoder.encode(terminal("chat"))); + controller.close(); + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); + const result = await guardToolResponse(source, "chat", policy); + const reader = result.body.getReader(); + let total = 0; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + assert.ok(!new TextDecoder().decode(value).includes('"error"')); + } + assert.ok(total > 32 * 1024 * 1024); +}); diff --git a/packages/zen-free/tools-smoke.mjs b/packages/zen-free/tools-smoke.mjs new file mode 100644 index 0000000..ab76939 --- /dev/null +++ b/packages/zen-free/tools-smoke.mjs @@ -0,0 +1,81 @@ +import { ZenFreePlugin } from "./index.mjs"; +import { collapseResponse } from "./stream.mjs"; + +const hooks = await ZenFreePlugin({ project: { id: "magpie" } }); +const auth = { type: "api", key: "public" }; +const models = await hooks.provider.models({ models: {} }, { auth }); +const loader = await hooks.auth.loader(async () => auth); +const names = ["Bash", "Read"]; +const schema = { + type: "object", + properties: { command: { type: "string" } }, + required: ["command"], +}; +for (const [id, stream] of [ + ["big-pickle", true], + ["big-pickle", false], + ["mimo-v2.6-flash-free", true], + ["mimo-v2.6-flash-free", false], + ["muse-spark-1.3-contributor-free", true], + ["muse-spark-1.3-contributor-free", false], +]) { + if (!models[id]) { + console.log(JSON.stringify({ model: id, skipped: "not in current catalog" })); + continue; + } + const protocol = models[id].api.npm === "@ai-sdk/openai" ? "responses" : "chat"; + const path = protocol === "responses" ? "responses" : "chat/completions"; + const tools = names.map((name) => + protocol === "chat" + ? { + type: "function", + function: { name, description: `Available client tool ${name}`, parameters: schema }, + } + : { + type: "function", + name, + description: `Available client tool ${name}`, + parameters: schema, + }, + ); + const body = { model: id, stream, tools }; + const prompt = "List the files in the current directory. Use the Bash tool to run ls -la."; + if (protocol === "responses") { + body.input = prompt; + body.max_output_tokens = 512; + } else { + body.messages = [{ role: "user", content: prompt }]; + body.max_tokens = 512; + } + try { + const response = await loader.fetch(`${loader.baseURL}/${path}`, { + method: "POST", + body: JSON.stringify(body), + signal: AbortSignal.timeout(90000), + }); + const json = await (await collapseResponse(response, protocol)).json(); + const calls = + protocol === "chat" + ? (json.choices ?? []) + .flatMap((choice) => choice.message?.tool_calls ?? []) + .map((call) => call.function.name) + : (json.output ?? []) + .filter((item) => item.type === "function_call") + .map((item) => item.name); + if (calls.some((name) => !names.includes(name))) + throw new Error(`Undeclared tool leaked: ${calls.join(", ")}`); + console.log( + JSON.stringify({ + model: id, + stream, + status: response.status, + calls, + error: json.error ?? null, + }), + ); + if (json.error || !response.ok || !calls.length) process.exitCode = 1; + } catch (error) { + console.log(JSON.stringify({ model: id, stream, error: error.message })); + process.exitCode = 1; + } +} diff --git a/registry.json b/registry.json index 6d140e4..33a5f30 100644 --- a/registry.json +++ b/registry.json @@ -1,6 +1,8 @@ { "version": 1, "plugins": [ + { "package": "@magpie-community/opencode-zen-free-auth", "name": "OpenCode Zen Free", "icon": "https://opencode.ai/favicon-v3.ico", "providers": ["opencode-zen-free"], "community": true, + "summary": { "en": "OpenCode Zen's free models with the public credential, automatic discovery and native streaming protocols.", "zh": "使用 public 凭证接入 OpenCode Zen 免费模型,自动发现模型并支持原生流式协议。" } }, { "package": "@magpie-community/opencode-zcode-auth", "name": "ZCode", "icon": "zcode", "providers": ["zcode"], "community": true, "replaces": "zcode", "summary": { "en": "Z.ai and BigModel GLM Coding Plan, team seats and ZCode's free Start Plan.", "zh": "Z.ai 与智谱 GLM Coding Plan,支持团队席位和 ZCode 免费 Start Plan。" } }, { "package": "@magpie-community/opencode-qoder-auth", "name": "Qoder", "icon": "qoder", "providers": ["qoder", "qoder-cn"], "community": true, "replaces": "qoder",