Skip to content

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

Mask reasoning across a continued reply and finish it as one item

erywim8130a91b83ac
diff --git a/server/drivers/cut-reply-text.ts b/server/drivers/cut-reply-text.ts
new file mode 100644
index 0000000000..05a6a82a51
--- /dev/null
+++ b/server/drivers/cut-reply-text.ts
@@ -0,0 +1,46 @@
+// The text of a reply that spans output-limit continuations: configured credentials stay masked even when one is split
+// between requests, and the pieces reach consumers as one answer.
+import { maskSecretHalves } from "./secret-halves.ts";
+
+export { maskSecretHalves } from "./secret-halves.ts";
+
+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. */
+export class MaskedDeltas {
+ private readonly held: Record<StreamKind, string> = { assistant_text: "", reasoning_text: "" };
+ private readonly secrets: readonly string[];
+ private readonly safe: (text: string) => string;
+ private readonly emit: (text: string, kind: StreamKind) => void;
+ constructor(
+ secrets: readonly string[],
+ safe: (text: string) => string,
+ emit: (text: string, kind: StreamKind) => void,
+ ) {
+ this.secrets = secrets;
+ this.safe = safe;
+ this.emit = emit;
+ }
+ seed(kind: StreamKind, text: string) { this.held[kind] = text; }
+ heldText(kind: StreamKind) { return this.held[kind]; }
+ feed(text: string, kind: StreamKind, flush = false) {
+ const masked = maskSecretHalves(this.held[kind] + text, this.secrets, this.safe, flush);
+ this.held[kind] = masked.held;
+ if (masked.visible) this.emit(masked.visible, kind);
+ }
+}
+
+/** The answer a continuation chain builds: emitted once when the chain ends, or when the turn fails, so a consumer that
+ * reads the last completed item gets the whole reply instead of its last fragment. */
+export class ContinuedReply {
+ private text = "";
+ private readonly emit: (text: string) => void;
+ constructor(emit: (text: string) => void) { this.emit = emit; }
+ add(part: string) { this.text += part; }
+ end() {
+ if (!this.text) return;
+ this.emit(this.text);
+ this.text = "";
+ }
+}
diff --git a/server/drivers/openai-chat.test.ts b/server/drivers/openai-chat.test.ts
index 6efc693092..7215201baa 100644
--- a/server/drivers/openai-chat.test.ts
+++ b/server/drivers/openai-chat.test.ts
@@ -1166,6 +1166,10 @@ describe("createOpenAIChatRuntime output-limit continuation", () => {
`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 two = (first: Record<string, unknown>, second: Record<string, unknown>, finishReason: string) =>
+ `data: ${JSON.stringify({ choices: [{ index: 0, delta: first }] })}\n\n`
+ + `data: ${JSON.stringify({ choices: [{ index: 0, delta: second }] })}\n\n`
+ + `data: ${JSON.stringify({ choices: [{ index: 0, delta: {}, finish_reason: finishReason }], usage: { prompt_tokens: 10, completion_tokens: 4 } })}\n\n`;
const json = (value: string, finishReason: string) => new Response(JSON.stringify({
choices: [{ index: 0, message: { role: "assistant", content: value }, finish_reason: finishReason }],
usage: { prompt_tokens: 10, completion_tokens: 4 },
@@ -1224,6 +1228,49 @@ describe("createOpenAIChatRuntime output-limit continuation", () => {
]);
});
+ it("keeps a credential split across the reasoning of a continuation masked", async () => {
+ const secret = "abcdefgh12345678";
+ let requests = 0;
+ const events = await runTurn(
+ () => ++requests === 1
+ ? sse(two({ reasoning_content: "checking abcdefgh" }, { content: "before" }, "length"))
+ : sse(two({ reasoning_content: "12345678 again" }, { content: " after" }, "stop")),
+ "openai-compat",
+ { MINIMAX_API_KEY: secret },
+ );
+ expect(requests).toBe(2);
+ expect(textOf(events)).toEqual(["before after"]);
+ const reasoning = events.flatMap((event) => event.type === "content.delta" && event.streamKind === "reasoning_text" ? [event.delta] : []).join("");
+ expect(reasoning).toContain("[redacted]");
+ expect(reasoning).not.toContain("abcdefgh");
+ expect(reasoning).not.toContain("12345678");
+ });
+
+ it("drops a held prefix when the continuation ends in a tool call", async () => {
+ let requests = 0;
+ const events = await runTurn(
+ () => ++requests === 1
+ ? sse(text("before abcdefgh", "length"))
+ : sse(stream({ tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "no_such_tool", arguments: "{}" } }] }, "tool_calls")),
+ "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");
+ });
+
+ it("keeps the partial answer when the continuation request fails", async () => {
+ let requests = 0;
+ const events = await runTurn(() => ++requests === 1
+ ? sse(text("The report is", "length"))
+ : new Response(JSON.stringify({ error: { message: "bad request" } }), { status: 400, headers: { "content-type": "application/json" } }));
+ expect(requests).toBe(2);
+ expect(textOf(events)).toEqual(["The report is"]);
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false });
+ });
+
it("still fails a length finish with no text", async () => {
let requests = 0;
const events = await runTurn(() => (requests++, sse(text("", "length"))));
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index 097956505d..4d1e1aec7a 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, CUT_REPLY_NOTE, cutReplyContinues, cutReplyWillContinue, object, replayableToolCalls, toolArguments, type ChatToolCall } from "./openai-chat-protocol.ts";
-import { maskSecretHalves } from "./secret-halves.ts";
+import { ContinuedReply, MaskedDeltas, maskSecretHalves } from "./cut-reply-text.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";
@@ -593,7 +593,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
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 };
- let carried = "", continuedReply = "";
+ const answer = new ContinuedReply((text) => emit({ ...base(turn.threadId, turnId), type: "item.completed", itemType: "assistant_text", text }));
+ let carried = "", carriedReasoning = "";
const denials: string[] = [], failedCalls: string[] = [];
const seenCalls = new Set<string>();
let nudges = 0;
@@ -644,12 +645,9 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
let answerStreamed = false;
const holdback = options.localModel && tools.definitions.length ? new TextCallHoldback() : undefined;
prefix = carried;
- const pending = { assistant_text: prefix, reasoning_text: "" };
- const delta = (text: string, streamKind: keyof typeof pending, flush = false) => {
- const masked = maskSecrets(pending[streamKind] + text, flush);
- pending[streamKind] = masked.held;
- if (masked.visible) emit({ ...base(turn.threadId, turnId), type: "content.delta", streamKind, delta: masked.visible });
- };
+ const deltas = new MaskedDeltas(secrets, safeText, (delta, streamKind) => emit({ ...base(turn.threadId, turnId), type: "content.delta", streamKind, delta }));
+ deltas.seed("assistant_text", prefix); deltas.seed("reasoning_text", carriedReasoning);
+ const delta = deltas.feed.bind(deltas);
try {
completion = await complete(messages, model, true, abort.signal, (text, streamKind) => {
streamed = true;
@@ -672,10 +670,11 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
}
willContinue = !completion.toolCalls.length
&& cutReplyWillContinue(cutReplies, completion, Boolean(options.localModel && tools.definitions.length));
- // A continuation resumes the same text, so a held credential prefix crosses over instead of being shown.
+ // A held prefix that no continuation will complete is dropped, not shown as half a credential.
+ if (prefix && (!completion.text.trim() || completion.toolCalls.length > 0)) { prefix = ""; deltas.seed("assistant_text", ""); }
delta("", "assistant_text", !willContinue);
- delta("", "reasoning_text", true);
- carried = willContinue ? maskSecrets(prefix + completion.text, false).held : "";
+ 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);
@@ -744,8 +743,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 ? maskSecrets(prefix + completion.text, !willContinue).visible : safeText(reply);
- if (reply.trim()) { spoke = true; continuedReply += shownReply; }
- if (!willContinue && continuedReply) { emit({ ...base(turn.threadId, turnId), type: "item.completed", itemType: "assistant_text", text: continuedReply }); continuedReply = ""; }
+ if (reply.trim()) { spoke = true; answer.add(shownReply); }
+ if (!willContinue) answer.end();
abort.signal.throwIfAborted();
if (unreadable) {
askedAgain = true;
@@ -896,6 +895,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
} finally {
turnEntry.ending = true;
approval.close();
+ answer.end();
let cleanupFailed = false;
try { await tools?.close(); }
catch {
diff --git a/server/drivers/openai-responses.test.ts b/server/drivers/openai-responses.test.ts
index 45399443fb..a845710457 100644
--- a/server/drivers/openai-responses.test.ts
+++ b/server/drivers/openai-responses.test.ts
@@ -497,6 +497,27 @@ describe("what Responses can answer", () => {
expect(textOf(seen, "assistant_text")).toBe("Half and half.");
});
+ it("does not repeat a cut message whose done event carried no output index", async () => {
+ let responses = 0;
+ const f = await fixture(onResponses((response) => {
+ responses += 1;
+ if (responses === 1) {
+ const reasoning = reasoningItem();
+ const partial = messageItem("Half");
+ events(response, [
+ created,
+ done(partial),
+ { type: "response.incomplete", response: { status: "incomplete", incomplete_details: { reason: "max_output_tokens" }, output: [reasoning, partial], usage } },
+ ]);
+ return;
+ }
+ answer(response, " and half.");
+ }));
+ const { end, events: seen } = await f.turn();
+ expect(end).toMatchObject({ ok: true });
+ expect(textOf(seen, "assistant_text")).toBe("Half and half.");
+ });
+
it("refuses a tool call cut off by an incomplete response without running it", async () => {
const f = await fixture(onResponses((response) => {
events(response, [done(callItem()), { type: "response.incomplete", response: { status: "incomplete", incomplete_details: { reason: "max_output_tokens" }, output: [callItem()] } }]);
diff --git a/server/drivers/openai-responses.ts b/server/drivers/openai-responses.ts
index 8e5f1049d0..fd90208b9f 100644
--- a/server/drivers/openai-responses.ts
+++ b/server/drivers/openai-responses.ts
@@ -169,6 +169,7 @@ export async function readResponsesStream(body: ReadableStream<Uint8Array> | nul
let usage: Completion["usage"] = null;
const streamed = new Set<unknown>();
const done = new Map<number, ResponseItem>();
+ const finishedItems = new Set<string>();
const calls = new ChatToolCalls();
let callCount = 0;
@@ -188,6 +189,7 @@ export async function readResponsesStream(body: ReadableStream<Uint8Array> | nul
};
const finishItem = (item: ResponseItem, position: number) => {
done.set(position, item);
+ if (typeof item.id === "string") finishedItems.add(item.id);
if (item.type === "function_call") {
calls.add([{ index: callCount++, id: item.call_id, type: "function", function: { name: item.name, arguments: item.arguments } }], true);
} else if (item.type === "message" && !streamed.has(item.id)) {
@@ -198,7 +200,10 @@ export async function readResponsesStream(body: ReadableStream<Uint8Array> | nul
};
const finish = (response: Record<string, unknown> | undefined) => {
if (Array.isArray(response?.output)) {
- for (const [position, item] of response.output.entries()) if (object(item) && !done.has(position)) finishItem(item as ResponseItem, position);
+ 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);
+ }
}
const used = object(response?.usage);
const cachedInput = object(used?.input_tokens_details)?.cached_tokens;