diff --git a/packages/commandcode/README.md b/packages/commandcode/README.md index 6b0f17c..501282e 100644 --- a/packages/commandcode/README.md +++ b/packages/commandcode/README.md @@ -37,6 +37,9 @@ Keys don't expire, so there is nothing to refresh. or not. - Failures keep their statuses: a model the plan lacks is a 403, running out of credits is a 402, and a usage-window limit is a 429. + - A reply that stops before its finish line is a 502, unless it was + streamed and had already said something. Then it ends cut short, with + a note saying so, and `[DONE]` (#91). The plan is read from `/alpha/billing/subscriptions`. It is cached for 10 minutes; after a failed read, the plugin tries again after 1 minute. diff --git a/packages/commandcode/cut-short.test.mjs b/packages/commandcode/cut-short.test.mjs new file mode 100644 index 0000000..3975411 --- /dev/null +++ b/packages/commandcode/cut-short.test.mjs @@ -0,0 +1,61 @@ +// A Go reply Command Code stops sending before its finish line (#91): a +// streamed one that said something ends cut short, with a note, instead of +// failing the turn; one that said nothing, or a non-streamed one, is a 502. +import { afterEach, expect, test } from "bun:test" +import { CommandCodePlugin, _internal } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => { + globalThis.fetch = real + _internal.subsSeen.clear() +}) + +const NOTE = "(The reply was cut short: Command Code closed the stream before it finished. Ask again to go on.)" + +async function ask(lines, stream) { + globalThis.fetch = async (url) => { + if (new URL(String(url)).pathname === "/alpha/generate") return new Response(lines.map((l) => JSON.stringify(l)).join("\n") + "\n") + return new Response("", { status: 404 }) + } + const hooks = await CommandCodePlugin() + const opts = await hooks.auth.loader(async () => ({ type: "api", key: "go-key", metadata: { plan: "Go" } })) + const res = await opts.fetch("https://api.commandcode.ai/provider/v1/chat/completions", { + method: "POST", + body: JSON.stringify({ model: "deepseek/deepseek-v4-pro", stream, messages: [{ role: "user", content: "hi" }] }), + }) + return { status: res.status, text: await res.text() } +} + +const frames = (text) => + text.split("\n\n").filter((f) => f.startsWith("data: ")).map((f) => (f === "data: [DONE]" ? "[DONE]" : JSON.parse(f.slice(6)))) + +test("a streamed reply cut short after its text ends with the note, a stop and [DONE]", async () => { + const r = await ask([{ type: "reasoning-delta", text: "thinking" }, { type: "text-delta", text: "Half an ans" }], true) + expect(r.status).toBe(200) + const f = frames(r.text) + expect(f.at(-1)).toBe("[DONE]") + expect(f.some((x) => x.error)).toBe(false) + expect(f.map((x) => x.choices?.[0]?.delta?.content ?? "").join("")).toBe("Half an ans\n\n" + NOTE) + expect(f.at(-2).choices[0].finish_reason).toBe("stop") +}) + +test("a streamed reply cut short after a whole tool call finishes as tool_calls", async () => { + const r = await ask([{ type: "tool-call", toolCallId: "c1", toolName: "read", input: { path: "a" } }], true) + const f = frames(r.text) + expect(f.at(-1)).toBe("[DONE]") + expect(f.at(-2).choices[0].finish_reason).toBe("tool_calls") + expect(f.flatMap((x) => x.choices?.[0]?.delta?.tool_calls ?? []).map((c) => c.function.name)).toEqual(["read"]) +}) + +test("a reply cut short with only reasoning says the note without a blank line before it", async () => { + const f = frames((await ask([{ type: "reasoning-delta", text: "hm" }], true)).text) + expect(f.map((x) => x.choices?.[0]?.delta?.content ?? "").join("")).toBe(NOTE) +}) + +test("a reply cut short before saying anything, or not streamed, is still a 502", async () => { + const none = await ask([{ type: "start" }], true) + expect(none.status).toBe(502) + const whole = await ask([{ type: "text-delta", text: "Half" }], false) + expect(whole.status).toBe(502) + expect(JSON.parse(whole.text).error.message).toBe("the reply ended before it was complete") +}) diff --git a/packages/commandcode/index.mjs b/packages/commandcode/index.mjs index 6868659..37f66df 100644 --- a/packages/commandcode/index.mjs +++ b/packages/commandcode/index.mjs @@ -953,12 +953,21 @@ async function* lines(body) { const FINISH = { "tool-calls": "tool_calls", length: "length", "content-filter": "content_filter" } +// CUT_SHORT_NOTE ends a streamed reply Command Code stopped sending +// before its finish line (as zen-free does, #91): magpie's gateway can't go +// on with a Chat Completions reply, and failing it would throw away what +// the client was already shown. +const CUT_SHORT_NOTE = "(The reply was cut short: Command Code closed the stream before it finished. Ask again to go on.)" + // events turns the reply's lines into chat completion pieces: text, // reasoning, whole tool calls, then the finish with the usage. A reply -// with no finish line was cut short: an error, not a shorter answer. +// with no finish line was cut short: { cut } when it said something +// (its tool calls come whole, never half written), else an error. async function* events(body) { let tools = 0 let cacheWrite = 0 + let said = false + let wrote = false for await (const s of lines(body)) { let l try { @@ -968,15 +977,22 @@ async function* events(body) { } switch (l.type) { case "text-delta": - if (l.text) yield { text: l.text } + if (l.text) { + said = wrote = true + yield { text: l.text } + } break case "reasoning-delta": - if (l.text) yield { reasoning: l.text } + if (l.text) { + said = true + yield { reasoning: l.text } + } break case "tool-call": { if (l.providerExecuted) break // run by the server, its result beside it let input = l.input ?? l.args input = typeof input === "string" ? parseArgs(input) : input ?? {} + said = true yield { tool: { index: tools++, id: l.toolCallId || "call_" + randomBytes(12).toString("hex"), name: l.toolName, args: JSON.stringify(input) } } break } @@ -1009,7 +1025,8 @@ async function* events(body) { return } } - yield { error: { status: 502, message: "the reply ended before it was complete" } } + const error = { status: 502, message: "the reply ended before it was complete" } + yield said ? { cut: tools > 0 ? "tool_calls" : "stop", wrote, error } : { error } } // generate answers a chat completion through /alpha/generate. @@ -1070,7 +1087,13 @@ async function generate(key, chat, signal, place) { else if (e.reasoning) ctl.enqueue(chunk({ reasoning_content: e.reasoning })) else if (e.tool) ctl.enqueue(chunk({ tool_calls: [{ index: e.tool.index, id: e.tool.id, type: "function", function: { name: e.tool.name, arguments: e.tool.args } }] })) else if (e.stop) ctl.enqueue(chunk({}, e.stop, e.usage ? { usage: e.usage } : {})) - else if (e.error) { + else if (e.cut) { + // the client has its start: a shorter turn that says so, not a lost one + ctl.enqueue(chunk({ content: (e.wrote ? "\n\n" : "") + CUT_SHORT_NOTE })) + ctl.enqueue(chunk({}, e.cut)) + ctl.enqueue(enc.encode("data: [DONE]\n\n")) + ctl.close() + } else if (e.error) { ctl.enqueue(enc.encode(`data: ${JSON.stringify({ error: { message: e.error.message, code: e.error.status } })}\n\n`)) ctl.close() } diff --git a/packages/commandcode/package.json b/packages/commandcode/package.json index c92fc72..95e8777 100644 --- a/packages/commandcode/package.json +++ b/packages/commandcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-commandcode-auth", - "version": "0.1.10", + "version": "0.1.11", "description": "Command Code plans (Pro, GOAT, Max, Ultra, Go, Teams) in OpenCode and magpie", "type": "module", "main": "./index.mjs",