#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
fix(hooks): break Stop-hook infinite recursion via agent-sdk fallback
Rohit Ghumare5e63846b294f
diff --git a/plugin/scripts/notification.mjs b/plugin/scripts/notification.mjsindex ad546082..f58c0823 100755--- a/plugin/scripts/notification.mjs+++ b/plugin/scripts/notification.mjs@@ -1,4 +1,6 @@#!/usr/bin/env node+import { t as isSdkChildContext } from "./sdk-guard-DI1NUOS9.mjs";+//#region src/hooks/notification.tsconst REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -16,6 +18,7 @@ async function main() {} catch {return;}+ if (isSdkChildContext(data)) return;if (data.notification_type !== "permission_prompt") return;const sessionId = data.session_id || "unknown";try {diff --git a/plugin/scripts/post-tool-failure.mjs b/plugin/scripts/post-tool-failure.mjsindex c3d4c2df..9ff073ec 100755--- a/plugin/scripts/post-tool-failure.mjs+++ b/plugin/scripts/post-tool-failure.mjs@@ -1,4 +1,6 @@#!/usr/bin/env node+import { t as isSdkChildContext } from "./sdk-guard-DI1NUOS9.mjs";+//#region src/hooks/post-tool-failure.tsconst REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -16,6 +18,7 @@ async function main() {} catch {return;}+ if (isSdkChildContext(data)) return;if (data.is_interrupt) return;const sessionId = data.session_id || "unknown";try {diff --git a/plugin/scripts/post-tool-use.mjs b/plugin/scripts/post-tool-use.mjsindex 1703fed0..86717262 100755--- a/plugin/scripts/post-tool-use.mjs+++ b/plugin/scripts/post-tool-use.mjs@@ -1,4 +1,6 @@#!/usr/bin/env node+import { t as isSdkChildContext } from "./sdk-guard-DI1NUOS9.mjs";+//#region src/hooks/post-tool-use.tsconst REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -16,6 +18,7 @@ async function main() {} catch {return;}+ if (isSdkChildContext(data)) return;const sessionId = data.session_id || "unknown";const { imageData, cleanOutput } = extractImageData(data.tool_output);try {diff --git a/plugin/scripts/pre-compact.mjs b/plugin/scripts/pre-compact.mjsindex 48c22663..e44eb78a 100755--- a/plugin/scripts/pre-compact.mjs+++ b/plugin/scripts/pre-compact.mjs@@ -1,4 +1,6 @@#!/usr/bin/env node+import { t as isSdkChildContext } from "./sdk-guard-DI1NUOS9.mjs";+//#region src/hooks/pre-compact.tsconst REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -16,6 +18,7 @@ async function main() {} catch {return;}+ if (isSdkChildContext(data)) return;const sessionId = data.session_id || "unknown";const project = data.cwd || process.cwd();if (process.env["CLAUDE_MEMORY_BRIDGE"] === "true") try {diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjsindex 5c641e22..54487348 100755--- a/plugin/scripts/pre-tool-use.mjs+++ b/plugin/scripts/pre-tool-use.mjs@@ -1,4 +1,6 @@#!/usr/bin/env node+import { t as isSdkChildContext } from "./sdk-guard-DI1NUOS9.mjs";+//#region src/hooks/pre-tool-use.tsconst INJECT_CONTEXT = process.env["AGENTMEMORY_INJECT_CONTEXT"] === "true";const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";@@ -18,6 +20,7 @@ async function main() {} catch {return;}+ if (isSdkChildContext(data)) return;const toolName = data.tool_name;if (!toolName) return;if (![diff --git a/plugin/scripts/prompt-submit.mjs b/plugin/scripts/prompt-submit.mjsindex 2623f65a..bd5e1fae 100755--- a/plugin/scripts/prompt-submit.mjs+++ b/plugin/scripts/prompt-submit.mjs@@ -1,4 +1,6 @@#!/usr/bin/env node+import { t as isSdkChildContext } from "./sdk-guard-DI1NUOS9.mjs";+//#region src/hooks/prompt-submit.tsconst REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -16,6 +18,7 @@ async function main() {} catch {return;}+ if (isSdkChildContext(data)) return;const sessionId = data.session_id || "unknown";try {await fetch(`${REST_URL}/agentmemory/observe`, {diff --git a/plugin/scripts/sdk-guard-DI1NUOS9.mjs b/plugin/scripts/sdk-guard-DI1NUOS9.mjsnew file mode 100644index 00000000..09ace3bb--- /dev/null+++ b/plugin/scripts/sdk-guard-DI1NUOS9.mjs@@ -0,0 +1,30 @@+//#region src/hooks/sdk-guard.ts+/**+* Recursion guard shared by every hook script.+*+* A Claude Code session spawned via @anthropic-ai/claude-agent-sdk inherits+* the same plugin hooks as the parent CC session. If any hook script in that+* child session calls back into /agentmemory/* (e.g. Stop → /summarize →+* provider.summarize() → another child session), we get unbounded recursion+* that burns tokens and fills .claude/projects/ with ghost sessions+* (#149 follow-up; see reported loop under v0.9.1).+*+* Two signals identify a SDK-child context:+* 1. AGENTMEMORY_SDK_CHILD=1 env var — set by our agent-sdk provider+* before it spawns `query()`. Inherited by child processes.+* 2. payload.entrypoint === "sdk-ts" — CC writes this into the hook+* stdin jsonl when the session was spawned by the Agent SDK.+*+* Hook scripts must call isSdkChildContext(payload) EARLY and return+* silently when it is true.+*/+function isSdkChildContext(payload) {+ if (process.env.AGENTMEMORY_SDK_CHILD === "1") return true;+ if (!payload || typeof payload !== "object") return false;+ if (payload["entrypoint"] === "sdk-ts") return true;+ return false;+}++//#endregion+export { isSdkChildContext as t };+//# sourceMappingURL=sdk-guard-DI1NUOS9.mjs.map\ No newline at end of filediff --git a/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjsindex ed4936e1..360ac065 100755--- a/plugin/scripts/session-end.mjs+++ b/plugin/scripts/session-end.mjs@@ -1,4 +1,6 @@#!/usr/bin/env node+import { t as isSdkChildContext } from "./sdk-guard-DI1NUOS9.mjs";+//#region src/hooks/session-end.tsconst REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -16,6 +18,7 @@ async function main() {} catch {return;}+ if (isSdkChildContext(data)) return;const sessionId = data.session_id || "unknown";try {await fetch(`${REST_URL}/agentmemory/session/end`, {diff --git a/plugin/scripts/session-start.mjs b/plugin/scripts/session-start.mjsindex 33032fe1..3bef6d84 100755--- a/plugin/scripts/session-start.mjs+++ b/plugin/scripts/session-start.mjs@@ -1,4 +1,6 @@#!/usr/bin/env node+import { t as isSdkChildContext } from "./sdk-guard-DI1NUOS9.mjs";+//#region src/hooks/session-start.tsconst INJECT_CONTEXT = process.env["AGENTMEMORY_INJECT_CONTEXT"] === "true";const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";@@ -17,6 +19,7 @@ async function main() {} catch {return;}+ if (isSdkChildContext(data)) return;const sessionId = data.session_id || `ses_${Date.now().toString(36)}`;const project = data.cwd || process.cwd();try {diff --git a/plugin/scripts/stop.mjs b/plugin/scripts/stop.mjsindex 02044233..9f4bf7f6 100755--- a/plugin/scripts/stop.mjs+++ b/plugin/scripts/stop.mjs@@ -1,4 +1,6 @@#!/usr/bin/env node+import { t as isSdkChildContext } from "./sdk-guard-DI1NUOS9.mjs";+//#region src/hooks/stop.tsconst REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -16,6 +18,7 @@ async function main() {} catch {return;}+ if (isSdkChildContext(data)) return;const sessionId = data.session_id || "unknown";try {await fetch(`${REST_URL}/agentmemory/summarize`, {diff --git a/plugin/scripts/subagent-start.mjs b/plugin/scripts/subagent-start.mjsindex 047d734d..50f83a84 100755--- a/plugin/scripts/subagent-start.mjs+++ b/plugin/scripts/subagent-start.mjs@@ -1,4 +1,6 @@#!/usr/bin/env node+import { t as isSdkChildContext } from "./sdk-guard-DI1NUOS9.mjs";+//#region src/hooks/subagent-start.tsconst REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -16,6 +18,7 @@ async function main() {} catch {return;}+ if (isSdkChildContext(data)) return;const sessionId = data.session_id || "unknown";try {await fetch(`${REST_URL}/agentmemory/observe`, {diff --git a/plugin/scripts/subagent-stop.mjs b/plugin/scripts/subagent-stop.mjsindex ad78b4f2..2cf2a6f5 100755--- a/plugin/scripts/subagent-stop.mjs+++ b/plugin/scripts/subagent-stop.mjs@@ -1,4 +1,6 @@#!/usr/bin/env node+import { t as isSdkChildContext } from "./sdk-guard-DI1NUOS9.mjs";+//#region src/hooks/subagent-stop.tsconst REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -16,6 +18,7 @@ async function main() {} catch {return;}+ 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 {diff --git a/plugin/scripts/task-completed.mjs b/plugin/scripts/task-completed.mjsindex 38a298dc..0a0aac4e 100755--- a/plugin/scripts/task-completed.mjs+++ b/plugin/scripts/task-completed.mjs@@ -1,4 +1,6 @@#!/usr/bin/env node+import { t as isSdkChildContext } from "./sdk-guard-DI1NUOS9.mjs";+//#region src/hooks/task-completed.tsconst REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -16,6 +18,7 @@ async function main() {} catch {return;}+ if (isSdkChildContext(data)) return;const sessionId = data.session_id || "unknown";try {await fetch(`${REST_URL}/agentmemory/observe`, {diff --git a/src/config.ts b/src/config.tsindex 45e50883..5c51ec3e 100644--- a/src/config.ts+++ b/src/config.ts@@ -41,11 +41,15 @@ function loadEnvFile(): Record<string, string> {return vars;}+function hasRealValue(v: string | undefined): v is string {+ return typeof v === "string" && v.trim().length > 0;+}+function detectProvider(env: Record<string, string>): ProviderConfig {const maxTokens = parseInt(env["MAX_TOKENS"] || "4096", 10);// MiniMax: Anthropic-compatible API, requires raw fetch to avoid SDK stainless headers- if (env["MINIMAX_API_KEY"]) {+ if (hasRealValue(env["MINIMAX_API_KEY"])) {return {provider: "minimax",model: env["MINIMAX_MODEL"] || "MiniMax-M2.7",@@ -53,7 +57,7 @@ function detectProvider(env: Record<string, string>): ProviderConfig {};}- if (env["ANTHROPIC_API_KEY"]) {+ if (hasRealValue(env["ANTHROPIC_API_KEY"])) {return {provider: "anthropic",model: env["ANTHROPIC_MODEL"] || "claude-sonnet-4-20250514",@@ -61,8 +65,8 @@ function detectProvider(env: Record<string, string>): ProviderConfig {baseURL: env["ANTHROPIC_BASE_URL"],};}- if (env["GEMINI_API_KEY"] || env["GOOGLE_API_KEY"]) {- if (!env["GEMINI_API_KEY"] && env["GOOGLE_API_KEY"]) {+ if (hasRealValue(env["GEMINI_API_KEY"]) || hasRealValue(env["GOOGLE_API_KEY"])) {+ if (!hasRealValue(env["GEMINI_API_KEY"]) && hasRealValue(env["GOOGLE_API_KEY"])) {process.stderr.write("[agentmemory] GOOGLE_API_KEY detected — treating as GEMINI_API_KEY. " +"Set GEMINI_API_KEY in ~/.agentmemory/.env to silence this warning.\n",@@ -74,22 +78,40 @@ function detectProvider(env: Record<string, string>): ProviderConfig {maxTokens,};}- if (env["OPENROUTER_API_KEY"]) {+ if (hasRealValue(env["OPENROUTER_API_KEY"])) {return {provider: "openrouter",model: env["OPENROUTER_MODEL"] || "anthropic/claude-sonnet-4-20250514",maxTokens,};}- if (env["AGENTMEMORY_AUTO_COMPRESS"] === "true") {++ const allowAgentSdk = env["AGENTMEMORY_ALLOW_AGENT_SDK"] === "true";+ if (!allowAgentSdk) {process.stderr.write(- "[agentmemory] WARNING: AGENTMEMORY_AUTO_COMPRESS=true but no LLM provider key found " +- "(GEMINI_API_KEY, ANTHROPIC_API_KEY, OPENROUTER_API_KEY). " +- "Falling back to agent-sdk which shares Claude Code's API quota — " +- "this can exhaust a Pro subscription during heavy sessions. " +- "Set an API key in ~/.agentmemory/.env to avoid rate limits (#149).\n",+ "[agentmemory] No LLM provider key found " ++ "(ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY, MINIMAX_API_KEY). " ++ "LLM-backed compression and summarization are DISABLED — using no-op provider. " ++ "This is the safe default: the agent-sdk fallback used to spawn Claude Agent SDK " ++ "child sessions which inherit Claude Code's plugin hooks and cause infinite Stop-hook " ++ "recursion (#149 follow-up). To opt in to the agent-sdk fallback anyway, set both " ++ "AGENTMEMORY_AUTO_COMPRESS=true AND AGENTMEMORY_ALLOW_AGENT_SDK=true — but be aware " ++ "it will burn your Claude Pro allocation and may still recurse if you use it from " ++ "inside Claude Code itself.\n",);+ return {+ provider: "noop",+ model: "noop",+ maxTokens,+ };}++ process.stderr.write(+ "[agentmemory] WARNING: agent-sdk fallback enabled via AGENTMEMORY_ALLOW_AGENT_SDK=true. " ++ "This spawns @anthropic-ai/claude-agent-sdk child sessions that can trigger the Stop-hook " ++ "recursion loop (#149 follow-up). A SDK-child env marker is set to block re-entry, " ++ "but prefer setting a real API key in ~/.agentmemory/.env instead.\n",+ );return {provider: "agent-sdk",model: "claude-sonnet-4-20250514",diff --git a/src/functions/summarize.ts b/src/functions/summarize.tsindex 7202e12b..b3d3a106 100644--- a/src/functions/summarize.ts+++ b/src/functions/summarize.ts@@ -72,9 +72,24 @@ export function registerSummarizeFunction(return { success: false, error: "no_observations" };}+ if (provider.name === "noop") {+ logger.info("Summarize skipped — no LLM provider configured", {+ sessionId,+ });+ return {+ success: false,+ error: "no_provider",+ reason:+ "No LLM provider key set; Summarize is a no-op. Set ANTHROPIC_API_KEY (or GEMINI/OPENROUTER/MINIMAX) in ~/.agentmemory/.env to enable.",+ };+ }+try {const prompt = buildSummaryPrompt(compressed);const response = await provider.summarize(SUMMARY_SYSTEM, prompt);+ if (!response || !response.trim()) {+ return { success: false, error: "empty_provider_response" };+ }const summary = parseSummaryXml(response,sessionId,diff --git a/src/hooks/notification.ts b/src/hooks/notification.tsindex ae349677..0784f083 100644--- a/src/hooks/notification.ts+++ b/src/hooks/notification.ts@@ -1,5 +1,7 @@#!/usr/bin/env node+import { isSdkChildContext } from "./sdk-guard.js";+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -22,6 +24,7 @@ async function main() {return;}+ if (isSdkChildContext(data)) return;if (data.notification_type !== "permission_prompt") return;const sessionId = (data.session_id as string) || "unknown";diff --git a/src/hooks/post-tool-failure.ts b/src/hooks/post-tool-failure.tsindex 7bf9668b..932586b2 100644--- a/src/hooks/post-tool-failure.ts+++ b/src/hooks/post-tool-failure.ts@@ -1,5 +1,7 @@#!/usr/bin/env node+import { isSdkChildContext } from "./sdk-guard.js";+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -22,6 +24,7 @@ async function main() {return;}+ if (isSdkChildContext(data)) return;if (data.is_interrupt) return;const sessionId = (data.session_id as string) || "unknown";diff --git a/src/hooks/post-tool-use.ts b/src/hooks/post-tool-use.tsindex 2b50d8a8..4595fc36 100644--- a/src/hooks/post-tool-use.ts+++ b/src/hooks/post-tool-use.ts@@ -1,5 +1,7 @@#!/usr/bin/env node+import { isSdkChildContext } from "./sdk-guard.js";+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -22,6 +24,8 @@ async function main() {return;}+ if (isSdkChildContext(data)) return;+const sessionId = (data.session_id as string) || "unknown";const { imageData, cleanOutput } = extractImageData(data.tool_output);diff --git a/src/hooks/pre-compact.ts b/src/hooks/pre-compact.tsindex 2e2ae370..7dba540a 100644--- a/src/hooks/pre-compact.ts+++ b/src/hooks/pre-compact.ts@@ -1,5 +1,7 @@#!/usr/bin/env node+import { isSdkChildContext } from "./sdk-guard.js";+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -22,6 +24,8 @@ async function main() {return;}+ if (isSdkChildContext(data)) return;+const sessionId = (data.session_id as string) || "unknown";const project = (data.cwd as string) || process.cwd();diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.tsindex 0f7ae724..129ac663 100644--- a/src/hooks/pre-tool-use.ts+++ b/src/hooks/pre-tool-use.ts@@ -1,5 +1,7 @@#!/usr/bin/env node+import { isSdkChildContext } from "./sdk-guard.js";+// Pre-tool-use enrichment hook.//// THIS HOOK IS A NO-OP BY DEFAULT AS OF 0.8.10 (#143). Previously it@@ -42,6 +44,8 @@ async function main() {return;}+ if (isSdkChildContext(data)) return;+const toolName = data.tool_name as string;if (!toolName) return;diff --git a/src/hooks/prompt-submit.ts b/src/hooks/prompt-submit.tsindex a959d80b..972ecf8b 100644--- a/src/hooks/prompt-submit.ts+++ b/src/hooks/prompt-submit.ts@@ -1,5 +1,7 @@#!/usr/bin/env node+import { isSdkChildContext } from "./sdk-guard.js";+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -22,6 +24,8 @@ async function main() {return;}+ if (isSdkChildContext(data)) return;+const sessionId = (data.session_id as string) || "unknown";try {diff --git a/src/hooks/sdk-guard.ts b/src/hooks/sdk-guard.tsnew file mode 100644index 00000000..8cc5f217--- /dev/null+++ b/src/hooks/sdk-guard.ts@@ -0,0 +1,26 @@+/**+ * Recursion guard shared by every hook script.+ *+ * A Claude Code session spawned via @anthropic-ai/claude-agent-sdk inherits+ * the same plugin hooks as the parent CC session. If any hook script in that+ * child session calls back into /agentmemory/* (e.g. Stop → /summarize →+ * provider.summarize() → another child session), we get unbounded recursion+ * that burns tokens and fills .claude/projects/ with ghost sessions+ * (#149 follow-up; see reported loop under v0.9.1).+ *+ * Two signals identify a SDK-child context:+ * 1. AGENTMEMORY_SDK_CHILD=1 env var — set by our agent-sdk provider+ * before it spawns `query()`. Inherited by child processes.+ * 2. payload.entrypoint === "sdk-ts" — CC writes this into the hook+ * stdin jsonl when the session was spawned by the Agent SDK.+ *+ * Hook scripts must call isSdkChildContext(payload) EARLY and return+ * silently when it is true.+ */+export function isSdkChildContext(payload: unknown): boolean {+ if (process.env.AGENTMEMORY_SDK_CHILD === "1") return true;+ if (!payload || typeof payload !== "object") return false;+ const p = payload as Record<string, unknown>;+ if (p["entrypoint"] === "sdk-ts") return true;+ return false;+}diff --git a/src/hooks/session-end.ts b/src/hooks/session-end.tsindex dd02f28a..715a4c2f 100644--- a/src/hooks/session-end.ts+++ b/src/hooks/session-end.ts@@ -1,5 +1,7 @@#!/usr/bin/env node+import { isSdkChildContext } from "./sdk-guard.js";+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -22,6 +24,8 @@ async function main() {return;}+ if (isSdkChildContext(data)) return;+const sessionId = (data.session_id as string) || "unknown";try {diff --git a/src/hooks/session-start.ts b/src/hooks/session-start.tsindex 047c19a1..519e8e57 100644--- a/src/hooks/session-start.ts+++ b/src/hooks/session-start.ts@@ -1,5 +1,7 @@#!/usr/bin/env node+import { isSdkChildContext } from "./sdk-guard.js";+// Session-start hook.//// Always registers the session for observation tracking (so memories@@ -31,6 +33,8 @@ async function main() {return;}+ if (isSdkChildContext(data)) return;+const sessionId =(data.session_id as string) || `ses_${Date.now().toString(36)}`;const project = (data.cwd as string) || process.cwd();diff --git a/src/hooks/stop.ts b/src/hooks/stop.tsindex fb6cb5d6..f21263e3 100644--- a/src/hooks/stop.ts+++ b/src/hooks/stop.ts@@ -1,5 +1,7 @@#!/usr/bin/env node+import { isSdkChildContext } from "./sdk-guard.js";+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -22,6 +24,12 @@ async function main() {return;}+ if (isSdkChildContext(data)) {+ // Do not summarize from inside a Claude Agent SDK child session;+ // would re-enter agent-sdk provider and loop (see sdk-guard.ts).+ return;+ }+const sessionId = (data.session_id as string) || "unknown";try {diff --git a/src/hooks/subagent-start.ts b/src/hooks/subagent-start.tsindex 2bacd8b1..9fa3b2f3 100644--- a/src/hooks/subagent-start.ts+++ b/src/hooks/subagent-start.ts@@ -1,5 +1,7 @@#!/usr/bin/env node+import { isSdkChildContext } from "./sdk-guard.js";+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -22,6 +24,8 @@ async function main() {return;}+ if (isSdkChildContext(data)) return;+const sessionId = (data.session_id as string) || "unknown";try {diff --git a/src/hooks/subagent-stop.ts b/src/hooks/subagent-stop.tsindex 5b96947a..ef753358 100644--- a/src/hooks/subagent-stop.ts+++ b/src/hooks/subagent-stop.ts@@ -1,5 +1,7 @@#!/usr/bin/env node+import { isSdkChildContext } from "./sdk-guard.js";+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -22,6 +24,8 @@ async function main() {return;}+ if (isSdkChildContext(data)) return;+const sessionId = (data.session_id as string) || "unknown";const lastMsg =typeof data.last_assistant_message === "string"diff --git a/src/hooks/task-completed.ts b/src/hooks/task-completed.tsindex c7a44cb9..849f6657 100644--- a/src/hooks/task-completed.ts+++ b/src/hooks/task-completed.ts@@ -1,5 +1,7 @@#!/usr/bin/env node+import { isSdkChildContext } from "./sdk-guard.js";+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -22,6 +24,8 @@ async function main() {return;}+ if (isSdkChildContext(data)) return;+const sessionId = (data.session_id as string) || "unknown";try {diff --git a/src/providers/agent-sdk.ts b/src/providers/agent-sdk.tsindex 5a33916e..38fbd28c 100644--- a/src/providers/agent-sdk.ts+++ b/src/providers/agent-sdk.ts@@ -12,6 +12,19 @@ export class AgentSDKProvider implements MemoryProvider {}private async query(systemPrompt: string, userPrompt: string): Promise<string> {+ if (process.env.AGENTMEMORY_SDK_CHILD === "1") {+ // We are already running inside a Claude Agent SDK-spawned session.+ // Spawning another one would let its plugin-hook-driven Stop loop+ // re-enter /agentmemory/summarize and cause unbounded recursion+ // (#149 follow-up). Degrade to empty string so callers short-circuit.+ return ""+ }++ // Mark any child process / SDK session spawned from here as a SDK+ // child. agentmemory hook scripts check this marker and skip their+ // REST calls to break the recursion loop.+ process.env.AGENTMEMORY_SDK_CHILD = "1"+const { query } = await import('@anthropic-ai/claude-agent-sdk')const messages = query({diff --git a/src/providers/index.ts b/src/providers/index.tsindex c9e09b49..b22907bc 100644--- a/src/providers/index.ts+++ b/src/providers/index.ts@@ -6,6 +6,7 @@ import type {import { AgentSDKProvider } from "./agent-sdk.js";import { AnthropicProvider } from "./anthropic.js";import { MinimaxProvider } from "./minimax.js";+import { NoopProvider } from "./noop.js";import { OpenRouterProvider } from "./openrouter.js";import { ResilientProvider } from "./resilient.js";import { FallbackChainProvider } from "./fallback-chain.js";@@ -93,6 +94,8 @@ function createBaseProvider(config: ProviderConfig): MemoryProvider {config.maxTokens,"https://openrouter.ai/api/v1/chat/completions",);+ case "noop":+ return new NoopProvider();case "agent-sdk":default:return new AgentSDKProvider();diff --git a/src/providers/noop.ts b/src/providers/noop.tsnew file mode 100644index 00000000..6e74f9aa--- /dev/null+++ b/src/providers/noop.ts@@ -0,0 +1,20 @@+import type { MemoryProvider } from "../types.js";++/**+ * Returns empty strings for every call. Used when no LLM API key is set+ * AND the user has not opted into the agent-sdk fallback via+ * AGENTMEMORY_ALLOW_AGENT_SDK=true. Callers (compress, summarize) must+ * detect the empty result and short-circuit instead of spawning a+ * provider session (#149 / Stop-hook recursion loop fix).+ */+export class NoopProvider implements MemoryProvider {+ name = "noop";++ async compress(): Promise<string> {+ return "";+ }++ async summarize(): Promise<string> {+ return "";+ }+}diff --git a/src/types.ts b/src/types.tsindex 5a450b9b..9d6776d9 100644--- a/src/types.ts+++ b/src/types.ts@@ -127,7 +127,7 @@ export interface ProviderConfig {baseURL?: string;}-export type ProviderType = "agent-sdk" | "anthropic" | "gemini" | "openrouter" | "minimax";+export type ProviderType = "agent-sdk" | "anthropic" | "gemini" | "openrouter" | "minimax" | "noop";export interface MemoryProvider {name: string;diff --git a/test/stop-hook-recursion-guard.test.ts b/test/stop-hook-recursion-guard.test.tsnew file mode 100644index 00000000..55d0f911--- /dev/null+++ b/test/stop-hook-recursion-guard.test.ts@@ -0,0 +1,57 @@+import { describe, it, expect, beforeEach, afterEach } from "vitest";+import { isSdkChildContext } from "../src/hooks/sdk-guard.js";+import { NoopProvider } from "../src/providers/noop.js";++describe("isSdkChildContext — Stop hook recursion guard", () => {+ const originalEnv = process.env.AGENTMEMORY_SDK_CHILD;++ beforeEach(() => {+ delete process.env.AGENTMEMORY_SDK_CHILD;+ });++ afterEach(() => {+ if (originalEnv === undefined) {+ delete process.env.AGENTMEMORY_SDK_CHILD;+ } else {+ process.env.AGENTMEMORY_SDK_CHILD = originalEnv;+ }+ });++ it("returns true when AGENTMEMORY_SDK_CHILD=1 is in env", () => {+ process.env.AGENTMEMORY_SDK_CHILD = "1";+ expect(isSdkChildContext({})).toBe(true);+ });++ it("returns true when payload.entrypoint === 'sdk-ts'", () => {+ expect(isSdkChildContext({ entrypoint: "sdk-ts" })).toBe(true);+ });++ it("returns false for a normal CC payload", () => {+ expect(isSdkChildContext({ entrypoint: "cli", session_id: "s1" })).toBe(false);+ });++ it("returns false when payload is null / undefined / non-object", () => {+ expect(isSdkChildContext(null)).toBe(false);+ expect(isSdkChildContext(undefined)).toBe(false);+ expect(isSdkChildContext("not-an-object")).toBe(false);+ expect(isSdkChildContext(42)).toBe(false);+ });++ it("env marker wins over payload shape", () => {+ process.env.AGENTMEMORY_SDK_CHILD = "1";+ expect(isSdkChildContext({ entrypoint: "cli" })).toBe(true);+ });+});++describe("NoopProvider — no-op fallback when no LLM key present", () => {+ it("reports name 'noop' so callers can detect it and short-circuit", () => {+ const p = new NoopProvider();+ expect(p.name).toBe("noop");+ });++ it("returns empty string for compress and summarize", async () => {+ const p = new NoopProvider();+ await expect(p.compress()).resolves.toBe("");+ await expect(p.summarize()).resolves.toBe("");+ });+});