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
3 changes: 2 additions & 1 deletion plugin/hooks/hooks.json
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@
{
"type": "command",
"command": "node",
"args": ["${CLAUDE_PLUGIN_ROOT}/scripts/session-end.mjs"]
"args": ["${CLAUDE_PLUGIN_ROOT}/scripts/session-end.mjs"],
"timeout": 10
Comment thread
rohitg00 marked this conversation as resolved.
Resolved
Comment thread
rohitg00 marked this conversation as resolved.
Resolved
Comment thread
rohitg00 marked this conversation as resolved.
Resolved
}
]
}
Expand Down
34 changes: 33 additions & 1 deletion plugin/scripts/session-end.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env node
import { execSync, spawn } from "node:child_process";
import { readFileSync, realpathSync } from "node:fs";
import { execSync } from "node:child_process";
import { basename, dirname, resolve } from "node:path";
import { REST_URL, authHeaders, captureObservation, isDrainChild, runDrainChild, transportBlocked, withEventId } from "./_capture.mjs";
//#region src/hooks/_capture-filter.ts
Expand Down Expand Up @@ -110,6 +110,37 @@ function extractTranscriptPrompts(data) {
}
return prompts;
}
const WORKER_ENV = "AGENTMEMORY_SESSION_END_WORKER";
function handOff(input) {
if (process.env[WORKER_ENV] === "1" || !process.argv[1]) return Promise.resolve(false);
return new Promise((resolve) => {
try {
const child = spawn(process.execPath, [process.argv[1]], {
detached: true,
stdio: [
"pipe",
"ignore",
"ignore"
],
windowsHide: true,
env: {
...process.env,
[WORKER_ENV]: "1"
}
});
child.on("error", () => resolve(false));
child.stdin.on("error", () => resolve(false));
child.once("spawn", () => {
child.stdin.end(input, () => {
child.unref();
resolve(true);
});
});
} catch {
resolve(false);
}
});
}
async function main() {
if (isDrainChild()) return runDrainChild();
let input = "";
Expand All @@ -122,6 +153,7 @@ async function main() {
}
if (!data || typeof data !== "object") return;
if (isSdkChildContext(data)) return;
if (data.hook_event_name === "SessionEnd" && await handOff(input)) return;
const sessionId = data.session_id || data.sessionId || data.conversation_id || "unknown";
const transcriptPrompts = extractTranscriptPrompts(data);
if (transcriptPrompts.length > 0) {
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 @@ -64,6 +64,7 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e
- `AGENTMEMORY_RUNTIME_DIR`
- `AGENTMEMORY_SDK_CHILD`
- `AGENTMEMORY_SECRET`
- `AGENTMEMORY_SESSION_END_WORKER`
- `AGENTMEMORY_SESSION_ID`
- `AGENTMEMORY_SESSION_SWEEP_ENABLED`
- `AGENTMEMORY_SESSION_SWEEP_STALE_HOURS`
Expand Down
28 changes: 28 additions & 0 deletions src/hooks/session-end.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env node
import { spawn } from "node:child_process";
import { readFileSync } from "node:fs";
import { truncateText } from "./_capture-filter.js";
import { resolveProject, hookCwd } from "./_project.js";
Expand Down Expand Up @@ -91,6 +92,32 @@ function extractTranscriptPrompts(data: Record<string, unknown>): TranscriptProm
return prompts;
}

const WORKER_ENV = "AGENTMEMORY_SESSION_END_WORKER";

function handOff(input: string): Promise<boolean> {
if (process.env[WORKER_ENV] === "1" || !process.argv[1]) return Promise.resolve(false);
return new Promise((resolve) => {
try {
const child = spawn(process.execPath, [process.argv[1]], {
detached: true,
stdio: ["pipe", "ignore", "ignore"],
windowsHide: true,
env: { ...process.env, [WORKER_ENV]: "1" },
});
child.on("error", () => resolve(false));
child.stdin.on("error", () => resolve(false));
child.once("spawn", () => {
child.stdin.end(input, () => {
child.unref();
resolve(true);
});
});
} catch {
resolve(false);
}
});
}

async function main() {
if (isDrainChild()) return runDrainChild();
let input = "";
Expand All @@ -107,6 +134,7 @@ async function main() {

if (!data || typeof data !== "object") return;
if (isSdkChildContext(data)) return;
if (data.hook_event_name === "SessionEnd" && (await handOff(input))) return;

const sessionId = ((data.session_id || data.sessionId || data.conversation_id) as string) || "unknown";

Expand Down
7 changes: 7 additions & 0 deletions test/claude-code-with-hooks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ describe("buildMergedHooks against plugin/hooks/hooks.json (Claude Code)", () =>
).toBe(true);
});

it("gives SessionEnd more time than Claude Code's 1.5 s default so the transcript back-fill and exit timer can finish", () => {
const merged = buildMergedHooks(null, PLUGIN_ROOT, "hooks.json");
const handler = merged.hooks["SessionEnd"]![0]!.hooks[0]!;
expect(handler.args![0]).toContain("session-end.mjs");
expect(handler.timeout).toBeGreaterThanOrEqual(10);
});

it("appends to existing user hooks without dropping them", () => {
const existing: HookManifest = {
hooks: {
Expand Down
44 changes: 41 additions & 3 deletions test/session-end-transcript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@ import { join } from "node:path";
let server: Server;
let port: number;
const posts: Array<{ path: string; body: Record<string, unknown> }> = [];
let observeDelayMs = 0;

function runHook(
payload: Record<string, unknown>,
script = "plugin/scripts/session-end.mjs",
extraEnv: Record<string, string> = {},
): Promise<number> {
return new Promise((resolve) => {
const child = spawn("node", [script], {
env: { ...process.env, AGENTMEMORY_URL: `http://127.0.0.1:${port}` },
env: { ...process.env, AGENTMEMORY_URL: `http://127.0.0.1:${port}`, ...extraEnv },
});
child.on("exit", (code) => resolve(code ?? 1));
child.stdin.write(JSON.stringify(payload));
Expand All @@ -37,8 +39,10 @@ describe("session-end transcript prompt backfill", () => {
} catch {
posts.push({ path: req.url ?? "", body: {} });
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end("{}");
setTimeout(() => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end("{}");
}, (req.url ?? "").includes("/observe") ? observeDelayMs : 0);
});
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
Expand Down Expand Up @@ -107,6 +111,40 @@ describe("session-end transcript prompt backfill", () => {
}
});

it("hands the work to a detached worker so the hook exits inside the 1.5 s SessionEnd budget", async () => {
posts.length = 0;
const transcript = join(dir, "handoff.jsonl");
writeFileSync(transcript, JSON.stringify({ type: "user", message: { role: "user", content: "handoff prompt" } }) + "\n");
observeDelayMs = 2500;
const started = Date.now();
const code = await runHook({ session_id: "ses_handoff", hook_event_name: "SessionEnd", transcript_path: transcript });
expect(code).toBe(0);
expect(Date.now() - started).toBeLessThan(1500);
const deadline = Date.now() + 10_000;
while (!posts.some((p) => p.path.includes("/session/end")) && Date.now() < deadline) {
Comment thread
rohitg00 marked this conversation as resolved.
Resolved
await new Promise((r) => setTimeout(r, 50));
}
observeDelayMs = 0;
const prompts = posts.filter((p) => p.path.includes("/observe")).map((p) => (p.body.data as { prompt: string }).prompt);
expect(prompts).toEqual(["handoff prompt"]);
const end = posts.find((p) => p.path.includes("/session/end"));
expect(end?.body).toMatchObject({ sessionId: "ses_handoff", final: true });
}, 20_000);

it("runs the Claude Code SessionEnd work inline inside the detached worker", async () => {
posts.length = 0;
const transcript = join(dir, "worker.jsonl");
writeFileSync(transcript, JSON.stringify({ type: "user", message: { role: "user", content: "worker prompt" } }) + "\n");
const code = await runHook(
{ session_id: "ses_worker", hook_event_name: "SessionEnd", transcript_path: transcript },
undefined,
{ AGENTMEMORY_SESSION_END_WORKER: "1" },
);
expect(code).toBe(0);
expect(posts.filter((p) => p.path.includes("/observe")).map((p) => (p.body.data as { prompt: string }).prompt)).toEqual(["worker prompt"]);
expect(posts.some((p) => p.path.includes("/session/end"))).toBe(true);
});

it("posts prompts from a Claude Code transcript, skipping tool results", async () => {
posts.length = 0;
const transcript = join(dir, "t-cc.jsonl");
Expand Down
Loading