-
Notifications
You must be signed in to change notification settings - Fork 20
feat(gateway): tool_use SSE events for client-side trace inspection #918
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
108 changes: 108 additions & 0 deletions
108
packages/agent-worker/src/__tests__/tool-use-events.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| import { describe, expect, test } from "bun:test"; | ||
| import { buildToolUseEventPayload } from "../openclaw/tool-use-events"; | ||
|
|
||
| // pi-agent's `tool_execution_end` event omits `args` (those live on the | ||
| // matching `tool_execution_start`); worker.ts re-attaches them from a Map | ||
| // before calling buildToolUseEventPayload. Tests mirror that — pass args | ||
| // explicitly to validate the merged shape. | ||
| const baseEvent = { | ||
| toolCallId: "call_1", | ||
| toolName: "search_memory", | ||
| args: { query: "rent due dates" }, | ||
| result: { | ||
| matches: [{ id: 1, name: "Acme Ltd" }], | ||
| content: [ | ||
| { | ||
| id: 42, | ||
| title: "Rent", | ||
| text_content: "Tenant Acme pays £1,200 on the 1st of each month", | ||
| author_name: null, | ||
| source_url: null, | ||
| platform: "manual", | ||
| occurred_at: null, | ||
| entity_ids: [1], | ||
| }, | ||
| { | ||
| id: 43, | ||
| title: "Lease renewal", | ||
| text_content: "Lease renewed through Dec 2027", | ||
| author_name: null, | ||
| source_url: null, | ||
| platform: "manual", | ||
| occurred_at: null, | ||
| entity_ids: [1], | ||
| }, | ||
| ], | ||
| metadata: { total_matches: 1, page_size: 5 }, | ||
| }, | ||
| isError: false, | ||
| }; | ||
|
|
||
| describe("buildToolUseEventPayload", () => { | ||
| test("includes name, input, toolCallId for any tool", () => { | ||
| const payload = buildToolUseEventPayload({ | ||
| toolCallId: "abc", | ||
| toolName: "bash", | ||
| args: { command: "ls" }, | ||
| result: "ok", | ||
| isError: false, | ||
| }); | ||
| expect(payload.name).toBe("bash"); | ||
| expect(payload.toolCallId).toBe("abc"); | ||
| expect(payload.input).toEqual({ command: "ls" }); | ||
| expect(payload.isError).toBe(false); | ||
| // Non-retrieval tools get no result_summary unless they error. | ||
| expect(payload.result_summary).toBeUndefined(); | ||
| }); | ||
|
|
||
| test("extracts event_ids + snippets for search_memory", () => { | ||
| const payload = buildToolUseEventPayload(baseEvent); | ||
| expect(payload.result_summary?.event_ids).toEqual([42, 43]); | ||
| expect(payload.result_summary?.snippets).toEqual([ | ||
| { | ||
| id: 42, | ||
| text: "Tenant Acme pays £1,200 on the 1st of each month", | ||
| }, | ||
| { id: 43, text: "Lease renewed through Dec 2027" }, | ||
| ]); | ||
| }); | ||
|
|
||
| test("treats lobu_search_memory the same as search_memory", () => { | ||
| const payload = buildToolUseEventPayload({ | ||
| ...baseEvent, | ||
| toolName: "lobu_search_memory", | ||
| }); | ||
| expect(payload.result_summary?.event_ids).toEqual([42, 43]); | ||
| }); | ||
|
|
||
| test("handles MCP CallToolResult wrapping", () => { | ||
| const payload = buildToolUseEventPayload({ | ||
| ...baseEvent, | ||
| result: { | ||
| content: [{ type: "text", text: JSON.stringify(baseEvent.result) }], | ||
| isError: false, | ||
| }, | ||
| }); | ||
| expect(payload.result_summary?.event_ids).toEqual([42, 43]); | ||
| }); | ||
|
|
||
| test("returns no result_summary when search_memory has no content", () => { | ||
| const payload = buildToolUseEventPayload({ | ||
| ...baseEvent, | ||
| result: { matches: [], metadata: { total_matches: 0, page_size: 0 } }, | ||
| }); | ||
| expect(payload.result_summary).toBeUndefined(); | ||
| }); | ||
|
|
||
| test("propagates error message when isError", () => { | ||
| const payload = buildToolUseEventPayload({ | ||
| toolCallId: "x", | ||
| toolName: "search_memory", | ||
| args: {}, | ||
| result: { message: "authentication required" }, | ||
| isError: true, | ||
| }); | ||
| expect(payload.isError).toBe(true); | ||
| expect(payload.result_summary?.error).toBe("authentication required"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| /** | ||
| * Helpers for surfacing tool-call traces from worker → gateway → SSE clients. | ||
| * | ||
| * Workers emit a `tool_use` custom event per `tool_execution_end` so any SSE | ||
| * subscriber (the @lobu/promptfoo-provider, the Mac menubar, the CLI eval) can | ||
| * inspect tool calls without having to scrape worker logs. The shape mirrors | ||
| * Anthropic's tool-use block (name + input) plus a `result_summary` field for | ||
| * structured, tool-specific metadata that's small enough to ship over SSE. | ||
| * | ||
| * For retrieval tools (`search_memory` / `lobu_search_memory`) we extract the | ||
| * matched event IDs and the snippet text content so promptfoo RAG assertions | ||
| * (`context-recall`, `context-faithfulness`, custom `javascript`) can join the | ||
| * agent's answer back to the retrieved evidence. | ||
| */ | ||
|
|
||
| export interface ToolUseEventPayload { | ||
| toolCallId: string; | ||
| name: string; | ||
| input: unknown; | ||
| isError: boolean; | ||
| result_summary?: ToolUseResultSummary; | ||
| } | ||
|
|
||
| export interface ToolUseResultSummary { | ||
| /** Event IDs the tool returned (search_memory etc). */ | ||
| event_ids?: number[]; | ||
| /** Inline snippet text keyed by event id — populated by retrieval tools so | ||
| * provider clients can compute `retrievedContext` without a round-trip. */ | ||
| snippets?: Array<{ id: number; text: string }>; | ||
| /** Tools may also include a short error string. */ | ||
| error?: string; | ||
| } | ||
|
|
||
| const SEARCH_MEMORY_TOOL_NAMES = new Set([ | ||
| "search_memory", | ||
| "lobu_search_memory", | ||
| ]); | ||
|
|
||
| /** | ||
| * Build the SSE payload for a `tool_execution_end` pi-agent event. | ||
| * | ||
| * Always returns a record — even on parse failure — so the SSE event reliably | ||
| * fires for every tool call. `result_summary` is best-effort: tool-specific | ||
| * shape parsing is wrapped in try/catch and a parse failure just leaves the | ||
| * summary off, never throws. | ||
| */ | ||
| export function buildToolUseEventPayload(event: { | ||
| toolCallId: string; | ||
| toolName: string; | ||
| args?: unknown; | ||
| result: unknown; | ||
| isError: boolean; | ||
| }): ToolUseEventPayload { | ||
| const payload: ToolUseEventPayload = { | ||
| toolCallId: event.toolCallId, | ||
| name: event.toolName, | ||
| input: event.args ?? null, | ||
| isError: event.isError === true, | ||
| }; | ||
|
|
||
| if (event.isError) { | ||
| const message = extractErrorMessage(event.result); | ||
| if (message) { | ||
| payload.result_summary = { error: message }; | ||
| } | ||
| return payload; | ||
| } | ||
|
|
||
| if (SEARCH_MEMORY_TOOL_NAMES.has(event.toolName)) { | ||
| const summary = summarizeSearchMemoryResult(event.result); | ||
| if (summary) { | ||
| payload.result_summary = summary; | ||
| } | ||
| } | ||
|
|
||
| return payload; | ||
| } | ||
|
|
||
| function summarizeSearchMemoryResult( | ||
| raw: unknown | ||
| ): ToolUseResultSummary | null { | ||
| const result = extractSearchMemoryBody(raw); | ||
| if (!result || typeof result !== "object") return null; | ||
|
|
||
| const summary: ToolUseResultSummary = {}; | ||
| const contentArr = (result as { content?: unknown }).content; | ||
| if (Array.isArray(contentArr) && contentArr.length > 0) { | ||
| const ids: number[] = []; | ||
| const snippets: Array<{ id: number; text: string }> = []; | ||
| for (const snippet of contentArr) { | ||
| if (!snippet || typeof snippet !== "object") continue; | ||
| const idVal = (snippet as { id?: unknown }).id; | ||
| const textVal = (snippet as { text_content?: unknown }).text_content; | ||
| if (typeof idVal !== "number") continue; | ||
| ids.push(idVal); | ||
| if (typeof textVal === "string" && textVal.length > 0) { | ||
| snippets.push({ id: idVal, text: textVal }); | ||
| } | ||
| } | ||
| if (ids.length > 0) summary.event_ids = ids; | ||
| if (snippets.length > 0) summary.snippets = snippets; | ||
| } | ||
|
|
||
| return Object.keys(summary).length > 0 ? summary : null; | ||
| } | ||
|
|
||
| /** | ||
| * MCP tool results from the gateway proxy land here as | ||
| * { content: [{ type: 'text', text: '<json>' }], isError: false } | ||
| * but in-process tools sometimes pass the raw object straight through. Handle | ||
| * both shapes. | ||
| */ | ||
| function extractSearchMemoryBody(raw: unknown): unknown { | ||
| if (!raw || typeof raw !== "object") return null; | ||
|
|
||
| // MCP CallToolResult shape — text content holds a JSON-stringified payload. | ||
| const mcpContent = (raw as { content?: unknown }).content; | ||
| if (Array.isArray(mcpContent)) { | ||
| for (const part of mcpContent) { | ||
| if (!part || typeof part !== "object") continue; | ||
| const type = (part as { type?: unknown }).type; | ||
| const text = (part as { text?: unknown }).text; | ||
| if (type === "text" && typeof text === "string") { | ||
| try { | ||
| return JSON.parse(text); | ||
| } catch { | ||
| // Plain text result — nothing to summarise. | ||
| return null; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Already the search_memory body. | ||
| return raw; | ||
| } | ||
|
|
||
| function extractErrorMessage(result: unknown): string | null { | ||
| if (typeof result === "string") return result; | ||
| if (!result || typeof result !== "object") return null; | ||
| const msg = (result as { message?: unknown }).message; | ||
| if (typeof msg === "string") return msg; | ||
| const err = (result as { error?: unknown }).error; | ||
| if (typeof err === "string") return err; | ||
| return null; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Don’t stop scanning MCP content after the first unparsable text block.
At Lines 126-128, returning
nullinsidecatchexits early and can miss a later valid JSONcontentpart, which dropsresult_summaryunexpectedly.Proposed fix
function extractSearchMemoryBody(raw: unknown): unknown { if (!raw || typeof raw !== "object") return null; @@ const mcpContent = (raw as { content?: unknown }).content; if (Array.isArray(mcpContent)) { for (const part of mcpContent) { if (!part || typeof part !== "object") continue; const type = (part as { type?: unknown }).type; const text = (part as { text?: unknown }).text; if (type === "text" && typeof text === "string") { try { return JSON.parse(text); } catch { - // Plain text result — nothing to summarise. - return null; + // Not JSON; keep scanning other parts. + continue; } } } + return null; } // Already the search_memory body. return raw; }🤖 Prompt for AI Agents