Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(acp): keep native sessions across external updates and honor the configured replay message bound
Santhi Prakash298a3b023cfe
diff --git a/docs/verification/context-compaction.md b/docs/verification/context-compaction.mdindex f93f2c3ad5..1b6b6302cd 100644--- a/docs/verification/context-compaction.md+++ b/docs/verification/context-compaction.md@@ -346,7 +346,8 @@ those at the top level. A URL inside a command is left as the command ran.`context` settings in config.json are optional. `autoCompact: false` disablesautomatic folding, `compactAt` is a fraction below 1 or a token count, and-`rebuildBytes` controls replay size (default 24,000 bytes). Context-only settings+`rebuildBytes` controls replay size in bytes (default 24,000) and `maxMessages`+bounds it by count (default 40). Context-only settingsdo not reload provider processes. The default threshold is 80% of the knownmodel window; a real latest-prompt measurement wins over a transcript estimate,except an ACP agent's own reading, which is shown and does not time compaction.diff --git a/server/acp-recovery.e2e.test.ts b/server/acp-recovery.e2e.test.tsindex e317a82fa6..51af059c5a 100644--- a/server/acp-recovery.e2e.test.ts+++ b/server/acp-recovery.e2e.test.ts@@ -101,7 +101,10 @@ it.each([false, true])("recovers the same conversation after an ACP internal errconst prompt = JSON.stringify(JSON.parse(readFileSync(`${dumpFile}.prompt.json`, "utf8")));expect(prompt.split(retryText).length - 1).toBe(1);expect(prompt).not.toContain(firstText);- expect(prompt).not.toContain(failedText);+ // session/prompt resolving is the receipt boundary: rejected before the agent acted, the failed+ // message never entered the session, so a strict-resume handoff offers it once as unseen.+ if (afterOutput) expect(prompt).not.toContain(failedText);+ else expect(prompt.split(failedText).length - 1).toBe(1);const finalMessages = await messages();for (const text of [firstText, failedText, retryText]) {expect(finalMessages.filter((message) => message.role === "user" && message.text === text)).toHaveLength(1);diff --git a/server/comms.test.ts b/server/comms.test.tsindex 69d329ebc8..7e5afd9fa2 100644--- a/server/comms.test.ts+++ b/server/comms.test.ts@@ -288,6 +288,12 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {environment: { FAKE_ACP_MODE: "delegate-peer" },config: { cli: FAKE_CLI, fullAuto: true },},+ // the same asker with every RPC request recorded, so a test can count the sessions it built+ askerResume: {+ driver: "grokAgent",+ environment: { FAKE_ACP_MODE: "delegate-peer", FAKE_ACP_RPC_APPEND_FILE: join(home, "asker-resume-rpc.jsonl") },+ config: { cli: FAKE_CLI, fullAuto: true },+ },// The resume is a fresh fake process that learns its agents server only from session/new, so it replays into a new session.askerRedelegate: {driver: "grokAgent",@@ -615,6 +621,35 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {45_000,);+ it(+ "keeps the asker's session when the teammate's result lands instead of rebuilding it",+ async () => {+ await hideAll();+ await named("Helper", { modelSelection: HELPER });+ const asker = await named("Asker", { modelSelection: { instanceId: "askerResume", model: "fake-model" } });++ const send = await startRoutine(asker.id, "hey @Helper please pick this up");+ expect(send.status).toBe(201);++ let askerBot: any;+ await waitUntil(async () => {+ askerBot = await bot(asker.id);+ const delegated = askerBot.messages.some((m: any) => m.kind === "text" && m.role === "bot" && m.text?.startsWith("delegated:"));+ const woke = lastText(askerBot.messages)?.text === WOKE_WITH_RESULT;+ return delegated && woke && !askerBot.busy;+ }, 30_000, "the hand-off never settled");++ // The result's landing marks the thread externally updated; a strict-resume driver keeps the live session and is+ // handed only the unseen lines, so the wake prompt rides the same session rather than session/new again.+ const sessions = readFileSync(join(home, "asker-resume-rpc.jsonl"), "utf8").trim().split("\n")+ .map((line) => JSON.parse(line) as { method: string })+ .map((call) => call.method)+ .filter((method) => ["session/new", "session/load", "session/prompt"].includes(method));+ expect(sessions).toEqual(["session/new", "session/prompt", "session/prompt"]);+ },+ 45_000,+ );+it("never quotes a routine's prompt as the user's request, and refuses the resumed turn's repeat work to a finished teammate without rework",async () => {@@ -672,6 +707,43 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {45_000,);+ it(+ "bounds the rebuilt conversation by context.maxMessages, not only the byte budget",+ async () => {+ await hideAll();+ rmSync(gateFile, { force: true });+ const helper = await named("Helper", { modelSelection: { instanceId: "helperGate", model: "fake-model" } });+ const asker = await named("Asker", { modelSelection: { instanceId: "askerNoLoad", model: "fake-model" } });++ expect((await api("PATCH", "/api/config", { context: { maxMessages: 1 } })).status).toBe(200);+ try {+ await startRoutine(asker.id, "hey @Helper please pick this up; keep the codename ORCHID_EARLIER_CONTEXT");+ await waitUntil(async () => (await bot(helper.id)).busy, 30_000, "the helper never took the assignment");+ // A shared-rules change while the helper holds makes the handed session state stale, so the wake+ // rebuilds the conversation from the bounded replay instead of resuming the warm session.+ expect((await api("PATCH", "/api/config", { everyBotRules: "keep answers short" })).status).toBe(200);+ writeFileSync(gateFile, "go");+ await waitUntil(async () => {+ const current = await bot(asker.id);+ return !current.busy && lastText(current.messages)?.text === WOKE_WITH_RESULT;+ }, 30_000, "the source never woke after its hand-off");++ const woke = JSON.parse(readFileSync(join(home, "asker-no-load.json.prompt.json"), "utf8")).map((block: any) => String(block.text ?? "")).join("\n");+ expect(woke).toContain("update outside your provider session");+ expect(woke).toContain("earlier messages omitted");+ expect(woke).toContain("Assistant: [What Asker did in an earlier turn");+ expect(woke).toContain('What @Helper said: "echo:');+ // Only the newest entry survives a one-message window: the routine request and the asker's+ // delegation reply (earlier transcript lines) drop out of the replay.+ expect(woke).not.toContain("User: (Routine");+ expect(woke).not.toContain("Assistant: delegated:");+ } finally {+ await api("PATCH", "/api/config", { context: { maxMessages: 10_000 }, everyBotRules: "" });+ }+ },+ 45_000,+ );+it("keeps a Chief available while its delegated teammate is still working",async () => {diff --git a/server/config.ts b/server/config.tsindex b6ab9b6eef..4dfedad222 100644--- a/server/config.ts+++ b/server/config.ts@@ -480,7 +480,7 @@ export interface AppConfig extends HelperConfig {rooms?: { turnTimeoutMinutes: number };mcp?: { callTimeoutMinutes?: number };threads?: { maxConcurrentPerBot: number; eventLogMaxBytes?: number; eventLogRetentionDays?: number }; burst?: { maxParallel?: number };- context?: { rebuildBytes?: number; compactAt?: number; autoCompact?: boolean; roomCompactAt?: number; roomSessions?: boolean; replayToolHistory?: boolean };+ context?: { rebuildBytes?: number; compactAt?: number; autoCompact?: boolean; roomCompactAt?: number; roomSessions?: boolean; replayToolHistory?: boolean; maxMessages?: number };memory?: { captureQuietMs?: number; tidyHour?: number };localVm?: { mode?: "shared" | "per-bot" | "pool"; maxInstances?: number; idleTimeoutMinutes?: number; preserveInstalledApps?: boolean; memoryGb?: number; cpus?: number };features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; smartSetupChoices?: boolean; autoRecall?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; parallelRoomJobs?: boolean; acpPlanLines?: boolean; agentsToolBridge?: boolean; savedSteps?: boolean; usbPhoneTakeover?: boolean; cloudComputerAutoReplace?: boolean; phonePush?: boolean };diff --git a/server/drivers/acp/capabilities.ts b/server/drivers/acp/capabilities.tsnew file mode 100644index 0000000000..76c7de35dc--- /dev/null+++ b/server/drivers/acp/capabilities.ts@@ -0,0 +1,23 @@+import type { ProviderAdapter } from "../../contracts.ts";+import type { AcpSupport } from "./core.ts";++export function acpCapabilities(support: AcpSupport): ProviderAdapter["capabilities"] {+ return {+ sessionModelSwitch: "unsupported",+ agentsMcp: true,+ customMcp: true,+ computerMcp: true,+ composioMcp: true,+ browserMcp: true,+ dataMcp: true, emailMcp: true, deviceMcp: true,+ images: support.images !== false,+ nativeImageInput: support.images === true,+ effortLevels: support.effortLevels,+ modelVariants: support.modelVariants === true,+ localComputerMcp: true,+ contextReading: "meter",+ engineAdmission: true, ...(support.askTool ? { askTool: { kind: "native" as const, name: support.askTool } } : {}),+ ...(support.steer ? { queueing: true } : {}),+ strictResume: true,+ };+}diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 30f02c4f78..4b67024c55 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -21,6 +21,7 @@ import { deletePromptSplitReceipt, promptHalves, readPromptSplitReceipt, splitSeimport type { PromptSplitReceipt } from "../prompt-split.ts";import { describeSpawnFailure, execCli, killCliTree, sharedBoxScope, spawnCli } from "../../procs.ts";import { runAcpOneShot } from "./background-text.ts";+import { acpCapabilities } from "./capabilities.ts";import { acpNativeLogMessage } from "./tool-log.ts";import { stripLeakedSystemHarnessMessages } from "../../../shared/system-message-guard.ts";import {@@ -1617,23 +1618,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>snapshot,adapter: {provider: DRIVER_KIND,- capabilities: {- sessionModelSwitch: "unsupported",- agentsMcp: true,- customMcp: true,- computerMcp: true,- composioMcp: true,- browserMcp: true,- dataMcp: true, emailMcp: true, deviceMcp: true,- images: support.images !== false,- nativeImageInput: support.images === true,- effortLevels: support.effortLevels,- modelVariants: support.modelVariants === true,- localComputerMcp: true,- contextReading: "meter",- engineAdmission: true, ...(support.askTool ? { askTool: { kind: "native" as const, name: support.askTool } } : {}),- ...(support.steer ? { queueing: true } : {}),- },+ capabilities: acpCapabilities(support),sendTurn,interruptTurn: async (threadId) => active.get(threadId)?.interrupt(),...(support.steer ? { steer: async (threadId: string, text: string, images?: readonly TurnImageInput[]) =>diff --git a/server/index.ts b/server/index.tsindex 59566bf47a..2659b6e4d7 100644--- a/server/index.ts+++ b/server/index.ts@@ -7820,7 +7820,7 @@ async function beginTurn(const contextOrder = context.map(m => m.id);const replayable = context.filter(m => !skipTranscript.has(m.id));const record = latestCompaction(activeMessages);- const selection = selectReplay(context, { budgetBytes: cfg.context?.rebuildBytes ?? DEFAULT_REBUILD_BYTES, excludedIds: skipTranscript, compaction: record, tools: replayToolCalls(activeMessages, cfg.context) });+ const selection = selectReplay(context, { budgetBytes: cfg.context?.rebuildBytes ?? DEFAULT_REBUILD_BYTES, maxMessages: cfg.context?.maxMessages, excludedIds: skipTranscript, compaction: record, tools: replayToolCalls(activeMessages, cfg.context) });const transcript = selection.transcript.map(({ role, text }) => ({ role, text }));const contextReset = selection.compacted > 0 && record?.id !== task.appliedCompactionId;if (contextReset) store.patchTask(bot.id, threadId, { resumeCursors: {} });diff --git a/server/replay-settings.test.ts b/server/replay-settings.test.tsindex 578abca797..dee36d9ad5 100644--- a/server/replay-settings.test.ts+++ b/server/replay-settings.test.ts@@ -8,11 +8,11 @@ describe("replaySettings", () => {// as server/config.ts takes them: added to the `context` groupconst context = z.object({ compactAt: z.number().optional() }).extend(replaySettings);- it("is the replay's two settings, each optional, beside whatever else the group holds", () => {- expect(Object.keys(replaySettings).sort()).toEqual(["rebuildBytes", "replayToolHistory"]);+ it("is the replay's three settings, each optional, beside whatever else the group holds", () => {+ expect(Object.keys(replaySettings).sort()).toEqual(["maxMessages", "rebuildBytes", "replayToolHistory"]);expect(context.parse({})).toEqual({});- expect(context.parse({ compactAt: 0.7, rebuildBytes: 32_000, replayToolHistory: true }))- .toEqual({ compactAt: 0.7, rebuildBytes: 32_000, replayToolHistory: true });+ expect(context.parse({ compactAt: 0.7, rebuildBytes: 32_000, maxMessages: 200, replayToolHistory: true }))+ .toEqual({ compactAt: 0.7, rebuildBytes: 32_000, maxMessages: 200, replayToolHistory: true });});it("bounds rebuildBytes, with the floor selectReplay itself refuses to go under", () => {@@ -23,6 +23,14 @@ describe("replaySettings", () => {expect(() => selectReplay([], { budgetBytes: 1_023 })).toThrow("invalid context");});+ it("bounds maxMessages, with the floor selectReplay itself refuses to go under", () => {+ for (const value of [1, 40, 10_000]) expect(context.parse({ maxMessages: value })).toEqual({ maxMessages: value });+ for (const value of [0, -1, 1.5, 10_001, "40", null]) expect(() => context.parse({ maxMessages: value })).toThrow();+ // a count this lets through never makes the replay throw, and the first one it refuses would+ expect(() => selectReplay([], { maxMessages: 1 })).not.toThrow();+ expect(() => selectReplay([], { maxMessages: 0 })).toThrow("invalid context");+ });+it("takes replayToolHistory as a boolean only", () => {for (const value of [true, false]) expect(context.parse({ replayToolHistory: value })).toEqual({ replayToolHistory: value });for (const value of ["1", 1, "true", null]) expect(() => context.parse({ replayToolHistory: value })).toThrow();diff --git a/server/replay-settings.ts b/server/replay-settings.tsindex 67f61e8422..44b66d3ca2 100644--- a/server/replay-settings.ts+++ b/server/replay-settings.ts@@ -3,6 +3,8 @@ import { z } from "zod";export const replaySettings = {/** Bytes of history a rebuilt session is replayed. */rebuildBytes: z.number().int().min(1_024).max(1_000_000).optional(),+ /** Messages of history a rebuilt session is replayed. */+ maxMessages: z.number().int().min(1).max(10_000).optional(),/** Also tell a session rebuilt from an inline replay which tools already ran, one line per call. Off unless true; OMB_REPLAY_TOOL_HISTORY=1 or 0 overrides. */replayToolHistory: z.boolean().optional(),};