Skip to content

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

Merge #7763: append-only chat-engine requests for prompt-cache reuse

milind-soniff05128acac2
diff --cc server/drivers/openai-chat.ts
index f018873703,275289a318..6a46bc3547
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@@ -1,8 -1,15 +1,8 @@@
import { RuntimeNoticeError, runtimeErrorText } from "./runtime-notice-error.ts";
- import { createHash } from "node:crypto";
+ import { createChatReplay, keepRecent, type DeliveredUserMessage } from "./openai-chat-replay.ts";
-import type {
- DriverCreateInput,
- ModelCatalog,
- ProviderInstance, ProviderSnapshot,
- RuntimeEvent,
- RuntimeEventListener,
- SendTurnInput,
- TextGenerationOptions,
-} from "../contracts.ts";
+import type { DriverCreateInput, ModelCatalog, ProviderInstance, ProviderSnapshot, RuntimeEvent, RuntimeEventListener, SendTurnInput, TextGenerationOptions } from "../contracts.ts";
import { newEventId, newId } from "../contracts.ts";
+import { CustomHeaderError, customHeaderSecrets, maskCustomSecrets, resolveCustomHeaders, scrubErrorSecrets, type OpenAICompatCustomHeadersConfig, type RuntimeHeaderContext } from "./openai-compat-headers.ts";
import { ASK_USER_TOOL, ASK_USER_TOOL_DEFINITION, askQuestionSummary, parseAskQuestions, questionChoices } from "../../shared/ask-question.ts";
import { allowsTool, parseToolScope } from "../../shared/tool-scope.ts";
import { redactSecretsInText } from "../redact.ts";
@@@ -144,52 -143,15 +144,8 @@@ const asError = (value: unknown): Erro
const MAX_TURN_TOOL_CALLS = 200;
const MAX_ANNOUNCEMENT_NUDGES = 3;
- interface DeliveredUserMessage {
- text: string;
- sent: string;
- volatile?: string;
- after: string;
- }
-
- const MAX_REPLAY_EXTRA_BYTES = 24_000;
- const MAX_DELIVERED_THREADS = 256;
-
- const fingerprint = (text: string) => createHash("sha256").update(text).digest("base64url");
-
- function replayDelivered(
- transcript: ReadonlyArray<{ role: "user" | "assistant"; text: string }>,
- records: readonly DeliveredUserMessage[],
- ): { content: Map<number, string>; matched: DeliveredUserMessage[]; volatile: string | undefined } {
- const found: Array<{ index: number; record: DeliveredUserMessage }> = [];
- let next = records.length - 1;
- for (let index = transcript.length - 1; index >= 0 && next >= 0; index--) {
- const message = transcript[index]!;
- if (message.role !== "user" || !message.text) continue;
- const after = index > 0 ? fingerprint(transcript[index - 1]!.text) : undefined;
- for (let at = next; at >= 0; at--) {
- const record = records[at]!;
- if (record.text !== message.text && !record.text.endsWith("\n\n" + message.text)) continue;
- if (after !== undefined && record.after !== after) continue;
- found.unshift({ index, record });
- next = at - 1;
- break;
- }
- }
- const content = new Map<number, string>();
- let volatile: string | undefined;
- let budget = MAX_REPLAY_EXTRA_BYTES;
- for (const { index, record } of found) {
- const extra = Buffer.byteLength(record.sent) - Buffer.byteLength(transcript[index]!.text);
- if (extra > budget) break;
- budget -= extra;
- content.set(index, record.sent);
- if (record.volatile !== undefined) volatile = record.volatile;
- }
- 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>();
@@@ -212,10 -174,14 +168,14 @@@
...(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[]>();
+ const conversations = createChatReplay();
+ /** Per bot (or conversation): the MCP servers its last turn listed tools from, started before the next turn's first request. */
+ const listedServers = new Map<string, Set<string>>();
+ /** The window a local server refused an oversized request with (llama.cpp's n_ctx), for compaction to time folds by. */
+ const refusedWindows = new Map<string, number>();
/** Not cleared on `sessionReset`: with no cursor the harness sends it on nearly every turn. */
const sessionGrants = new Map<string, Set<string>>();
@@@ -579,9 -536,6 +525,9 @@@
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 answer = new ContinuedReply((text) => emit({ ...base(turn.threadId, turnId), type: "item.completed", itemType: "assistant_text", text }));
++ const answer = new ContinuedReply((text) => { replies.push(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;
@@@ -623,10 -579,11 +571,11 @@@
// Servers still starting join between rounds, never once the tools were dropped (none left while ask_user is allowed).
const joined = !questionAllowed || tools.definitions.length ? await joinLateChatTools(tools, [ASK_USER_TOOL_DEFINITION]) : undefined;
for (const message of joined ?? []) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });
- native("out", options.nativeLog.outgoing(turn, messages, model, tools.definitions));
+ native("out", { ...object(options.nativeLog.outgoing(turn, messages, model, tools.definitions)), ...conversations.repeated(turn.threadId, messages, tools.definitions),
+ ...(process.env.OPENMAUS_LOG_CHAT_REQUESTS === "1" ? { messages, tools: tools.definitions } : {}) });
let attempt = 0;
let resends = 0;
- let completion: Completion;
+ let completion: Completion, prefix = "", willContinue = false;
for (;;) {
let streamed = false;
let answerStreamed = false;
@@@ -880,7 -844,7 +833,8 @@@
} finally {
turnEntry.ending = true;
approval.close();
+ answer.end();
+ if (tools) keepRecent(listedServers, serversKey, new Set(tools.listedServers()));
let cleanupFailed = false;
try { await tools?.close(); }
catch {