Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
22 changes: 20 additions & 2 deletions plugin/scripts/pre-tool-use.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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();
Expand Down Expand Up @@ -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 {}
}
Expand Down
3 changes: 2 additions & 1 deletion plugin/skills/agentmemory-config/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<!-- AUTOGEN:env START - generated by scripts/skills/generate.ts, do not edit by hand -->
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`
Expand Down Expand Up @@ -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`
Expand Down
28 changes: 25 additions & 3 deletions src/hooks/pre-tool-use.ts
Comment thread
rohitg00 marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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<string, string> {
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;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function isPlainTextHost(): boolean {
return Boolean(process.env["FACTORY_PROJECT_DIR"] || process.env["DROID_PLUGIN_ROOT"]);
}

function contextPayload(data: Record<string, unknown>, context: string): string {
if (data.hook_event_name !== "PreToolUse" || isPlainTextHost()) return context;
return JSON.stringify({
hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: context },
});
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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.
Expand All @@ -36,6 +57,7 @@ async function main() {

if (!data || typeof data !== "object") return;
if (isSdkChildContext(data)) return;
if (typeof data.cursor_version === "string") return;
Comment thread
rohitg00 marked this conversation as resolved.
Resolved

const toolName =
typeof data.tool_name === "string"
Expand Down Expand Up @@ -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 {
Expand Down
123 changes: 123 additions & 0 deletions test/pre-tool-use-output.test.ts
Original file line number Diff line number Diff line change
@@ -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 = '<agentmemory-context>remembered "quoted"\nline</agentmemory-context>';

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<string, unknown>,
env: Record<string, string> = {},
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<void>((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<string, string | undefined> = { ...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<void>((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<void>((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("");
});
});
Loading