Skip to content

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

Continue an OpenAI-compatible reply cut at the output limit

erywim9a8c5667cb91
diff --git a/scripts/testing/file-size-ratchet.test.ts b/scripts/testing/file-size-ratchet.test.ts
index c13a89bb76..3ec8c1f149 100644
--- a/scripts/testing/file-size-ratchet.test.ts
+++ b/scripts/testing/file-size-ratchet.test.ts
@@ -24,6 +24,7 @@ const LINES: Record<string, number> = {
"server/drivers/claude.ts": 2016,
"server/drivers/acp/core.ts": 1541,
"server/drivers/codex.ts": 1583,
+ "server/drivers/openai-chat.ts": 1005, // the turn loop's output-limit continuation; the rule itself lives in openai-chat-protocol.ts
"server/routines.ts": 1553,
"src/components/ComputerPanel.tsx": 1782,
"src/components/RoutineCalendarPage.tsx": 1485,
diff --git a/server/drivers/openai-chat-protocol.ts b/server/drivers/openai-chat-protocol.ts
index d9808e2df3..51202f1f6c 100644
--- a/server/drivers/openai-chat-protocol.ts
+++ b/server/drivers/openai-chat-protocol.ts
@@ -19,6 +19,20 @@ export const MAX_REASONING_DETAIL_CHARS = 4_000_000;
export class ChatProtocolError extends Error {}
+export const CUT_REPLY_NOTE = "[OpenMausBot: your reply was cut at the output limit. Continue exactly where you stopped.]";
+const MAX_LENGTH_CONTINUATIONS = 8;
+
+/** True when a reply cut at the output limit should be continued; throws once the cap is reached. A local model writes
+ * tool calls as text, so a cut reply there may be half a call and stays a failure. */
+export function cutReplyContinues(state: { count: number }, completion: { finishReason: string | null; text: string }, localTools: boolean): boolean {
+ if (completion.finishReason !== "length" || !completion.text.trim() || localTools) return false;
+ if (state.count >= MAX_LENGTH_CONTINUATIONS) {
+ throw new ChatProtocolError(`The reply was still cut at the output limit after ${MAX_LENGTH_CONTINUATIONS} continuations; the turn was stopped.`);
+ }
+ state.count += 1;
+ return true;
+}
+
export function object(value: unknown): Record<string, unknown> | undefined {
return value !== null && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown> : undefined;
diff --git a/server/drivers/openai-chat.test.ts b/server/drivers/openai-chat.test.ts
index e50e859e3e..5a556336c9 100644
--- a/server/drivers/openai-chat.test.ts
+++ b/server/drivers/openai-chat.test.ts
@@ -1158,3 +1158,55 @@ describe("createOpenAIChatRuntime transient retries", () => {
expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false });
}, 20_000);
});
+
+describe("createOpenAIChatRuntime output-limit continuation", () => {
+ const LENGTH_CONTINUATION = "[OpenMausBot: your reply was cut at the output limit. Continue exactly where you stopped.]";
+ const stream = (delta: Record<string, unknown>, finishReason: string) =>
+ `data: ${JSON.stringify({ choices: [{ index: 0, delta }] })}\n\n`
+ + `data: ${JSON.stringify({ choices: [{ index: 0, delta: {}, finish_reason: finishReason }], usage: { prompt_tokens: 10, completion_tokens: 4 } })}\n\n`;
+ const text = (value: string, finishReason: string) => stream({ content: value }, finishReason);
+ const textOf = (events: RuntimeEvent[]) =>
+ events.filter((event) => event.type === "item.completed" && event.itemType === "assistant_text").map((event) => event.text);
+
+ it("continues a reply cut at the output limit and returns the whole answer", async () => {
+ let requests = 0;
+ const events = await runTurn(() => ++requests === 1 ? sse(text("The report is", "length")) : sse(text(" written.", "stop")));
+ expect(requests).toBe(2);
+ expect(textOf(events)).toEqual(["The report is", " written."]);
+ expect(events.some((event) => event.type === "runtime.error")).toBe(false);
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: true });
+
+ const bodies = vi.mocked(fetch).mock.calls
+ .filter(([url]) => String(url).endsWith("/chat/completions"))
+ .map(([, init]) => JSON.parse(String(init?.body)) as { messages: Array<{ role: string; content: unknown }> });
+ expect(bodies[1]!.messages.slice(-2)).toEqual([
+ { role: "assistant", content: "The report is" },
+ { role: "user", content: LENGTH_CONTINUATION },
+ ]);
+ });
+
+ it("still fails a length finish with no text", async () => {
+ let requests = 0;
+ const events = await runTurn(() => (requests++, sse(text("", "length"))));
+ expect(requests).toBe(1);
+ expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ message: "provider returned an empty response" });
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false });
+ });
+
+ it("still fails a reasoning-only length finish", async () => {
+ let requests = 0;
+ const events = await runTurn(() => (requests++, sse(stream({ reasoning_content: "thinking" }, "length"))));
+ expect(requests).toBe(1);
+ expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ message: expect.stringContaining("provider did not finish the response (length)") });
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false });
+ });
+
+ it("stops at the continuation cap instead of looping forever", async () => {
+ let requests = 0;
+ const events = await runTurn(() => (requests++, sse(text(`part ${requests}`, "length"))));
+ expect(requests).toBe(9);
+ expect(textOf(events)).toHaveLength(9);
+ expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ message: expect.stringContaining("output limit") });
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false });
+ });
+});
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index dc723fdc71..029f3623f5 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -20,7 +20,7 @@ import { chatToolLimitFor, chatToolLimitKey } from "../tool-count-limit.ts";
import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent, type ChatContentPart } from "./chat-images.ts";
import { promptHalves, volatileContextNote, withContextNote } from "./prompt-split.ts";
import { createChatToolApproval, refusal } from "./chat-tool-approval.ts";
-import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, object, replayableToolCalls, toolArguments, type ChatToolCall } from "./openai-chat-protocol.ts";
+import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, CUT_REPLY_NOTE, cutReplyContinues, object, replayableToolCalls, toolArguments, type ChatToolCall } from "./openai-chat-protocol.ts";
import { ChatHttpError, completionError, httpErrorDetail, refusedToolCall, refusedToolCallFailure, rejectsReasoningReplay, rejectsToolsParameter, RejectedToolCallError, sseData, 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";
@@ -218,7 +218,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
...(completion.protocolReasoning && !reasoningReplayRejected.has(model) ? { [options.reasoningReplayField ?? "reasoning_content"]: completion.protocolReasoning } : {}),
...(completion.protocolReasoningDetails.length ? { reasoning_details: completion.protocolReasoningDetails } : {}),
...(toolCalls ? { tool_calls: toolCalls } : {}) };
- if (completion.responseOutput) responseOutputs.set(reply, completion.responseOutput);
+ if (completion.responseOutput?.length) responseOutputs.set(reply, completion.responseOutput);
return reply;
};
const delivered = new Map<string, DeliveredUserMessage[]>();
@@ -590,6 +590,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
let failureText: ReturnType<typeof runtimeErrorText>;
let toolFailed = false, spoke = false, unfloored = 0, blockedAfterReply = false; // unfloored: failed calls the safety floor did not block after the bot spoke
let correctiveRounds = 0;
+ const cutReplies = { count: 0 };
const denials: string[] = [], failedCalls: string[] = [];
const seenCalls = new Set<string>();
let nudges = 0;
@@ -753,6 +754,10 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
}
if (!completion.toolCalls.length) {
if (!reply.trim()) throw new ChatProtocolError("provider returned an empty response");
+ if (cutReplyContinues(cutReplies, completion, Boolean(options.localModel && tools.definitions.length))) {
+ messages.push(assistantReply(model, completion, completion.text), { role: "user", content: CUT_REPLY_NOTE });
+ continue;
+ }
if (completion.finishReason && completion.finishReason !== "stop") {
throw new ChatProtocolError(`provider did not finish the response (${completion.finishReason})`);
}
diff --git a/server/drivers/openai-responses.test.ts b/server/drivers/openai-responses.test.ts
index 9e4c895692..dc2c01b481 100644
--- a/server/drivers/openai-responses.test.ts
+++ b/server/drivers/openai-responses.test.ts
@@ -449,13 +449,28 @@ describe("what Responses can answer", () => {
expect(textOf(seen, "assistant_text")).toBe("Note.\n\nAnswer.");
});
- it("does not finish a turn on an incomplete response", async () => {
+ it("continues a response cut at the output limit", async () => {
+ let responses = 0;
const f = await fixture(onResponses((response) => {
- events(response, [textDelta("Half"), { type: "response.incomplete", response: { status: "incomplete", incomplete_details: { reason: "max_output_tokens" }, output: [], usage } }]);
+ responses += 1;
+ if (responses === 1) {
+ events(response, [created, textDelta("Half"), done(messageItem("Half")), {
+ type: "response.incomplete",
+ response: { status: "incomplete", incomplete_details: { reason: "max_output_tokens" }, output: [messageItem("Half")], usage },
+ }]);
+ return;
+ }
+ answer(response, " and half.");
}));
const { end, events: seen } = await f.turn();
- expect(end).toMatchObject({ ok: false });
- expect(failureOf(seen)).toContain("provider did not finish the response (length)");
+ expect(end).toMatchObject({ ok: true });
+ const continuation = f.calls.at(-1)!;
+ expect(continuation.path).toContain("/responses");
+ expect(continuation.body.input.at(-1)).toEqual({
+ role: "user",
+ content: "[OpenMausBot: your reply was cut at the output limit. Continue exactly where you stopped.]",
+ });
+ expect(textOf(seen, "assistant_text")).toBe("Half and half.");
});
it("refuses a tool call cut off by an incomplete response without running it", async () => {