From e03a1cf7691713aabff81717642b8e972d4a1cb4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 23 Jun 2026 17:22:10 -0700 Subject: [PATCH] Prevent managed agent hooks from hanging (#6148) --- src/main/agent-hooks/installer-utils.test.ts | 1 + src/main/agent-hooks/installer-utils.ts | 23 + .../agent-hooks/managed-hook-timeout.test.ts | 399 ++++++++++++++++++ src/main/antigravity/hook-service.ts | 8 +- src/main/claude/hook-settings.ts | 3 +- src/main/codex/hook-service.test.ts | 38 +- src/main/codex/hook-service.ts | 33 +- src/main/command-code/hook-service.ts | 3 +- src/main/cursor/hook-service.ts | 5 +- src/main/devin/hook-settings.ts | 3 +- src/main/droid/hook-service.ts | 3 +- src/main/gemini/hook-service.ts | 8 +- src/main/grok/hook-service.ts | 3 +- src/main/kimi/kimi-hook-config-toml.ts | 11 +- 14 files changed, 519 insertions(+), 22 deletions(-) create mode 100644 src/main/agent-hooks/managed-hook-timeout.test.ts diff --git a/src/main/agent-hooks/installer-utils.test.ts b/src/main/agent-hooks/installer-utils.test.ts index 43c08542c..d316c869d 100644 --- a/src/main/agent-hooks/installer-utils.test.ts +++ b/src/main/agent-hooks/installer-utils.test.ts @@ -397,6 +397,7 @@ describe('buildWindowsAgentHookPostCommand', () => { expect(command).toContain('[Console]::OutputEncoding=$utf8') expect(command).toContain('$bodyBytes=$utf8.GetBytes($body)') expect(command).toContain("-ContentType 'application/json; charset=utf-8'") + expect(command).toContain('-TimeoutSec 2') expect(command).toContain('/hook/codex') expect(command).not.toContain("'Content-Type'='application/json'") }) diff --git a/src/main/agent-hooks/installer-utils.ts b/src/main/agent-hooks/installer-utils.ts index a533fb0ed..c4c112f8e 100644 --- a/src/main/agent-hooks/installer-utils.ts +++ b/src/main/agent-hooks/installer-utils.ts @@ -37,6 +37,29 @@ export type HooksConfig = { [key: string]: unknown } +// Why: host-level backstop (seconds) for Orca-managed status hooks. The shell +// wrapper's curl `--max-time 1.5` is the normal dead-endpoint bound; this caps a +// hook the agent host itself runs in case that transport budget is bypassed. +// Intentionally independent of Copilot's `timeoutSec: 5` — both managed budgets +// coexist by design (#4633). +export const MANAGED_HOOK_TIMEOUT_SECONDS = 10 +export const MANAGED_HOOK_TIMEOUT_MILLISECONDS = MANAGED_HOOK_TIMEOUT_SECONDS * 1000 + +// Nested command hook used by the Claude-shaped `hooks: [...]` schema (Claude, +// Codex, Gemini, Droid, Grok, Command Code, Devin). +export function buildManagedCommandHook( + command: string, + timeout = MANAGED_HOOK_TIMEOUT_SECONDS +): HookCommandConfig { + return { type: 'command', command, timeout } +} + +// Direct command definition used by schemas that put `command` on the +// definition itself (Cursor's documented top-level shape). +export function buildManagedCommandDefinition(command: string): HookDefinition { + return { command, timeout: MANAGED_HOOK_TIMEOUT_SECONDS } +} + export function isPlainObject(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } diff --git a/src/main/agent-hooks/managed-hook-timeout.test.ts b/src/main/agent-hooks/managed-hook-timeout.test.ts new file mode 100644 index 000000000..6ff32c7a2 --- /dev/null +++ b/src/main/agent-hooks/managed-hook-timeout.test.ts @@ -0,0 +1,399 @@ +// Why: one regression fixture proves the managed hook timeout budget across every +// managed agent (config entries, wrapper curl flags, and a real dead-endpoint +// shell run) so the cross-agent coverage lives together rather than fragmenting. +import { afterEach, describe, expect, it, vi } from 'vitest' +import { spawn, spawnSync } from 'child_process' +import { createServer, type Server, type Socket } from 'net' +import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' +import type { SFTPWrapper } from 'ssh2' +import type * as osModule from 'os' + +const { homedirMock } = vi.hoisted(() => ({ + homedirMock: vi.fn<() => string>() +})) + +vi.mock('electron', () => ({ + app: { + getPath: () => '/tmp/orca-user-data' + } +})) + +vi.mock('os', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + homedir: homedirMock.mockImplementation(actual.homedir) + } +}) + +import { MANAGED_HOOK_TIMEOUT_MILLISECONDS, MANAGED_HOOK_TIMEOUT_SECONDS } from './installer-utils' +import { CodexHookService } from '../codex/hook-service' +import { CursorHookService } from '../cursor/hook-service' +import { CommandCodeHookService } from '../command-code/hook-service' +import { GeminiHookService } from '../gemini/hook-service' +import { AntigravityHookService } from '../antigravity/hook-service' +import { ClaudeHookService } from '../claude/hook-service' +import { GrokHookService } from '../grok/hook-service' +import { CopilotHookService } from '../copilot/hook-service' +import { DevinHookService } from '../devin/hook-service' +import { DroidHookService } from '../droid/hook-service' +import { KimiHookService } from '../kimi/hook-service' +import { openClaudeHookService } from '../openclaude/hook-service' + +type FakeFs = { + files: Map + dirs: Set + modes: Map +} + +function createFakeSftp(initialFiles: Record = {}): { + sftp: SFTPWrapper + fs: FakeFs +} { + const fs: FakeFs = { + files: new Map(Object.entries(initialFiles)), + dirs: new Set(['/']), + modes: new Map() + } + const noEntryError = (path: string): { code: number; message: string } => ({ + code: 2, + message: `ENOENT ${path}` + }) + + const sftp = { + readFile: (path: string, _enc: string, cb: (err: unknown, data?: string) => void): void => { + const v = fs.files.get(path) + if (v === undefined) { + cb(noEntryError(path)) + return + } + cb(null, v) + }, + writeFile: ( + path: string, + content: string, + options: string | { mode?: number }, + cb: (err: unknown) => void + ): void => { + fs.files.set(path, content) + if (typeof options !== 'string' && options.mode !== undefined) { + fs.modes.set(path, options.mode) + } + cb(null) + }, + rename: (src: string, dst: string, cb: (err: unknown) => void): void => { + const v = fs.files.get(src) + if (v === undefined) { + cb(noEntryError(src)) + return + } + fs.files.set(dst, v) + fs.files.delete(src) + const mode = fs.modes.get(src) + if (mode !== undefined) { + fs.modes.set(dst, mode) + fs.modes.delete(src) + } + cb(null) + }, + unlink: (path: string, cb: (err: unknown) => void): void => { + fs.files.delete(path) + fs.modes.delete(path) + cb(null) + }, + chmod: (path: string, mode: number, cb: (err: unknown) => void): void => { + fs.modes.set(path, mode) + cb(null) + }, + stat: (path: string, cb: (err: unknown, stats?: { mode: number }) => void): void => { + if (!fs.files.has(path)) { + cb(noEntryError(path)) + return + } + cb(null, { mode: fs.modes.get(path) ?? 0o100644 }) + }, + readdir: (path: string, cb: (err: unknown, list?: { filename: string }[]) => void): void => { + if (fs.dirs.has(path)) { + cb(null, []) + return + } + cb(noEntryError(path)) + }, + mkdir: (path: string, cb: (err: unknown) => void): void => { + fs.dirs.add(path) + cb(null) + } + } as unknown as SFTPWrapper + return { sftp, fs } +} + +const REMOTE_HOME = '/home/dev' + +// Each managed agent that ships an SSH-compatible JSON/TOML hook config. Amp and +// Hermes are intentionally excluded: they are plugin systems with no hook config +// entries, so their transport budgets live in plugin source (see design doc). +const JSON_INSTALLERS = [ + { + agent: 'claude', + timeout: MANAGED_HOOK_TIMEOUT_SECONDS, + configPath: `${REMOTE_HOME}/.claude/settings.json`, + install: (sftp: SFTPWrapper) => new ClaudeHookService().installRemote(sftp, REMOTE_HOME) + }, + { + agent: 'openclaude', + timeout: MANAGED_HOOK_TIMEOUT_SECONDS, + configPath: `${REMOTE_HOME}/.openclaude/settings.json`, + install: (sftp: SFTPWrapper) => openClaudeHookService.installRemote(sftp, REMOTE_HOME) + }, + { + agent: 'codex', + timeout: MANAGED_HOOK_TIMEOUT_SECONDS, + configPath: `${REMOTE_HOME}/.codex/hooks.json`, + install: (sftp: SFTPWrapper) => new CodexHookService().installRemote(sftp, REMOTE_HOME) + }, + { + agent: 'gemini', + timeout: MANAGED_HOOK_TIMEOUT_MILLISECONDS, + configPath: `${REMOTE_HOME}/.gemini/settings.json`, + install: (sftp: SFTPWrapper) => new GeminiHookService().installRemote(sftp, REMOTE_HOME) + }, + { + agent: 'antigravity', + timeout: MANAGED_HOOK_TIMEOUT_SECONDS, + configPath: `${REMOTE_HOME}/.gemini/config/hooks.json`, + install: (sftp: SFTPWrapper) => new AntigravityHookService().installRemote(sftp, REMOTE_HOME) + }, + { + agent: 'cursor', + timeout: MANAGED_HOOK_TIMEOUT_SECONDS, + configPath: `${REMOTE_HOME}/.cursor/hooks.json`, + install: (sftp: SFTPWrapper) => new CursorHookService().installRemote(sftp, REMOTE_HOME) + }, + { + agent: 'command-code', + timeout: MANAGED_HOOK_TIMEOUT_SECONDS, + configPath: `${REMOTE_HOME}/.commandcode/settings.json`, + install: (sftp: SFTPWrapper) => new CommandCodeHookService().installRemote(sftp, REMOTE_HOME) + }, + { + agent: 'grok', + timeout: MANAGED_HOOK_TIMEOUT_SECONDS, + configPath: `${REMOTE_HOME}/.grok/hooks/orca-status.json`, + install: (sftp: SFTPWrapper) => new GrokHookService().installRemote(sftp, REMOTE_HOME) + }, + { + agent: 'copilot', + timeout: 5, + configPath: `${REMOTE_HOME}/.copilot/hooks/orca.json`, + install: (sftp: SFTPWrapper) => new CopilotHookService().installRemote(sftp, REMOTE_HOME) + }, + { + agent: 'devin', + timeout: MANAGED_HOOK_TIMEOUT_SECONDS, + configPath: `${REMOTE_HOME}/.config/devin/config.json`, + install: (sftp: SFTPWrapper) => new DevinHookService().installRemote(sftp, REMOTE_HOME) + } +] as const + +const MANAGED_HOOKS_DIR_NEEDLE = '/.orca/agent-hooks/' + +// Walk the parsed config and assert every Orca-managed command carrier (a node +// with a `command`/`bash`/`powershell` string pointing at the managed script +// dir) has a positive config-level timeout sibling (`timeout` or the +// provider-specific `timeoutSec`). Returns the count of managed carriers found +// so callers can assert the scan was not vacuous. +function countManagedCarriersWithTimeout(node: unknown, expectedTimeout: number): number { + if (Array.isArray(node)) { + return node.reduce( + (sum, child) => sum + countManagedCarriersWithTimeout(child, expectedTimeout), + 0 + ) + } + if (node === null || typeof node !== 'object') { + return 0 + } + const record = node as Record + let found = 0 + const carrier = [record.command, record.bash, record.powershell].find( + (value): value is string => + typeof value === 'string' && value.includes(MANAGED_HOOKS_DIR_NEEDLE) + ) + if (carrier !== undefined) { + const timeout = typeof record.timeout === 'number' ? record.timeout : record.timeoutSec + expect(typeof timeout, `managed carrier "${carrier}" is missing a config timeout`).toBe( + 'number' + ) + expect(timeout as number).toBe(expectedTimeout) + found += 1 + } + for (const value of Object.values(record)) { + found += countManagedCarriersWithTimeout(value, expectedTimeout) + } + return found +} + +describe('managed agent hook timeouts', () => { + it('writes a config-level timeout on every managed JSON hook entry', async () => { + for (const { agent, configPath, install, timeout } of JSON_INSTALLERS) { + const { sftp, fs } = createFakeSftp() + const status = await install(sftp) + expect(status.state, `${agent} install state`).toBe('installed') + const raw = fs.files.get(configPath) + expect(raw, `${agent} config written`).toBeDefined() + const carriers = countManagedCarriersWithTimeout(JSON.parse(raw!), timeout) + expect( + carriers, + `${agent} should have at least one managed timeout-bearing entry` + ).toBeGreaterThan(0) + } + }) + + it('writes a timeout on the managed Kimi TOML hook block', async () => { + const { sftp, fs } = createFakeSftp() + const status = await new KimiHookService().installRemote(sftp, REMOTE_HOME) + expect(status.state).toBe('installed') + const config = fs.files.get(`${REMOTE_HOME}/.kimi-code/config.toml`)! + // One timeout line per managed [[hooks]] event entry. + const timeoutLines = config.match(new RegExp(`timeout = ${MANAGED_HOOK_TIMEOUT_SECONDS}`, 'g')) + expect(timeoutLines?.length ?? 0).toBeGreaterThan(0) + expect(config).toContain('/home/dev/.orca/agent-hooks/kimi-hook.sh') + }) + + it('writes a config-level timeout on local-only Droid hooks', () => { + const homeDir = mkdtempSync(join(tmpdir(), 'orca-droid-hook-timeout-')) + homedirMock.mockReturnValue(homeDir) + try { + const status = new DroidHookService().install() + expect(status.state).toBe('installed') + const config = JSON.parse(readFileSync(join(homeDir, '.factory', 'settings.json'), 'utf8')) + const carriers = countManagedCarriersWithTimeout(config, MANAGED_HOOK_TIMEOUT_SECONDS) + expect(carriers).toBeGreaterThan(0) + } finally { + homedirMock.mockImplementation(() => process.env.HOME ?? tmpdir()) + rmSync(homeDir, { recursive: true, force: true }) + } + }) + + it('bounds every generated POSIX curl wrapper with --connect-timeout and --max-time', async () => { + let curlWrappersChecked = 0 + for (const { agent, install } of JSON_INSTALLERS) { + const { sftp, fs } = createFakeSftp() + await install(sftp) + for (const [path, content] of fs.files) { + if (!path.endsWith('.sh')) { + continue + } + expect(content, `${agent} wrapper missing curl transport`).toContain('curl') + expect(content, `${agent} wrapper missing --connect-timeout`).toContain('--connect-timeout') + expect(content, `${agent} wrapper missing --max-time`).toContain('--max-time') + curlWrappersChecked += 1 + } + } + const kimi = createFakeSftp() + await new KimiHookService().installRemote(kimi.sftp, REMOTE_HOME) + const kimiWrapper = kimi.fs.files.get(`${REMOTE_HOME}/.orca/agent-hooks/kimi-hook.sh`)! + expect(kimiWrapper, 'kimi wrapper missing --connect-timeout').toContain('--connect-timeout') + expect(kimiWrapper, 'kimi wrapper missing --max-time').toContain('--max-time') + curlWrappersChecked += 1 + expect(curlWrappersChecked).toBeGreaterThan(0) + }) + + describe('dead-endpoint transport budget', () => { + let tempDir: string | null = null + let server: Server | null = null + const openSockets: Socket[] = [] + + afterEach(() => { + for (const socket of openSockets.splice(0)) { + socket.destroy() + } + if (server) { + server.close() + server = null + } + if (tempDir) { + rmSync(tempDir, { recursive: true, force: true }) + tempDir = null + } + }) + + const hasPosixCurl = + process.platform !== 'win32' && + spawnSync('sh', ['-c', 'command -v curl'], { encoding: 'utf8' }).status === 0 + + function runHookScript(scriptPath: string, port: number): Promise<{ status: number | null }> { + return new Promise((resolve, reject) => { + const child = spawn('sh', [scriptPath], { + env: { + ...process.env, + ORCA_AGENT_HOOK_ENDPOINT: '', + ORCA_AGENT_HOOK_PORT: String(port), + ORCA_AGENT_HOOK_TOKEN: 'test-token', + ORCA_PANE_KEY: 'pane-1', + ORCA_TAB_ID: 'tab-1', + ORCA_WORKTREE_ID: 'wt-1' + }, + stdio: ['pipe', 'ignore', 'ignore'] + }) + const timeout = setTimeout(() => { + child.kill('SIGKILL') + reject(new Error('hook script exceeded test timeout')) + }, 10_000) + child.on('error', (error) => { + clearTimeout(timeout) + reject(error) + }) + child.on('close', (status) => { + clearTimeout(timeout) + resolve({ status }) + }) + child.stdin.end('{"hook_event_name":"Stop"}') + }) + } + + // Why: an accepted-but-unanswered connection is the worst-case hang that only + // `--max-time` (1.5s) governs — `--connect-timeout` already passes once the + // TCP handshake completes. Point the wrapper at a real loopback listener that + // accepts and then stalls, and assert the wrapper still returns well under a + // generous CI budget. + it.skipIf(!hasPosixCurl)( + 'returns within budget when the local listener accepts but never responds', + async () => { + // Reuse a real generated POSIX wrapper rather than re-deriving the script. + const { sftp, fs } = createFakeSftp() + await new CodexHookService().installRemote(sftp, REMOTE_HOME) + const wrapperBody = fs.files.get(`${REMOTE_HOME}/.orca/agent-hooks/codex-hook.sh`)! + + tempDir = mkdtempSync(join(tmpdir(), 'orca-hook-timeout-')) + const scriptPath = join(tempDir, 'codex-hook.sh') + writeFileSync(scriptPath, wrapperBody, 'utf8') + chmodSync(scriptPath, 0o755) + + const stallingServer = createServer((socket) => { + // Accept the connection and hold it open without ever replying. + openSockets.push(socket) + }) + server = stallingServer + const port = await new Promise((resolve) => { + stallingServer.listen(0, '127.0.0.1', () => { + const address = stallingServer.address() + resolve(typeof address === 'object' && address ? address.port : 0) + }) + }) + + const startedAt = Date.now() + const result = await runHookScript(scriptPath, port) + const elapsedMs = Date.now() - startedAt + + // The hook fails open (`|| true`) and exits 0 even though the POST timed out. + expect(result.status).toBe(0) + expect(openSockets.length).toBeGreaterThan(0) + expect(elapsedMs).toBeGreaterThanOrEqual(1_000) + // --max-time 1.5s + process overhead; a hang would blow well past this. + expect(elapsedMs).toBeLessThan(6_000) + } + ) + }) +}) diff --git a/src/main/antigravity/hook-service.ts b/src/main/antigravity/hook-service.ts index e78d4cf5f..343c4d215 100644 --- a/src/main/antigravity/hook-service.ts +++ b/src/main/antigravity/hook-service.ts @@ -6,9 +6,11 @@ import { join } from 'path' import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types' import { + buildManagedCommandHook, createManagedCommandMatcher, getSharedManagedScriptPath, hookDefinitionHasManagedCommand, + MANAGED_HOOK_TIMEOUT_SECONDS, readHooksJson, removeManagedCommands, wrapPosixHookCommand, @@ -228,10 +230,12 @@ function buildEventDefinition(event: AntigravityEvent, command: string): HookDef if (event.schema === 'tool') { return { matcher: '*', - hooks: [{ type: 'command', command }] + hooks: [buildManagedCommandHook(command)] } } - return { type: 'command', command } + // Antigravity's direct-command event schema carries the command on the + // definition; add the host-level timeout backstop alongside it. + return { type: 'command', command, timeout: MANAGED_HOOK_TIMEOUT_SECONDS } } function removeManagedCommandsFromBundle( diff --git a/src/main/claude/hook-settings.ts b/src/main/claude/hook-settings.ts index fc94d6e2c..594cb7e33 100644 --- a/src/main/claude/hook-settings.ts +++ b/src/main/claude/hook-settings.ts @@ -1,6 +1,7 @@ import { homedir } from 'os' import { join } from 'path' import { + buildManagedCommandHook, createManagedCommandMatcher, getSharedManagedScriptPath, removeManagedCommands, @@ -101,7 +102,7 @@ export function applyManagedHooks( const cleaned = removeManagedCommands(current, isManagedCommand) const definition: HookDefinition = { ...event.definition, - hooks: [{ type: 'command', command }] + hooks: [buildManagedCommandHook(command)] } nextHooks[event.eventName] = [...cleaned, definition] } diff --git a/src/main/codex/hook-service.test.ts b/src/main/codex/hook-service.test.ts index 94f365a21..cc72c4c30 100644 --- a/src/main/codex/hook-service.test.ts +++ b/src/main/codex/hook-service.test.ts @@ -14,7 +14,7 @@ import { tmpdir } from 'os' import type * as Os from 'os' import { join } from 'path' import { createManagedCommandMatcher, wrapPosixHookCommand } from '../agent-hooks/installer-utils' -import { upsertHookTrustEntriesInContent } from './config-toml-trust' +import { computeTrustedHash, upsertHookTrustEntriesInContent } from './config-toml-trust' const { getPathMock, homedirMock } = vi.hoisted(() => ({ getPathMock: vi.fn<(name: string) => string>(), @@ -1039,6 +1039,42 @@ describe('CodexHookService', () => { expect(runtimeToml).not.toContain(':stop:0:0') }) + it('removes legacy managed trust entries hashed before hook timeouts existed', () => { + const service = new CodexHookService() + expect(service.install().state).toBe('installed') + + const managedCodexHome = join(userDataDir, 'codex-runtime-home', 'home') + const managedHooksPath = join(managedCodexHome, 'hooks.json') + const runtimeTomlPath = join(managedCodexHome, 'config.toml') + const hooksConfig = JSON.parse(readFileSync(managedHooksPath, 'utf-8')) as { + hooks: Record + } + const command = hooksConfig.hooks.PermissionRequest?.[0]?.hooks?.[0]?.command + expect(command).toBeDefined() + const legacyHash = computeTrustedHash({ + sourcePath: managedHooksPath, + eventLabel: 'permission_request', + groupIndex: 0, + handlerIndex: 0, + command: command! + }) + writeFileSync( + runtimeTomlPath, + [ + hookTrustHeader(`${managedHooksPath}:permission_request:0:0`), + 'enabled = true', + `trusted_hash = "${legacyHash}"`, + '' + ].join('\n'), + 'utf-8' + ) + + expect(service.remove().state).toBe('not_installed') + + const runtimeToml = readFileSync(runtimeTomlPath, 'utf-8') + expect(runtimeToml).not.toContain(':permission_request:0:0') + }) + it('mirrors system Codex config while preserving runtime hook trust on hook install', () => { const systemCodexHome = join(tmpHome, '.codex') mkdirSync(systemCodexHome, { recursive: true }) diff --git a/src/main/codex/hook-service.ts b/src/main/codex/hook-service.ts index 99638a787..15c415f94 100644 --- a/src/main/codex/hook-service.ts +++ b/src/main/codex/hook-service.ts @@ -4,10 +4,12 @@ import { join } from 'path' import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types' import { + buildManagedCommandHook, createManagedCommandMatcher, buildWindowsAgentHookPostCommand, getSharedManagedScriptPath, hookDefinitionHasManagedCommand, + MANAGED_HOOK_TIMEOUT_SECONDS, readHooksJson, removeManagedCommands, wrapPosixHookCommand, @@ -608,14 +610,19 @@ function removeRuntimeManagedHookTrustEntries(configPath: string): void { if (!managedEventLabels.has(parts.eventLabel)) { continue } - const expectedHash = computeTrustedHash({ + const expectedEntry: CodexTrustEntry = { sourcePath: configPath, eventLabel: parts.eventLabel, groupIndex: parts.groupIndex, handlerIndex: parts.handlerIndex, - command - }) - if (state.trustedHash !== expectedHash) { + command, + // Why: match the timeout install() wrote, or remove() would fail to + // recognize (and clean up) its own managed trust entries. + timeoutSec: MANAGED_HOOK_TIMEOUT_SECONDS + } + const expectedHash = computeTrustedHash(expectedEntry) + const legacyHash = computeTrustedHash({ ...expectedEntry, timeoutSec: undefined }) + if (state.trustedHash !== expectedHash && state.trustedHash !== legacyHash) { continue } ourKeys.push(key) @@ -749,12 +756,16 @@ export class CodexHookService { // Why: capture the actual handler index — Codex's hook_key uses the // positional handlerIndex, and a user-merged hook array can put our // command at a non-zero slot, so hardcoding 0 would misreport trust. + // Why: the managed hook is written with `timeout` (see install()), and + // Codex folds the handler timeout into its trust hash. Hash the same + // timeout here or status would report every managed hook as stale-trust. const trustInput: CodexTrustEntry = { sourcePath: configPath, eventLabel: CODEX_EVENT_LABEL[eventName], groupIndex: foundGroupIndex, handlerIndex: foundHandlerIndex, - command + command, + timeoutSec: MANAGED_HOOK_TIMEOUT_SECONDS } const expectedHash = computeTrustedHash(trustInput) const actualState = trustEntries.get(computeTrustKey(trustInput)) @@ -858,18 +869,21 @@ export class CodexHookService { const current = Array.isArray(nextHooks[eventName]) ? nextHooks[eventName] : [] const cleaned = removeManagedCommands(current, isManagedCommand) const definition: HookDefinition = { - hooks: [{ type: 'command', command }] + hooks: [buildManagedCommandHook(command)] } nextHooks[eventName] = [definition, ...cleaned] // Why: the status hook must run before user hooks so a slow // PostToolUse/Stop hook cannot leave the sidebar stuck on the previous // state while Codex visibly reports that hooks are still running. + // timeoutSec mirrors the hook's `timeout` so the trust hash matches the + // entry actually written to hooks.json. trustEntries.push({ sourcePath: configPath, eventLabel: CODEX_EVENT_LABEL[eventName], groupIndex: 0, handlerIndex: 0, - command + command, + timeoutSec: MANAGED_HOOK_TIMEOUT_SECONDS }) } @@ -946,7 +960,7 @@ export class CodexHookService { const current = Array.isArray(nextHooks[eventName]) ? nextHooks[eventName] : [] const cleaned = removeManagedCommands(current, isManagedCommand) const definition: HookDefinition = { - hooks: [{ type: 'command', command }] + hooks: [buildManagedCommandHook(command)] } nextHooks[eventName] = [...cleaned, definition] trustEntries.push({ @@ -954,7 +968,8 @@ export class CodexHookService { eventLabel: CODEX_EVENT_LABEL[eventName], groupIndex: cleaned.length, handlerIndex: 0, - command + command, + timeoutSec: MANAGED_HOOK_TIMEOUT_SECONDS }) } diff --git a/src/main/command-code/hook-service.ts b/src/main/command-code/hook-service.ts index a5a34a305..64413bdd7 100644 --- a/src/main/command-code/hook-service.ts +++ b/src/main/command-code/hook-service.ts @@ -4,6 +4,7 @@ import { join } from 'path' import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types' import { + buildManagedCommandHook, createManagedCommandMatcher, buildWindowsAgentHookPostCommand, getSharedManagedScriptPath, @@ -212,7 +213,7 @@ function buildInstalledConfig( const cleaned = removeManagedCommands(current, isManagedCommand) const definition: HookDefinition = { ...event.definition, - hooks: [{ type: 'command', command }] + hooks: [buildManagedCommandHook(command)] } nextHooks[event.eventName] = [...cleaned, definition] } diff --git a/src/main/cursor/hook-service.ts b/src/main/cursor/hook-service.ts index fb57ce1b8..1eb2a2f4e 100644 --- a/src/main/cursor/hook-service.ts +++ b/src/main/cursor/hook-service.ts @@ -3,6 +3,7 @@ import { join } from 'path' import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types' import { + buildManagedCommandDefinition, createManagedCommandMatcher, buildWindowsAgentHookPostCommand, getSharedManagedScriptPath, @@ -230,7 +231,7 @@ export class CursorHookService { // Why: Cursor's documented schema puts `command` directly on the // definition (not under `hooks`). Emit that shape so cursor-agent // actually invokes the script. - const definition: HookDefinition = { command } + const definition: HookDefinition = buildManagedCommandDefinition(command) nextHooks[eventName] = [...cleaned, definition] } @@ -280,7 +281,7 @@ export class CursorHookService { const cleaned = removeManagedCommands(current, isManagedCommand).filter( (definition) => !isManagedCommand(definition.command as string | undefined) ) - const definition: HookDefinition = { command } + const definition: HookDefinition = buildManagedCommandDefinition(command) nextHooks[eventName] = [...cleaned, definition] } diff --git a/src/main/devin/hook-settings.ts b/src/main/devin/hook-settings.ts index 62cb4bd25..873836897 100644 --- a/src/main/devin/hook-settings.ts +++ b/src/main/devin/hook-settings.ts @@ -1,6 +1,7 @@ import { homedir } from 'os' import { join } from 'path' import { + buildManagedCommandHook, createManagedCommandMatcher, getSharedManagedScriptPath, removeManagedCommands, @@ -74,7 +75,7 @@ export function applyDevinManagedHooks( const cleaned = removeManagedCommands(current, isManagedCommand) const definition: HookDefinition = { ...event.definition, - hooks: [{ type: 'command', command }] + hooks: [buildManagedCommandHook(command)] } nextHooks[event.eventName] = [...cleaned, definition] } diff --git a/src/main/droid/hook-service.ts b/src/main/droid/hook-service.ts index f8e07cec3..ce61c9a01 100644 --- a/src/main/droid/hook-service.ts +++ b/src/main/droid/hook-service.ts @@ -2,6 +2,7 @@ import { homedir } from 'os' import { join } from 'path' import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types' import { + buildManagedCommandHook, createManagedCommandMatcher, buildWindowsAgentHookPostCommand, getSharedManagedScriptPath, @@ -211,7 +212,7 @@ export class DroidHookService { const cleaned = removeManagedCommands(current, isManagedCommand) const definition: HookDefinition = { ...event.definition, - hooks: [{ type: 'command', command }] + hooks: [buildManagedCommandHook(command)] } nextHooks[event.eventName] = [...cleaned, definition] } diff --git a/src/main/gemini/hook-service.ts b/src/main/gemini/hook-service.ts index 889e7a467..d724ced28 100644 --- a/src/main/gemini/hook-service.ts +++ b/src/main/gemini/hook-service.ts @@ -3,9 +3,11 @@ import { join } from 'path' import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types' import { + buildManagedCommandHook, createManagedCommandMatcher, buildWindowsAgentHookPostCommand, getSharedManagedScriptPath, + MANAGED_HOOK_TIMEOUT_MILLISECONDS, readHooksJson, removeManagedCommands, wrapPosixHookCommand, @@ -204,7 +206,8 @@ export class GeminiHookService { const current = Array.isArray(nextHooks[eventName]) ? nextHooks[eventName] : [] const cleaned = removeManagedCommands(current, isManagedCommand) const definition: HookDefinition = { - hooks: [{ type: 'command', command }] + // Why: Gemini's hook `timeout` unit is milliseconds, unlike Claude/Codex. + hooks: [buildManagedCommandHook(command, MANAGED_HOOK_TIMEOUT_MILLISECONDS)] } nextHooks[eventName] = [...cleaned, definition] } @@ -261,7 +264,8 @@ export class GeminiHookService { const current = Array.isArray(nextHooks[eventName]) ? nextHooks[eventName] : [] const cleaned = removeManagedCommands(current, isManagedCommand) const definition: HookDefinition = { - hooks: [{ type: 'command', command }] + // Why: Gemini's hook `timeout` unit is milliseconds, unlike Claude/Codex. + hooks: [buildManagedCommandHook(command, MANAGED_HOOK_TIMEOUT_MILLISECONDS)] } nextHooks[eventName] = [...cleaned, definition] } diff --git a/src/main/grok/hook-service.ts b/src/main/grok/hook-service.ts index e8a81952a..bbd881d7d 100644 --- a/src/main/grok/hook-service.ts +++ b/src/main/grok/hook-service.ts @@ -3,6 +3,7 @@ import { join } from 'path' import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types' import { + buildManagedCommandHook, createManagedCommandMatcher, buildWindowsAgentHookPostCommand, getSharedManagedScriptPath, @@ -133,7 +134,7 @@ function buildInstalledConfig( const cleaned = removeManagedCommands(current, isManagedCommand) const definition: HookDefinition = { ...event.definition, - hooks: [{ type: 'command', command }] + hooks: [buildManagedCommandHook(command)] } nextHooks[event.eventName] = [...cleaned, definition] } diff --git a/src/main/kimi/kimi-hook-config-toml.ts b/src/main/kimi/kimi-hook-config-toml.ts index 5e8008070..82118c675 100644 --- a/src/main/kimi/kimi-hook-config-toml.ts +++ b/src/main/kimi/kimi-hook-config-toml.ts @@ -6,6 +6,8 @@ // untouched. Appending table headers is always valid TOML, so the block can live // at the end of any existing file. +import { MANAGED_HOOK_TIMEOUT_SECONDS } from '../agent-hooks/installer-utils' + // Why: mirror the Claude-compatible events Orca normalizes for status. Kimi uses // these exact event names (see normalizeKimiEvent), so each maps to a // working/waiting/done transition. @@ -55,8 +57,15 @@ export function buildManagedKimiHooksBlock(command: string): string { const commandLiteral = tomlBasicString(command) // Omit `matcher`: Kimi treats it as a regex (so Claude's literal "*" is // invalid) and an absent matcher already matches every tool. + // `timeout` is the host-level backstop; the shell wrapper's curl budget is + // the normal dead-endpoint bound. const entries = KIMI_HOOK_EVENTS.map((event) => - [`[[hooks]]`, `event = "${event}"`, `command = ${commandLiteral}`].join('\n') + [ + `[[hooks]]`, + `event = "${event}"`, + `command = ${commandLiteral}`, + `timeout = ${MANAGED_HOOK_TIMEOUT_SECONDS}` + ].join('\n') ) return [BLOCK_START, ...entries, BLOCK_END].join('\n') }