From b0c83dd7f74ccf664aca1667ea9deb3704194fa6 Mon Sep 17 00:00:00 2001 From: jesusweb3 Date: Sat, 25 Jul 2026 14:42:26 +0300 Subject: [PATCH] fix(openclaw): scope memory per agent and stop dropping captures The OpenClaw integration never persisted anything, and all agents shared a single memory pool. Three related causes: 1. Hooks are invoked as (event, ctx), and the agent identity lives in ctx (PluginHookAgentContext.agentId, alongside sessionKey/workspaceDir - see openclaw src/plugins/hook-types.ts). Both handlers were declared as (event) => ..., so ctx was discarded and every agent fell back to the same scope. 2. /agentmemory/observe requires project and cwd. Neither was sent, so the server answered HTTP 400. Because fallback_on_error defaults to true the error was swallowed, and capture silently did nothing at all. 3. Agents running on a Codex app-server answer by calling a message-sending tool instead of emitting an assistant text block, so lastAssistantText() returned "" and agent_end bailed out before observing. Recall now passes agentId to smart-search, and the session is tagged via /agentmemory/session/start before observe, since observe inherits agentId from an existing session rather than accepting it directly. Verified on OpenClaw 2026.7.1 with agentmemory 0.9.28: two agents writing distinct codewords each retrieve only their own, and neither sees the other's. Adds regression tests for all three cases. --- integrations/openclaw/plugin.mjs | 56 ++++++++++++++++++- test/openclaw-plugin.test.ts | 95 ++++++++++++++++++++++++++++++++ 2 files changed, 149 insertions(+), 2 deletions(-) diff --git a/integrations/openclaw/plugin.mjs b/integrations/openclaw/plugin.mjs index 332189d7e3..286fb5f950 100644 --- a/integrations/openclaw/plugin.mjs +++ b/integrations/openclaw/plugin.mjs @@ -46,10 +46,43 @@ function lastAssistantText(messages) { if (message.role !== "assistant") continue; const text = extractText(message.content); if (text) return text; + // Agents running on a Codex app-server (e.g. gpt-5.6-*) do not emit a plain + // assistant text block: they answer by CALLING a message-sending tool, so + // the user-visible reply lives in that tool call's arguments. + if (!Array.isArray(message.content)) continue; + for (const block of [...message.content].reverse()) { + if (!block || typeof block !== "object") continue; + if (block.type !== "toolCall") continue; + const args = block.arguments || block.input || {}; + const candidate = args.message || args.text || args.body || args.content; + if (typeof candidate === "string" && candidate.trim()) return candidate.trim(); + } } return ""; } +/** + * Resolve the id of the agent this turn belongs to. + * + * OpenClaw invokes plugin hooks as (event, ctx) where ctx is a + * PluginHookAgentContext carrying agentId/sessionKey/sessionId/workspaceDir + * (see openclaw src/plugins/hook-types.ts). Without this, every agent shares a + * single memory pool. + */ +function resolveAgentId(ctx, event) { + const context = ctx || {}; + if (context.agentId) return String(context.agentId); + const sessionKey = + context.sessionKey || + context.sessionId || + (event && (event.sessionKey || event.sessionId)) || + ""; + const match = /^agent:([^:]+):/.exec(String(sessionKey)); + if (match) return match[1]; + if (event && event.agentId) return String(event.agentId); + return "main"; +} + function latestUserText(messages) { for (const message of [...messages].reverse()) { if (!message || typeof message !== "object") continue; @@ -175,13 +208,16 @@ const plugin = { }); } - api.on("before_agent_start", async (event) => { + api.on("before_agent_start", async (event, ctx) => { if (!cfg.enabled) return; const prompt = typeof event?.prompt === "string" ? event.prompt.trim() : ""; if (!prompt) return; + const agentId = resolveAgentId(ctx, event); const result = await client.postJson("/agentmemory/smart-search", { query: prompt, limit: 5, + project: agentId, + agentId, }); const block = formatResults(result?.results || []); if (!block) return; @@ -190,19 +226,35 @@ const plugin = { }; }); - api.on("agent_end", async (event) => { + api.on("agent_end", async (event, ctx) => { if (!cfg.enabled || !event?.success || !Array.isArray(event.messages)) return; const userText = latestUserText(event.messages); const assistantText = lastAssistantText(event.messages); if (!userText || !assistantText) return; + const agentId = resolveAgentId(ctx, event); const sessionId = + ctx?.sessionId || + ctx?.sessionKey || event.sessionId || event.sessionKey || event.runId || `openclaw-${Date.now()}`; + // Tag the session with agentId first: /agentmemory/observe does not accept + // an agentId itself, it inherits it from an already-existing session. + await client.postJson("/agentmemory/session/start", { + sessionId, + project: agentId, + cwd: ctx?.workspaceDir || agentId, + agentId, + }); await client.postJson("/agentmemory/observe", { hookType: "post_tool_use", sessionId, + // project and cwd are required by the server; without them the request + // is rejected with HTTP 400 and, because fallback_on_error defaults to + // true, the failure is swallowed and nothing is ever captured. + project: agentId, + cwd: ctx?.workspaceDir || agentId, timestamp: new Date().toISOString(), data: { tool_name: "conversation", diff --git a/test/openclaw-plugin.test.ts b/test/openclaw-plugin.test.ts index ed95d49383..9f75fb798a 100644 --- a/test/openclaw-plugin.test.ts +++ b/test/openclaw-plugin.test.ts @@ -60,3 +60,98 @@ describe("openclaw plugin — memory capability registration (closes #286 follow expect(lines.join("\n")).toMatch(/memory\.internal:9999/); }); }); + +type HookHandler = (event: unknown, ctx?: unknown) => Promise; + +async function registerAndCollect() { + const mod = await import("../integrations/openclaw/plugin.mjs"); + const plugin = (mod as unknown as { default: { register(api: FakeApi): void } }).default; + const api = makeApi(); + plugin.register(api); + const handlers = new Map(); + for (const [name, fn] of (api.on as ReturnType).mock.calls) { + handlers.set(name as string, fn as HookHandler); + } + const requests: { path: string; body: Record }[] = []; + vi.stubGlobal( + "fetch", + vi.fn(async (url: string, init: { body: string }) => { + requests.push({ path: new URL(url).pathname, body: JSON.parse(init.body) }); + return { ok: true, json: async () => ({ results: [] }) }; + }), + ); + return { handlers, requests }; +} + +describe("openclaw plugin — per-agent memory scoping", () => { + it("scopes recall to the agent from the hook context", async () => { + const { handlers, requests } = await registerAndCollect(); + await handlers.get("before_agent_start")?.( + { prompt: "what did we decide?" }, + { agentId: "prompt-engineer", sessionKey: "agent:prompt-engineer:cli" }, + ); + const search = requests.find((r) => r.path === "/agentmemory/smart-search"); + expect(search?.body.agentId).toBe("prompt-engineer"); + expect(search?.body.project).toBe("prompt-engineer"); + }); + + it("falls back to parsing sessionKey when ctx.agentId is absent", async () => { + const { handlers, requests } = await registerAndCollect(); + await handlers.get("before_agent_start")?.( + { prompt: "hello" }, + { sessionKey: "agent:trading-agent:telegram:direct:42" }, + ); + const search = requests.find((r) => r.path === "/agentmemory/smart-search"); + expect(search?.body.agentId).toBe("trading-agent"); + }); + + it("tags the session with agentId and sends the fields observe requires", async () => { + const { handlers, requests } = await registerAndCollect(); + await handlers.get("agent_end")?.( + { + success: true, + runId: "run-1", + messages: [ + { role: "user", content: "remember X" }, + { role: "assistant", content: [{ type: "text", text: "noted" }] }, + ], + }, + { agentId: "prompt-engineer", workspaceDir: "/w/prompt-engineer" }, + ); + const start = requests.find((r) => r.path === "/agentmemory/session/start"); + expect(start?.body.agentId).toBe("prompt-engineer"); + + const observe = requests.find((r) => r.path === "/agentmemory/observe"); + // The server rejects observe without project/cwd, and fallback_on_error + // hides the 400 - so a regression here silently disables capture entirely. + expect(observe?.body.project).toBe("prompt-engineer"); + expect(observe?.body.cwd).toBe("/w/prompt-engineer"); + }); + + it("captures replies delivered as a tool call instead of an assistant text block", async () => { + const { handlers, requests } = await registerAndCollect(); + await handlers.get("agent_end")?.( + { + success: true, + runId: "run-2", + messages: [ + { role: "user", content: "ping" }, + { + role: "assistant", + content: [ + { + type: "toolCall", + name: "message", + arguments: { action: "send", message: "pong" }, + }, + ], + }, + { role: "toolResult", content: [{ type: "toolResult", content: "{\"ok\":true}" }] }, + ], + }, + { agentId: "main" }, + ); + const observe = requests.find((r) => r.path === "/agentmemory/observe"); + expect((observe?.body.data as { tool_output: string }).tool_output).toBe("pong"); + }); +});