import "./subsystem-Ci61Iebe.js";
import "./paths-aMBPuCJR.js";
import "./auth-profiles-CfyCILIe.js";
import { a as resolveCliName } from "./env-3oW17BWM.js";
import "./exec-B5OgjUV4.js";
import "./agent-scope-CCFV2dzL.js";
import "./github-copilot-token-CgLcR-3z.js";
import "./reliability-B6TVU4OW.js";
import "./sqlite-CbyDDiup.js";
import "./message-channel-BCPYwYUJ.js";
import { d as imageMimeFromFormat } from "./image-ops-DfgorOBP.js";
import "./config-CaBTSkpu.js";
import "./manifest-registry-BPLS_vpk.js";
import { i as resolveImageSanitizationLimits } from "./tool-images-D39TNWEi.js";
import { a as jsonResult, r as imageResult, u as readStringParam } from "./common-BkBiFnII.js";
import "./call-CHvC3jba.js";
import { n as readGatewayCallOptions, t as callGatewayTool } from "./gateway-B-qVaiZA.js";
import { n as resolveNodeId } from "./nodes-utils-MqV9QJHm.js";
import { i as stringEnum, r as optionalStringEnum } from "./typebox-BrLUZMNm.js";
import { c as asString, i as writeBase64ToFile, l as resolveTempPathParts, s as asRecord } from "./nodes-camera-Dwjln7zy.js";
import fs from "node:fs/promises";
import * as path$1 from "node:path";
import { Type } from "@sinclair/typebox";
import crypto from "node:crypto";

//#region src/cli/nodes-canvas.ts
function parseCanvasSnapshotPayload(value) {
	const obj = asRecord(value);
	const format = asString(obj.format);
	const base64 = asString(obj.base64);
	if (!format || !base64) throw new Error("invalid canvas.snapshot payload");
	return {
		format,
		base64
	};
}
function canvasSnapshotTempPath(opts) {
	const { tmpDir, id, ext } = resolveTempPathParts(opts);
	const cliName = resolveCliName();
	return path$1.join(tmpDir, `${cliName}-canvas-snapshot-${id}${ext}`);
}

//#endregion
//#region src/agents/tools/ui/canvas-tool.ts
const CanvasToolSchema = Type.Object({
	action: stringEnum([
		"present",
		"hide",
		"navigate",
		"eval",
		"snapshot",
		"a2ui_push",
		"a2ui_reset"
	]),
	gatewayUrl: Type.Optional(Type.String()),
	gatewayToken: Type.Optional(Type.String()),
	timeoutMs: Type.Optional(Type.Number()),
	node: Type.Optional(Type.String()),
	target: Type.Optional(Type.String()),
	x: Type.Optional(Type.Number()),
	y: Type.Optional(Type.Number()),
	width: Type.Optional(Type.Number()),
	height: Type.Optional(Type.Number()),
	url: Type.Optional(Type.String()),
	javaScript: Type.Optional(Type.String()),
	outputFormat: optionalStringEnum([
		"png",
		"jpg",
		"jpeg"
	]),
	maxWidth: Type.Optional(Type.Number()),
	quality: Type.Optional(Type.Number()),
	delayMs: Type.Optional(Type.Number()),
	jsonl: Type.Optional(Type.String()),
	jsonlPath: Type.Optional(Type.String())
});
function createCanvasTool(options) {
	const imageSanitization = resolveImageSanitizationLimits(options?.config);
	return {
		label: "Canvas",
		name: "canvas",
		description: "Control node canvases (present/hide/navigate/eval/snapshot/A2UI). Use snapshot to capture the rendered UI.",
		parameters: CanvasToolSchema,
		execute: async (_toolCallId, args) => {
			const params = args;
			const action = readStringParam(params, "action", { required: true });
			const gatewayOpts = readGatewayCallOptions(params);
			const nodeId = await resolveNodeId(gatewayOpts, readStringParam(params, "node", { trim: true }), true);
			const invoke = async (command, invokeParams) => await callGatewayTool("node.invoke", gatewayOpts, {
				nodeId,
				command,
				params: invokeParams,
				idempotencyKey: crypto.randomUUID()
			});
			switch (action) {
				case "present": {
					const placement = {
						x: typeof params.x === "number" ? params.x : void 0,
						y: typeof params.y === "number" ? params.y : void 0,
						width: typeof params.width === "number" ? params.width : void 0,
						height: typeof params.height === "number" ? params.height : void 0
					};
					const invokeParams = {};
					const presentTarget = readStringParam(params, "target", { trim: true }) ?? readStringParam(params, "url", { trim: true });
					if (presentTarget) invokeParams.url = presentTarget;
					if (Number.isFinite(placement.x) || Number.isFinite(placement.y) || Number.isFinite(placement.width) || Number.isFinite(placement.height)) invokeParams.placement = placement;
					await invoke("canvas.present", invokeParams);
					return jsonResult({ ok: true });
				}
				case "hide":
					await invoke("canvas.hide", void 0);
					return jsonResult({ ok: true });
				case "navigate":
					await invoke("canvas.navigate", { url: readStringParam(params, "url", { trim: true }) ?? readStringParam(params, "target", {
						required: true,
						trim: true,
						label: "url"
					}) });
					return jsonResult({ ok: true });
				case "eval": {
					const result = (await invoke("canvas.eval", { javaScript: readStringParam(params, "javaScript", { required: true }) }))?.payload?.result;
					if (result) return {
						content: [{
							type: "text",
							text: result
						}],
						details: { result }
					};
					return jsonResult({ ok: true });
				}
				case "snapshot": {
					const formatRaw = typeof params.outputFormat === "string" ? params.outputFormat.toLowerCase() : "png";
					const payload = parseCanvasSnapshotPayload((await invoke("canvas.snapshot", {
						format: formatRaw === "jpg" || formatRaw === "jpeg" ? "jpeg" : "png",
						maxWidth: typeof params.maxWidth === "number" && Number.isFinite(params.maxWidth) ? params.maxWidth : void 0,
						quality: typeof params.quality === "number" && Number.isFinite(params.quality) ? params.quality : void 0
					}))?.payload);
					const filePath = canvasSnapshotTempPath({ ext: payload.format === "jpeg" ? "jpg" : payload.format });
					await writeBase64ToFile(filePath, payload.base64);
					const mimeType = imageMimeFromFormat(payload.format) ?? "image/png";
					return await imageResult({
						label: "canvas:snapshot",
						path: filePath,
						base64: payload.base64,
						mimeType,
						details: { format: payload.format },
						imageSanitization
					});
				}
				case "a2ui_push": {
					const jsonl = typeof params.jsonl === "string" && params.jsonl.trim() ? params.jsonl : typeof params.jsonlPath === "string" && params.jsonlPath.trim() ? await fs.readFile(params.jsonlPath.trim(), "utf8") : "";
					if (!jsonl.trim()) throw new Error("jsonl or jsonlPath required");
					await invoke("canvas.a2ui.pushJSONL", { jsonl });
					return jsonResult({ ok: true });
				}
				case "a2ui_reset":
					await invoke("canvas.a2ui.reset", void 0);
					return jsonResult({ ok: true });
				default: throw new Error(`Unknown action: ${action}`);
			}
		}
	};
}

//#endregion
export { createCanvasTool };