Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(drivers): identify stream truncation by its error type, not message text

ninesummer3e6a9f2590dd
diff --git a/server/drivers/openai-chat-refusals.ts b/server/drivers/openai-chat-refusals.ts
index 59ff9f8a55..92836e2a8f 100644
--- a/server/drivers/openai-chat-refusals.ts
+++ b/server/drivers/openai-chat-refusals.ts
@@ -34,6 +34,9 @@ export function httpErrorDetail(body: string, limit = 500): string {
export class UnsupportedChatToolsError extends Error {}
+/** The provider closed the stream with neither finish_reason nor [DONE]; resending repeats nothing. */
+export class StreamTruncatedError extends ChatProtocolError {}
+
export function rejectsToolsParameter(status: number, body: string): boolean {
if (status !== 400 && status !== 422) return false;
let envelope: Record<string, unknown> | undefined;
diff --git a/server/drivers/openai-chat-stream-retry.test.ts b/server/drivers/openai-chat-stream-retry.test.ts
index 10312ddfaa..c9f00c74bd 100644
--- a/server/drivers/openai-chat-stream-retry.test.ts
+++ b/server/drivers/openai-chat-stream-retry.test.ts
@@ -1,5 +1,8 @@
// The chat runtime may resend a stream the provider closed before any completion marker; these
// tests pin that one protocol error's retry and the guards that keep a resend side-effect free.
+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { RuntimeEvent } from "../contracts.ts";
@@ -71,4 +74,60 @@ describe("createOpenAIChatRuntime stream truncation retry", () => {
expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "error" });
expect(requests).toBe(1);
});
+
+ it("does not resend a truncation after a tool call ran, so its effect happens once", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-chat-trunc-tool-"));
+ const script = join(dir, "fake-mcp.mjs");
+ const receipt = join(dir, "receipt.log");
+ writeFileSync(script, `#!/usr/bin/env node
+ import { appendFileSync } from "node:fs";
+ const send = (m) => process.stdout.write(JSON.stringify(m) + "\\n");
+ let buffer = "";
+ process.stdin.setEncoding("utf8");
+ process.stdin.on("data", (chunk) => {
+ buffer += chunk;
+ let nl;
+ while ((nl = buffer.indexOf("\\n")) !== -1) {
+ const line = buffer.slice(0, nl); buffer = buffer.slice(nl + 1);
+ const m = JSON.parse(line);
+ if (m.method === "initialize") send({jsonrpc:"2.0",id:m.id,result:{protocolVersion:"2024-11-05",capabilities:{tools:{}}}});
+ else if (m.method === "tools/list") send({jsonrpc:"2.0",id:m.id,result:{tools:[{name:"write",description:"Fixture write",inputSchema:{type:"object",properties:{},additionalProperties:false}}]}});
+ else if (m.method === "tools/call") { appendFileSync(${JSON.stringify(receipt)}, "write\\n"); send({jsonrpc:"2.0",id:m.id,result:{content:[{type:"text",text:"ok"}]}}); }
+ }
+ });
+ `);
+ chmodSync(script, 0o755);
+ const callBody = 'data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"c1","type":"function","function":{"name":"fx_write","arguments":"{}"}}]}}]}\n\n'
+ + 'data: {"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}\n\n';
+ const bodies: Array<{ messages: Array<{ role: string }> }> = [];
+ vi.stubGlobal("fetch", vi.fn(async (input: unknown, init?: RequestInit) => {
+ if (!String(input).endsWith("/chat/completions")) return new Response(JSON.stringify({ data: [] }));
+ bodies.push(JSON.parse(String(init?.body)));
+ // The tool result goes back up, and that second attempt's stream is the truncation.
+ return new Response(bodies.length === 1 ? callBody : "", { headers: { "content-type": "text/event-stream" } });
+ }));
+ const instance = await OpenAICompatDriver.create({
+ instanceId: "trunc", displayName: "Synthetic", enabled: true,
+ config: OpenAICompatDriver.decodeConfig({ url: "https://api.example.test/v1", apiKeyEnv: "K", model: "fixture" }),
+ environment: { K: "synthetic" },
+ });
+ const events: RuntimeEvent[] = [];
+ instance.adapter.onEvent((event) => events.push(event));
+ try {
+ await instance.adapter.sendTurn({
+ threadId: "trunc", text: "Use the tool, then answer.", approvalMode: "full",
+ integrations: { custom: { fx: { command: script, args: [], env: {} } } },
+ });
+ await vi.waitFor(() => expect(events.some((event) => event.type === "turn.completed")).toBe(true), { timeout: 10_000 });
+ expect(bodies).toHaveLength(2);
+ expect(bodies[1]?.messages.some((message) => message.role === "tool")).toBe(true);
+ expect(events.some((event) => event.type === "turn.retrying")).toBe(false);
+ expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ message: "Stream ended before completion" });
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "error" });
+ expect(readFileSync(receipt, "utf8").trim().split("\n")).toEqual(["write"]);
+ } finally {
+ await instance.dispose();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }, 20_000);
});
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index 7d11a5ec38..99c8e48688 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -21,7 +21,7 @@ import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent,
import { promptHalves, volatileContextNote, withContextNote } from "./prompt-split.ts";
import { createChatToolApproval, refusal } from "./chat-tool-approval.ts";
import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, object, type ChatToolCall } from "./openai-chat-protocol.ts";
-import { completionError, httpErrorDetail, refusedToolCall, refusedToolCallFailure, rejectsReasoningReplay, rejectsToolsParameter, RejectedToolCallError, UnsupportedChatToolsError, UnsupportedReasoningReplayError, type ProviderBody } from "./openai-chat-refusals.ts";
+import { completionError, httpErrorDetail, refusedToolCall, refusedToolCallFailure, rejectsReasoningReplay, rejectsToolsParameter, RejectedToolCallError, StreamTruncatedError, UnsupportedChatToolsError, UnsupportedReasoningReplayError, type ProviderBody } from "./openai-chat-refusals.ts";
import { ChatRepeatGuard } from "./chat-repeat-guard.ts";
import { TextCallHoldback, textToolCalls } from "./chat-text-tool-calls.ts";
import { createModelRoutes, ModelRouteRefused, noRouteLeft, readResponsesStream, responsesRequest, routeRefusal, type ModelRoute, type ResponseItem } from "./openai-responses.ts";
@@ -423,7 +423,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const bodyError = body ? completionError(body, "completion error") : null;
if (bodyError) throw bodyError;
}
- throw new ChatProtocolError("Stream ended before completion");
+ throw new StreamTruncatedError("Stream ended before completion");
}
resetIdleTimer();
buffer += decoder.decode(value, { stream: true });
@@ -707,16 +707,14 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
continue;
}
// Once a call has been handled, never replay it through a turn retry.
- // A stream the provider closed with no completion marker is the one protocol error
- // worth resending: the guards above prove nothing streamed and no tool call ran, so
- // the resend repeats no text and executes nothing — and it applies even where the
- // caller never opted into transient retries (openai-compat and five friends).
- const truncation = verdict.reason === "stream_truncated";
+ // A stream closed before any completion marker executed nothing upstream, so exactly
+ // that protocol error may resend — even where the caller never opted into retries.
+ const truncation = error instanceof StreamTruncatedError;
const retryScale = truncation ? options.retryScale ?? 1 : options.retryScale;
if (retryScale === undefined || abort.signal.aborted || streamed || seenCalls.size ||
- (error instanceof ChatProtocolError && !truncation) || !verdict.transient || attempt >= RETRY_MAX_ATTEMPTS - 1) throw error;
+ (error instanceof ChatProtocolError && !truncation) || (!verdict.transient && !truncation) || attempt >= RETRY_MAX_ATTEMPTS - 1) throw error;
const delayMs = computeBackoff(attempt++);
- emit({ ...base(turn.threadId, turnId), type: "turn.retrying", attempt, delayMs, reason: verdict.reason });
+ emit({ ...base(turn.threadId, turnId), type: "turn.retrying", attempt, delayMs, reason: truncation ? "stream_truncated" : verdict.reason });
await interruptibleDelay(delayMs * retryScale, abort.signal).promise;
abort.signal.throwIfAborted();
}
diff --git a/server/drivers/retry.ts b/server/drivers/retry.ts
index ff0512c369..db54d89746 100644
--- a/server/drivers/retry.ts
+++ b/server/drivers/retry.ts
@@ -13,8 +13,7 @@ export type TransientReason =
| "overloaded"
| "server_error"
| "connection_reset"
- | "timeout"
- | "stream_truncated";
+ | "timeout";
export type TerminalReason =
| "auth"
@@ -44,9 +43,6 @@ const TRANSIENT_PATTERNS: Array<{ pattern: RegExp; reason: TransientReason }> =
reason: "connection_reset",
},
{ pattern: /\btimeout(ed)?\b|\btimed? out\b/i, reason: "timeout" },
- // A provider closing the stream with neither finish_reason nor [DONE]. Retriable only while the
- // chat runtime's resend gate proves nothing streamed and no tool call ran.
- { pattern: /\bstream ended before completion\b/i, reason: "stream_truncated" },
];
/** A subscription's usage running out: terminal even when phrased as a rate limit. Claude Code 2.1.295