diff --git a/packages/zen-free/README.md b/packages/zen-free/README.md index 72c3774..f5755ca 100644 --- a/packages/zen-free/README.md +++ b/packages/zen-free/README.md @@ -44,3 +44,18 @@ to `todo_write`, `webfetch` to `web_fetch`), when exactly one does. A call with no such tool (or with no name) is left out of the reply, and the reply's text says which name was left out; a turn whose every call was left out ends as an ordinary answer. Tools run in the agent. + +Zen's free tier only answers a request that carries tools, so a request +is sent with the five core OpenCode tools the agent doesn't declare +itself (`bash`, `edit`, `glob`, `grep`, `read`), described as not +available. A call of one of them the agent doesn't have is left out like +any other. + +Now and then Zen closes a streamed Chat Completions reply before its +`[DONE]`. When the reply has said something and no tool call of it is +unfinished, it ends there as an ordinary answer, and its text says it was +cut short; asking again goes on. A reply cut short with a tool call +unfinished, with nothing said, or collapsed for a client that doesn't +stream fails with an error naming the reply's id and how much of it came. +An Anthropic Messages or Responses reply cut short fails too: magpie +tells it from a whole one and, where the model can, goes on with it. diff --git a/packages/zen-free/index.test.mjs b/packages/zen-free/index.test.mjs index bee72aa..35b3f6b 100644 --- a/packages/zen-free/index.test.mjs +++ b/packages/zen-free/index.test.mjs @@ -441,3 +441,28 @@ test("a model made free since the list was read is served after the list is aske assert.equal(response.status, 200); assert.equal(state.calls.at(-1).body.model, "late-free"); }); + +test("a Chat stream Zen closes before its [DONE] ends cut short for a streaming client and fails for one that doesn't (#91)", 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 = + 'data: {"id":"x2","object":"chat.completion.chunk","created":1,"model":"chat-free","choices":[{"index":0,"delta":{"role":"assistant"}}],"usage":null}\n\n' + + 'data: {"id":"x2","object":"chat.completion.chunk","created":1,"model":"chat-free","choices":[{"index":0,"delta":{"content":"Installed successfully and all"}}],"usage":null}\n\n' + + 'data: {"id":"x2","object":"chat.completion.chunk","created":1,"model":"chat-free","choices":[{"index":0,"delta":{"content":" other plugins are intact."}}],"usage":null}\n\n'; + const send = (stream) => + loader.fetch(`${origin}/v1/chat/completions`, { + method: "POST", + body: JSON.stringify({ model: "chat-free", stream, messages: [{ role: "user", content: "hi" }] }), + }); + const streamed = await send(true); + assert.equal(streamed.status, 200); + const text = await streamed.text(); + assert.match(text, /other plugins are intact\./); + assert.match(text, /The reply was cut short.*"finish_reason":"stop"/); + assert.match(text, /data: \[DONE\]\n\n$/); + assert.doesNotMatch(text, /"error"/); + const whole = await send(false); + assert.notEqual(whole.status, 200); + assert.match(await whole.text(), /without a completion marker \(reply x2, 3 events/); +}); diff --git a/packages/zen-free/package.json b/packages/zen-free/package.json index f2fce13..9aa4101 100644 --- a/packages/zen-free/package.json +++ b/packages/zen-free/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zen-free-auth", - "version": "0.1.3", + "version": "0.1.4", "description": "OpenCode Zen free models through the public credential, with native streaming protocols", "type": "module", "main": "./index.mjs", diff --git a/packages/zen-free/provider.mjs b/packages/zen-free/provider.mjs index c252acd..463137e 100644 --- a/packages/zen-free/provider.mjs +++ b/packages/zen-free/provider.mjs @@ -286,7 +286,9 @@ async function server(_input, options = {}) { signal: request.signal, redirect: "error", }); - const guarded = await guardToolResponse(response, protocol, toolPolicy); + const guarded = await guardToolResponse(response, protocol, toolPolicy, { + endCutShort: streaming, + }); return streaming ? guarded : collapseResponse(guarded, protocol); }, }; diff --git a/packages/zen-free/tool-response.mjs b/packages/zen-free/tool-response.mjs index 055069d..cedef0f 100644 --- a/packages/zen-free/tool-response.mjs +++ b/packages/zen-free/tool-response.mjs @@ -621,9 +621,88 @@ async function* framesFrom(reader) { } } -function guardedStream(response, protocol, checkName) { - const reader = response.body?.getReader(); +// A Chat stream Zen closed before its [DONE] (#91: space-bunny-free, about +// 0.1% of turns) is ended as a turn cut short when it has said something +// and no tool call of it is pending: each choice still open gets a note +// saying so and a stop, then [DONE]. Failing it threw away the reasoning +// and text the agent already had, and a Chat reply through Zen can't be +// asked to go on from there. A pending call's arguments may be half +// written, and a reply that said nothing is an empty one, so both still +// fail, as does one collapsed for a client that doesn't stream, which can +// still be asked again. Anthropic and Responses streams cut short fail +// too: magpie's gateway tells such a reply from a whole one itself +// (#370), and goes on with it where the upstream can (an Anthropic one), +// which a made-up end here would stop. +export const cutShortNote = + "(The reply was cut short: Zen closed the stream before it finished. Ask again to go on.)"; + +function chatTrack() { + const open = new Set(); + const finished = new Set(); + const wrote = new Set(); + let said = false; + let meta = null; + return { + see(data) { + if (!object(data)) return; + meta = { + id: data.id ?? meta?.id, + created: data.created ?? meta?.created, + model: data.model ?? meta?.model, + }; + for (const choice of Array.isArray(data.choices) ? data.choices : []) { + if (!object(choice)) continue; + const index = position(choice.index); + const delta = object(choice.delta) ? choice.delta : {}; + for (const key of ["content", "reasoning_content", "reasoning"]) { + if (typeof delta[key] === "string" && delta[key]) said = true; + } + if (typeof delta.content === "string" && delta.content) wrote.add(index); + if (choice.finish_reason != null) { + finished.add(index); + open.delete(index); + } else if (!finished.has(index)) open.add(index); + } + }, + // ending answers the frames that end the reply as cut short, or null + // when it can't be. + ending() { + if (!said) return null; + const choices = [...open] + .sort((a, b) => a - b) + .map((index) => ({ + index, + delta: { content: (wrote.has(index) ? "\n\n" : "") + cutShortNote }, + finish_reason: "stop", + })); + const head = { + id: meta?.id ?? "chatcmpl-cut-short", + object: "chat.completion.chunk", + created: meta?.created ?? Math.floor(Date.now() / 1000), + model: meta?.model ?? "", + }; + return (choices.length ? encodeEvent({ ...head, choices }) : "") + "data: [DONE]\n\n"; + }, + }; +} + +function guardedStream(response, protocol, checkName, endCutShort) { + const source = response.body?.getReader(); + // What came before a stream cut short, for its error to say (#91). + let bytes = 0; + let events = 0; + let replyID; + const reader = source && { + async read() { + const result = await source.read(); + if (result.value) bytes += result.value.byteLength; + return result; + }, + releaseLock: () => source.releaseLock(), + cancel: (reason) => source.cancel(reason), + }; const chat = protocol === "chat" ? chatBuffer(checkName) : null; + const track = chat && endCutShort ? chatTrack() : null; const snapshots = chat ? null : snapshotStream(protocol, checkName); let frames = reader ? framesFrom(reader) : null; let completed = false; @@ -656,8 +735,25 @@ function guardedStream(response, protocol, checkName) { 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"); + const ending = !completed && !chat?.size ? track?.ending() : null; + if (ending) { + stopped = true; + release(); + controller.enqueue(encoder.encode(ending)); + controller.close(); + return; + } + if (!completed || chat?.size) { + const came = [ + replyID ? `reply ${String(replyID).slice(0, 128)}` : "", + `${events} event${events === 1 ? "" : "s"}`, + `${bytes} bytes received`, + chat?.size ? "a tool call unfinished" : "", + ].filter(Boolean); + throw new GuardError( + `Upstream SSE ended without a completion marker (${came.join(", ")})`, + ); + } stopped = true; release(); controller.close(); @@ -676,8 +772,10 @@ function guardedStream(response, protocol, checkName) { controller.enqueue(encoder.encode((final ? encodeEvent(final) : "") + frame.raw)); return; } + events++; const data = frame.name === "error" ? null : parseJSON(frame.text); const type = data?.type ?? frame.name; + replyID = data?.id ?? data?.message?.id ?? data?.response?.id ?? replyID; if ( frame.name === "error" || type === "error" || @@ -698,6 +796,7 @@ function guardedStream(response, protocol, checkName) { } const checked = chat ? chat.apply(data) : snapshots.apply(data, type); const { changed, data: result, extra = [] } = checked; + if (result) track?.see(result); if ( (protocol === "responses" && ["response.completed", "response.incomplete"].includes(type)) || @@ -745,7 +844,11 @@ function guardedStream(response, protocol, checkName) { ); } -export async function guardToolResponse(response, protocol, policy) { +// options.endCutShort lets a Chat stream cut short end as one (#91): for a +// client that streams, which has the reply's start already. A reply +// collapsed for a client that doesn't stream fails instead, so it can be +// asked again before anything reached the client. +export async function guardToolResponse(response, protocol, policy, options = {}) { if (!response.ok) return response; if (!["chat", "responses", "anthropic"].includes(protocol)) throw new TypeError(`Unsupported protocol: ${protocol}`); @@ -753,7 +856,7 @@ export async function guardToolResponse(response, protocol, 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), { + return new Response(guardedStream(response, protocol, checkName, options.endCutShort === true), { status: response.status, statusText: response.statusText, headers, diff --git a/packages/zen-free/tool-response.test.mjs b/packages/zen-free/tool-response.test.mjs index 7d3212e..c882676 100644 --- a/packages/zen-free/tool-response.test.mjs +++ b/packages/zen-free/tool-response.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { droppedNote, guardToolResponse } from "./tool-response.mjs"; +import { cutShortNote, droppedNote, guardToolResponse } from "./tool-response.mjs"; const encoder = new TextEncoder(); @@ -1317,3 +1317,83 @@ test("text streams larger than 32 MiB are not subject to the pending-tool limit" } assert.ok(total > 32 * 1024 * 1024); }); + +// #91: Zen closed space-bunny-free's Chat stream after these three frames, +// with no finish_reason, usage or [DONE] (the reporter's bytes). +const cutFrames = + `data: {"id":"x2","object":"chat.completion.chunk","created":1,"model":"space-bunny-free","choices":[{"index":0,"delta":{"role":"assistant"}}],"usage":null}\n\n` + + `data: {"id":"x2","object":"chat.completion.chunk","created":1,"model":"space-bunny-free","choices":[{"index":0,"delta":{"content":"Installed successfully and all"}}],"usage":null}\n\n` + + `data: {"id":"x2","object":"chat.completion.chunk","created":1,"model":"space-bunny-free","choices":[{"index":0,"delta":{"content":" other plugins are intact."}}],"usage":null}\n\n`; +const streaming = { endCutShort: true }; + +test("chat: a stream cut short after its text ends as one, with a note and [DONE] (#91)", async () => { + for (const chunkSize of [7, 31, 4096]) { + const result = await guardToolResponse(sse(cutFrames, { chunkSize }), "chat", policy, streaming); + const text = await result.text(); + assert.equal(result.status, 200); + assert.ok(text.startsWith(cutFrames), "what was said goes on unchanged"); + assert.doesNotMatch(text, /"error"/); + const frames = parse(text); + assert.equal(frames.at(-1).data, "[DONE]"); + const end = frames.at(-2).data; + assert.equal(end.id, "x2"); + assert.equal(end.model, "space-bunny-free"); + assert.deepEqual(end.choices, [ + { index: 0, delta: { content: `\n\n${cutShortNote}` }, finish_reason: "stop" }, + ]); + } +}); + +test("chat: a stream cut short in its reasoning ends as one too, the note its text (#91)", async () => { + const text = event(chat({ role: "assistant" })) + event(chat({ reasoning_content: "Let me think" })); + const result = await guardToolResponse(sse(text), "chat", policy, streaming); + const frames = parse(await result.text()); + assert.equal(frames.at(-1).data, "[DONE]"); + assert.deepEqual(frames.at(-2).data.choices, [ + { index: 0, delta: { content: cutShortNote }, finish_reason: "stop" }, + ]); +}); + +test("chat: a stream whose every choice finished is only missing its [DONE] (#91)", async () => { + const text = cutFrames + event(chat({}, "stop")); + const result = await guardToolResponse(sse(text), "chat", policy, streaming); + const out = await result.text(); + assert.equal(out, text + "data: [DONE]\n\n"); +}); + +test("chat: a stream cut short still fails with a call pending, saying nothing, or not streamed (#91)", async () => { + const cases = [ + [cutFrames + event(chat({ tool_calls: [call("bash", 0, '{"comm')] })), streaming, /tool call unfinished/], + [event(chat({ role: "assistant" })), streaming, /1 event,/], + ["", streaming, /0 events, 0 bytes/], + [cutFrames, {}, /reply x2, 3 events, \d+ bytes/], + ]; + for (const [text, options, detail] of cases) { + const result = await guardToolResponse(sse(text), "chat", policy, options); + const frames = parse(await result.text()); + assert.doesNotMatch(JSON.stringify(frames), /comm/); + const data = frames.at(-1).data; + assertError("chat", data); + assert.match(data.error.message, /^Upstream SSE ended without a completion marker \(/); + assert.match(data.error.message, detail); + } +}); + +test("anthropic and responses: a stream cut short still fails, naming the reply (#91)", async () => { + const cut = { + anthropic: + event({ type: "message_start", message: { id: "msg_1", type: "message", role: "assistant", content: [] } }, "message_start") + + event({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }, "content_block_start") + + event({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Installed" } }, "content_block_delta"), + responses: + event({ type: "response.created", response: { id: "resp_1", status: "in_progress", output: [] } }, "response.created") + + event({ type: "response.output_text.delta", item_id: "m", output_index: 0, content_index: 0, delta: "Installed" }, "response.output_text.delta"), + }; + for (const [protocol, text] of Object.entries(cut)) { + const result = await guardToolResponse(sse(text), protocol, policy, streaming); + const data = parse(await result.text()).at(-1).data; + assertError(protocol, data); + const message = protocol === "anthropic" ? data.error.message : data.message; + assert.match(message, protocol === "anthropic" ? /reply msg_1/ : /reply resp_1/); + } +});