Skip to content

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

Keep credential masking through every round that sends a request

erywim459da558f6dd
diff --git a/server/drivers/cut-reply-text.ts b/server/drivers/cut-reply-text.ts
index 8f51a01b22..10fa579a26 100644
--- a/server/drivers/cut-reply-text.ts
+++ b/server/drivers/cut-reply-text.ts
@@ -4,6 +4,27 @@ 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
diff --git a/server/drivers/openai-chat.test.ts b/server/drivers/openai-chat.test.ts
index 49c3282a1b..163385e883 100644
--- a/server/drivers/openai-chat.test.ts
+++ b/server/drivers/openai-chat.test.ts
@@ -1261,6 +1261,75 @@ describe("createOpenAIChatRuntime output-limit continuation", () => {
expect(shown).toContain("before");
});
+ it("keeps a credential split before a queued aside masked", async () => {
+ 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"));
+ }));
+ 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" },
+ });
+ 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")));
+ 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(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 () => {
+ 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"));
+ }));
+ 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" },
+ });
+ const events: RuntimeEvent[] = [];
+ instance.adapter.onEvent((event) => events.push(event));
+ try {
+ await instance.adapter.sendTurn({
+ threadId: "thread", text: "hi", approvalMode: "full",
+ integrations: { custom: { fx: { type: "http", url: remote.url, headers: {} } } },
+ });
+ await vi.waitFor(() => {
+ if (!events.some((event) => event.type === "turn.completed")) throw new Error("turn still running");
+ }, { timeout: 15_000 });
+ } finally {
+ await instance.dispose();
+ 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(events.at(-1)).toMatchObject({ type: "turn.completed", ok: true });
+ }, 30_000);
+
it("keeps a released prefix in both the deltas and the item when a tool call follows", async () => {
let requests = 0;
const events = await runTurn(
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index 411823d0cd..bfac59f619 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 { ContinuedReply, MaskedDeltas, maskSecretHalves } from "./cut-reply-text.ts";
+import { anotherRequestFollows, 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";
@@ -639,7 +639,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;
+ let completion: Completion, prefix = "", willContinue = false, willRequest = false;
for (;;) {
let streamed = false;
let answerStreamed = false;
@@ -668,13 +668,13 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const rest = holdback?.rest();
if (rest) delta(rest, "assistant_text");
}
- willContinue = !completion.toolCalls.length
- && cutReplyWillContinue(cutReplies, completion, Boolean(options.localModel && tools.definitions.length));
- // Held text is flushed only when the turn's answer ends, so a credential prefix is never shown in halves.
- const flushHeld = !willContinue && !completion.toolCalls.length;
- delta("", "assistant_text", flushHeld);
- delta("", "reasoning_text", flushHeld);
- carried = willContinue ? maskSecrets(prefix + completion.text, false).held : ""; carriedReasoning = willContinue ? maskSecrets(carriedReasoning + completion.reasoning, false).held : "";
+ 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 : "";
break;
} catch (value) {
const error = asError(value);
@@ -742,7 +742,7 @@ 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, !willContinue && !completion.toolCalls.length).visible : safeText(reply);
+ const shownReply = prefix || willContinue || completion.text.trim() ? maskSecrets(prefix + completion.text, !willRequest).visible : safeText(reply);
if (reply.trim()) { spoke = true; answer.add(shownReply); }
if (!willContinue) answer.end();
abort.signal.throwIfAborted();