Skip to content

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

Train E2: a cut reply's continuation carries the credential hold, nothing else does

milind-sonif909454a2f13
diff --git a/scripts/testing/file-size-ratchet.test.ts b/scripts/testing/file-size-ratchet.test.ts
index df6b567f75..6297401c46 100644
--- a/scripts/testing/file-size-ratchet.test.ts
+++ b/scripts/testing/file-size-ratchet.test.ts
@@ -24,7 +24,6 @@ const LINES: Record<string, number> = {
"server/drivers/claude.ts": 1989,
"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/cut-reply-text.ts b/server/drivers/cut-reply-text.ts
index 10fa579a26..adb39ce16a 100644
--- a/server/drivers/cut-reply-text.ts
+++ b/server/drivers/cut-reply-text.ts
@@ -4,31 +4,10 @@ import { maskSecretHalves } from "./secret-halves.ts";
export { maskSecretHalves } from "./secret-halves.ts";
-/** The turn loop's checks that can answer a finished reply with another request. */
-export interface ReplyFollowUp {
- unreadable: boolean;
- cut: boolean;
- corrective: boolean;
- nudge: boolean;
- asides: boolean;
-}
-
-/** True when another request follows this reply: a tool round, an unreadable call, a cut continuation, a corrective
- * round, an announcement nudge, or a queued aside. The credential hold must survive every one of them. */
-export function anotherRequestFollows(
- reply: { finishReason: string | null; text: string; reasoning: string; toolCalls: readonly unknown[] },
- follows: ReplyFollowUp,
-): boolean {
- if (reply.toolCalls.length > 0 || follows.unreadable || follows.cut) return true;
- if (!reply.text.trim() && !reply.reasoning.trim()) return false;
- if (reply.finishReason && reply.finishReason !== "stop") return false;
- return follows.corrective || follows.nudge || follows.asides;
-}
-
type StreamKind = "assistant_text" | "reasoning_text";
/** The masked deltas of one reply: a suffix that could start a configured credential is held until the next chunk
- * proves what it is, and the hold survives a continuation so a secret split at the cut is never shown in halves. */
+ * proves what it is, and the hold survives a cut reply's continuation so a secret split at the cut is never shown in halves. */
export class MaskedDeltas {
private readonly held: Record<StreamKind, string> = { assistant_text: "", reasoning_text: "" };
private readonly secrets: readonly string[];
diff --git a/server/drivers/openai-chat-prompts.ts b/server/drivers/openai-chat-prompts.ts
new file mode 100644
index 0000000000..d2a28cce34
--- /dev/null
+++ b/server/drivers/openai-chat-prompts.ts
@@ -0,0 +1,11 @@
+// The user-role instructions a chat turn injects between rounds (corrections, nudges) and the notes for a model that cannot see images.
+
+export const CORRECTIVE_ROUND = "[OpenMausBot: a tool call in this turn failed (its result is marked ok:false). Re-run the failed operations with corrected inputs where possible, check the results, then give your final answer. Do not report results you did not get.]";
+
+export const NUDGE_ANNOUNCED_ACTION = "You said what you would do next but called no tool. Use your tools for only the remaining work, or reply with verified results if nothing is left to do. Never repeat an operation that succeeded, was denied, or may already have taken effect; inspect its state instead. Do not retry a destructive operation.";
+
+export const UNREADABLE_CALL = "[OpenMausBot: your last tool call could not be read, so nothing ran. Call the tool again using only the tools you were given, with valid JSON arguments.]";
+
+export const TEXT_ONLY_ATTACHMENT_NOTE = "[The person attached image(s), but this model cannot see images. Say so if the request depends on them.]";
+
+export const TEXT_ONLY_SCREENSHOT_NOTE = "[Screenshot not shown: this model cannot see images. Read the page with a snapshot or a text tool instead.]";
diff --git a/server/drivers/openai-chat.test.ts b/server/drivers/openai-chat.test.ts
index 163385e883..59e2844963 100644
--- a/server/drivers/openai-chat.test.ts
+++ b/server/drivers/openai-chat.test.ts
@@ -1246,7 +1246,7 @@ describe("createOpenAIChatRuntime output-limit continuation", () => {
expect(reasoning).not.toContain("12345678");
});
- it("drops a held prefix when the continuation ends in a tool call", async () => {
+ it("releases a held prefix in the deltas and the item alike when the continuation ends in a tool call", async () => {
let requests = 0;
const events = await runTurn(
() => ++requests === 1
@@ -1255,58 +1255,56 @@ describe("createOpenAIChatRuntime output-limit continuation", () => {
"openai-compat",
{ MINIMAX_API_KEY: "abcdefgh12345678" },
);
- const shown = events.flatMap((event) => event.type === "content.delta" && event.streamKind === "assistant_text" ? [event.delta]
- : event.type === "item.completed" && event.itemType === "assistant_text" ? [event.text] : []).join("");
- expect(shown).not.toContain("abcdefgh");
- expect(shown).toContain("before");
+ const deltas = events.flatMap((event) => event.type === "content.delta" && event.streamKind === "assistant_text" ? [event.delta] : []).join("");
+ expect(textOf(events)[0]).toBe("before abcdefgh");
+ expect(deltas.startsWith("before abcdefgh")).toBe(true);
});
- it("keeps a credential split before a queued aside masked", async () => {
+ it("keeps a reply's last characters in its own message when a queued aside follows", async () => {
+ // Each reply is its own message: a tail that could start the key is not carried into the next one.
const bodies: string[] = [];
let release!: (response: Response) => void;
const gate = new Promise<Response>((resolve) => { release = resolve; });
vi.stubGlobal("fetch", vi.fn(async (input: string | URL, init?: RequestInit) => {
if (!String(input).endsWith("/chat/completions")) return new Response(JSON.stringify({ data: [] }));
bodies.push(String(init?.body));
- return bodies.length === 1 ? await gate : sse(text("12345678 after", "stop"));
+ return bodies.length === 1 ? await gate : sse(text("Done.", "stop"));
}));
const instance = await OpenAICompatDriver.create({
instanceId: "compat", displayName: "Compat", enabled: true,
config: OpenAICompatDriver.decodeConfig({ url: "https://api.minimax.io/v1", apiKeyEnv: "MINIMAX_API_KEY", model: "MiniMax-M3" }),
- environment: { MINIMAX_API_KEY: "abcdefgh12345678" },
+ environment: { MINIMAX_API_KEY: "sabcdefgh12345678" },
});
const events: RuntimeEvent[] = [];
instance.adapter.onEvent((event) => events.push(event));
await instance.adapter.sendTurn({ threadId: "t", text: "hi" });
await vi.waitFor(() => expect(bodies).toHaveLength(1), { timeout: 10_000 });
await expect(instance.adapter.steer!("t", "one more thing")).resolves.toBe("steered");
- release(sse(text("before abcdefgh", "stop")));
+ release(sse(text("I read the logs", "stop")));
await vi.waitFor(() => {
if (!events.some((event) => event.type === "turn.completed")) throw new Error("turn still running");
}, { timeout: 10_000 });
await instance.dispose();
expect(bodies).toHaveLength(2);
- const shown = events.flatMap((event) => event.type === "content.delta" && event.streamKind === "assistant_text" ? [event.delta]
- : event.type === "item.completed" && event.itemType === "assistant_text" ? [event.text] : []).join("");
- expect(shown).not.toContain("abcdefgh");
- expect(shown).not.toContain("12345678");
+ expect(textOf(events)).toEqual(["I read the logs", "Done."]);
expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: true });
}, 20_000);
- it("keeps a credential split between a tool-call reply and the following reply masked", async () => {
+ it("keeps the last characters before a tool call in that message", async () => {
+ // The text before a tool call ends on what could start the key; it stays in that message, not the next one.
const remote = await startFakeHttpMcp({ tools: [{ name: "read_notes", description: "Read notes", inputSchema: { type: "object", properties: {}, additionalProperties: false } }] });
let requests = 0;
vi.stubGlobal("fetch", vi.fn(async (input: unknown) => {
if (!String(input).endsWith("/chat/completions")) return new Response(JSON.stringify({ data: [] }));
requests += 1;
return sse(requests === 1
- ? two({ content: "before abcdefgh" }, { tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "fx_read_notes", arguments: "{}" } }] }, "tool_calls")
- : text("12345678 after", "stop"));
+ ? two({ content: "Let me check the logs" }, { tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "fx_read_notes", arguments: "{}" } }] }, "tool_calls")
+ : text("All clear.", "stop"));
}));
const instance = await OpenAICompatDriver.create({
instanceId: "compat", displayName: "Compat", enabled: true,
config: OpenAICompatDriver.decodeConfig({ url: "https://api.minimax.io/v1", apiKeyEnv: "MINIMAX_API_KEY", model: "MiniMax-M3" }),
- environment: { MINIMAX_API_KEY: "abcdefgh12345678" },
+ environment: { MINIMAX_API_KEY: "sabcdefgh12345678" },
});
const events: RuntimeEvent[] = [];
instance.adapter.onEvent((event) => events.push(event));
@@ -1323,10 +1321,7 @@ describe("createOpenAIChatRuntime output-limit continuation", () => {
await remote.close();
}
expect(requests).toBe(2);
- const shown = events.flatMap((event) => event.type === "content.delta" && event.streamKind === "assistant_text" ? [event.delta]
- : event.type === "item.completed" && event.itemType === "assistant_text" ? [event.text] : []).join("");
- expect(shown).not.toContain("abcdefgh");
- expect(shown).not.toContain("12345678");
+ expect(textOf(events)).toEqual(["Let me check the logs", "All clear."]);
expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: true });
}, 30_000);
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index acb106d713..e222517353 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -21,7 +21,8 @@ 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, CUT_REPLY_NOTE, cutReplyContinues, cutReplyWillContinue, object, replayableToolCalls, toolArguments, type ChatToolCall } from "./openai-chat-protocol.ts";
-import { anotherRequestFollows, ContinuedReply, MaskedDeltas, maskSecretHalves } from "./cut-reply-text.ts";
+import { ContinuedReply, MaskedDeltas, maskSecretHalves } from "./cut-reply-text.ts";
+import { CORRECTIVE_ROUND, NUDGE_ANNOUNCED_ACTION, TEXT_ONLY_ATTACHMENT_NOTE, TEXT_ONLY_SCREENSHOT_NOTE, UNREADABLE_CALL } from "./openai-chat-prompts.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";
@@ -188,15 +189,8 @@ function replayDelivered(
return { content, matched: found.map(({ record }) => record), volatile };
}
-const CORRECTIVE_ROUND = "[OpenMausBot: a tool call in this turn failed (its result is marked ok:false). Re-run the failed operations with corrected inputs where possible, check the results, then give your final answer. Do not report results you did not get.]";
-const NUDGE_ANNOUNCED_ACTION = "You said what you would do next but called no tool. Use your tools for only the remaining work, or reply with verified results if nothing is left to do. Never repeat an operation that succeeded, was denied, or may already have taken effect; inspect its state instead. Do not retry a destructive operation.";
-
-const UNREADABLE_CALL = "[OpenMausBot: your last tool call could not be read, so nothing ran. Call the tool again using only the tools you were given, with valid JSON arguments.]";
const LOCAL_CORRECTIVE_ROUNDS = 2;
-const TEXT_ONLY_ATTACHMENT_NOTE = "[The person attached image(s), but this model cannot see images. Say so if the request depends on them.]";
-const TEXT_ONLY_SCREENSHOT_NOTE = "[Screenshot not shown: this model cannot see images. Read the page with a snapshot or a text tool instead.]";
-
export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>): ProviderInstance {
const { input } = options;
const listeners = new Set<RuntimeEventListener>();
@@ -639,7 +633,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
native("out", options.nativeLog.outgoing(turn, messages, model, tools.definitions));
let attempt = 0;
let resends = 0;
- let completion: Completion, prefix = "", willContinue = false, willRequest = false;
+ let completion: Completion, prefix = "", willContinue = false;
for (;;) {
let streamed = false;
let answerStreamed = false;
@@ -669,12 +663,9 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
if (rest) delta(rest, "assistant_text");
}
willContinue = !completion.toolCalls.length && cutReplyWillContinue(cutReplies, completion, Boolean(options.localModel && tools.definitions.length));
- // The hold survives a reply another request may answer, so a credential is never shown in halves.
- willRequest = anotherRequestFollows(completion, { unreadable, cut: willContinue,
- corrective: toolFailed && !denials.length && correctiveRounds < Math.max(turn.toolErrorCorrectiveRounds ?? 0, options.localModel ? LOCAL_CORRECTIVE_ROUNDS : 0),
- nudge: Boolean(options.nudgeAnnouncedAction) && tools.definitions.length > 0 && announcesAction(completion.text) && nudges < MAX_ANNOUNCEMENT_NUDGES && callsAtNudge !== seenCalls.size, asides: turnEntry.asides.length > 0 });
- delta("", "assistant_text", !willRequest); delta("", "reasoning_text", !willRequest);
- carried = willRequest ? maskSecrets(prefix + completion.text, false).held : ""; carriedReasoning = willRequest ? maskSecrets(carriedReasoning + completion.reasoning, false).held : "";
+ // Only a cut reply's continuation joins this one in a single message, so only there does a held credential prefix carry over.
+ delta("", "assistant_text", !willContinue); delta("", "reasoning_text", !willContinue);
+ carried = willContinue ? maskSecrets(prefix + completion.text, false).held : ""; carriedReasoning = willContinue ? maskSecrets(carriedReasoning + completion.reasoning, false).held : "";
break;
} catch (value) {
const error = asError(value);
@@ -742,8 +733,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
}
// Reasoning on a tool-call round belongs to the protocol, not a final reply.
const reply = completion.text.trim() ? completion.text : completion.toolCalls.length || unreadable ? "" : completion.reasoning;
- const shownReply = prefix || willContinue || completion.text.trim() ? maskSecrets(prefix + completion.text, !willRequest).visible : safeText(reply);
- if (reply.trim()) { spoke = true; answer.add(shownReply); }
+ const shownReply = prefix || willContinue || completion.text.trim() ? maskSecrets(prefix + completion.text, !willContinue).visible : safeText(reply);
+ if (reply.trim() || prefix) { spoke = true; answer.add(shownReply); }
if (!willContinue) answer.end();
abort.signal.throwIfAborted();
if (unreadable) {
diff --git a/server/drivers/openai-responses.ts b/server/drivers/openai-responses.ts
index fd90208b9f..02be5f4ab9 100644
--- a/server/drivers/openai-responses.ts
+++ b/server/drivers/openai-responses.ts
@@ -200,9 +200,12 @@ export async function readResponsesStream(body: ReadableStream<Uint8Array> | nul
};
const finish = (response: Record<string, unknown> | undefined) => {
if (Array.isArray(response?.output)) {
+ // Items the stream never finished (a cut message) join from the final output; one without an id only when nothing
+ // finished, so a call already finished under another position can never run twice.
+ const none = !done.size;
for (const [position, item] of response.output.entries()) {
const known = object(item) ? (item as ResponseItem).id : undefined;
- if (object(item) && !done.has(position) && !(typeof known === "string" && finishedItems.has(known))) finishItem(item as ResponseItem, position);
+ if (object(item) && !done.has(position) && (typeof known === "string" ? !finishedItems.has(known) : none)) finishItem(item as ResponseItem, position);
}
}
const used = object(response?.usage);