Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(hooks): a tool's full output that lands after its turn ended is still saved
Absterrg0102da0470d91
diff --git a/docs/verification/digests.md b/docs/verification/digests.mdindex a6179022eb..69038ba4f1 100644--- a/docs/verification/digests.md+++ b/docs/verification/digests.md@@ -34,13 +34,16 @@ Electron binary in the desktop app). Only two replies change what the enginedoes: the hint for a timed-out Bash call (`PostToolUseFailure`, matcher`Bash`) and the digests re-sent after a compaction (`SessionStart`, matcher`compact`). `PostToolUse` only saves the full output, so it runs `async` with-a 60 s timeout; there is no `Stop` hook. A `PostToolUse` that lands after its-turn has ended finds the turn's hook token revoked: that row keeps its-preview, as it would with `OMB_HOOKS=0`, and the digest says "from tool-previews".+a 60 s timeout; there is no `Stop` hook. A `PostToolUse` can land after its+turn has ended. For 60 s after that, the ended turn's hook token is honoured+for one thing only: saving the full output of that turn's own tool calls not+yet saved, each once. The digest was written at the turn's end, so it still+says "from tool previews". `server/hooks.e2e.test.ts` plays this with+`FAKE_CLAUDE_HOOKS_AFTER_TURN_MS`.To see the difference with the real CLI, run `claude -p` in an empty folder-with `--settings` holding `claudeHookSettings(...)`'s output and+with `--settings` pointing at a file holding+`{ "hooks": claudeHookSettings(helperPath) }` and`ELECTRON_RUN_AS_NODE=1`, ask for a few Bash calls, and compare each`tool_use` to its `tool_result` in the stream-json output against the same runwith every hook synchronous.diff --git a/server/hooks.e2e.test.ts b/server/hooks.e2e.test.tsindex 5a794fe15f..d538b452b8 100644--- a/server/hooks.e2e.test.ts+++ b/server/hooks.e2e.test.ts@@ -1,5 +1,6 @@// POSIX-gated: the fake CLI is a shebang script.import { spawn, type ChildProcess } from "node:child_process";+import { createHash } from "node:crypto";import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";@@ -142,6 +143,27 @@ posixOnly("engine hooks e2e (fake Claude honouring the settings hooks)", () => {});});+posixOnly("engine hooks e2e: full tool output that arrives after its turn ended", () => {+ const h = harness("late", {}, { FAKE_CLAUDE_HOOKS_AFTER_TURN_MS: "1500" });++ it("is still saved on that turn's rows, each once, and the ended turn's bearer is good for nothing else", async () => {+ const bot = await h.runTurn();+ expect(bot.messages.find((m: Msg) => m.kind === "digest").digest?.hookCoverage).toBe("preview");+ const rows = async (): Promise<Msg[]> => (await h.getBot(bot.id)).messages.filter((m: Msg) => m.kind === "activity" && m.tool?.itemId);+ await h.waitFor(async () => (await rows()).every((m) => m.tool!.fullResult === true), "the late hooks to save both outputs");+ const root = join(h.home(), ".openmausbot", "tool-results");+ const spilled = readdirSync(join(root, readdirSync(root)[0]!)).map((name) => readFileSync(join(root, readdirSync(root)[0]!, name), "utf8"));+ expect(spilled.some((text) => text.includes(BIG.slice(0, 200)))).toBe(true);++ const digest = createHash("sha256").update(`${bot.id}\0${bot.threadId}`).digest("hex").slice(0, 24);+ const bearer = { authorization: `Bearer ${readFileSync(join(h.home(), ".openmausbot", "hook-tokens", digest, "token"), "utf8").trim()}` };+ const [first] = await rows();+ const again = await h.api("POST", "/api/internal/hook", { event: "PostToolUse", payload: { tool_use_id: first!.tool!.itemId, tool_response: "replaced" } }, bearer);+ expect(again.status).toBe(401);+ expect((await h.api("POST", "/api/internal/hook", { event: "PreCompact", payload: { trigger: "auto" } }, bearer)).status).toBe(401);+ }, 60_000);+});+posixOnly("engine hooks e2e: compaction", () => {const h = harness("compact", {}, { FAKE_CLAUDE_COMPACT: "1" });diff --git a/server/host/late-tool-results.test.ts b/server/host/late-tool-results.test.tsnew file mode 100644index 0000000000..8d4136b072--- /dev/null+++ b/server/host/late-tool-results.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from "vitest";++import { createLateToolResults, LATE_TOOL_RESULT_MS } from "./late-tool-results.ts";++const turn = { threadId: "t1", botId: "b1", turnId: "turn-1", token: "secret", toolUseIds: new Set(["tool-a", "tool-b"]) };++describe("late tool results", () => {+ it("lets an ended turn's bearer save each of its own tool calls once", () => {+ const late = createLateToolResults(() => 0);+ late.turnEnded(turn);+ expect(late.holder("Bearer secret")).toEqual({ botId: "b1", threadId: "t1" });+ expect(late.claim("t1", "b1", "tool-a")).toBe("turn-1");+ expect(late.claim("t1", "b1", "tool-a")).toBeNull();+ expect(late.claim("t1", "b1", "tool-b")).toBe("turn-1");+ expect(late.holder("Bearer secret")).toBeNull();+ });++ it("knows no other bearer, conversation, bot or tool call", () => {+ const late = createLateToolResults(() => 0);+ late.turnEnded(turn);+ for (const header of ["Bearer secreT", "Bearer secret ", "secret", undefined, ["Bearer secret"]]) expect(late.holder(header)).toBeNull();+ expect(late.claim("t2", "b1", "tool-a")).toBeNull();+ expect(late.claim("t1", "b2", "tool-a")).toBeNull();+ expect(late.claim("t1", "b1", "tool-c")).toBeNull();+ });++ it("ends with its window, when the conversation's bearers are revoked, or when nothing was left to save", () => {+ let now = 0;+ const late = createLateToolResults(() => now);+ late.turnEnded(turn);+ now = LATE_TOOL_RESULT_MS;+ expect(late.holder("Bearer secret")).toBeNull();+ expect(late.claim("t1", "b1", "tool-a")).toBeNull();++ late.turnEnded(turn);+ late.forgetThread("t1");+ expect(late.claim("t1", "b1", "tool-a")).toBeNull();++ late.turnEnded({ ...turn, toolUseIds: new Set() });+ expect(late.holder("Bearer secret")).toBeNull();+ });+});diff --git a/server/host/late-tool-results.ts b/server/host/late-tool-results.tsnew file mode 100644index 0000000000..dd9709c29c--- /dev/null+++ b/server/host/late-tool-results.ts@@ -0,0 +1,52 @@+import { timingSafeEqual } from "node:crypto";++/** How long after its turn ends a background `PostToolUse` may still save that turn's full tool output. */+export const LATE_TOOL_RESULT_MS = 60_000;++export interface EndedHookTurn {+ threadId: string;+ botId: string;+ turnId: string;+ /** The turn's hooks bearer. */+ token: string;+ /** Tool calls of the turn whose full output was not saved when it ended; each may be claimed once. */+ toolUseIds: ReadonlySet<string>;+}++/** Security invariant: an ended turn's hooks bearer is honoured for nothing but saving the full output of that turn's own+ * tool calls, each once, until LATE_TOOL_RESULT_MS after the turn ended; revoking the thread's bearers ends it at once. */+export function createLateToolResults(now: () => number = Date.now) {+ const ended: Array<Omit<EndedHookTurn, "toolUseIds"> & { toolUseIds: Set<string>; until: number }> = [];+ const live = () => {+ const at = now();+ for (let i = ended.length - 1; i >= 0; i--) if (ended[i]!.until <= at || ended[i]!.toolUseIds.size === 0) ended.splice(i, 1);+ return ended;+ };+ return {+ turnEnded(turn: EndedHookTurn): void {+ if (turn.toolUseIds.size) ended.push({ ...turn, toolUseIds: new Set(turn.toolUseIds), until: now() + LATE_TOOL_RESULT_MS });+ },+ /** The bot and conversation an ended turn's bearer belongs to, compared in constant time. */+ holder(header: string | string[] | undefined): { botId: string; threadId: string } | null {+ const got = Buffer.from(Array.isArray(header) ? "" : (header ?? ""));+ for (const turn of live()) {+ const expected = Buffer.from(`Bearer ${turn.token}`);+ if (got.length === expected.length && timingSafeEqual(got, expected)) return { botId: turn.botId, threadId: turn.threadId };+ }+ return null;+ },+ /** The ended turn a tool call of this conversation belongs to, if its output may still be saved; claims it. */+ claim(threadId: string, botId: string, toolUseId: string): string | null {+ const turn = live().find((candidate) => candidate.threadId === threadId && candidate.botId === botId && candidate.toolUseIds.has(toolUseId));+ if (!turn) return null;+ turn.toolUseIds.delete(toolUseId);+ return turn.turnId;+ },+ forgetThread(threadId: string): void {+ for (let i = ended.length - 1; i >= 0; i--) if (ended[i]!.threadId === threadId) ended.splice(i, 1);+ },+ clear(): void {+ ended.length = 0;+ },+ };+}diff --git a/server/index.ts b/server/index.tsindex db12e8c526..1d739d548d 100644--- a/server/index.ts+++ b/server/index.ts@@ -649,7 +649,7 @@ import { createWebhookRoutes } from "./routes/webhooks.ts";import { withScopeHint } from "./connector-scope-hint.ts";import { connectorFileDeps, connectorFileScope, prepareConnectorFiles, withMissingFileHint } from "./connector-files.ts";import { createConnectorCards } from "./host/connector-cards.ts";-import { createLoginMailCodes } from "./host/login-mail-codes.ts";+import { createLoginMailCodes } from "./host/login-mail-codes.ts"; import { createLateToolResults } from "./host/late-tool-results.ts";import { onThreadSeen, personAsks as personAskAt, sawThread } from "./thread-presence.ts"; import { createWarmSummaryHost, HARNESS_IDLE_FRACTION } from "./host/warm-summary-host.ts";const PORT = Number(process.env.OMB_PORT || process.env.OGB_PORT || 8799);@@ -1619,6 +1619,7 @@ const MAX_CREATED_BOT_INSTRUCTIONS = 4_000;// Only an orphan backstop: normal terminal paths revoke a capability synchronously.const INTERNAL_CAPABILITY_ORPHAN_MS = 30 * 24 * 60 * 60_000;const internalCapabilities = new Map<string, InternalCapability>();+const lateToolResults = createLateToolResults();const activeInternalGenerationByThread = new Map<string, string>();const turnCallSignals = createTurnCallSignals(internalCapabilityIsActive);const internalGenerationByProviderTurn = new ProviderTurnGenerationRegistry();@@ -1742,13 +1743,13 @@ function revokeEarlierTurnCapabilities(threadId: string): void {/** Also retires the thread's bearers, so nothing that still holds one is honoured again. */function revokeInternalCapabilitiesForThread(threadId: string): void {- revokeEarlierTurnCapabilities(threadId);+ revokeEarlierTurnCapabilities(threadId); lateToolResults.forgetThread(threadId);sessionCredentials.delete(threadId);}function revokeAllInternalCapabilities(): void {computerSelectionTurns.clear();- internalCapabilities.clear();+ internalCapabilities.clear(); lateToolResults.clear();sessionCredentials.clear();// foreignTurns stays: a foreign turn can still write while its engine is torn down, and only its own end judges it.activeInternalGenerationByThread.clear();@@ -1766,6 +1767,9 @@ function revokeInternalCapabilityForProviderEvent(event: RuntimeEvent): void {if (!event.turnId) return;const owner = internalGenerationByProviderTurn.complete(event.threadId, event.turnId);if (!owner) return;+ const hooks = [...internalCapabilities].find(([, capability]) => capability.kind === "hooks" && capability.threadId === owner.threadId && capability.generation === owner.generation);+ if (hooks) lateToolResults.turnEnded({ threadId: owner.threadId, botId: hooks[1].botId, turnId: event.turnId, token: hooks[0], toolUseIds: new Set(store.activePath(owner.threadId)+ .flatMap((m) => m.kind === "activity" && m.turnId === event.turnId && m.tool?.itemId && m.tool.fullResult === undefined ? [m.tool.itemId] : [])) });revokeInternalCapabilityGeneration(owner.threadId, owner.generation);}@@ -5415,11 +5419,12 @@ const TOOL_RESULTS_DIR = join(DATA_DIR, "tool-results");const TOOL_RESULT_SPILL_MAX = 512 * 1024;const DIGESTS_AFTER_COMPACTION = 2;-function ingestEngineHook(capability: InternalCapability, body: unknown): { ok: boolean; ignored?: string; context?: string; hookSpecificOutput?: unknown } {+function ingestEngineHook(capability: Pick<InternalCapability, "botId" | "threadId">, body: unknown, turnEnded = false): { ok: boolean; ignored?: string; context?: string; hookSpecificOutput?: unknown } {const event = body && typeof body === "object" ? (body as { event?: unknown; payload?: unknown }) : {};const name = typeof event.event === "string" ? event.event : "";const payload = event.payload && typeof event.payload === "object" ? (event.payload as Record<string, unknown>) : {};const threadId = capability.threadId;+ if (turnEnded && name !== "PostToolUse") return { ok: true, ignored: `${name || "unknown"} after its turn ended` };const chip = (text: string) => store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: text, ok: true } });if (name === "PreCompact" || (name === "SessionStart" && payload.source === "compact")) roomSessions.distrust(threadId, capability.botId);if (name === "PreCompact") {@@ -5443,8 +5448,9 @@ function ingestEngineHook(capability: InternalCapability, body: unknown): { ok:if (!Object.hasOwn(payload, "tool_response")) return { ok: true, ignored: "hook did not include a tool response" };const response = payload.tool_response;const text = typeof response === "string" ? response : JSON.stringify(response ?? null, null, 2);- const turnId = liveTurnByThread.get(threadId);- const row = store.activePath(threadId).findLast((m) => m.kind === "activity" && m.turnId === turnId && m.tool?.itemId === toolUseId);+ const rows = store.activePath(threadId), toolRow = (turn: string | null | undefined) => turn ? rows.findLast((m) => m.kind === "activity" && m.turnId === turn && m.tool?.itemId === toolUseId) : undefined;+ let turnId: string | null | undefined = turnEnded ? undefined : liveTurnByThread.get(threadId), row = toolRow(turnId);+ if (!row) row = toolRow(turnId = lateToolResults.claim(threadId, capability.botId, toolUseId));if (!turnId || !row?.tool) return { ok: true, ignored: "tool not observed in this turn" };const key = `${threadId}:${turnId}:${toolUseId}`;if (!commandReceipt("hook.ingest", key)) {@@ -12830,7 +12836,8 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (path.startsWith("/api/internal/")) {const internalCapability = authorizedInternalCapability(req.headers.authorization);if (!internalCapability) {- return json(res, 401, { error: "unauthorized" });+ const ended = method === "POST" && path === "/api/internal/hook" ? lateToolResults.holder(req.headers.authorization) : null;+ return ended ? json(res, 200, ingestEngineHook(ended, await readBody(req), true)) : json(res, 401, { error: "unauthorized" });}const internalSender = store.bot(internalCapability.botId);if (!internalSender) {diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.tsindex 416ae5e03d..11c9f762b7 100755--- a/server/testing/fake-claude-cli.ts+++ b/server/testing/fake-claude-cli.ts@@ -48,6 +48,8 @@// FAKE_CLAUDE_CONNECT_APPS toolkits (gmail,slack): first call COMPOSIO_MANAGE_CONNECTIONS via `composio`// FAKE_CLAUDE_HOOKS 1: run the --settings hooks like the CLI (PostToolUse per tool_result, PostToolUseFailure for// an ok:false call with its additionalContext echoed into the reply, Stop at the end)+// FAKE_CLAUDE_HOOKS_AFTER_TURN_MS with FAKE_CLAUDE_HOOKS: run each `async` hook this many ms after its turn's result,+// as the CLI does when a hook's start outlasts the model's last reply (unset: async hooks run in place, like the rest)// FAKE_CLAUDE_COMPACT 1: from the second turn, play a compaction (PreCompact, compact_boundary, then SessionStart "compact")// FAKE_CLAUDE_TURN_STATE counter file keeping FAKE_CLAUDE_COMPACT's turn count across respawns// FAKE_CLAUDE_CONTEXT_GROWTH "<start>:<per turn>": a session starts at <start> tokens and each turn's work adds <per turn>,@@ -244,7 +246,7 @@ const replyForPrompt = (prompt: JsonValue): string[] | null => {};const argv = process.argv.slice(2);-const settingsHooks: Record<string, Array<{ matcher?: string; hooks?: Array<{ type?: string; command?: string; args?: string[]; timeout?: number }> }>> = (() => {+const settingsHooks: Record<string, Array<{ matcher?: string; hooks?: Array<{ type?: string; command?: string; args?: string[]; timeout?: number; async?: boolean }> }>> = (() => {if (process.env.FAKE_CLAUDE_HOOKS !== "1") return {};const i = argv.indexOf("--settings");if (i === -1) return {};@@ -255,6 +257,12 @@ const settingsHooks: Record<string, Array<{ matcher?: string; hooks?: Array<{ tyreturn {};}})();+const hooksAfterTurnMs = Number(process.env.FAKE_CLAUDE_HOOKS_AFTER_TURN_MS);+const hooksAfterTurn: Array<() => unknown> = [];+const runHooksAfterTurn = () => {+ const due = hooksAfterTurn.splice(0);+ if (due.length) setTimeout(() => { for (const run of due) run(); }, hooksAfterTurnMs);+};function runHooks(event: FakeHookEvent, payload: Record<string, unknown>): string {let stdout = "";for (const entry of settingsHooks[event] ?? []) {@@ -262,7 +270,7 @@ function runHooks(event: FakeHookEvent, payload: Record<string, unknown>): strinfor (const hook of entry.hooks ?? []) {if (hook.type !== "command" || !hook.command) continue;// Like Claude Code: a hook with `args` starts `command` itself; otherwise `command` is a shell line.- const result = spawnSync(hook.command, hook.args ?? [], {+ const run = () => spawnSync(hook.command!, hook.args ?? [], {shell: !hook.args,input: JSON.stringify({ hook_event_name: event, session_id: "fake-session", cwd: process.cwd(), ...payload }),env: process.env,@@ -270,7 +278,8 @@ function runHooks(event: FakeHookEvent, payload: Record<string, unknown>): strinstdio: ["pipe", "pipe", "pipe"],encoding: "utf8",});- stdout += result.stdout ?? "";+ if (hook.async && hooksAfterTurnMs >= 0) hooksAfterTurn.push(run);+ else stdout += run().stdout ?? "";}}return stdout;@@ -649,6 +658,7 @@ const finishIfDone = () => {const finishTurn = () => {runHooks("Stop", { stop_hook_active: false });out({ type: "result", is_error: false, stop_reason: "end_turn", total_cost_usd: 0.01, usage: { input_tokens: 10, cache_read_input_tokens: 2, output_tokens: 5 } });+ runHooksAfterTurn();turnRunning = false;finishIfDone();};@@ -1129,6 +1139,7 @@ const playTurn = (prompt: JsonValue, late = false) => {modelUsage: runningCost.modelUsage,...(queued === "zero" ? { queued_turn_count: 0 } : queued === "count" ? { queued_turn_count: lateSteers.length } : {}),});+ runHooksAfterTurn();turnRunning = false;finishIfDone();};