import { _ as readStringParam } from "./common-Av78VkEK.js";
import { t as jsonResult } from "./tool-results-BCM3fdVS.js";
import { t as escapeHtml } from "./text-utility-runtime-DBaOyU2G.js";
import "./channel-actions-B-4CViYw.js";
import { n as assertWidgetHtmlSize, t as WidgetHtmlInputError } from "./widget-html-Dy17hllR.js";
import { a as resolveCanvasHostConfig } from "./config-B4sKIIPP.js";
import { n as SHOW_WIDGET_REQUIRED_CLIENT_CAPS, r as ShowWidgetToolSchema } from "./tool-schema-D9Z37Le7.js";
import { n as createCanvasDocument } from "./documents-CvMzcz8n.js";
import { createHash } from "node:crypto";
//#region extensions/canvas/src/widget-tool.ts
/** Agent-facing inline chat widget tool. */
const WIDGET_CODE_MAX_CHARS = 262144;
function buildWidgetDocument(title, widgetCode) {
	const bodyClass = /^<svg/i.test(widgetCode) ? " class=\"svg-widget\"" : "";
	return `<!doctype html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data:;"><title>${escapeHtml(title)}</title><style>:root{color-scheme:light dark}*{box-sizing:border-box}html,body{margin:0}body{font:14px system-ui,sans-serif}.svg-widget{display:grid;place-items:center}.svg-widget>svg{max-width:100%}</style></head><body${bodyClass}><script>(()=>{if(!window.parent||window.parent===window)return;const c=new MessageChannel();const post=c.port1.postMessage.bind(c.port1);let act=null;try{const ua=navigator.userActivation;const d=ua&&Object.getOwnPropertyDescriptor(Object.getPrototypeOf(ua),"isActive");if(d&&d.get)act=d.get.bind(ua);}catch{}window.parent.postMessage({type:"openclaw:widget-prompt-offer"},"*",[c.port2]);window.sendPrompt=text=>{if(!act||act()!==true)return;post({type:"openclaw:widget-prompt",prompt:String(text)});};})();<\/script>${widgetCode}<script>(()=>{if(!window.parent||window.parent===window)return;let last=0;const report=()=>{const b=document.body;if(!b)return;const h=Math.ceil(Math.max(b.scrollHeight,b.offsetHeight,b.getBoundingClientRect().height));if(h&&h!==last){last=h;window.parent.postMessage({type:"openclaw:widget-size",height:h},"*");}};addEventListener('load',report);new ResizeObserver(report).observe(document.body);setTimeout(report,50);setTimeout(report,500);})();<\/script></body></html>`;
}
function resolveRetentionScope(options) {
	const scope = options.sessionId ? `session:${options.sessionId}` : `agent:${options.agentId ?? "default"}`;
	return createHash("sha256").update(scope).digest("hex");
}
/** Creates a self-contained widget hosted by the Canvas plugin. */
function createShowWidgetTool(options = {}) {
	return {
		label: "Show Widget",
		name: "show_widget",
		description: "Show an interactive, self-contained HTML or SVG widget to the user on their current surface. Inline all required code and data. In web chat, a global sendPrompt(text) function submits text to the chat as if the user typed it — wire it to buttons or controls to build interactive widgets. It only works after the user clicks inside the widget (plain conversational text only; slash commands are rejected), so never call it automatically.",
		parameters: ShowWidgetToolSchema,
		requiredClientCaps: SHOW_WIDGET_REQUIRED_CLIENT_CAPS,
		execute: async (_toolCallId, args) => {
			const params = args;
			const title = readStringParam(params, "title", { required: true });
			const rawWidgetCode = readStringParam(params, "widget_code", {
				required: true,
				trim: false
			});
			if (!rawWidgetCode.trim()) throw new WidgetHtmlInputError("widget_code required");
			assertWidgetHtmlSize(rawWidgetCode, WIDGET_CODE_MAX_CHARS, {
				inputName: "widget_code",
				unit: "characters"
			});
			const widgetCode = rawWidgetCode.trim();
			const canvasRootDir = resolveCanvasHostConfig({ config: options.config }).root;
			const document = await createCanvasDocument({
				kind: "html_bundle",
				title,
				entrypoint: {
					type: "html",
					value: buildWidgetDocument(title, widgetCode)
				},
				surface: "assistant_message",
				retentionScope: resolveRetentionScope(options),
				cspSandbox: "scripts"
			}, {
				stateDir: options.stateDir,
				canvasRootDir,
				maxDocumentsPerScope: 32
			});
			return jsonResult({
				kind: "canvas",
				presentation: {
					target: "assistant_message",
					title,
					sandbox: "scripts"
				},
				view: {
					id: document.id,
					url: document.entryUrl
				},
				text: `Widget hosted at ${document.entryUrl}`
			});
		}
	};
}
//#endregion
export { createShowWidgetTool };
