Skip to content

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

perf(claude): hooks stop holding tool results; no hook process where the harness never replies

Absterrg060636c739b43
diff --git a/docs/agents-tool-bridge.md b/docs/agents-tool-bridge.md
index e1aa009faa..a7cbff0f16 100644
--- a/docs/agents-tool-bridge.md
+++ b/docs/agents-tool-bridge.md
@@ -117,8 +117,8 @@ Claude Code is not bridged when any of these holds:
whatever it matches: an empty or wildcard matcher sees every call, and a
hook's own script can test the tool's name. OpenMausBot's own hooks are none
of these and are in none of these files: it registers `PostToolUse`,
- `PreCompact`, `SessionStart` and `Stop` through a private settings file
- written for each launch.
+ `PostToolUseFailure`, `PreCompact` and `SessionStart` through a private
+ settings file written for each launch.
- A settings file's `permissions.deny` or `permissions.ask` list (keys in any
case) holds a rule with a wildcard in a tool's name, even one about another
server (`mcp__github__*`, `*exec*`). Claude Code matches a deny or ask
diff --git a/docs/verification/digests.md b/docs/verification/digests.md
index 95e69951fa..a6179022eb 100644
--- a/docs/verification/digests.md
+++ b/docs/verification/digests.md
@@ -26,6 +26,25 @@ another fake engine. The multi-engine and older hook suites currently run on
POSIX; the shared-control test is cross-platform. CI must establish Windows
behavior rather than treating a local macOS run as Windows verification.
+## Hooks that do not hold the engine
+
+Claude Code waits for a synchronous hook before it hands a tool's result back
+to the model, and each hook starts the helper as its own process (the whole
+Electron binary in the desktop app). Only two replies change what the engine
+does: 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".
+
+To see the difference with the real CLI, run `claude -p` in an empty folder
+with `--settings` holding `claudeHookSettings(...)`'s output 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 run
+with every hook synchronous.
+
## Shell calls that hit their time limit
Claude Code stops a Bash call after 2 minutes unless the call passes a larger
diff --git a/server/drivers/claude-box.test.ts b/server/drivers/claude-box.test.ts
index 9ba74ffdc8..a8aed666aa 100644
--- a/server/drivers/claude-box.test.ts
+++ b/server/drivers/claude-box.test.ts
@@ -145,7 +145,7 @@ describe("a Claude turn in the bot box", () => {
await instance.adapter.sendTurn({ threadId: "t-boxed-hooks", botId: "bot-a", text: "hi", approvalMode: "full", cwd, integrations: { hooks: { url, token: "hook-bearer-1" } } });
await recorder.until((event) => event.type === "turn.completed", 30_000);
- expect(hooks.map((hook) => hook.event), "the hooks fired from inside the box").toEqual(expect.arrayContaining(["PostToolUse", "Stop"]));
+ expect(hooks.map((hook) => hook.event), "the hooks fired from inside the box").toEqual(["PostToolUse"]);
for (const hook of hooks) expect(hook.authorization).toBe("Bearer hook-bearer-1");
const boxed = wrap.mock.results.map((result) => result.value as WrappedSpawn | null).find((spawned) => spawned?.plan.botId === "bot-a");
expect(boxed, "the engine ran in the box").toBeTruthy();
diff --git a/server/drivers/claude-hooks.ts b/server/drivers/claude-hooks.ts
new file mode 100644
index 0000000000..68bf372c37
--- /dev/null
+++ b/server/drivers/claude-hooks.ts
@@ -0,0 +1,19 @@
+/** Hooks for the private --settings file. Claude Code runs each command with the event JSON on
+ * stdin and applies any hookSpecificOutput it prints. */
+export function claudeHookSettings(helperPath: string, platform: NodeJS.Platform = process.platform): Record<string, unknown> {
+ // Claude Code runs `command` as a shell line: sh on macOS and Linux; on Windows Git Bash, or PowerShell
+ // when Git Bash is missing, and the two quote differently. Given `args` (2.1.139), it starts `command` itself.
+ // JSON quoting is not shell quoting: $(), backticks and $names expand inside double quotes.
+ const hook = platform === "win32"
+ ? { type: "command", command: process.execPath, args: [helperPath], timeout: 5 }
+ : { type: "command", command: [process.execPath, helperPath].map(path => `'${path.replace(/'/g, "'\\''")}'`).join(" "), timeout: 5 };
+ // Claude Code holds a tool's result until its synchronous hooks exit, and every hook starts a process (on Windows the
+ // whole Electron binary). An async hook (2.1.325) holds nothing but is still killed at its timeout, so it gets room for
+ // a slow start. The matchers keep a process from starting for events whose reply the harness never sends.
+ return {
+ PostToolUse: [{ matcher: "", hooks: [{ ...hook, async: true, timeout: 60 }] }],
+ PostToolUseFailure: [{ matcher: "Bash", hooks: [hook] }],
+ PreCompact: [{ matcher: "", hooks: [hook] }],
+ SessionStart: [{ matcher: "compact", hooks: [hook] }],
+ };
+}
diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.ts
index 36d8d93ff8..874238a51a 100644
--- a/server/drivers/claude.test.ts
+++ b/server/drivers/claude.test.ts
@@ -11,12 +11,12 @@ import { TurnAuthenticationRefusedError, type ProviderInstance, type SendTurnInp
import { UNGATED_MCP_OUTPUT_TOKENS } from "../mcp-gate-config.ts";
import { recordEvents, type EventRecorder } from "../testing/events.ts";
import { BACKGROUND_CALL_TIMEOUT_MS, BACKGROUND_SETTINGS, backgroundCallArgs } from "./claude-background.ts";
+import { claudeHookSettings } from "./claude-hooks.ts";
import {
autoCompactWindow,
brokerSocketCandidates,
claudeCliSupports,
claudeCliUpdate,
- claudeHookSettings,
ClaudeDriver,
createPermissionBroker,
hookTokenFile,
@@ -103,14 +103,27 @@ describe("ClaudeDriver.decodeConfig", () => {
it("starts the hook helper without a shell on Windows, where Git Bash or PowerShell would read the command line", () => {
const helper = "C:\\Users\\it's $OMB_HOOK_TEST `literal`\\helper.ts";
- const settings = claudeHookSettings(helper, "win32") as { PostToolUse: Array<{ hooks: unknown[] }> };
- expect(settings.PostToolUse[0]!.hooks).toEqual([{ type: "command", command: process.execPath, args: [helper], timeout: 5 }]);
+ const settings = claudeHookSettings(helper, "win32") as { PostToolUseFailure: Array<{ hooks: unknown[] }> };
+ expect(settings.PostToolUseFailure[0]!.hooks).toEqual([{ type: "command", command: process.execPath, args: [helper], timeout: 5 }]);
});
it("hooks failed tool calls too, so a timed-out command can be given a hint", () => {
expect(Object.keys(claudeHookSettings("/tmp/helper.ts"))).toContain("PostToolUseFailure");
});
+ it("starts a hook process that holds the engine only where the harness replies: a failed shell call and a compaction", () => {
+ type Entry = { matcher: string; hooks: Array<{ async?: boolean; timeout: number }> };
+ const settings = claudeHookSettings("/tmp/helper.ts", "linux") as Record<string, Entry[]>;
+ const held = Object.entries(settings).map(([event, [entry]]) => [event, entry!.matcher, entry!.hooks[0]!.async ?? false]);
+ expect(held).toEqual([
+ ["PostToolUse", "", true],
+ ["PostToolUseFailure", "Bash", false],
+ ["PreCompact", "", false],
+ ["SessionStart", "compact", false],
+ ]);
+ expect(settings.PostToolUse![0]!.hooks[0]!.timeout).toBeGreaterThan(30);
+ });
+
it("keeps the per-turn hook token where workspace backups never look", () => {
const path = relative(DATA_DIR, hookTokenFile("thread", "bot")).replaceAll("\\", "/");
expect(ephemeralWorkspaceTokenPath(path)).toBe(true);
@@ -1734,8 +1747,7 @@ describe("ClaudeDriver turns (fake CLI)", () => {
const seen = JSON.parse(readFileSync(dump, "utf8"));
expect(realpathSync(seen.cwd)).toBe(realpathSync(thread));
expect(seen.settings.hooks.PreToolUse).toEqual([guard]);
- expect(seen.settings.hooks.Stop).toHaveLength(2);
- expect(seen.settings.hooks.Stop[0]).toEqual({ hooks: [{ type: "command", command: "/opt/guards/notify.sh" }] });
+ expect(seen.settings.hooks.Stop).toEqual([{ hooks: [{ type: "command", command: "/opt/guards/notify.sh" }] }]);
expect(Object.keys(seen.settings.hooks)).toEqual(expect.arrayContaining(Object.keys(claudeHookSettings("/helper.ts"))));
expect(seen.settings.enabledPlugins).toEqual({ "guard@team": true });
expect(seen.settings.permissions).toEqual({ deny: ["Read(./.env)"] });
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index 6c004ee8ac..71f25930d2 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -14,7 +14,7 @@ import { brokerSocketPath, describeSpawnFailure, execCli, killCliTree, spawnCli
import { cliToLaunch, cliVersionProbe } from "../cli-version-probe.ts";
import { claudeAuthStatus } from "./claude-auth-status.ts";
import { projectMcpServers } from "./claude-project-mcp.ts";
-import { botSettingsFor, folderSettingsEnv, withBotSettings } from "./claude-bot-settings.ts";
+import { botSettingsFor, folderSettingsEnv, withBotSettings } from "./claude-bot-settings.ts"; import { claudeHookSettings } from "./claude-hooks.ts";
import { claudeBilling, claudeCallUsage } from "./claude-billing.ts";
import { claudeAuthFailure, claudeAuthRecovery, claudeOAuthExpired } from "./claude-auth-recovery.ts"; import { AWS_CREDENTIAL_ENV_KEYS, bedrockResultError, withBedrockCredentialError } from "./claude-bedrock-aws.ts";
import { CLAUDE_MODEL_ID, STATIC_CLAUDE_MODELS, claudeModelExtras, currentEngineCatalog, endpointModelCatalog, withCliVersionGate } from "./claude-model-extras.ts";
@@ -410,19 +410,6 @@ export function hookTokenFile(threadId: string, botId?: string): string {
return join(DATA_DIR, "hook-tokens", digest, "token");
}
-/** Hooks for the private --settings file. Claude Code runs each command with the event JSON on
- * stdin and applies any hookSpecificOutput it prints. */
-export function claudeHookSettings(helperPath: string, platform: NodeJS.Platform = process.platform): Record<string, unknown> {
- // Claude Code runs `command` as a shell line: sh on macOS and Linux; on Windows Git Bash, or PowerShell
- // when Git Bash is missing, and the two quote differently. Given `args` (2.1.139), it starts `command` itself.
- // JSON quoting is not shell quoting: $(), backticks and $names expand inside double quotes.
- const hook = platform === "win32"
- ? { type: "command", command: process.execPath, args: [helperPath], timeout: 5 }
- : { type: "command", command: [process.execPath, helperPath].map(path => `'${path.replace(/'/g, "'\\''")}'`).join(" "), timeout: 5 };
- const entry = [{ matcher: "", hooks: [hook] }];
- return { PostToolUse: entry, PostToolUseFailure: entry, PreCompact: entry, SessionStart: entry, Stop: entry };
-}
-
export function permissionSocketPath(threadId: string, botId?: string) {
// Half the tag digests the full bot+thread key: Windows named pipes share one global namespace
// and are never unlinked, and 8 chars keeps POSIX paths under the 104-byte sun_path limit.
diff --git a/server/index.ts b/server/index.ts
index 26e1af6878..db12e8c526 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -5436,7 +5436,6 @@ function ingestEngineHook(capability: InternalCapability, body: unknown): { ok:
const context = digests.map((m) => digestPromptLine(m.digest!, m.from?.name ?? store.bot(m.digest!.botId)?.name ?? bot?.name ?? "the bot")).join("\n");
return { ok: true, context };
}
- if (name === "Stop") return { ok: true };
if (name === "PostToolUseFailure") return shellTimeoutHookResult(payload);
if (name !== "PostToolUse") return { ok: true, ignored: name || "unknown" };
const toolUseId = typeof payload.tool_use_id === "string" ? payload.tool_use_id : "";
diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.ts
index 74410254a3..b2036daaa5 100755
--- a/server/testing/fake-claude-cli.ts
+++ b/server/testing/fake-claude-cli.ts
@@ -243,7 +243,7 @@ const replyForPrompt = (prompt: JsonValue): string[] | null => {
};
const argv = process.argv.slice(2);
-const settingsHooks: Record<string, Array<{ 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 }> }>> = (() => {
if (process.env.FAKE_CLAUDE_HOOKS !== "1") return {};
const i = argv.indexOf("--settings");
if (i === -1) return {};
@@ -254,9 +254,14 @@ const settingsHooks: Record<string, Array<{ hooks?: Array<{ type?: string; comma
return {};
}
})();
+// Like Claude Code: a matcher tests the tool name, a session's source or a compaction's trigger; "" and "*" match all.
+const HOOK_MATCHED_FIELD: Record<string, string> = { PostToolUse: "tool_name", PostToolUseFailure: "tool_name", SessionStart: "source", PreCompact: "trigger" };
+const hookMatches = (matcher: string | undefined, value: unknown) =>
+ !matcher || matcher === "*" || new RegExp(`^(?:${matcher})$`).test(String(value ?? ""));
function runHooks(event: string, payload: Record<string, unknown>): string {
let stdout = "";
for (const entry of settingsHooks[event] ?? []) {
+ if (!hookMatches(entry.matcher, payload[HOOK_MATCHED_FIELD[event] ?? ""])) continue;
for (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.