From 31f7ce5ceff8719a673e366525d68c510d43d224 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Wed, 27 May 2026 19:50:43 +0100 Subject: [PATCH 1/3] perf(hooks): fire-and-forget telemetry hooks (closes #573) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Telemetry hooks (notification, post-tool-failure, post-tool-use, prompt-submit, stop, session-end, subagent-start, subagent-stop, task-completed) previously `await fetch(..., AbortSignal.timeout(N))` inside a try/catch. The await kept the hook process alive until the response arrived — up to N ms per request — which blocks Claude Code's next-prompt boundary on every assistant turn. Switch to fire-and-forget: fetch(url, { signal: AbortSignal.timeout(N) }).catch(() => {}); setTimeout(() => process.exit(0), 500).unref(); The unawaited fetch dispatches the request; the unref'd setTimeout force-exits the process after the request has been flushed to the local daemon's socket buffer (~500ms is enough). Without the setTimeout Node keeps the event loop alive waiting for any in-flight fetch to settle, which means the hook still blocks Claude Code's next-prompt boundary for up to the AbortSignal duration. Context-injecting hooks (pre-tool-use, pre-compact, session-start) still use `await fetch` because Claude Code reads their stdout for context injection — left untouched. AGENTS.md updated with the two-pattern guidance. --- AGENTS.md | 5 ++- plugin/scripts/notification.mjs | 37 +++++++++-------- plugin/scripts/post-tool-failure.mjs | 37 +++++++++-------- plugin/scripts/post-tool-use.mjs | 39 +++++++++--------- plugin/scripts/prompt-submit.mjs | 29 +++++++------- plugin/scripts/session-end.mjs | 57 ++++++++++++-------------- plugin/scripts/stop.mjs | 29 ++++++-------- plugin/scripts/subagent-start.mjs | 1 + plugin/scripts/subagent-stop.mjs | 37 +++++++++-------- plugin/scripts/task-completed.mjs | 41 ++++++++++--------- src/hooks/notification.ts | 43 ++++++++++---------- src/hooks/post-tool-failure.ts | 51 +++++++++++------------ src/hooks/post-tool-use.ts | 40 +++++++++---------- src/hooks/prompt-submit.ts | 31 +++++++------- src/hooks/session-end.ts | 60 ++++++++++++---------------- src/hooks/stop.ts | 47 +++++++++------------- src/hooks/subagent-start.ts | 1 + src/hooks/subagent-stop.ts | 39 +++++++++--------- src/hooks/task-completed.ts | 47 ++++++++++------------ 19 files changed, 314 insertions(+), 357 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ebcf35844b..019648f4b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,7 +89,10 @@ case "memory_your_tool": { ``` ### Hook Scripts -Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). They read JSON from stdin, make HTTP calls to the REST API, and exit. Always use `try/catch` with `AbortSignal.timeout()` for best-effort calls. +Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). They read JSON from stdin, make HTTP calls to the REST API, and exit. There are two patterns depending on whether Claude Code consumes the script's stdout: + +- **Context-injecting hooks** (`pre-tool-use`, `pre-compact`, `session-start`) write recalled context to stdout for Claude Code to inject. These MUST use `try/catch` with `await fetch(..., { signal: AbortSignal.timeout(N) })` — the script has to wait for the response before exiting, and the timeout is the only bound on hang time. +- **Telemetry-only hooks** (`notification`, `post-tool-failure`, `post-tool-use`, `prompt-submit`, `stop`, `session-end`, `subagent-start`, `subagent-stop`, `task-completed`) write nothing to stdout. These MUST use fire-and-forget `fetch(..., { signal: AbortSignal.timeout(N) }).catch(() => {})` paired with `setTimeout(() => process.exit(0), 500).unref()`. The unawaited fetch dispatches the request; the unref'd `setTimeout` force-exits the process after the request has been flushed to the local daemon's socket buffer (~500ms is enough). Without the `setTimeout` Node keeps the event loop alive waiting for any in-flight fetch to settle, which means the hook still blocks Claude Code's next-prompt boundary for up to the AbortSignal duration — exactly the bug fire-and-forget is meant to fix. ## Coding Standards diff --git a/plugin/scripts/notification.mjs b/plugin/scripts/notification.mjs index 9c3f4665bd..b1cb59060c 100755 --- a/plugin/scripts/notification.mjs +++ b/plugin/scripts/notification.mjs @@ -48,25 +48,24 @@ async function main() { if (isSdkChildContext(data)) return; if (data.notification_type !== "permission_prompt") return; const sessionId = data.session_id || "unknown"; - try { - await fetch(`${REST_URL}/agentmemory/observe`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ - hookType: "notification", - sessionId, - project: resolveProject(data.cwd), - cwd: data.cwd || process.cwd(), - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - data: { - notification_type: data.notification_type, - title: data.title, - message: data.message - } - }), - signal: AbortSignal.timeout(2e3) - }); - } catch {} + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "notification", + sessionId, + project: resolveProject(data.cwd), + cwd: data.cwd || process.cwd(), + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { + notification_type: data.notification_type, + title: data.title, + message: data.message + } + }), + signal: AbortSignal.timeout(2e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } main(); diff --git a/plugin/scripts/post-tool-failure.mjs b/plugin/scripts/post-tool-failure.mjs index f6a49ace10..b584d26aa4 100755 --- a/plugin/scripts/post-tool-failure.mjs +++ b/plugin/scripts/post-tool-failure.mjs @@ -48,25 +48,24 @@ async function main() { if (isSdkChildContext(data)) return; if (data.is_interrupt) return; const sessionId = data.session_id || "unknown"; - try { - await fetch(`${REST_URL}/agentmemory/observe`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ - hookType: "post_tool_failure", - sessionId, - project: resolveProject(data.cwd), - cwd: data.cwd || process.cwd(), - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - data: { - tool_name: data.tool_name, - tool_input: typeof data.tool_input === "string" ? data.tool_input.slice(0, 4e3) : JSON.stringify(data.tool_input ?? "").slice(0, 4e3), - error: typeof data.error === "string" ? data.error.slice(0, 4e3) : JSON.stringify(data.error ?? "").slice(0, 4e3) - } - }), - signal: AbortSignal.timeout(3e3) - }); - } catch {} + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "post_tool_failure", + sessionId, + project: resolveProject(data.cwd), + cwd: data.cwd || process.cwd(), + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { + tool_name: data.tool_name, + tool_input: typeof data.tool_input === "string" ? data.tool_input.slice(0, 4e3) : JSON.stringify(data.tool_input ?? "").slice(0, 4e3), + error: typeof data.error === "string" ? data.error.slice(0, 4e3) : JSON.stringify(data.error ?? "").slice(0, 4e3) + } + }), + signal: AbortSignal.timeout(3e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } main(); diff --git a/plugin/scripts/post-tool-use.mjs b/plugin/scripts/post-tool-use.mjs index 4a50357f82..76add3b9dc 100755 --- a/plugin/scripts/post-tool-use.mjs +++ b/plugin/scripts/post-tool-use.mjs @@ -48,26 +48,25 @@ async function main() { if (isSdkChildContext(data)) return; const sessionId = data.session_id || "unknown"; const { imageData, cleanOutput } = extractImageData(data.tool_response ?? data.tool_output); - try { - await fetch(`${REST_URL}/agentmemory/observe`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ - hookType: "post_tool_use", - sessionId, - project: resolveProject(data.cwd), - cwd: data.cwd || process.cwd(), - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - data: { - tool_name: data.tool_name, - tool_input: data.tool_input, - tool_output: truncate(cleanOutput, 8e3), - ...imageData ? { image_data: imageData } : {} - } - }), - signal: AbortSignal.timeout(3e3) - }); - } catch {} + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "post_tool_use", + sessionId, + project: resolveProject(data.cwd), + cwd: data.cwd || process.cwd(), + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { + tool_name: data.tool_name, + tool_input: data.tool_input, + tool_output: truncate(cleanOutput, 8e3), + ...imageData ? { image_data: imageData } : {} + } + }), + signal: AbortSignal.timeout(3e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } function isBase64Image(val) { return typeof val === "string" && (val.startsWith("data:image/") || val.startsWith("iVBORw0KGgo") || val.startsWith("/9j/")); diff --git a/plugin/scripts/prompt-submit.mjs b/plugin/scripts/prompt-submit.mjs index cf099bd5ca..7d7f380d29 100755 --- a/plugin/scripts/prompt-submit.mjs +++ b/plugin/scripts/prompt-submit.mjs @@ -47,21 +47,20 @@ async function main() { } if (isSdkChildContext(data)) return; const sessionId = data.session_id || "unknown"; - try { - await fetch(`${REST_URL}/agentmemory/observe`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ - hookType: "prompt_submit", - sessionId, - project: resolveProject(data.cwd), - cwd: data.cwd || process.cwd(), - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - data: { prompt: data.prompt } - }), - signal: AbortSignal.timeout(3e3) - }); - } catch {} + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "prompt_submit", + sessionId, + project: resolveProject(data.cwd), + cwd: data.cwd || process.cwd(), + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { prompt: data.prompt } + }), + signal: AbortSignal.timeout(3e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } main(); diff --git a/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjs index 8e1de092e8..0855a68c99 100755 --- a/plugin/scripts/session-end.mjs +++ b/plugin/scripts/session-end.mjs @@ -23,42 +23,35 @@ async function main() { } if (isSdkChildContext(data)) return; const sessionId = data.session_id || "unknown"; - try { - await fetch(`${REST_URL}/agentmemory/session/end`, { + fetch(`${REST_URL}/agentmemory/session/end`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ sessionId }), + signal: AbortSignal.timeout(3e4) + }).catch(() => {}); + if (process.env["CONSOLIDATION_ENABLED"] === "true") { + fetch(`${REST_URL}/agentmemory/crystals/auto`, { method: "POST", headers: authHeaders(), - body: JSON.stringify({ sessionId }), - signal: AbortSignal.timeout(3e4) - }); - } catch {} - if (process.env["CONSOLIDATION_ENABLED"] === "true") { - try { - await fetch(`${REST_URL}/agentmemory/crystals/auto`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ olderThanDays: 0 }), - signal: AbortSignal.timeout(6e4) - }); - } catch {} - try { - await fetch(`${REST_URL}/agentmemory/consolidate-pipeline`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ - tier: "all", - force: true - }), - signal: AbortSignal.timeout(12e4) - }); - } catch {} - } - if (process.env["CLAUDE_MEMORY_BRIDGE"] === "true") try { - await fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, { + body: JSON.stringify({ olderThanDays: 0 }), + signal: AbortSignal.timeout(6e4) + }).catch(() => {}); + fetch(`${REST_URL}/agentmemory/consolidate-pipeline`, { method: "POST", headers: authHeaders(), - signal: AbortSignal.timeout(3e4) - }); - } catch {} + body: JSON.stringify({ + tier: "all", + force: true + }), + signal: AbortSignal.timeout(12e4) + }).catch(() => {}); + } + if (process.env["CLAUDE_MEMORY_BRIDGE"] === "true") fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, { + method: "POST", + headers: authHeaders(), + signal: AbortSignal.timeout(3e4) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } main(); diff --git a/plugin/scripts/stop.mjs b/plugin/scripts/stop.mjs index a7dff13fe7..c3f777da10 100755 --- a/plugin/scripts/stop.mjs +++ b/plugin/scripts/stop.mjs @@ -23,22 +23,19 @@ async function main() { } if (isSdkChildContext(data)) return; const sessionId = data.session_id || "unknown"; - try { - await fetch(`${REST_URL}/agentmemory/summarize`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ sessionId }), - signal: AbortSignal.timeout(12e4) - }); - } catch {} - try { - await fetch(`${REST_URL}/agentmemory/session/end`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ sessionId }), - signal: AbortSignal.timeout(5e3) - }); - } catch {} + fetch(`${REST_URL}/agentmemory/summarize`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ sessionId }), + signal: AbortSignal.timeout(12e4) + }).catch(() => {}); + fetch(`${REST_URL}/agentmemory/session/end`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ sessionId }), + signal: AbortSignal.timeout(5e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } main(); diff --git a/plugin/scripts/subagent-start.mjs b/plugin/scripts/subagent-start.mjs index 5b27936200..96fc46363d 100755 --- a/plugin/scripts/subagent-start.mjs +++ b/plugin/scripts/subagent-start.mjs @@ -64,6 +64,7 @@ async function main() { }), signal: AbortSignal.timeout(TIMEOUT_MS) }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } main(); diff --git a/plugin/scripts/subagent-stop.mjs b/plugin/scripts/subagent-stop.mjs index 2f2947d0e1..7210c2b4ab 100755 --- a/plugin/scripts/subagent-stop.mjs +++ b/plugin/scripts/subagent-stop.mjs @@ -48,25 +48,24 @@ async function main() { if (isSdkChildContext(data)) return; const sessionId = data.session_id || "unknown"; const lastMsg = typeof data.last_assistant_message === "string" ? data.last_assistant_message.slice(0, 4e3) : ""; - try { - await fetch(`${REST_URL}/agentmemory/observe`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ - hookType: "subagent_stop", - sessionId, - project: resolveProject(data.cwd), - cwd: data.cwd || process.cwd(), - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - data: { - agent_id: data.agent_id, - agent_type: data.agent_type, - last_message: lastMsg - } - }), - signal: AbortSignal.timeout(2e3) - }); - } catch {} + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "subagent_stop", + sessionId, + project: resolveProject(data.cwd), + cwd: data.cwd || process.cwd(), + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { + agent_id: data.agent_id, + agent_type: data.agent_type, + last_message: lastMsg + } + }), + signal: AbortSignal.timeout(2e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } main(); diff --git a/plugin/scripts/task-completed.mjs b/plugin/scripts/task-completed.mjs index ebcec7595a..478f0688e8 100755 --- a/plugin/scripts/task-completed.mjs +++ b/plugin/scripts/task-completed.mjs @@ -47,27 +47,26 @@ async function main() { } if (isSdkChildContext(data)) return; const sessionId = data.session_id || "unknown"; - try { - await fetch(`${REST_URL}/agentmemory/observe`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ - hookType: "task_completed", - sessionId, - project: resolveProject(data.cwd), - cwd: data.cwd || process.cwd(), - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - data: { - task_id: data.task_id, - task_subject: data.task_subject, - task_description: typeof data.task_description === "string" ? data.task_description.slice(0, 2e3) : "", - teammate_name: data.teammate_name, - team_name: data.team_name - } - }), - signal: AbortSignal.timeout(2e3) - }); - } catch {} + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "task_completed", + sessionId, + project: resolveProject(data.cwd), + cwd: data.cwd || process.cwd(), + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { + task_id: data.task_id, + task_subject: data.task_subject, + task_description: typeof data.task_description === "string" ? data.task_description.slice(0, 2e3) : "", + teammate_name: data.teammate_name, + team_name: data.team_name + } + }), + signal: AbortSignal.timeout(2e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } main(); diff --git a/src/hooks/notification.ts b/src/hooks/notification.ts index acca7143d2..7ac6201df5 100644 --- a/src/hooks/notification.ts +++ b/src/hooks/notification.ts @@ -34,27 +34,28 @@ async function main() { const sessionId = (data.session_id as string) || "unknown"; - try { - await fetch(`${REST_URL}/agentmemory/observe`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ - hookType: "notification", - sessionId, - project: resolveProject(data.cwd as string | undefined), - cwd: (data.cwd as string | undefined) || process.cwd(), - timestamp: new Date().toISOString(), - data: { - notification_type: data.notification_type, - title: data.title, - message: data.message, - }, - }), - signal: AbortSignal.timeout(2000), - }); - } catch { - // fire and forget - } + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "notification", + sessionId, + project: resolveProject(data.cwd as string | undefined), + cwd: (data.cwd as string | undefined) || process.cwd(), + timestamp: new Date().toISOString(), + data: { + notification_type: data.notification_type, + title: data.title, + message: data.message, + }, + }), + signal: AbortSignal.timeout(2000), + }).catch(() => {}); + // Force-exit after the request has been flushed to the daemon's socket + // buffer so node doesn't keep the event loop alive waiting for the + // in-flight fetch — otherwise the hook still blocks Claude Code's + // next-prompt boundary for up to the AbortSignal duration. + setTimeout(() => process.exit(0), 500).unref(); } main(); diff --git a/src/hooks/post-tool-failure.ts b/src/hooks/post-tool-failure.ts index c269faa1a4..9208c4159a 100644 --- a/src/hooks/post-tool-failure.ts +++ b/src/hooks/post-tool-failure.ts @@ -34,33 +34,30 @@ async function main() { const sessionId = (data.session_id as string) || "unknown"; - try { - await fetch(`${REST_URL}/agentmemory/observe`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ - hookType: "post_tool_failure", - sessionId, - project: resolveProject(data.cwd as string | undefined), - cwd: (data.cwd as string | undefined) || process.cwd(), - timestamp: new Date().toISOString(), - data: { - tool_name: data.tool_name, - tool_input: - typeof data.tool_input === "string" - ? data.tool_input.slice(0, 4000) - : JSON.stringify(data.tool_input ?? "").slice(0, 4000), - error: - typeof data.error === "string" - ? data.error.slice(0, 4000) - : JSON.stringify(data.error ?? "").slice(0, 4000), - }, - }), - signal: AbortSignal.timeout(3000), - }); - } catch { - // fire and forget - } + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "post_tool_failure", + sessionId, + project: resolveProject(data.cwd as string | undefined), + cwd: (data.cwd as string | undefined) || process.cwd(), + timestamp: new Date().toISOString(), + data: { + tool_name: data.tool_name, + tool_input: + typeof data.tool_input === "string" + ? data.tool_input.slice(0, 4000) + : JSON.stringify(data.tool_input ?? "").slice(0, 4000), + error: + typeof data.error === "string" + ? data.error.slice(0, 4000) + : JSON.stringify(data.error ?? "").slice(0, 4000), + }, + }), + signal: AbortSignal.timeout(3000), + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } main(); diff --git a/src/hooks/post-tool-use.ts b/src/hooks/post-tool-use.ts index c3f7b67003..d3e94866c0 100644 --- a/src/hooks/post-tool-use.ts +++ b/src/hooks/post-tool-use.ts @@ -37,27 +37,25 @@ async function main() { data.tool_response ?? data.tool_output, ); - try { - await fetch(`${REST_URL}/agentmemory/observe`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ - hookType: "post_tool_use", - sessionId, - project: resolveProject(data.cwd as string | undefined), - cwd: (data.cwd as string | undefined) || process.cwd(), - timestamp: new Date().toISOString(), - data: { - tool_name: data.tool_name, - tool_input: data.tool_input, - tool_output: truncate(cleanOutput, 8000), - ...(imageData ? { image_data: imageData } : {}), - }, - }), - signal: AbortSignal.timeout(3000), - }); - } catch { - } + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "post_tool_use", + sessionId, + project: resolveProject(data.cwd as string | undefined), + cwd: (data.cwd as string | undefined) || process.cwd(), + timestamp: new Date().toISOString(), + data: { + tool_name: data.tool_name, + tool_input: data.tool_input, + tool_output: truncate(cleanOutput, 8000), + ...(imageData ? { image_data: imageData } : {}), + }, + }), + signal: AbortSignal.timeout(3000), + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } function isBase64Image(val: unknown): val is string { diff --git a/src/hooks/prompt-submit.ts b/src/hooks/prompt-submit.ts index 76540a8003..39ebf4ce96 100644 --- a/src/hooks/prompt-submit.ts +++ b/src/hooks/prompt-submit.ts @@ -33,23 +33,20 @@ async function main() { const sessionId = (data.session_id as string) || "unknown"; - try { - await fetch(`${REST_URL}/agentmemory/observe`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ - hookType: "prompt_submit", - sessionId, - project: resolveProject(data.cwd as string | undefined), - cwd: (data.cwd as string | undefined) || process.cwd(), - timestamp: new Date().toISOString(), - data: { prompt: data.prompt }, - }), - signal: AbortSignal.timeout(3000), - }); - } catch { - // fire and forget - } + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "prompt_submit", + sessionId, + project: resolveProject(data.cwd as string | undefined), + cwd: (data.cwd as string | undefined) || process.cwd(), + timestamp: new Date().toISOString(), + data: { prompt: data.prompt }, + }), + signal: AbortSignal.timeout(3000), + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } main(); diff --git a/src/hooks/session-end.ts b/src/hooks/session-end.ts index 31bef22e00..b3e47b2fdc 100644 --- a/src/hooks/session-end.ts +++ b/src/hooks/session-end.ts @@ -32,48 +32,38 @@ async function main() { const sessionId = (data.session_id as string) || "unknown"; - try { - await fetch(`${REST_URL}/agentmemory/session/end`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ sessionId }), - signal: AbortSignal.timeout(30000), // Increased from 5s - }); - } catch { - // best-effort - } + fetch(`${REST_URL}/agentmemory/session/end`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ sessionId }), + signal: AbortSignal.timeout(30000), + }).catch(() => {}); if (process.env["CONSOLIDATION_ENABLED"] === "true") { - try { - await fetch(`${REST_URL}/agentmemory/crystals/auto`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ olderThanDays: 0 }), - signal: AbortSignal.timeout(60000), // Increased from 15s - }); - } catch {} + fetch(`${REST_URL}/agentmemory/crystals/auto`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ olderThanDays: 0 }), + signal: AbortSignal.timeout(60000), + }).catch(() => {}); - try { - await fetch(`${REST_URL}/agentmemory/consolidate-pipeline`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ tier: "all", force: true }), - signal: AbortSignal.timeout(120000), // Increased from 30s - }); - } catch {} + fetch(`${REST_URL}/agentmemory/consolidate-pipeline`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ tier: "all", force: true }), + signal: AbortSignal.timeout(120000), + }).catch(() => {}); } if (process.env["CLAUDE_MEMORY_BRIDGE"] === "true") { - try { - await fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, { - method: "POST", - headers: authHeaders(), - signal: AbortSignal.timeout(30000), // Increased from 5s - }); - } catch { - // best-effort - } + fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, { + method: "POST", + headers: authHeaders(), + signal: AbortSignal.timeout(30000), + }).catch(() => {}); } + + setTimeout(() => process.exit(0), 500).unref(); } main(); \ No newline at end of file diff --git a/src/hooks/stop.ts b/src/hooks/stop.ts index fedcb4822d..b571db8d2f 100644 --- a/src/hooks/stop.ts +++ b/src/hooks/stop.ts @@ -39,34 +39,25 @@ async function main() { const sessionId = (data.session_id as string) || "unknown"; - try { - await fetch(`${REST_URL}/agentmemory/summarize`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ sessionId }), - signal: AbortSignal.timeout(120000), // Increased from 30s to 120s - }); - } catch { - // summarize is best-effort - } - - // Claude Code fires a separate `SessionEnd` hook that closes the - // viewer session lifecycle. Codex does not have a SessionEnd event, - // so the only signal we get when a Codex session ends is this Stop - // hook (#493). Always best-effort POST /agentmemory/session/end here - // so the viewer shows `completed` for Codex sessions; for Claude Code - // this is a harmless idempotent second call (session-end.mjs runs on - // SessionEnd and sets the same fields). - try { - await fetch(`${REST_URL}/agentmemory/session/end`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ sessionId }), - signal: AbortSignal.timeout(5000), - }); - } catch { - // session/end is best-effort - } + fetch(`${REST_URL}/agentmemory/summarize`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ sessionId }), + signal: AbortSignal.timeout(120000), + }).catch(() => {}); + + // Codex has no SessionEnd event, so this Stop hook is the only signal + // we get to close out the viewer session. For Claude Code this is a + // harmless idempotent second call (session-end runs on SessionEnd and + // sets the same fields). + fetch(`${REST_URL}/agentmemory/session/end`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ sessionId }), + signal: AbortSignal.timeout(5000), + }).catch(() => {}); + + setTimeout(() => process.exit(0), 500).unref(); } main(); \ No newline at end of file diff --git a/src/hooks/subagent-start.ts b/src/hooks/subagent-start.ts index bdd9a16470..53462a740b 100644 --- a/src/hooks/subagent-start.ts +++ b/src/hooks/subagent-start.ts @@ -57,6 +57,7 @@ async function main() { }), signal: AbortSignal.timeout(TIMEOUT_MS), }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } main(); diff --git a/src/hooks/subagent-stop.ts b/src/hooks/subagent-stop.ts index d7fbfc3237..f03853b018 100644 --- a/src/hooks/subagent-stop.ts +++ b/src/hooks/subagent-stop.ts @@ -37,27 +37,24 @@ async function main() { ? data.last_assistant_message.slice(0, 4000) : ""; - try { - await fetch(`${REST_URL}/agentmemory/observe`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ - hookType: "subagent_stop", - sessionId, - project: resolveProject(data.cwd as string | undefined), - cwd: (data.cwd as string | undefined) || process.cwd(), - timestamp: new Date().toISOString(), - data: { - agent_id: data.agent_id, - agent_type: data.agent_type, - last_message: lastMsg, - }, - }), - signal: AbortSignal.timeout(2000), - }); - } catch { - // fire and forget - } + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "subagent_stop", + sessionId, + project: resolveProject(data.cwd as string | undefined), + cwd: (data.cwd as string | undefined) || process.cwd(), + timestamp: new Date().toISOString(), + data: { + agent_id: data.agent_id, + agent_type: data.agent_type, + last_message: lastMsg, + }, + }), + signal: AbortSignal.timeout(2000), + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } main(); diff --git a/src/hooks/task-completed.ts b/src/hooks/task-completed.ts index 1216e83a1b..dbdf815ac8 100644 --- a/src/hooks/task-completed.ts +++ b/src/hooks/task-completed.ts @@ -33,31 +33,28 @@ async function main() { const sessionId = (data.session_id as string) || "unknown"; - try { - await fetch(`${REST_URL}/agentmemory/observe`, { - method: "POST", - headers: authHeaders(), - body: JSON.stringify({ - hookType: "task_completed", - sessionId, - project: resolveProject(data.cwd as string | undefined), - cwd: (data.cwd as string | undefined) || process.cwd(), - timestamp: new Date().toISOString(), - data: { - task_id: data.task_id, - task_subject: data.task_subject, - task_description: typeof data.task_description === "string" - ? data.task_description.slice(0, 2000) - : "", - teammate_name: data.teammate_name, - team_name: data.team_name, - }, - }), - signal: AbortSignal.timeout(2000), - }); - } catch { - // fire and forget - } + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "task_completed", + sessionId, + project: resolveProject(data.cwd as string | undefined), + cwd: (data.cwd as string | undefined) || process.cwd(), + timestamp: new Date().toISOString(), + data: { + task_id: data.task_id, + task_subject: data.task_subject, + task_description: typeof data.task_description === "string" + ? data.task_description.slice(0, 2000) + : "", + teammate_name: data.teammate_name, + team_name: data.team_name, + }, + }), + signal: AbortSignal.timeout(2000), + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); } main(); From 0dea5b65dfd6303f41c35cf423cc9797a4fbc8bd Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Wed, 27 May 2026 19:56:41 +0100 Subject: [PATCH 2/3] chore(hooks): drop verbose comments on fire-and-forget hooks --- src/hooks/notification.ts | 4 ---- src/hooks/stop.ts | 4 ---- 2 files changed, 8 deletions(-) diff --git a/src/hooks/notification.ts b/src/hooks/notification.ts index 7ac6201df5..daa5a913ea 100644 --- a/src/hooks/notification.ts +++ b/src/hooks/notification.ts @@ -51,10 +51,6 @@ async function main() { }), signal: AbortSignal.timeout(2000), }).catch(() => {}); - // Force-exit after the request has been flushed to the daemon's socket - // buffer so node doesn't keep the event loop alive waiting for the - // in-flight fetch — otherwise the hook still blocks Claude Code's - // next-prompt boundary for up to the AbortSignal duration. setTimeout(() => process.exit(0), 500).unref(); } diff --git a/src/hooks/stop.ts b/src/hooks/stop.ts index b571db8d2f..c5147e5a61 100644 --- a/src/hooks/stop.ts +++ b/src/hooks/stop.ts @@ -46,10 +46,6 @@ async function main() { signal: AbortSignal.timeout(120000), }).catch(() => {}); - // Codex has no SessionEnd event, so this Stop hook is the only signal - // we get to close out the viewer session. For Claude Code this is a - // harmless idempotent second call (session-end runs on SessionEnd and - // sets the same fields). fetch(`${REST_URL}/agentmemory/session/end`, { method: "POST", headers: authHeaders(), From 04e2223075936fe12d64addf8e655681e01dfd77 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Wed, 27 May 2026 20:47:46 +0100 Subject: [PATCH 3/3] fix(hooks): bump stop+session-end exit delay to 1500ms MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Multi-request hooks (stop fires 2, session-end up to 4) need more than 500ms to initiate all fetches when AGENTMEMORY_URL points to a remote daemon — DNS + TCP + TLS handshakes can eat the budget before the second/third fetch is even dispatched. Bump to 1500ms on those two hooks only; single-request hooks keep 500ms. AGENTS.md updated with the multi-request exception. --- AGENTS.md | 2 +- plugin/scripts/session-end.mjs | 2 +- plugin/scripts/stop.mjs | 2 +- src/hooks/session-end.ts | 2 +- src/hooks/stop.ts | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 019648f4b5..4f57eaa587 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,7 +92,7 @@ case "memory_your_tool": { Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). They read JSON from stdin, make HTTP calls to the REST API, and exit. There are two patterns depending on whether Claude Code consumes the script's stdout: - **Context-injecting hooks** (`pre-tool-use`, `pre-compact`, `session-start`) write recalled context to stdout for Claude Code to inject. These MUST use `try/catch` with `await fetch(..., { signal: AbortSignal.timeout(N) })` — the script has to wait for the response before exiting, and the timeout is the only bound on hang time. -- **Telemetry-only hooks** (`notification`, `post-tool-failure`, `post-tool-use`, `prompt-submit`, `stop`, `session-end`, `subagent-start`, `subagent-stop`, `task-completed`) write nothing to stdout. These MUST use fire-and-forget `fetch(..., { signal: AbortSignal.timeout(N) }).catch(() => {})` paired with `setTimeout(() => process.exit(0), 500).unref()`. The unawaited fetch dispatches the request; the unref'd `setTimeout` force-exits the process after the request has been flushed to the local daemon's socket buffer (~500ms is enough). Without the `setTimeout` Node keeps the event loop alive waiting for any in-flight fetch to settle, which means the hook still blocks Claude Code's next-prompt boundary for up to the AbortSignal duration — exactly the bug fire-and-forget is meant to fix. +- **Telemetry-only hooks** (`notification`, `post-tool-failure`, `post-tool-use`, `prompt-submit`, `stop`, `session-end`, `subagent-start`, `subagent-stop`, `task-completed`) write nothing to stdout. These MUST use fire-and-forget `fetch(..., { signal: AbortSignal.timeout(N) }).catch(() => {})` paired with `setTimeout(() => process.exit(0), 500).unref()`. The unawaited fetch dispatches the request; the unref'd `setTimeout` force-exits the process after the request has been flushed to the local daemon's socket buffer (~500ms is enough for single-request hooks; use 1500ms for multi-request hooks like `stop` and `session-end` so all fetches have time to start, especially when `AGENTMEMORY_URL` points to a remote daemon). Without the `setTimeout` Node keeps the event loop alive waiting for any in-flight fetch to settle, which means the hook still blocks Claude Code's next-prompt boundary for up to the AbortSignal duration — exactly the bug fire-and-forget is meant to fix. ## Coding Standards diff --git a/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjs index 0855a68c99..45fd11af21 100755 --- a/plugin/scripts/session-end.mjs +++ b/plugin/scripts/session-end.mjs @@ -51,7 +51,7 @@ async function main() { headers: authHeaders(), signal: AbortSignal.timeout(3e4) }).catch(() => {}); - setTimeout(() => process.exit(0), 500).unref(); + setTimeout(() => process.exit(0), 1500).unref(); } main(); diff --git a/plugin/scripts/stop.mjs b/plugin/scripts/stop.mjs index c3f777da10..51630ca9be 100755 --- a/plugin/scripts/stop.mjs +++ b/plugin/scripts/stop.mjs @@ -35,7 +35,7 @@ async function main() { body: JSON.stringify({ sessionId }), signal: AbortSignal.timeout(5e3) }).catch(() => {}); - setTimeout(() => process.exit(0), 500).unref(); + setTimeout(() => process.exit(0), 1500).unref(); } main(); diff --git a/src/hooks/session-end.ts b/src/hooks/session-end.ts index b3e47b2fdc..60bd9795cb 100644 --- a/src/hooks/session-end.ts +++ b/src/hooks/session-end.ts @@ -63,7 +63,7 @@ async function main() { }).catch(() => {}); } - setTimeout(() => process.exit(0), 500).unref(); + setTimeout(() => process.exit(0), 1500).unref(); } main(); \ No newline at end of file diff --git a/src/hooks/stop.ts b/src/hooks/stop.ts index c5147e5a61..2aa39d0463 100644 --- a/src/hooks/stop.ts +++ b/src/hooks/stop.ts @@ -53,7 +53,7 @@ async function main() { signal: AbortSignal.timeout(5000), }).catch(() => {}); - setTimeout(() => process.exit(0), 500).unref(); + setTimeout(() => process.exit(0), 1500).unref(); } main(); \ No newline at end of file