Skip to content

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

Keep credential masking across a continued reply

erywimfc8f55f961ba
diff --git a/server/drivers/openai-chat-protocol.ts b/server/drivers/openai-chat-protocol.ts
index 51202f1f6c..d904267bac 100644
--- a/server/drivers/openai-chat-protocol.ts
+++ b/server/drivers/openai-chat-protocol.ts
@@ -22,12 +22,19 @@ 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. */
+/** True when a reply cut at the output limit has a continuation left. A local model writes tool calls as text, so a
+ * cut reply there may be half a call and stays a failure. */
+export function cutReplyWillContinue(state: { count: number }, completion: { finishReason: string | null; text: string }, localTools: boolean): boolean {
+ return completion.finishReason === "length" && Boolean(completion.text.trim()) && !localTools && state.count < MAX_LENGTH_CONTINUATIONS;
+}
+
+/** True when a reply cut at the output limit should be continued; throws once the cap is reached. */
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.`);
+ if (!cutReplyWillContinue(state, completion, localTools)) {
+ if (completion.finishReason === "length" && completion.text.trim() && !localTools) {
+ throw new ChatProtocolError(`The reply was still cut at the output limit after ${MAX_LENGTH_CONTINUATIONS} continuations; the turn was stopped.`);
+ }
+ return false;
}
state.count += 1;
return true;
diff --git a/server/drivers/openai-chat.test.ts b/server/drivers/openai-chat.test.ts
index 5a556336c9..92cd2a4c53 100644
--- a/server/drivers/openai-chat.test.ts
+++ b/server/drivers/openai-chat.test.ts
@@ -20,19 +20,20 @@ afterEach(() => vi.unstubAllGlobals());
const sse = (body: string) => new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } });
/** `body` is every request's stream, or a factory per chat completion (the catalog fetch then gets a 404). */
-async function runTurn(body: string | (() => Response), driver: "openai-compat" | "minimax" = "openai-compat") {
+async function runTurn(body: string | (() => Response), driver: "openai-compat" | "minimax" = "openai-compat",
+ environment: Record<string, string> = { MINIMAX_API_KEY: "secret" }) {
vi.stubGlobal("fetch", vi.fn(async (url: string | URL) => typeof body === "string" ? sse(body)
: String(url).endsWith("/chat/completions") ? body() : new Response("", { status: 404 })));
const instance = driver === "minimax"
? await MinimaxDriver.create({
instanceId: "minimax", displayName: "MiniMax", enabled: true,
config: MinimaxDriver.defaultConfig(),
- environment: { MINIMAX_API_KEY: "secret" },
+ environment,
})
: await OpenAICompatDriver.create({
instanceId: "minimax", displayName: "MiniMax", enabled: true,
config: OpenAICompatDriver.decodeConfig({ url: "https://api.minimax.io/v1", apiKeyEnv: "MINIMAX_API_KEY", model: "MiniMax-M3" }),
- environment: { MINIMAX_API_KEY: "secret" },
+ environment,
});
const events: RuntimeEvent[] = [];
instance.adapter.onEvent((event) => events.push(event));
@@ -1185,6 +1186,22 @@ describe("createOpenAIChatRuntime output-limit continuation", () => {
]);
});
+ it("never shows either half of a credential split at a continuation boundary", async () => {
+ const secret = "abcdefgh12345678";
+ let requests = 0;
+ const events = await runTurn(
+ () => ++requests === 1 ? sse(text("before abcdefgh", "length")) : sse(text("12345678 after", "stop")),
+ "openai-compat",
+ { MINIMAX_API_KEY: secret },
+ );
+ expect(requests).toBe(2);
+ expect(textOf(events)).toEqual(["before ", "[redacted] after"]);
+ 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] : []);
+ expect(shown.join("")).not.toContain("abcdefgh");
+ expect(shown.join("")).not.toContain("12345678");
+ });
+
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 029f3623f5..6ca9f95305 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -20,7 +20,8 @@ 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, CUT_REPLY_NOTE, cutReplyContinues, object, replayableToolCalls, toolArguments, type ChatToolCall } from "./openai-chat-protocol.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 { 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";
@@ -539,6 +540,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
for (const secret of secrets) if (secret) safe = safe.split(secret).join("[redacted]");
return redactSecretsInText(safe);
};
+ const maskSecrets = (text: string, flush: boolean) => maskSecretHalves(text, secrets, safeText, flush);
const preview = (value: unknown) => toolDetailPreview(JSON.parse(JSON.stringify(value, (_key, part) =>
typeof part === "string" ? safeText(part) : part)));
const native = (dir: "out" | "in", msg: unknown) => appendNative(turn.threadId, {
@@ -591,6 +593,7 @@ 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 = "";
const denials: string[] = [], failedCalls: string[] = [];
const seenCalls = new Set<string>();
let nudges = 0;
@@ -635,26 +638,17 @@ 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;
+ let completion: Completion, prefix = "", willContinue = false;
for (;;) {
let streamed = false;
let answerStreamed = false;
const holdback = options.localModel && tools.definitions.length ? new TextCallHoldback() : undefined;
- const pending = { assistant_text: "", reasoning_text: "" };
+ prefix = carried;
+ const pending = { assistant_text: prefix, reasoning_text: "" };
const delta = (text: string, streamKind: keyof typeof pending, flush = false) => {
- let combined = pending[streamKind] + text;
- // Mask whole matches before holding a suffix, or "abab" could split at its own repeated prefix.
- for (const secret of secrets) if (secret) combined = combined.split(secret).join("[redacted]");
- let hold = 0;
- // A configured credential can straddle chunks: hold any suffix that could be its prefix.
- if (!flush) for (const secret of secrets) {
- for (let length = Math.min(secret.length - 1, combined.length); length > hold; length--) {
- if (combined.endsWith(secret.slice(0, length))) { hold = length; break; }
- }
- }
- pending[streamKind] = hold ? combined.slice(-hold) : "";
- const visible = safeText(hold ? combined.slice(0, -hold) : combined);
- if (visible) emit({ ...base(turn.threadId, turnId), type: "content.delta", streamKind, delta: visible });
+ 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 });
};
try {
completion = await complete(messages, model, true, abort.signal, (text, streamKind) => {
@@ -676,8 +670,12 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const rest = holdback?.rest();
if (rest) delta(rest, "assistant_text");
}
- delta("", "assistant_text", true);
+ 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.
+ delta("", "assistant_text", !willContinue);
delta("", "reasoning_text", true);
+ carried = willContinue ? pending.assistant_text : "";
break;
} catch (value) {
const error = asError(value);
@@ -745,7 +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;
- if (reply.trim()) { spoke = true; emit({ ...base(turn.threadId, turnId), type: "item.completed", itemType: "assistant_text", text: safeText(reply) }); }
+ const shownReply = prefix || willContinue ? maskSecrets(prefix + completion.text, !willContinue).visible : safeText(reply);
+ if (reply.trim()) { spoke = true; emit({ ...base(turn.threadId, turnId), type: "item.completed", itemType: "assistant_text", text: shownReply }); }
abort.signal.throwIfAborted();
if (unreadable) {
askedAgain = true;
diff --git a/server/drivers/secret-halves.ts b/server/drivers/secret-halves.ts
new file mode 100644
index 0000000000..bc0b2e934e
--- /dev/null
+++ b/server/drivers/secret-halves.ts
@@ -0,0 +1,13 @@
+/** Masks whole credentials in `text`; unless flushing, holds back a trailing piece that could start one, so a
+ * credential split across chunks or requests is never shown in halves. */
+export function maskSecretHalves(text: string, secrets: readonly string[], safe: (text: string) => string, flush: boolean): { visible: string; held: string } {
+ let combined = text;
+ for (const secret of secrets) if (secret) combined = combined.split(secret).join("[redacted]");
+ let hold = 0;
+ if (!flush) for (const secret of secrets) {
+ for (let length = Math.min(secret.length - 1, combined.length); length > hold; length--) {
+ if (combined.endsWith(secret.slice(0, length))) { hold = length; break; }
+ }
+ }
+ return { visible: safe(hold ? combined.slice(0, -hold) : combined), held: hold ? combined.slice(-hold) : "" };
+}