Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Codex: fuse accumulated developer instruction blocks and rebuild the session
skygunnerb683e4116a90
diff --git a/server/drivers/codex-instructions.test.ts b/server/drivers/codex-instructions.test.tsindex 5fef12a163..9fe98ef9cd 100644--- a/server/drivers/codex-instructions.test.ts+++ b/server/drivers/codex-instructions.test.ts@@ -3,7 +3,7 @@ import { readFileSync, writeFileSync } from "node:fs";import { join } from "node:path";import { describe, expect, it, vi } from "vitest";import { DATA_DIR } from "../config.ts";-import { CODEX_LINUX_SANDBOX_NOTE, codexDeveloperInstructions, codexSandboxNote, syncCodexInstructions } from "./codex-instructions.ts";+import { CODEX_INJECTED_CHAR_LIMIT, CODEX_LINUX_SANDBOX_NOTE, codexDeveloperInstructions, codexSandboxNote, syncCodexInstructions } from "./codex-instructions.ts";import { customApprovalParams, namedApprovalParams } from "./codex-approval-config.ts";const receiptPath = (key: string, nativeThreadId: string) =>@@ -152,15 +152,55 @@ describe("Codex instruction receipts", () => {expect(first.deliverVolatile).toBe(true);const path = receiptPath(key, "native");const pending = JSON.parse(readFileSync(path, "utf8"));- expect(pending).toEqual({ instructions: expect.any(String) });+ expect(pending).toEqual({ instructions: expect.any(String), injected: expect.any(Number) });const retry = await syncCodexInstructions(key, "native", "rules", "memory v1", true, request);expect(retry.deliverVolatile).toBe(true);expect(first.commitVolatile).toBeTypeOf("function");first.commitVolatile?.();const committed = JSON.parse(readFileSync(path, "utf8"));- expect(committed).toEqual({ instructions: pending.instructions, volatile: expect.any(String) });+ expect(committed).toEqual({ instructions: pending.instructions, volatile: expect.any(String), injected: pending.injected });const after = await syncCodexInstructions(key, "native", "rules", "memory v1", true, request);expect(after.deliverVolatile).toBe(false);expect(after.commitVolatile).toBeNull();});++ it("counts each thread's developer blocks and fuses edits near the provider cap instead of growing the history unbounded", async () => {+ const key = randomUUID();+ const request = vi.fn().mockResolvedValue({});+ const rules = "x".repeat(40_000);+ await syncCodexInstructions(key, "native", rules, "", false, request);+ const path = receiptPath(key, "native");+ expect(JSON.parse(readFileSync(path, "utf8"))).toMatchObject({ injected: rules.length });+ let resets = 0;+ for (let edit = 1; edit <= 10; edit++) {+ const result = await syncCodexInstructions(key, "native", `${rules}${"!".repeat(edit)}`, "", true, request);+ resets += result.resetSession ? 1 : 0;+ }+ // One ~40k edit still fits under the 85,000-character provider bound; each later one would cross it.+ expect(request).toHaveBeenCalledTimes(1);+ expect(resets).toBe(9);+ const injected = request.mock.calls[0][1].items[0].content[0].text as string;+ const receipt = JSON.parse(readFileSync(path, "utf8"));+ expect(receipt).toEqual({+ instructions: createHash("sha256").update(`${rules}!`).digest("hex"),+ injected: rules.length + injected.length,+ });+ // A tripped sync acknowledges nothing, so the fresh session's own receipt starts from its initial block.+ const tripped = await syncCodexInstructions(key, "native", `${rules}??`, "", true, request);+ expect(tripped).toEqual({ deliverVolatile: false, hadVolatile: false, commitVolatile: null, resetSession: true });+ expect(request).toHaveBeenCalledTimes(1);+ });++ it("asks for a fresh session even without a new edit once the accumulated blocks pass the provider cap", async () => {+ const key = randomUUID();+ const request = vi.fn().mockResolvedValue({});+ await syncCodexInstructions(key, "native", "rules", "", false, request);+ const path = receiptPath(key, "native");+ const receipt = JSON.parse(readFileSync(path, "utf8"));+ writeFileSync(path, JSON.stringify({ ...receipt, injected: CODEX_INJECTED_CHAR_LIMIT + 1 }), { mode: 0o600 });+ const result = await syncCodexInstructions(key, "native", "rules", "", true, request);+ expect(result).toEqual({ deliverVolatile: false, hadVolatile: false, commitVolatile: null, resetSession: true });+ expect(request).not.toHaveBeenCalled();+ expect(JSON.parse(readFileSync(path, "utf8")).injected).toBe(CODEX_INJECTED_CHAR_LIMIT + 1);+ });});diff --git a/server/drivers/codex-instructions.ts b/server/drivers/codex-instructions.tsindex cd49875b45..9647496f5c 100644--- a/server/drivers/codex-instructions.ts+++ b/server/drivers/codex-instructions.ts@@ -31,8 +31,13 @@ const digest = (value: string) => createHash("sha256").update(value).digest("hexexport interface CodexInstructionReceipt {instructions: string;volatile?: string;+ /** Characters of OpenMausBot developer blocks this native thread's history carries. */+ injected?: number;}+// Providers merge developer content into one system prompt with a hard character cap (issue #5317: GLM rejects above 100,000); 85,000 leaves room for Codex's own developer blocks.+export const CODEX_INJECTED_CHAR_LIMIT = 85_000;+const isFingerprint = (value: string) => /^[0-9a-f]{64}$/.test(value);function parseReceipt(raw: string | undefined): CodexInstructionReceipt | null {@@ -42,11 +47,12 @@ function parseReceipt(raw: string | undefined): CodexInstructionReceipt | null {try {const parsed = JSON.parse(trimmed) as unknown;if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {- const record = parsed as { instructions?: unknown; volatile?: unknown };+ const record = parsed as { instructions?: unknown; volatile?: unknown; injected?: unknown };if (typeof record.instructions === "string" && isFingerprint(record.instructions)) {return {instructions: record.instructions,...(typeof record.volatile === "string" && isFingerprint(record.volatile) ? { volatile: record.volatile } : {}),+ ...(typeof record.injected === "number" && Number.isSafeInteger(record.injected) && record.injected >= 0 ? { injected: record.injected } : {}),};}}@@ -78,7 +84,7 @@ export async function syncCodexInstructions(resumed: boolean,request: (method: string, params: Record<string, unknown>) => Promise<unknown>,mentionTurn = false,-): Promise<{ deliverVolatile: boolean; hadVolatile: boolean; commitVolatile: (() => void) | null }> {+): Promise<{ deliverVolatile: boolean; hadVolatile: boolean; commitVolatile: (() => void) | null; resetSession: boolean }> {const directory = join(DATA_DIR, "codex-instructions");const path = join(directory, `${digest(JSON.stringify([key, nativeThreadId]))}.sha256`);const fingerprint = digest(instructions);@@ -90,6 +96,15 @@ export async function syncCodexInstructions(if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;previous = null;}+ const injected = previous?.injected ?? 0;+ const hadVolatile = typeof previous?.volatile === "string" && previous.volatile !== digest("");+ const replacement = "The following replaces the previous developer instruction block supplied by OpenMausBot, including its native configured rules and bot-specific instructions. Other Codex instructions and permissions still apply.\n\n"+ + (instructions || "No OpenMausBot bot-specific instructions remain.");+ if (resumed && injected + (previous?.instructions === fingerprint ? 0 : replacement.length) > CODEX_INJECTED_CHAR_LIMIT) {+ // Superseded blocks stay in the thread until codex compacts, so another injection would only push the+ // provider's system prompt past its cap; the driver's fresh-session recovery is the only cleanup.+ return { deliverVolatile: false, hadVolatile, commitVolatile: null, resetSession: true };+ }if (resumed && previous?.instructions !== fingerprint) {// Codex 0.153.4 keeps the old initial developer message until compaction, so an update is appended// only on change. inject_items flushes history before acknowledging; only then is the receipt written.@@ -99,11 +114,7 @@ export async function syncCodexInstructions(items: [{type: "message",role: "developer",- content: [{- type: "input_text",- text: "The following replaces the previous developer instruction block supplied by OpenMausBot, including its native configured rules and bot-specific instructions. Other Codex instructions and permissions still apply.\n\n"- + (instructions || "No OpenMausBot bot-specific instructions remain."),- }],+ content: [{ type: "input_text", text: replacement }],}],});} catch (error) {@@ -114,17 +125,20 @@ export async function syncCodexInstructions(}}const deliverVolatile = !resumed || previous?.volatile !== volatileFingerprint || mentionTurn;- const hadVolatile = typeof previous?.volatile === "string" && previous.volatile !== digest("");+ // A fresh thread carries its block through thread/start instead of inject_items, so it counts toward the same total.+ const acknowledged = !resumed || previous?.instructions !== fingerprint+ ? { instructions: fingerprint, injected: !resumed ? instructions.length : injected + replacement.length }+ : { instructions: fingerprint, injected };if (!resumed || previous?.instructions !== fingerprint) {// The volatile digest stays pending until the provider accepts the turn, so a rejected one redelivers.mkdirSync(directory, { recursive: true });- writeFileAtomic(path, JSON.stringify({ instructions: fingerprint }), { mode: 0o600 });+ writeFileAtomic(path, JSON.stringify(acknowledged), { mode: 0o600 });}const commitVolatile = previous?.instructions === fingerprint && previous?.volatile === volatileFingerprint? null: () => {mkdirSync(directory, { recursive: true });- writeFileAtomic(path, JSON.stringify({ instructions: fingerprint, volatile: volatileFingerprint }), { mode: 0o600 });+ writeFileAtomic(path, JSON.stringify({ ...acknowledged, volatile: volatileFingerprint }), { mode: 0o600 });};- return { deliverVolatile, hadVolatile, commitVolatile };+ return { deliverVolatile, hadVolatile, commitVolatile, resetSession: false };}diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.tsindex 5eb83c1284..db7428a9b9 100644--- a/server/drivers/codex.test.ts+++ b/server/drivers/codex.test.ts@@ -29,7 +29,7 @@ import { CODEX_USAGE_LIMIT_REACHED } from "../../shared/codex-usage-limit.ts";import { removeTempDir } from "../testing/cleanup.ts";import { TEAM_TOOLS_FAILED } from "./team-tools.ts";import { unsupportedCallsNotice } from "./codex-unsupported-calls.ts";-import { rebuiltSessionNotice } from "../resume-recovery.ts";+import { instructionsOverflowNotice, rebuiltSessionNotice } from "../resume-recovery.ts";import { startFakeHttpMcp, type FakeHttpMcp } from "../testing/fake-http-mcp-server.ts";import { OWN_MCP_HTTP_ENV } from "./own-mcp-http.ts";import { ownMcpHttpRoutes } from "../routes/own-mcp-http.ts";@@ -876,6 +876,28 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)expect(turnText(fourth)).toContain("fourth");});+ it("replaces a resumed thread whose accumulated instruction blocks pass the provider cap with a fresh session", async () => {+ await create({ mode: "resume" });+ process.env.FAKE_CODEX_RETRY_SCALE = "0.001";+ const instructions = `Stable rules.${codexSandboxSuffix}`;+ const receiptPath = join(DATA_DIR, "codex-instructions", `${createHash("sha256").update(JSON.stringify(["t-overflow", "codex-thread-1"])).digest("hex")}.sha256`);+ mkdirSync(dirname(receiptPath), { recursive: true });+ writeFileSync(receiptPath, JSON.stringify({ instructions: createHash("sha256").update(instructions).digest("hex"), injected: 90_000 }), { mode: 0o600 });+ const dump = join(scratch, "instruction-overflow.json");+ process.env.FAKE_CODEX_DUMP = dump;+ const recoveryText = "History\nUser: go on";+ const { turnId } = await instance.adapter.sendTurn({ threadId: "t-overflow", text: "go on", systemStable: instructions, systemVolatile: "", resumeCursor: "codex-thread-1", recoveryText });+ await expect(recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId)).resolves.toMatchObject({ ok: true });+ const calls = JSON.parse(readFileSync(dump, "utf8")).calls;+ expect(calls.map((call: { method: string }) => call.method)).not.toContain("thread/resume");+ expect(calls.map((call: { method: string }) => call.method)).not.toContain("thread/inject_items");+ expect(calls.find((call: { method: string }) => call.method === "turn/start").params.input).toEqual([{ type: "text", text: recoveryText }]);+ expect(recorder.events.filter((e) => e.type === "turn.retrying")).toMatchObject([{ reason: "instruction_overflow" }]);+ expect(recorder.events.filter((e) => e.type === "runtime.error" && e.turnId === turnId)).toEqual([]);+ expect(recorder.events.filter((e) => e.type === "session.started").at(-1)).toMatchObject({ sessionId: "codex-thread-1", rebuilt: true });+ expect(recorder.events.filter((e) => e.type === "runtime.notice")).toEqual([expect.objectContaining({ message: instructionsOverflowNotice("Codex") })]);+ });+it("saves a conversation's thread but not one no later turn resumes", async () => {await create({ mode: "resume" });const threadStart = async (dumpName: string, threadId: string, ephemeral?: boolean) => {diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex 8fca263836..d6929a6076 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -58,7 +58,7 @@ import { mcpAppApprovalForm, mcpAppApprovalText, mcpElicitationDeclined, plainReimport { archivedNativeCodexThread, CODEX_MISSING_CREDENTIALS, codexProviderMismatch, CODEX_SIGN_IN_EXPIRED, codexLimitFacts, codexNotSignedIn, CodexRpcError, codexSignInExpired, codexPlanModelRefused, codexPlanUnsupportedInput, codexSignInRefused, codexUserError, codexUserFailure, missingNativeCodexThread, type CodexRoute } from "./codex-errors.ts";import { codexTierOf } from "./codex-tier.ts"; import { codexLoginCheck, keptCodexLogin, readCodexLogin, storedCodexLogin } from "./codex-login.ts";import { keyRejected, noteKeyAccepted, noteKeyRejected } from "../key-rejections.ts";-import { classifyResumeFailure, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts";+import { classifyResumeFailure, instructionsOverflowNotice, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts";import { extractMcpImages } from "../mcp-tool-images.ts"; import { codexImageInputs, withoutInlineImages } from "./codex-images.ts";import { parseProtocolAskQuestions, questionChoices } from "../../shared/ask-question.ts";import { codexQuestionReply, openAsyncQuestion, type CodexAsk } from "./codex-questions.ts";@@ -392,7 +392,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {// Interrupt state belongs to this turn so activity on other threads cannot cancel or revive its retry.let stopRequested = false;let promptSubmitted = false;- let recoveredMissingSession = false, droppedUnsupportedSession = false;+ let recoveredMissingSession = false, droppedSession: "unsupported-input" | "instruction-overflow" | null = null;let loginRaceRetried = false;const stopSignal = new AbortController();const { threadId } = turn;@@ -890,7 +890,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {};const turnError = (error: { message?: unknown; codexErrorInfo?: unknown }) => {const raw = String(error.message);- if (!droppedUnsupportedSession && resumedNativeThread && !state.streamed && !stopRequested && turn.recoveryText?.trim() && codexPlanUnsupportedInput(raw, route)) { droppedUnsupportedSession = true; void relaunch("unsupported_input", raw, "rpc_error").catch(() => {}); return; }+ if (!droppedSession && resumedNativeThread && !state.streamed && !stopRequested && turn.recoveryText?.trim() && codexPlanUnsupportedInput(raw, route)) { droppedSession = "unsupported-input"; void relaunch("unsupported_input", raw, "rpc_error").catch(() => {}); return; }const refused = chatgptTurn && loginMark() !== null && (codexSignInRefused(error) ||(state.authRecovery && !/\b403\b|forbidden/i.test(raw) && /\b401\b|unauthorized/i.test(raw)));if (retryLoginRace(raw, refused)) return;@@ -1245,10 +1245,10 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {// only Full may synthesize approvals.autoAcceptPermissions = approvalMode === "full";const selection = codexThreadSelection({ routedProvider: routed ? routedProvider : undefined, plan }, turn.model);- const cursor = !droppedUnsupportedSession && typeof turn.resumeCursor === "string" ? turn.resumeCursor : null;+ const cursor = !droppedSession && typeof turn.resumeCursor === "string" ? turn.resumeCursor : null;let startedModel: string | null = null;// The plan refused the dropped session before anything ran, so replaying the chat repeats no side effects.- let { text: promptText, replayed: rebuiltFromReplay } = droppedUnsupportedSession ? recoveryPromptFor({ recoveryText: turn.recoveryText, currentText: turn.text, failure: "before-accept" }) : { text: turn.text, replayed: false };+ let { text: promptText, replayed: rebuiltFromReplay } = droppedSession ? recoveryPromptFor({ recoveryText: turn.recoveryText, currentText: turn.text, failure: "before-accept" }) : { text: turn.text, replayed: false };if (reused) {codexThreadId = reused.nativeThreadId; approvalParams = reused.carried.approvalParams; resumedNativeThread = true;rolloutAt = rolloutMark(reused.carried.rolloutPath); state.usageBaseline = connection.usageTotal;@@ -1318,15 +1318,9 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {startedModel = started?.model ?? null;}if (!codexThreadId) throw new Error("Codex did not return a native thread id");- const { deliverVolatile, hadVolatile, commitVolatile } = await syncCodexInstructions(- threadId,- codexThreadId,- instructionsFor(approvalParams),- promptSplit ? turn.systemVolatile ?? "" : "",- resumedNativeThread,- request,- Boolean(turn.mentionTurn),- );+ const { deliverVolatile, hadVolatile, commitVolatile, resetSession } = await syncCodexInstructions(threadId, codexThreadId, instructionsFor(approvalParams),+ promptSplit ? turn.systemVolatile ?? "" : "", resumedNativeThread, request, Boolean(turn.mentionTurn));+ if (resetSession) { droppedSession = "instruction-overflow"; return relaunch("instruction_overflow", "Codex did not shut down while moving this conversation to a fresh session", "rpc_error"); }if (deliverVolatile) {promptText = withContextNote(volatileContextNote(promptSplit ? turn.systemVolatile ?? "" : "", hadVolatile),@@ -1334,7 +1328,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {);}emit({ ...base(threadId, turnId), type: "session.started", sessionId: codexThreadId, model: startedModel ?? turn.model ?? null, ...(rebuiltFromReplay ? { rebuilt: true } : {}) });- if (rebuiltFromReplay) emit({ ...base(threadId, turnId), type: "runtime.notice", message: rebuiltSessionNotice("Codex") });+ if (rebuiltFromReplay) emit({ ...base(threadId, turnId), type: "runtime.notice", message: droppedSession === "instruction-overflow" ? instructionsOverflowNotice("Codex") : rebuiltSessionNotice("Codex") });const turnInput = [...(promptText ? [{ type: "text" as const, text: promptText }] : []),...await codexImageInputs(turn.images),diff --git a/server/resume-recovery.ts b/server/resume-recovery.tsindex b96af50c90..dada68c092 100644--- a/server/resume-recovery.ts+++ b/server/resume-recovery.ts@@ -44,3 +44,7 @@ export function recoveryPromptFor(input: RecoveryPromptInput): RecoveryPrompt {export function rebuiltSessionNotice(engine: string): string {return `${engine} could not reopen this conversation's session, so it went on in a new one started from the chat; results of earlier tool calls did not carry over.`;}++export function instructionsOverflowNotice(engine: string): string {+ return `${engine} moved this conversation to a new session: its accumulated developer instruction blocks were close to the provider's system-prompt limit, so the superseded ones did not carry over.`;+}