import { defineTool, type ToolDefinition, } from "@earendil-works/pi-coding-agent"; import { Type } from "typebox"; import type { UiWidgetEvent } from "./protocol"; import { WidgetStore } from "./widget-state"; export type VisualToolsOptions = { store?: WidgetStore; publish?: (event: UiWidgetEvent) => void; }; const mountParams = Type.Object({ title: Type.String(), fallback: Type.String(), html: Type.String(), }); const updateParams = Type.Object({ widgetId: Type.String(), html: Type.String(), }); const waitParams = Type.Object({ widgetId: Type.String(), prompt: Type.Optional(Type.String()), }); export function createVisualTools( options: VisualToolsOptions = {}, ): ToolDefinition[] { const store = options.store ?? new WidgetStore(); return [ mountTool("ui_card", "Card", store, options.publish), mountTool("ui_table", "Table", store, options.publish), mountTool("ui_diagram", "Diagram", store, options.publish), mountTool("ui_form", "Form", store, options.publish), mountTool("ui_mockup", "Mockup", store, options.publish), mountTool("ui_html", "HTML", store, options.publish), defineTool({ name: "ui_update", label: "UI Update", description: "Update an existing trusted UI widget by id.", parameters: updateParams, async execute(_toolCallId, params) { const event = store.update(params.widgetId, { html: params.html }); options.publish?.(event); return { content: [{ type: "text", text: `Updated ${params.widgetId}` }], details: event, }; }, }), defineTool({ name: "ui_wait_action", label: "UI Wait Action", description: "Declare that the agent is waiting for a visible action from a trusted UI widget.", parameters: waitParams, async execute(_toolCallId, params) { return { content: [ { type: "text", text: `Waiting for action from ${params.widgetId}${params.prompt ? `: ${params.prompt}` : ""}`, }, ], details: params, }; }, }), ]; } function mountTool( name: string, label: string, store: WidgetStore, publish: ((event: UiWidgetEvent) => void) | undefined, ): ToolDefinition { return defineTool({ name, label: `UI ${label}`, description: `Render a trusted ${label.toLowerCase()} widget in the browser UI stream.`, parameters: mountParams, async execute(toolCallId, params) { const event = store.mount({ toolCallId, title: params.title, fallback: params.fallback, html: params.html, }); publish?.(event); return { content: [{ type: "text", text: params.fallback }], details: event, }; }, }); }