Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(plugin): 修复 OpenClaw 工具调用消息格式不兼容导致的 toolResult 孤儿错误 (#1632)

lilili6c763180133a
diff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.md
index b7fe1dc74..c767a728f 100644
--- a/examples/openclaw-plugin/README.md
+++ b/examples/openclaw-plugin/README.md
@@ -110,7 +110,7 @@ Session handling is the main axis of this design. In the current implementation
- `latest_archive_overview` becomes `[Session History Summary]`
- `pre_archive_abstracts` becomes `[Archive Index]`
- active session messages stay in message-block form
-- assistant tool parts become `toolUse`
+- assistant tool parts become `toolCall` (input compatible: `toolUse`/`input` is normalized to `toolCall`/`arguments`)
- tool output becomes separate `toolResult`
- the final message list goes through a tool-use/result pairing repair pass
@@ -122,7 +122,7 @@ That means OpenClaw sees “compressed history summary + archive index + active
- it slices only the newly added messages
- it keeps only `user` / `assistant` capture text
-- it preserves `toolUse` / `toolResult` content in the serialized turn text
+- it preserves `toolCall` / `toolResult` content in the serialized turn text
- it strips injected `<relevant-memories>` blocks and metadata noise before capture
- it appends the sanitized turn text into the OpenViking session
diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.md
index 90b309aec..35dd702ed 100644
--- a/examples/openclaw-plugin/README_CN.md
+++ b/examples/openclaw-plugin/README_CN.md
@@ -110,9 +110,9 @@ Session 是这套设计的主轴。当前实现里,它覆盖了“历史组装
- `latest_archive_overview` 被改写成 `[Session History Summary]`
- `pre_archive_abstracts` 被改写成 `[Archive Index]`
- 当前活跃消息保持 message block 形式回放
-- assistant 的 tool part 会被还原成 `toolUse`
+- assistant 的 tool part 会被还原成 `toolCall`(输入兼容 `toolUse`/`input`,输出统一规范为 `toolCall`/`arguments`)
- tool output 会被拆成独立的 `toolResult`
-- 之后再做一轮 `toolUse/toolResult` 配对修复,降低 transcript 结构不稳定的风险
+- 之后再做一轮 `toolCall/toolResult` 配对修复,降低 transcript 结构不稳定的风险
因此,OpenClaw 拿到的是“压缩后的历史摘要 + archive 索引 + 当前活跃消息”,而不是无限增长的原始 transcript。
@@ -122,7 +122,7 @@ Session 是这套设计的主轴。当前实现里,它覆盖了“历史组装
- 只切出本轮新增消息,不重写整段对话
- 只保留 `user` / `assistant` 相关文本内容
-- 会把 `toolUse` / `toolResult` 格式化进 capture 文本
+- 会把 `toolCall` / `toolResult` 格式化进 capture 文本
- 会先剥掉注入过的 `<relevant-memories>` 和元数据噪音
- 最终把清洗后的增量内容追加到 OpenViking session
diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.ts
index 9487c115c..67a8af078 100644
--- a/examples/openclaw-plugin/context-engine.ts
+++ b/examples/openclaw-plugin/context-engine.ts
@@ -193,7 +193,7 @@ function messageDigest(messages: AgentMessage[], maxCharsPerMsg = 2000): Array<{
text = (raw as Record<string, unknown>[])
.map((b) => {
if (b.type === "text") return String(b.text ?? "");
- if (b.type === "toolUse") return `[toolUse: ${String(b.name)}(${JSON.stringify(b.arguments ?? {}).slice(0, 200)})]`;
+ if (b.type === "toolCall") return `[toolCall: ${String(b.name)}(${JSON.stringify(b.arguments ?? {}).slice(0, 200)})]`;
if (b.type === "toolResult") return `[toolResult: ${JSON.stringify(b.content ?? "").slice(0, 200)}]`;
return `[${String(b.type)}]`;
})
@@ -301,13 +301,13 @@ export function openClawSessionRefToOvStorageId(ref: string): string {
* OpenClaw AgentMessages (content-blocks format).
*
* For assistant messages with ToolParts, this produces:
- * 1. The assistant message with toolUse blocks in its content array
+ * 1. The assistant message with canonical toolCall blocks in its content array
* 2. A separate toolResult message per ToolPart (carrying tool_output)
*/
export function convertToAgentMessages(msg: { role: string; parts: unknown[] }): AgentMessage[] {
const parts = msg.parts ?? [];
const contentBlocks: Record<string, unknown>[] = [];
- const toolUseBlocks: Record<string, unknown>[] = [];
+ const toolCallBlocks: Record<string, unknown>[] = [];
const toolResults: AgentMessage[] = [];
for (const part of parts) {
@@ -322,32 +322,36 @@ export function convertToAgentMessages(msg: { role: string; parts: unknown[] }):
}
} else if (p.type === "tool") {
const toolId = typeof p.tool_id === "string" ? p.tool_id : "";
- const toolName = typeof p.tool_name === "string" ? p.tool_name : "unknown";
+ const toolName = typeof p.tool_name === "string" ? p.tool_name : undefined;
const status = typeof p.tool_status === "string" ? p.tool_status : "unknown";
const output = typeof p.tool_output === "string" ? p.tool_output : "";
if (toolId) {
- // Structured path: emit toolUse + toolResult pair (works for any role)
- toolUseBlocks.push({
- type: "toolUse",
+ // Structured path: emit canonical toolCall + toolResult pair (works for any role)
+ toolCallBlocks.push({
+ type: "toolCall",
id: toolId,
- name: toolName,
- input: p.tool_input ?? {},
+ name: toolName ?? "unknown",
+ arguments: p.tool_input ?? {},
});
const resultText = (status === "completed" || status === "error")
? (output || "(no output)")
: "(interrupted — tool did not complete)";
- toolResults.push({
+ const resultPayload: Record<string, unknown> = {
role: "toolResult",
toolCallId: toolId,
- toolName,
content: [{ type: "text", text: resultText }],
isError: status === "error",
- } as unknown as AgentMessage);
+ };
+ if (toolName) {
+ resultPayload.toolName = toolName;
+ }
+ toolResults.push(resultPayload as unknown as AgentMessage);
} else {
// No tool_id: degrade to text block
- const segments = [`[${toolName}] (${status})`];
+ const fallbackName = toolName ?? "unknown";
+ const segments = [`[${fallbackName}] (${status})`];
if (p.tool_input) {
try {
segments.push(`Input: ${JSON.stringify(p.tool_input)}`);
@@ -366,21 +370,21 @@ export function convertToAgentMessages(msg: { role: string; parts: unknown[] }):
const result: AgentMessage[] = [];
if (msg.role === "assistant") {
- // Assistant: text + toolUse in one message, then toolResults
- result.push({ role: "assistant", content: [...contentBlocks, ...toolUseBlocks] });
+ // Assistant: text + toolCall in one message, then toolResults
+ result.push({ role: "assistant", content: [...contentBlocks, ...toolCallBlocks] });
result.push(...toolResults);
} else {
- // Non-assistant: emit text as original role, then synthesize assistant(toolUse) + toolResult
+ // Non-assistant: emit text as original role, then synthesize assistant(toolCall) + toolResult
const texts = contentBlocks
.filter((b) => b.type === "text")
.map((b) => b.text as string);
if (texts.length > 0) {
result.push({ role: msg.role, content: texts.join("\n") });
- } else if (toolUseBlocks.length === 0) {
+ } else if (toolCallBlocks.length === 0) {
result.push({ role: msg.role, content: "" });
}
- if (toolUseBlocks.length > 0) {
- result.push({ role: "assistant", content: toolUseBlocks });
+ if (toolCallBlocks.length > 0) {
+ result.push({ role: "assistant", content: toolCallBlocks });
result.push(...toolResults);
}
}
@@ -400,6 +404,85 @@ function normalizeAssistantContent(messages: AgentMessage[]): void {
}
}
+function canonicalizeAssistantBlock(block: unknown): unknown {
+ if (!block || typeof block !== "object") {
+ return block;
+ }
+
+ const rec = block as Record<string, unknown>;
+ const type = typeof rec.type === "string" ? rec.type : "";
+ if (type === "toolCall") {
+ if (rec.arguments !== undefined) {
+ return rec;
+ }
+ return {
+ ...rec,
+ arguments: rec.input ?? rec.toolInput ?? {},
+ };
+ }
+
+ if (type === "toolUse" || type === "functionCall" || type === "tool_call") {
+ return {
+ type: "toolCall",
+ id: rec.id ?? rec.toolCallId ?? rec.toolUseId,
+ name: rec.name,
+ arguments: rec.arguments ?? rec.input ?? rec.toolInput ?? {},
+ };
+ }
+
+ return rec;
+}
+
+function canonicalizeAgentMessages(messages: AgentMessage[]): AgentMessage[] {
+ let changed = false;
+ const next = messages.map((msg) => {
+ if (!msg || typeof msg !== "object") {
+ return msg;
+ }
+
+ if (msg.role === "assistant") {
+ const content = Array.isArray(msg.content)
+ ? msg.content.map((block) => canonicalizeAssistantBlock(block))
+ : typeof msg.content === "string"
+ ? [{ type: "text", text: msg.content }]
+ : msg.content;
+
+ if (content !== msg.content) {
+ changed = true;
+ return { ...msg, content };
+ }
+ return msg;
+ }
+
+ if (msg.role === "toolResult") {
+ const raw = msg as Record<string, unknown>;
+ const toolCallId =
+ (typeof raw.toolCallId === "string" && raw.toolCallId) ||
+ (typeof raw.toolUseId === "string" && raw.toolUseId) ||
+ undefined;
+ const toolName =
+ typeof raw.toolName === "string" && raw.toolName.trim()
+ ? raw.toolName.trim()
+ : undefined;
+
+ const nextMsg = {
+ ...msg,
+ ...(toolCallId ? { toolCallId } : {}),
+ ...(toolName ? { toolName } : {}),
+ } as AgentMessage;
+
+ if (nextMsg !== msg) {
+ changed = true;
+ }
+ return nextMsg;
+ }
+
+ return msg;
+ });
+
+ return changed ? next : messages;
+}
+
export function formatMessageFaithful(msg: OVMessage): string {
const roleTag = `[${msg.role}]`;
if (!msg.parts || msg.parts.length === 0) {
@@ -796,7 +879,8 @@ export function createMemoryOpenVikingContextEngine(params: {
);
normalizeAssistantContent(assembled);
- const sanitized = sanitizeToolUseResultPairing(assembled as never[]) as AgentMessage[];
+ const canonical = canonicalizeAgentMessages(assembled);
+ const sanitized = sanitizeToolUseResultPairing(canonical as never[]) as AgentMessage[];
return { sanitized, archive, session, budgets, instruction };
}
diff --git a/examples/openclaw-plugin/package-lock.json b/examples/openclaw-plugin/package-lock.json
index 86b4a12f1..ae6971e98 100644
--- a/examples/openclaw-plugin/package-lock.json
+++ b/examples/openclaw-plugin/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@openclaw/openviking",
- "version": "2026.3.25",
+ "version": "2026.4.33",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@openclaw/openviking",
- "version": "2026.3.25",
+ "version": "2026.4.33",
"dependencies": {
"@sinclair/typebox": "0.34.48",
"fflate": "^0.8.2"
@@ -19,6 +19,31 @@
"openclaw": ">=2026.3.7"
}
},
+ "node_modules/@emnapi/core": {
+ "version": "1.10.0",
+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
+ "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "1.2.1",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "1.10.0",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
+ "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
"node_modules/@emnapi/wasi-threads": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",
@@ -289,6 +314,29 @@
"node": ">=14.0.0"
}
},
+ "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/core": {
+ "version": "1.9.2",
+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.2.tgz",
+ "integrity": "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "1.2.1",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/runtime": {
+ "version": "1.9.2",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.2.tgz",
+ "integrity": "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
"node_modules/@rolldown/binding-win32-arm64-msvc": {
"version": "1.0.0-rc.15",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.15.tgz",
@@ -385,7 +433,6 @@
"integrity": "sha512-oX8xrhvpiyRCQkG1MFchB09f+cXftgIXb3a7UUa4Y3wpmZPw5tyZGTLWhlESOLq1Rq6oDlc8npVU2/9xiCuXMA==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"undici-types": "~7.18.0"
}
@@ -927,7 +974,6 @@
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=12"
},
@@ -1094,7 +1140,6 @@
"integrity": "sha512-dbU7/iLVa8KZALJyLOBOQ88nOXtNG8vxKuOT4I2mD+Ya70KPceF4IAmDsmU0h1Qsn5bPrvsY9HJstCRh3hG6Uw==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"lightningcss": "^1.32.0",
"picomatch": "^4.0.4",
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
index d9d1c1e97..81615f5e7 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
@@ -144,10 +144,10 @@ describe("context-engine assemble()", () => {
{ type: "text", text: "I checked the latest context." },
{ type: "text", text: "User prefers concise answers." },
{
- type: "toolUse",
+ type: "toolCall",
id: "tool_123",
name: "read_file",
- input: { path: "src/app.ts" },
+ arguments: { path: "src/app.ts" },
},
],
});
@@ -272,10 +272,10 @@ describe("context-engine assemble()", () => {
role: "assistant",
content: [
{
- type: "toolUse",
+ type: "toolCall",
id: "tool_running",
name: "bash",
- input: { command: "npm test" },
+ arguments: { command: "npm test" },
},
],
});
diff --git a/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts b/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts
index b30cc785c..2866fb905 100644
--- a/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts
+++ b/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts
@@ -72,7 +72,7 @@ describe("extractNewTurnMessages: toolCallId propagation", () => {
});
describe("convertToAgentMessages: structured tool round-trip", () => {
- it("user-role tool with tool_id → assistant(toolUse) + toolResult", () => {
+ it("user-role tool with tool_id → assistant(toolCall) + toolResult", () => {
const msg = {
role: "user",
parts: [
@@ -93,10 +93,10 @@ describe("convertToAgentMessages: structured tool round-trip", () => {
const assistantMsg = result[0]!;
expect(assistantMsg.role).toBe("assistant");
const blocks = assistantMsg.content as Array<Record<string, unknown>>;
- expect(blocks[0]!.type).toBe("toolUse");
+ expect(blocks[0]!.type).toBe("toolCall");
expect(blocks[0]!.id).toBe("call_abc123");
expect(blocks[0]!.name).toBe("read");
- expect(blocks[0]!.input).toEqual({ path: "/tmp/test.txt" });
+ expect(blocks[0]!.arguments).toEqual({ path: "/tmp/test.txt" });
const toolResult = result[1]!;
expect(toolResult.role).toBe("toolResult");
@@ -104,7 +104,7 @@ describe("convertToAgentMessages: structured tool round-trip", () => {
expect((toolResult as Record<string, unknown>).isError).toBe(false);
});
- it("assistant-role tool with tool_id → toolUse + toolResult (unchanged)", () => {
+ it("assistant-role tool with tool_id → toolCall + toolResult", () => {
const msg = {
role: "assistant",
parts: [
@@ -128,7 +128,7 @@ describe("convertToAgentMessages: structured tool round-trip", () => {
const blocks = assistantMsg.content as Array<Record<string, unknown>>;
expect(blocks).toHaveLength(2);
expect(blocks[0]!.type).toBe("text");
- expect(blocks[1]!.type).toBe("toolUse");
+ expect(blocks[1]!.type).toBe("toolCall");
expect(blocks[1]!.id).toBe("call_abc123");
expect(result[1]!.role).toBe("toolResult");
@@ -208,7 +208,7 @@ describe("convertToAgentMessages: structured tool round-trip", () => {
expect(result[1]!.role).toBe("assistant");
const blocks = result[1]!.content as Array<Record<string, unknown>>;
- expect(blocks[0]!.type).toBe("toolUse");
+ expect(blocks[0]!.type).toBe("toolCall");
expect(result[2]!.role).toBe("toolResult");
});
@@ -263,7 +263,7 @@ describe("mergeConsecutiveAssistants", () => {
it("merges two consecutive assistant messages", () => {
const messages = [
{ role: "assistant", content: [{ type: "text", text: "Hello" }] },
- { role: "assistant", content: [{ type: "toolUse", id: "c1", name: "read", input: {} }] },
+ { role: "assistant", content: [{ type: "toolCall", id: "c1", name: "read", arguments: {} }] },
] as Array<{ role: string; content: unknown }>;
const merged = mergeConsecutiveAssistants(messages);
@@ -273,7 +273,7 @@ describe("mergeConsecutiveAssistants", () => {
const blocks = merged[0]!.content as Array<Record<string, unknown>>;
expect(blocks).toHaveLength(2);
expect(blocks[0]!.type).toBe("text");
- expect(blocks[1]!.type).toBe("toolUse");
+ expect(blocks[1]!.type).toBe("toolCall");
});
it("does not merge non-consecutive assistants", () => {
@@ -290,7 +290,7 @@ describe("mergeConsecutiveAssistants", () => {
it("handles string content in assistant messages", () => {
const messages = [
{ role: "assistant", content: "Hello" },
- { role: "assistant", content: [{ type: "toolUse", id: "c1", name: "read", input: {} }] },
+ { role: "assistant", content: [{ type: "toolCall", id: "c1", name: "read", arguments: {} }] },
] as Array<{ role: string; content: unknown }>;
const merged = mergeConsecutiveAssistants(messages);
@@ -299,7 +299,7 @@ describe("mergeConsecutiveAssistants", () => {
const blocks = merged[0]!.content as Array<Record<string, unknown>>;
expect(blocks).toHaveLength(2);
expect(blocks[0]!.text).toBe("Hello");
- expect(blocks[1]!.type).toBe("toolUse");
+ expect(blocks[1]!.type).toBe("toolCall");
});
it("simulates real OV sequence: assistant(text) + user(tool→assistant+toolResult)", () => {
@@ -328,7 +328,7 @@ describe("mergeConsecutiveAssistants", () => {
expect(blocks).toHaveLength(2);
expect(blocks[0]!.type).toBe("text");
expect(blocks[0]!.text).toBe("Let me check.");
- expect(blocks[1]!.type).toBe("toolUse");
+ expect(blocks[1]!.type).toBe("toolCall");
expect(blocks[1]!.id).toBe("call_abc");
expect(merged[1]!.role).toBe("toolResult");