Skip to content
Closed
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
56 changes: 54 additions & 2 deletions integrations/openclaw/plugin.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Comment on lines +57 to +58

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Skip blank tool-call fields before selecting a fallback.

Line 57 treats whitespace-only message as truthy, so a valid later text/body/content is never considered and the capture is dropped.

Proposed fix
-      const candidate = args.message || args.text || args.body || args.content;
-      if (typeof candidate === "string" && candidate.trim()) return candidate.trim();
+      const candidate = [args.message, args.text, args.body, args.content].find(
+        (value) => typeof value === "string" && value.trim(),
+      );
+      if (candidate) return candidate.trim();

Add a regression case with message: " " and text: "pong".

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const candidate = args.message || args.text || args.body || args.content;
if (typeof candidate === "string" && candidate.trim()) return candidate.trim();
const candidate = [args.message, args.text, args.body, args.content].find(
(value) => typeof value === "string" && value.trim(),
);
if (candidate) return candidate.trim();
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@integrations/openclaw/plugin.mjs` around lines 57 - 58, Update the
candidate-selection logic around the extraction function to ignore blank or
whitespace-only values before falling back from message to text, body, and
content; ensure message: " " selects text: "pong". Add a regression test
covering this fallback behavior.

}
}
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);
Comment on lines +75 to +82

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Parse every session-key candidate before falling back to main.

If ctx.sessionId is opaque while ctx.sessionKey is agent:<id>:..., Lines 76-80 only inspect the opaque ID and return "main". This mis-scopes recall and capture into the main agent’s memory pool.

Proposed fix
-  const sessionKey =
-    context.sessionKey ||
-    context.sessionId ||
-    (event && (event.sessionKey || event.sessionId)) ||
-    "";
-  const match = /^agent:([^:]+):/.exec(String(sessionKey));
-  if (match) return match[1];
+  for (const sessionKey of [
+    context.sessionKey,
+    context.sessionId,
+    event?.sessionKey,
+    event?.sessionId,
+  ]) {
+    const match = /^agent:([^:]+):/.exec(String(sessionKey));
+    if (match) return match[1];
+  }

Add coverage with both ctx.sessionId: "opaque-id" and an agent-encoded ctx.sessionKey.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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);
for (const sessionKey of [
context.sessionKey,
context.sessionId,
event?.sessionKey,
event?.sessionId,
]) {
const match = /^agent:([^:]+):/.exec(String(sessionKey));
if (match) return match[1];
}
if (event && event.agentId) return String(event.agentId);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@integrations/openclaw/plugin.mjs` around lines 75 - 82, Update the
session-key resolution in the agent extraction logic around the sessionKey and
match variables to inspect every available candidate—context.sessionKey,
context.sessionId, event.sessionKey, and event.sessionId—until one matches the
agent:<id>: format, before falling back to event.agentId or "main". Add coverage
for an opaque ctx.sessionId alongside an agent-encoded ctx.sessionKey and ensure
the encoded agent ID is selected.

return "main";
}

function latestUserText(messages) {
for (const message of [...messages].reverse()) {
if (!message || typeof message !== "object") continue;
Expand Down Expand Up @@ -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;
Expand All @@ -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",
Expand Down
95 changes: 95 additions & 0 deletions test/openclaw-plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<unknown>;

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<string, HookHandler>();
for (const [name, fn] of (api.on as ReturnType<typeof vi.fn>).mock.calls) {
handlers.set(name as string, fn as HookHandler);
}
const requests: { path: string; body: Record<string, unknown> }[] = [];
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");
});
});