diff --git a/.env.example b/.env.example index b8d9e51ede..0a83544d08 100644 --- a/.env.example +++ b/.env.example @@ -137,6 +137,7 @@ # AGENTMEMORY_AUTO_COMPRESS=true # Run LLM-written compression on every observation batch. Requires BOTH this flag and a configured provider; a provider alone leaves synthetic compression active. # AGENTMEMORY_INJECT_CONTEXT=true # Opt in to Claude-style hook context injection. Pi/OMP use 1 in their launch environment for file enrichment; native prompt recall is independent. +# AGENTMEMORY_ENRICH_TIMEOUT_MS=2000 # How long the PreToolUse hook waits for /agentmemory/enrich before it gives up and adds no context. Default 2000 ms. Raise it when enrich replies arrive after the hook has given up. # CONSOLIDATION_ENABLED=false # Disable the consolidation pipeline. Otherwise enabled when an LLM provider is configured, unless AGENTMEMORY_PROVIDER=noop. # CONSOLIDATION_DECAY_DAYS=30 # Age (days) after which non-reinforced memories decay during consolidation # GRAPH_EXTRACTION_ENABLED=true # Extract concept-graph edges on remember; powers the graph-traversal recall path diff --git a/README.md b/README.md index 4e8fc39cd3..0cf650da80 100644 --- a/README.md +++ b/README.md @@ -1198,6 +1198,8 @@ EMBEDDING_PROVIDER=local # Optional automatic context injection through the shared hooks # AGENTMEMORY_INJECT_CONTEXT=true +# How long the PreToolUse hook waits for that context, in ms (default 2000) +# AGENTMEMORY_ENRICH_TIMEOUT_MS=2000 # Optional outside LLM for summaries and consolidation. A key alone does nothing; # this line selects the provider whose key agentmemory may use. diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs index 80b6b7aa75..c3baf6fd25 100755 --- a/plugin/scripts/pre-tool-use.mjs +++ b/plugin/scripts/pre-tool-use.mjs @@ -152,9 +152,26 @@ function isSdkChildContext(payload) { const INJECT_CONTEXT = process.env["AGENTMEMORY_INJECT_CONTEXT"] === "true"; const ENDPOINT = resolveHookEndpoint(); const REST_URL = ENDPOINT.url; +const DEFAULT_ENRICH_TIMEOUT_MS = 2e3; function authHeaders() { return hookAuthHeaders(ENDPOINT); } +const MAX_TIMER_MS = 2147483647; +function enrichTimeoutMs() { + const raw = hookSetting("AGENTMEMORY_ENRICH_TIMEOUT_MS")?.trim() ?? ""; + const n = /^\d+$/.test(raw) ? Number(raw) : 0; + return n >= 1 && n <= MAX_TIMER_MS ? n : DEFAULT_ENRICH_TIMEOUT_MS; +} +function isPlainTextHost() { + return Boolean(process.env["FACTORY_PROJECT_DIR"] || process.env["DROID_PLUGIN_ROOT"]); +} +function contextPayload(data, context) { + if (data.hook_event_name !== "PreToolUse" || isPlainTextHost()) return context; + return JSON.stringify({ hookSpecificOutput: { + hookEventName: "PreToolUse", + additionalContext: context + } }); +} async function main() { if (!INJECT_CONTEXT) return; if (reportBlockedTransport(ENDPOINT)) return; @@ -168,6 +185,7 @@ async function main() { } if (!data || typeof data !== "object") return; if (isSdkChildContext(data)) return; + if (typeof data.cursor_version === "string") return; const toolName = typeof data.tool_name === "string" ? data.tool_name : typeof data.toolName === "string" ? data.toolName : void 0; if (!toolName) return; const normalizedToolName = toolName.toLowerCase(); @@ -213,11 +231,11 @@ async function main() { toolName, ...project !== void 0 && { project } }), - signal: AbortSignal.timeout(2e3) + signal: AbortSignal.timeout(enrichTimeoutMs()) }); if (res.ok) { const result = await res.json(); - if (result.context) process.stdout.write(result.context); + if (result.context) process.stdout.write(contextPayload(data, result.context)); } } catch {} } diff --git a/plugin/skills/agentmemory-config/REFERENCE.md b/plugin/skills/agentmemory-config/REFERENCE.md index 891f4d156c..3cdea7606e 100644 --- a/plugin/skills/agentmemory-config/REFERENCE.md +++ b/plugin/skills/agentmemory-config/REFERENCE.md @@ -3,7 +3,7 @@ Generated by scanning `src/` for `AGENTMEMORY_*` usage. Do not edit the block below by hand; run `npm run skills:gen` after adding or removing a variable. Internal markers ending in two underscores are excluded. -Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 76 recognized variables: +Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 77 recognized variables: - `AGENTMEMORY_AGENT_SCOPE` - `AGENTMEMORY_ALLOW_AGENT_SDK` @@ -36,6 +36,7 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e - `AGENTMEMORY_DROP_STALE_INDEX` - `AGENTMEMORY_ENGINE_MANAGES_WORKER` - `AGENTMEMORY_ENGINE_READY_TIMEOUT_MS` +- `AGENTMEMORY_ENRICH_TIMEOUT_MS` - `AGENTMEMORY_ENV_FILE` - `AGENTMEMORY_EXPORT_ROOT` - `AGENTMEMORY_FINALIZE_IDLE_MS` diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.ts index 18247d7664..6c38931ce4 100644 --- a/src/hooks/pre-tool-use.ts +++ b/src/hooks/pre-tool-use.ts @@ -1,5 +1,5 @@ #!/usr/bin/env node -import { hookAuthHeaders, reportBlockedTransport, resolveHookEndpoint } from "./_endpoint.js"; +import { hookAuthHeaders, hookSetting, reportBlockedTransport, resolveHookEndpoint } from "./_endpoint.js"; function isSdkChildContext(payload: unknown): boolean { if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; @@ -12,10 +12,31 @@ const INJECT_CONTEXT = process.env["AGENTMEMORY_INJECT_CONTEXT"] === "true"; const ENDPOINT = resolveHookEndpoint(); const REST_URL = ENDPOINT.url; +const DEFAULT_ENRICH_TIMEOUT_MS = 2000; + function authHeaders(): Record { return hookAuthHeaders(ENDPOINT); } +const MAX_TIMER_MS = 2_147_483_647; + +function enrichTimeoutMs(): number { + const raw = hookSetting("AGENTMEMORY_ENRICH_TIMEOUT_MS")?.trim() ?? ""; + const n = /^\d+$/.test(raw) ? Number(raw) : 0; + return n >= 1 && n <= MAX_TIMER_MS ? n : DEFAULT_ENRICH_TIMEOUT_MS; +} + +function isPlainTextHost(): boolean { + return Boolean(process.env["FACTORY_PROJECT_DIR"] || process.env["DROID_PLUGIN_ROOT"]); +} + +function contextPayload(data: Record, context: string): string { + if (data.hook_event_name !== "PreToolUse" || isPlainTextHost()) return context; + return JSON.stringify({ + hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: context }, + }); +} + async function main() { // Default off: exit immediately so we don't even open stdin. This keeps // Claude Code's tool-call hot path as cheap as possible. @@ -36,6 +57,7 @@ async function main() { if (!data || typeof data !== "object") return; if (isSdkChildContext(data)) return; + if (typeof data.cursor_version === "string") return; const toolName = typeof data.tool_name === "string" @@ -96,13 +118,13 @@ async function main() { toolName, ...(project !== undefined && { project }), }), - signal: AbortSignal.timeout(2000), + signal: AbortSignal.timeout(enrichTimeoutMs()), }); if (res.ok) { const result = (await res.json()) as { context?: string }; if (result.context) { - process.stdout.write(result.context); + process.stdout.write(contextPayload(data, result.context)); } } } catch { diff --git a/test/pre-tool-use-output.test.ts b/test/pre-tool-use-output.test.ts new file mode 100644 index 0000000000..bdc8f3c59b --- /dev/null +++ b/test/pre-tool-use-output.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, it } from "vitest"; +import { join, resolve } from "node:path"; +import { createServer } from "node:http"; +import { spawn } from "node:child_process"; + +const script = join(resolve(__dirname, ".."), "plugin", "scripts", "pre-tool-use.mjs"); +const CONTEXT = 'remembered "quoted"\nline'; + +const HOST_ENV_KEYS = [ + "AGENTMEMORY_INJECT_CONTEXT", + "AGENTMEMORY_ENRICH_TIMEOUT_MS", + "CLAUDE_PLUGIN_OPTION_AGENTMEMORY_ENRICH_TIMEOUT_MS", + "FACTORY_PROJECT_DIR", + "DROID_PLUGIN_ROOT", +]; + +async function runPreToolUse( + payload: Record, + env: Record = {}, + delayMs = 0, +): Promise<{ stdout: string }> { + const server = createServer((req, res) => { + req.resume(); + req.on("end", () => { + setTimeout(() => { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ context: CONTEXT })); + }, delayMs); + }); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const address = server.address(); + if (!address || typeof address === "string") { + server.close(); + throw new Error("test server did not bind to a TCP port"); + } + const baseEnv: Record = { ...process.env }; + for (const k of HOST_ENV_KEYS) delete baseEnv[k]; + try { + const child = spawn(process.execPath, [script], { + env: { + ...baseEnv, + AGENTMEMORY_URL: `http://127.0.0.1:${address.port}`, + AGENTMEMORY_SECRET: "", + AGENTMEMORY_INJECT_CONTEXT: "true", + ...env, + }, + stdio: ["pipe", "pipe", "ignore"], + }); + let stdout = ""; + child.stdout.on("data", (chunk) => { + stdout += chunk; + }); + child.stdin.end(JSON.stringify(payload)); + await new Promise((resolveExit, reject) => { + const timeout = setTimeout(() => { + child.kill(); + reject(new Error("pre-tool-use timed out")); + }, 10_000); + child.on("error", reject); + child.on("close", () => { + clearTimeout(timeout); + resolveExit(); + }); + }); + return { stdout }; + } finally { + server.closeAllConnections(); + await new Promise((r) => server.close(() => r())); + } +} + +const claudePayload = { + session_id: "ses-1", + hook_event_name: "PreToolUse", + tool_name: "Read", + tool_input: { file_path: "src/foo.ts" }, +}; + +describe("pre-tool-use context output", () => { + it("wraps context in the PreToolUse hook envelope so Claude Code shows it to the model", async () => { + const { stdout } = await runPreToolUse(claudePayload); + expect(JSON.parse(stdout)).toEqual({ + hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: CONTEXT }, + }); + }); + + it("keeps plain text for payloads without a PreToolUse event name", async () => { + const { hook_event_name: _ignored, ...payload } = claudePayload; + const { stdout } = await runPreToolUse(payload); + expect(stdout).toBe(CONTEXT); + }); + + it("keeps plain text on plain-text hosts", async () => { + const { stdout } = await runPreToolUse(claudePayload, { FACTORY_PROJECT_DIR: "/repo" }); + expect(stdout).toBe(CONTEXT); + }); + + it("drops a reply slower than the default 2 s budget", async () => { + const { stdout } = await runPreToolUse(claudePayload, {}, 2500); + expect(stdout).toBe(""); + }); + + it("AGENTMEMORY_ENRICH_TIMEOUT_MS gives a slow enrich reply time to arrive", async () => { + const { stdout } = await runPreToolUse(claudePayload, { AGENTMEMORY_ENRICH_TIMEOUT_MS: "6000" }, 2500); + expect(JSON.parse(stdout).hookSpecificOutput.additionalContext).toBe(CONTEXT); + }); + + it.each(["0.5", "3000000000"])("falls back to the default instead of aborting at once for %s", async (value) => { + const { stdout } = await runPreToolUse(claudePayload, { AGENTMEMORY_ENRICH_TIMEOUT_MS: value }, 100); + expect(JSON.parse(stdout).hookSpecificOutput.additionalContext).toBe(CONTEXT); + }); + + it.each(["1e6", "6000ms"])("keeps the 2 s default for the malformed value %s", async (value) => { + const { stdout } = await runPreToolUse(claudePayload, { AGENTMEMORY_ENRICH_TIMEOUT_MS: value }, 2500); + expect(stdout).toBe(""); + }); + + it("writes nothing for Cursor, whose preToolUse response has no context field", async () => { + const { stdout } = await runPreToolUse({ ...claudePayload, hook_event_name: "preToolUse", cursor_version: "1.7.0" }); + expect(stdout).toBe(""); + }); +});