UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2,522 lines • 79.2 kB
import { a as asOptionalRecord, l as isRecord, p as readStringField } from "../../record-coerce-CVPuDqcc.mjs";
import { n as materializeErrorStack } from "../../error-graph-internal-DdjdM90N.mjs";
import { w as root } from "../../fs-safe-BbWvmdVn.mjs";
import { n as resolvePreferredOpenClawTmpDir } from "../../tmp-openclaw-dir-Bf0oU1Cn.mjs";
import { Fn as object, Jn as string, Lt as boolean, Nt as array, Pn as number, qn as strictObject, xn as literal } from "../../schemas-Cy6abvsu.mjs";
import { n as createLazyRuntimeMethodBinder } from "../../lazy-runtime-zGjszCtt.mjs";
import { n as createNormalizedPluginsConfig } from "../../config-state-B1JlHgba.mjs";
import { t as canonicalizeBase64 } from "../../base64-CnKpkbff.mjs";
import { t as KeyedAsyncQueue } from "../../keyed-async-queue-DewLnYvW.mjs";
import { i as parseScreenSnapshotParamsJSON, p as COMPUTER_USE_V2_ACTION_NAMES, t as parseComputerActParamsJSON } from "../../computer-use-contract-DrB9JL-Y.mjs";
import { c as removePathWithinRoot } from "../../file-access-runtime-BD2Fjfbw.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import "../../error-runtime-BM740gJj.mjs";
import { n as buildPluginConfigSchema } from "../../config-schema-BjPebUmU.mjs";
import { t as definePluginEntry } from "../../plugin-entry-CiJdaHtx.mjs";
import "../../plugin-config-runtime-CFUaG6iN.mjs";
import "../../media-runtime-B-kyz_D7.mjs";
import "../../temp-path-CW7QMeae.mjs";
import { t as registerComputerUseProvider } from "../../computer-use-IkQ3-QxO.mjs";
import { n as registerCuaDriverDoctorChecks, r as verifyInstalledCuaDriverArtifacts } from "../../api-9mI4JusX.mjs";
import fs from "node:fs";
import path from "node:path";
import { createHash, randomUUID } from "node:crypto";
import { createRastermill } from "rastermill";
//#region extensions/cua-computer/src/actions.ts
const CLICK_ACTIONS = {
	left_click: {
		button: "left",
		count: 1
	},
	right_click: {
		button: "right",
		count: 1
	},
	middle_click: {
		button: "middle",
		count: 1
	},
	double_click: {
		button: "left",
		count: 2
	},
	triple_click: {
		button: "left",
		count: 3
	}
};
const MODIFIER_ALIASES = /* @__PURE__ */ new Map([
	["ctrl", "ctrl"],
	["control", "ctrl"],
	["shift", "shift"],
	["alt", "alt"],
	["menu", "alt"],
	["option", "alt"],
	["mod1", "alt"],
	["cmd", "meta"],
	["command", "meta"],
	["meta", "meta"],
	["super", "meta"],
	["win", "meta"],
	["windows", "meta"],
	["mod4", "meta"]
]);
const KEY_ALIASES = /* @__PURE__ */ new Map([
	["return", "enter"],
	["enter", "enter"],
	["tab", "tab"],
	["escape", "escape"],
	["esc", "escape"],
	["space", "space"],
	["backspace", "backspace"],
	["delete", "delete"],
	["del", "delete"],
	["insert", "insert"],
	["ins", "insert"],
	["home", "home"],
	["end", "end"],
	["pageup", "pageup"],
	["pgup", "pageup"],
	["pagedown", "pagedown"],
	["pgdn", "pagedown"],
	["up", "up"],
	["down", "down"],
	["left", "left"],
	["right", "right"],
	["capslock", "capslock"],
	["numlock", "numlock"]
]);
for (let e = 1; e <= 12; e += 1) KEY_ALIASES.set(`f${e}`, `f${e}`);
function unsupportedKey(e) {
	return /* @__PURE__ */ new Error(`COMPUTER_UNSUPPORTED_KEY: ${e}`);
}
function modifierAlias(e, t) {
	const n = MODIFIER_ALIASES.get(e.toLowerCase());
	return t === "darwin" && n === "meta" ? "cmd" : n;
}
function normalizeModifierList(e, t) {
	return e.map((e) => {
		const n = e.trim();
		const r = modifierAlias(n, t);
		if (!r) throw unsupportedKey(`unknown modifier ${JSON.stringify(n)}`);
		return r;
	});
}
function normalizeModifiers(e, t) {
	return e?.trim() ? normalizeModifierList(e.split("+"), t) : [];
}
function normalizeKey(e, t) {
	const n = e.toLowerCase();
	const r = modifierAlias(n, t) ?? KEY_ALIASES.get(n);
	if (r) return r;
	if (/^[a-z]$/i.test(e)) return n;
	if (e.length === 1) throw unsupportedKey(`single-character key ${JSON.stringify(e)} loses layout shift state in cua-driver; use the type action instead`);
	throw unsupportedKey(`unknown key ${JSON.stringify(e)}`);
}
function parseKeyChord(e, t) {
	const n = e?.split("+").map((e) => e.trim()) ?? [];
	const r = n.pop();
	if (!r) throw unsupportedKey("key chord is empty");
	const i = normalizeModifierList(n, t);
	return {
		key: normalizeKey(r, t),
		modifiers: i
	};
}
function scalePoint(e, t, n, r) {
	if (t === void 0 || n === void 0) throw new Error(`COMPUTER_INVALID_REQUEST: ${r} coordinates are required`);
	if (t >= e.deliveredWidth || n >= e.deliveredHeight) throw new Error(`COMPUTER_INVALID_REQUEST: ${r} coordinates are outside the captured primary-display frame`);
	return {
		x: Math.min(e.nativeWidth - 1, Math.round(t * e.nativeWidth / e.deliveredWidth)),
		y: Math.min(e.nativeHeight - 1, Math.round(n * e.nativeHeight / e.deliveredHeight))
	};
}
//#endregion
//#region extensions/cua-computer/src/driver-client.ts
const ClickButton = {
	Left: 0,
	Right: 1,
	Middle: 2
};
const ScrollDirection = {
	Up: 0,
	Down: 1,
	Left: 2,
	Right: 3
};
function isExpiredSessionError(e, t) {
	return e.DriverError.Tool.instanceOf(t) && t.inner.errorCode === "permission_denied" && t.inner.message === "Permission denied: authorization context expired";
}
function driverToolError(e, t) {
	if (!e.DriverError.Tool.instanceOf(t)) return t;
	const { tool: n, message: r, errorCode: i } = t.inner;
	return new Error(`CUA_DRIVER_TOOL_ERROR: ${n}: ${r}${i ? ` (${i})` : ""}`, { cause: t });
}
function asyncOptions(e) {
	return e ? { signal: e } : void 0;
}
var DirectCuaDriverSession = class {
	constructor(e) {
		this.sdk = e;
		this.publicSession = `openclaw-${randomUUID()}`;
		this.started = false;
		this.disposed = false;
		const t = e.SessionPermissionMode.Unrestricted;
		const n = {
			allowedModes: [t],
			compatibilityMode: t,
			unrestrictedAcknowledged: true,
			maxSessionTtlSeconds: 3600n,
			maxIdleTtlSeconds: 300n
		};
		this.runtime = e.CuaDriver.createConfigured({
			claudeCodeCompatibility: false,
			authorization: n
		});
		this.session = e.createTrustedSession(this.runtime, {
			mode: t,
			ttlSeconds: n.maxSessionTtlSeconds,
			idleTtlSeconds: n.maxIdleTtlSeconds,
			publicSession: this.publicSession
		});
		this.desktopTarget = e.ActionTarget.Desktop.new({ displayId: "primary" });
	}
	async ensureSessionStarted(e) {
		if (this.disposed) throw new Error("COMPUTER_DRIVER_UNAVAILABLE: cua-computer is stopping");
		this.startPromise ??= this.session.startSession({ session: this.publicSession }, asyncOptions(e)).then(() => {
			this.started = true;
		}).catch((e) => {
			this.startPromise = void 0;
			throw e;
		});
		await this.startPromise;
	}
	async invoke(e, t) {
		await this.ensureSessionStarted(e);
		return await t();
	}
	isAvailable() {
		return !this.disposed && this.runtime.isAvailable();
	}
	async callTool(e, t, n) {
		return await this.invoke(n, () => this.session.callTool(e, JSON.stringify({
			...t,
			session: this.publicSession
		}), asyncOptions(n)));
	}
	async getCursorPosition(e) {
		return await this.invoke(e, () => this.session.getCursorPosition({ session: this.publicSession }, asyncOptions(e)));
	}
	async getSessionState(e) {
		return await this.invoke(e, () => this.session.getSessionState({ session: this.publicSession }, asyncOptions(e)));
	}
	async getDesktopState(e) {
		return await this.invoke(e, () => this.session.getDesktopState({}, asyncOptions(e)));
	}
	async getScreenSize(e) {
		return await this.invoke(e, () => this.session.getScreenSize({}, asyncOptions(e)));
	}
	async click(e, t) {
		return await this.invoke(t, async () => {
			try {
				return {
					text: "",
					images: [],
					isError: false,
					degraded: false,
					rawJson: "{}",
					action: await this.session.click({
						position: this.sdk.ClickPosition.Coordinates.new({
							x: e.x,
							y: e.y
						}),
						deliveryMode: this.sdk.InputDeliveryMode.Foreground,
						button: e.button,
						count: e.count,
						target: this.desktopTarget
					}, asyncOptions(t))
				};
			} catch (e) {
				if (!this.sdk.DriverError.Tool.instanceOf(e)) throw e;
				return {
					text: e.inner.message,
					images: [],
					isError: true,
					degraded: false,
					rawJson: "{}",
					errorCode: e.inner.errorCode
				};
			}
		});
	}
	async drag(e, t) {
		return await this.invoke(t, () => this.session.drag({
			...e,
			target: this.desktopTarget
		}, asyncOptions(t)));
	}
	async moveCursor(e, t) {
		return await this.invoke(t, () => this.session.moveCursor({
			...e,
			target: this.desktopTarget
		}, asyncOptions(t)));
	}
	async scroll(e, t) {
		return await this.invoke(t, () => this.session.scroll({
			...e,
			target: this.desktopTarget,
			by: this.sdk.ScrollBy.Line
		}, asyncOptions(t)));
	}
	async typeText(e, t) {
		return await this.invoke(t, () => this.session.typeText({
			text: e,
			target: this.desktopTarget
		}, asyncOptions(t)));
	}
	async pressKey(e, t) {
		return await this.invoke(t, () => this.session.pressKey({
			...e,
			target: this.desktopTarget
		}, asyncOptions(t)));
	}
	async dispose() {
		if (this.disposed) return;
		this.disposed = true;
		let e = await this.startPromise?.catch((e) => e);
		if (this.started) try {
			await this.session.endSession({ session: this.publicSession });
		} catch (t) {
			if (!isExpiredSessionError(this.sdk, t) && !this.sdk.DriverError.Shutdown.instanceOf(t)) e ??= t;
		}
		try {
			this.session.close();
		} catch (t) {
			e ??= t;
		}
		try {
			await this.runtime.shutdown();
		} catch (t) {
			e ??= t;
		}
		try {
			this.runtime.uniffiDestroy?.();
		} catch (t) {
			e ??= t;
		}
		if (e) throw e instanceof Error ? e : new Error("CUA Driver cleanup failed", { cause: e });
	}
};
async function loadCuaDriverSdk() {
	const e = verifyInstalledCuaDriverArtifacts();
	if (!e.ok) throw new Error(e.diagnostic);
	return await import("@trycua/cua-driver");
}
function unavailableError(e) {
	if (e instanceof Error && /^COMPUTER_DRIVER_[A-Z_]+:/u.test(e.message)) return e;
	const t = e instanceof Error ? e.message : String(e);
	return new Error(`COMPUTER_DRIVER_UNAVAILABLE: failed to load CUA Driver SDK: ${t}`, { cause: e });
}
var LazyCuaDriverSession = class {
	constructor(e) {
		this.loadSdk = e;
		this.generation = randomUUID();
		this.hasLoadFailure = false;
		this.disposed = false;
		this.bindRuntime = createLazyRuntimeMethodBinder(() => this.requireRuntime());
		this.getDesktopState = this.bindRuntime((e) => e.getDesktopState.bind(e));
		this.callTool = this.bindRuntime((e) => e.callTool.bind(e));
		this.getCursorPosition = this.bindRuntime((e) => e.getCursorPosition.bind(e));
		this.getSessionState = this.bindRuntime((e) => e.getSessionState.bind(e));
		this.getScreenSize = this.bindRuntime((e) => e.getScreenSize.bind(e));
		this.click = this.bindRuntime((e) => e.click.bind(e));
		this.drag = this.bindRuntime((e) => e.drag.bind(e));
		this.moveCursor = this.bindRuntime((e) => e.moveCursor.bind(e));
		this.scroll = this.bindRuntime((e) => e.scroll.bind(e));
		this.typeText = this.bindRuntime((e) => e.typeText.bind(e));
		this.pressKey = this.bindRuntime((e) => e.pressKey.bind(e));
	}
	resolveRuntime() {
		if (this.disposed || this.hasLoadFailure || this.loadPromise) return;
		if (this.runtime) return this.runtime;
		const e = this.loadSdk().then((e) => {
			this.loadedSdk = e;
			this.runtime = new DirectCuaDriverSession(e);
			return this.runtime;
		}).catch((e) => {
			materializeErrorStack(e);
			this.loadFailure = e;
			this.hasLoadFailure = true;
			throw e;
		}).finally(() => {
			this.loadPromise = void 0;
		});
		this.loadPromise = e;
		e.catch(() => {});
	}
	async requireRuntime() {
		const e = this.resolveRuntime();
		if (e) return e;
		if (this.loadPromise) try {
			return await this.loadPromise;
		} catch (e) {
			throw unavailableError(this.loadFailure ?? e);
		}
		throw unavailableError(this.disposed ? /* @__PURE__ */ new Error("cua-computer is stopping") : this.loadFailure);
	}
	isAvailable() {
		return this.resolveRuntime()?.isAvailable() ?? false;
	}
	async prepareAvailability() {
		this.resolveRuntime();
		await this.loadPromise?.catch(() => {});
	}
	resetAvailabilityCache() {
		if (!this.runtime && !this.disposed && !this.loadPromise) {
			this.loadFailure = void 0;
			this.hasLoadFailure = false;
		}
	}
	async prepareExecution(e, t) {
		const assertActive = () => {
			e?.throwIfAborted();
			t?.();
			if (this.disposed) throw unavailableError(/* @__PURE__ */ new Error("cua-computer is stopping"));
		};
		assertActive();
		this.preparePromise ??= (async () => {
			const t = await this.requireRuntime();
			assertActive();
			try {
				await t.getSessionState(e);
			} catch (n) {
				const r = this.loadedSdk;
				if (!r || !isExpiredSessionError(r, n)) throw r ? driverToolError(r, n) : n;
				assertActive();
				try {
					await t.dispose();
				} finally {
					this.runtime = void 0;
					this.generation = randomUUID();
				}
				assertActive();
				this.runtime = new DirectCuaDriverSession(r);
				await this.runtime.getSessionState(e).catch((e) => {
					throw driverToolError(r, e);
				});
			}
		})().finally(() => {
			this.preparePromise = void 0;
		});
		await this.preparePromise;
		assertActive();
	}
	async dispose() {
		if (this.disposed) return;
		this.disposed = true;
		try {
			await this.loadPromise;
		} catch {}
		await this.preparePromise?.catch(() => {});
		await this.runtime?.dispose();
	}
};
function createCuaDriver(e = {}) {
	return new LazyCuaDriverSession(e.loadSdk ?? loadCuaDriverSdk);
}
//#endregion
//#region extensions/cua-computer/src/frame.ts
function staleFrame(e) {
	return /* @__PURE__ */ new Error(`COMPUTER_STALE_FRAME: ${e}; take a new screenshot`);
}
function staleObservation() {
	return /* @__PURE__ */ new Error("COMPUTER_STALE_OBSERVATION: take a fresh observation and retry");
}
function opaqueRef(e) {
	return `cua:v2:${e}:${randomUUID()}`;
}
function issueRef(e, t, n, r) {
	if (r) {
		for (const [e, n] of t) if (r(n)) return e;
	}
	const i = opaqueRef(e);
	t.set(i, n);
	return i;
}
function adoptGeneration(e, t) {
	if (e.generation !== t) {
		e.lastFrame = void 0;
		e.apps = void 0;
		e.windows = void 0;
		e.observation = void 0;
		e.browsers = void 0;
		e.pages = void 0;
		e.browserObservation = void 0;
		e.dialog = void 0;
	}
	e.generation = t;
}
function verifyGeneration(e, t) {
	if (e.generation !== t) {
		adoptGeneration(e, t);
		throw staleObservation();
	}
}
function issueAppRef(e, t) {
	return issueRef("app", e.apps ??= /* @__PURE__ */ new Map(), t);
}
function issueWindowRef(e, t) {
	return issueRef("window", e.windows ??= /* @__PURE__ */ new Map(), t, (e) => e.pid === t.pid && e.windowId === t.windowId);
}
function requireRef(e, t) {
	const n = e?.get(t);
	if (n === void 0) throw staleObservation();
	return n;
}
function resolveWindowRef(e, t) {
	return requireRef(e.windows, t);
}
function issueObservation(e, t, n = {}) {
	const r = {
		id: opaqueRef("observation"),
		windowRef: t,
		fromZoom: n.fromZoom === true,
		elements: /* @__PURE__ */ new Map()
	};
	e.observation = r;
	return r;
}
function issueElementRef(e, t) {
	return issueRef("element", e.elements, t);
}
function resolveObservation(e, t, n) {
	const r = e.observation;
	if (!r || r.id !== t || r.windowRef !== n) throw staleObservation();
	return r;
}
function resolveElementRef(e, t) {
	return requireRef(e.elements, t);
}
function issueBrowserRef(e, t) {
	return issueRef("browser", e.browsers ??= /* @__PURE__ */ new Map(), t, (e) => e.targetId === t.targetId && e.windowRef === t.windowRef);
}
function resolveBrowserRef(e, t) {
	return requireRef(e.browsers, t);
}
function issuePageRef(e, t, n) {
	return issueRef("page", e.pages ??= /* @__PURE__ */ new Map(), {
		browserRef: t,
		tabId: n
	}, (e) => e.browserRef === t && e.tabId === n);
}
function resolvePageRef(e, t, n) {
	const r = e.pages?.get(n);
	if (!r || r.browserRef !== t) throw staleObservation();
	return r;
}
function issueBrowserObservation(e, t, n) {
	const r = {
		id: opaqueRef("observation"),
		browserRef: t,
		pageRef: n,
		elements: /* @__PURE__ */ new Map()
	};
	e.browserObservation = r;
	e.dialog = void 0;
	return r;
}
function issueBrowserElementRef(e, t) {
	return issueRef("element", e.elements, t);
}
function resolveBrowserObservation(e, t, n, r) {
	const i = e.browserObservation;
	if (!i || i.id !== t || i.browserRef !== n || i.pageRef !== r) throw staleObservation();
	return i;
}
function resolveBrowserElementRef(e, t) {
	return requireRef(e.elements, t);
}
function invalidateBrowserObservation(e) {
	e.browserObservation = void 0;
	e.dialog = void 0;
}
function invalidateBrowserReferences(e) {
	e.browsers = void 0;
	e.pages = void 0;
	invalidateBrowserObservation(e);
}
function issueDialogRef(e, t, n, r) {
	const i = opaqueRef("dialog");
	e.dialog = {
		ref: i,
		nativeId: t,
		browserRef: n,
		pageRef: r
	};
	return i;
}
function resolveDialogRef(e, t, n, r) {
	const i = e.dialog;
	if (!i || i.ref !== t || i.browserRef !== n || i.pageRef !== r) throw staleObservation();
	return i.nativeId;
}
/**
* CUA Driver exposes only the primary-display label, not a stable display ID.
* Bind authorization to connection generation plus the complete live geometry.
*/
function issueFrame(e, t, n) {
	const r = `cua:v1:${createHash("sha256").update(JSON.stringify([
		e.generation,
		t,
		n
	])).digest("hex")}`;
	e.lastFrame = {
		id: r,
		referenceWidth: n.referenceWidth,
		nativeWidth: t.screenshotWidth,
		nativeHeight: t.screenshotHeight,
		deliveredWidth: n.width,
		deliveredHeight: n.height,
		geometry: {
			width: t.screenWidth,
			height: t.screenHeight,
			scaleFactor: t.scaleFactor
		}
	};
	return r;
}
function verifyFrame(e, t, n, r) {
	const i = e.lastFrame;
	if (!i || !t || t !== i.id) {
		e.lastFrame = void 0;
		throw staleFrame("the coordinate frame is missing or no longer current");
	}
	if (!(n.width === i.geometry.width && n.height === i.geometry.height && n.scaleFactor === i.geometry.scaleFactor)) {
		e.lastFrame = void 0;
		throw staleFrame("the primary display geometry changed");
	}
	if (r !== i.referenceWidth && r !== i.deliveredWidth) {
		e.lastFrame = void 0;
		throw staleFrame("the coordinate reference width changed");
	}
	return i;
}
//#endregion
//#region extensions/cua-computer/src/driver-result.ts
const CUA_WIRE_ACTION_NAMES = COMPUTER_USE_V2_ACTION_NAMES.slice(1, 14);
const NativeAppSchema = object({
	pid: number().int().nonnegative().nullable().optional(),
	bundle_id: string().nullable().optional(),
	name: string().min(1),
	running: boolean().nullable().optional(),
	active: boolean().optional(),
	kind: string().nullable().optional(),
	launch_path: string().nullable().optional(),
	last_used: string().nullable().optional()
});
const NativeBoundsSchema = object({
	x: number(),
	y: number(),
	width: number().nonnegative(),
	height: number().nonnegative()
});
const NativeWindowSchema = object({
	window_id: number().int().nonnegative(),
	pid: number().int().positive().nullable().optional(),
	app_name: string().optional(),
	title: string().optional(),
	bounds: NativeBoundsSchema,
	is_on_screen: boolean().optional(),
	minimized: boolean().optional(),
	z_index: number().int().nullable().optional()
});
const NativeElementSchema = object({
	element_index: number().int().nonnegative(),
	element_token: string().min(1).optional(),
	role: string().optional(),
	label: string().optional(),
	value: string().optional(),
	frame: object({
		x: number(),
		y: number(),
		w: number().nonnegative(),
		h: number().nonnegative()
	}).optional()
});
const NativeBrowserTabSchema = object({
	tab_id: string().min(1),
	title: string().optional(),
	url: string().optional(),
	active: boolean().optional()
});
const NativeBrowserRefSchema = object({
	ref: string().min(1),
	node: string().optional(),
	role: string().optional(),
	label: string().optional(),
	name: string().optional(),
	value: string().optional(),
	states: array(string()).optional(),
	actions: array(string()).optional(),
	frame: string().optional(),
	visibility: string().optional()
});
const MAX_DISCOVERY_ITEMS = 500;
const MAX_BROWSER_ELEMENTS = 2e3;
const PARTIAL_EFFECT = 1;
const VALUE_READBACK_EVIDENCE = 0;
function platformActions(e) {
	return COMPUTER_USE_V2_ACTION_NAMES.filter((t) => t !== "hold_key" && t !== "wait" && (e === "linux" || t !== "left_mouse_down" && t !== "left_mouse_up"));
}
function boundedItems(e) {
	return {
		items: e.slice(0, MAX_DISCOVERY_ITEMS),
		truncated: Math.max(0, e.length - MAX_DISCOVERY_ITEMS)
	};
}
function driverEffect(e) {
	switch (Number(e.action?.effect)) {
		case 0: return "confirmed";
		case 1:
		case 2: return "unverifiable";
		case 3: return "suspected_noop";
		case 4: throw new Error("COMPUTER_REFUSED_action_refused: CUA Driver refused the action");
		default: return;
	}
}
function driverEscalation(e) {
	const t = e.action?.escalation;
	if (!t) return;
	const n = {
		0: "window-pixel",
		1: "foreground",
		2: "window-pixel",
		3: "desktop"
	}[t.target];
	const r = {
		0: "route_unavailable",
		1: "delivery_failed",
		2: "effect_unconfirmed",
		3: "suspected_noop",
		4: "permission_required"
	}[t.reason];
	if (!n || !r) throw new Error("COMPUTER_DRIVER_ERROR: invalid CUA Driver action escalation");
	return {
		recommended: n,
		reasonCode: r
	};
}
function driverActionDetails(e) {
	const t = e.action;
	if (!t) return;
	const n = { route: [
		"accessibility",
		"synthetic_events",
		"global_input",
		"system_api",
		"dom",
		"trusted_input"
	][t.route] };
	if (t.effect === PARTIAL_EFFECT) n.partial = true;
	if (t.delivery) {
		n.deliveryMode = [
			"background",
			"foreground",
			"not_applicable",
			"unknown"
		][t.delivery.mode];
		if (t.delivery.deliveredCount !== void 0) n.deliveredCount = t.delivery.deliveredCount;
	}
	if (t.evidence?.length) n.evidence = t.evidence.map(({ kind: e }) => e === VALUE_READBACK_EVIDENCE ? "value_readback" : "window_change");
	return Object.values(n).some((e) => e !== void 0) ? n : void 0;
}
function actionEnvelope(e, t) {
	const n = driverEffect(e);
	const r = driverEscalation(e);
	const i = driverActionDetails(e);
	return {
		ok: true,
		...n ? { effect: n } : {},
		...r ? { escalation: r } : {},
		...i || t ? { details: {
			...i,
			...t
		} } : {}
	};
}
async function callWindowTool(e, t, n, r, i) {
	const a = e.generation;
	const o = t.generation === a;
	const s = await e.callTool(n, r, i);
	if (o && e.generation !== a) {
		adoptGeneration(t, e.generation);
		throw new Error("COMPUTER_STALE_OBSERVATION: computer driver generation changed during action");
	}
	adoptGeneration(t, e.generation);
	const c = (s.isError ? s.errorCode : void 0) ?? structuredRefusalCode(s);
	if (s.isError || c) {
		if (c && [
			"browser_binding_stale",
			"browser_tab_not_found",
			"browser_ref_stale",
			"browser_reconnect_exhausted"
		].includes(c)) {
			invalidateBrowserReferences(t);
			throw new Error("COMPUTER_STALE_OBSERVATION: take a fresh browser observation and retry");
		}
		const e = c ? `COMPUTER_REFUSED_${c}` : "COMPUTER_DRIVER_ERROR";
		throw new Error(`${e}: ${s.text || `${n} failed`}`);
	}
	return s;
}
function structuredRefusalCode(e) {
	if (!e.structuredContent && !e.structuredJson) return;
	try {
		const t = e.structuredContent ?? (e.structuredJson ? JSON.parse(e.structuredJson) : void 0);
		const n = isRecord(t) ? asOptionalRecord(t.refusal) : void 0;
		return isRecord(t) && t.status === "refused" && typeof n?.code === "string" ? n.code : void 0;
	} catch {
		return;
	}
}
function projectedToolDetails(e, t) {
	if (e.structuredContent) return e.structuredContent;
	if (!e.structuredJson) throw new Error(`COMPUTER_DRIVER_ERROR: ${t} returned no structuredContent`);
	try {
		const t = JSON.parse(e.structuredJson);
		if (isRecord(t)) return t;
	} catch {}
	throw new Error(`COMPUTER_DRIVER_ERROR: ${t} returned invalid structuredContent`);
}
function nativeWindows(e) {
	if (!Array.isArray(e)) return [];
	return e.flatMap((e) => {
		const t = NativeWindowSchema.safeParse(e);
		return t.success && t.data.pid ? [t.data] : [];
	});
}
function projectWindows(e, t) {
	const n = boundedItems(t);
	return {
		windows: n.items.map((t) => ({
			windowRef: issueWindowRef(e, {
				pid: t.pid,
				windowId: t.window_id
			}),
			...t.app_name ? { appName: t.app_name } : {},
			...t.title ? { title: t.title } : {},
			bounds: t.bounds,
			...t.is_on_screen !== void 0 ? { isOnScreen: t.is_on_screen } : {},
			...t.minimized !== void 0 ? { minimized: t.minimized } : {},
			...t.z_index !== void 0 ? { zIndex: t.z_index } : {}
		})),
		...n.truncated ? { truncatedWindows: n.truncated } : {}
	};
}
function projectApps(e, t) {
	const n = (Array.isArray(t) ? t : []).flatMap((t) => {
		const n = NativeAppSchema.safeParse(t);
		if (!n.success) return [];
		return [{
			app: issueAppRef(e, {
				...n.data.pid ? { pid: n.data.pid } : {},
				name: n.data.name,
				...n.data.bundle_id ? { bundleId: n.data.bundle_id } : {},
				...n.data.launch_path ? { launchPath: n.data.launch_path } : {}
			}),
			name: n.data.name,
			...n.data.running !== void 0 ? { running: n.data.running } : {},
			...n.data.active !== void 0 ? { active: n.data.active } : {},
			...n.data.kind ? { kind: n.data.kind } : {},
			...n.data.last_used ? { lastUsed: n.data.last_used } : {}
		}];
	});
	const r = boundedItems(n);
	return {
		apps: r.items,
		totalApps: n.length,
		...r.truncated ? { truncatedApps: r.truncated } : {}
	};
}
function projectProcesses(e) {
	const t = boundedItems(Array.isArray(e) ? e : []);
	return {
		processes: t.items,
		...t.truncated ? { truncatedProcesses: t.truncated } : {}
	};
}
function observationImage(e, t, n) {
	const r = e.images.find((e) => e.mimeType === "image/png" || e.mimeType === "image/jpeg");
	const i = r ? canonicalizeBase64(r.dataBase64) : void 0;
	if (r && !i) throw new Error("COMPUTER_DRIVER_ERROR: CUA Driver returned malformed observation image base64");
	return {
		...i ? {
			base64: i,
			format: r?.mimeType === "image/jpeg" ? "jpeg" : "png"
		} : {},
		...typeof t === "number" && t >= 1 ? { width: Math.trunc(t) } : {},
		...typeof n === "number" && n >= 1 ? { height: Math.trunc(n) } : {}
	};
}
function windowObservation(e, t, n, r = {}) {
	const i = projectedToolDetails(e, r.fromZoom ? "zoom" : "get_window_state");
	const a = issueObservation(t, n, r);
	const o = typeof i.snapshot_id === "string" ? i.snapshot_id : void 0;
	const s = Array.isArray(i.elements) ? i.elements : [];
	let c = 0;
	const l = s.slice(0, 2e3).flatMap((e) => {
		const t = NativeElementSchema.safeParse(e);
		if (!t.success || !t.data.frame) {
			c += 1;
			return [];
		}
		return [{
			elementRef: issueElementRef(a, {
				elementIndex: t.data.element_index,
				...t.data.element_token ? { elementToken: t.data.element_token } : {},
				...o ? { snapshotId: o } : {}
			}),
			role: t.data.role?.trim() || "unknown",
			...t.data.label !== void 0 ? { label: t.data.label } : {},
			...t.data.value !== void 0 ? { value: t.data.value } : {},
			bounds: {
				x: t.data.frame.x,
				y: t.data.frame.y,
				width: t.data.frame.w,
				height: t.data.frame.h
			}
		}];
	});
	const u = actionEnvelope(e, {
		coordinateSpace: "image-pixels",
		...typeof i.total_element_count === "number" ? { totalElementCount: i.total_element_count } : {},
		...s.length > 2e3 ? { truncatedElements: s.length - 2e3 } : {},
		...c ? { omittedElementsWithoutBounds: c } : {},
		...i.degraded === true ? { degraded: true } : {},
		...typeof i.degraded_reason === "string" ? { degradedReason: i.degraded_reason } : {},
		...typeof i.screenshot_error === "string" ? { screenshotError: i.screenshot_error } : {}
	});
	return {
		...u,
		observation: {
			kind: "window",
			...observationImage(e, i[r.fromZoom ? "width" : "screenshot_width"], i[r.fromZoom ? "height" : "screenshot_height"]),
			observationId: a.id,
			...l.length ? { elements: l } : {}
		},
		...!u.escalation && i.escalation && typeof i.escalation === "object" ? { escalation: {
			recommended: "window-pixel",
			reasonCode: "ax_tree_unavailable"
		} } : {}
	};
}
function browserBinding(e, t, n) {
	const r = projectedToolDetails(e, "get_browser_state");
	if (r.mode !== "bind" || typeof r.target_id !== "string" || r.target_id.length === 0 || !Array.isArray(r.tabs)) throw new Error("COMPUTER_DRIVER_ERROR: invalid browser bind result");
	const i = issueBrowserRef(t, {
		targetId: r.target_id,
		windowRef: n
	});
	const a = boundedItems(r.tabs.flatMap((e) => {
		const n = NativeBrowserTabSchema.safeParse(e);
		if (!n.success) return [];
		const { tab_id: r, ...a } = n.data;
		return [{
			pageRef: issuePageRef(t, i, r),
			...a
		}];
	}));
	return {
		ok: true,
		details: {
			browserRef: i,
			pages: a.items,
			...a.truncated ? { truncatedPages: a.truncated } : {},
			...typeof r.binding_quality === "string" ? { bindingQuality: r.binding_quality } : {},
			...typeof r.binding_route === "string" ? { bindingRoute: r.binding_route } : {},
			...typeof r.mutation_allowed === "boolean" ? { mutationAllowed: r.mutation_allowed } : {},
			...typeof r.native_title === "string" ? { nativeTitle: r.native_title } : {}
		}
	};
}
function browserObservation(e, t, n) {
	const r = projectedToolDetails(e, "get_browser_state");
	if (r.mode !== "snapshot" || r.target_id !== n.targetId || r.tab_id !== n.tabId) throw new Error("COMPUTER_DRIVER_ERROR: invalid browser snapshot result");
	const i = issueBrowserObservation(t, n.browserRef, n.pageRef);
	const a = [];
	const o = /* @__PURE__ */ new Set();
	for (const [e, t] of [["action", r.refs], ["content", r.content_refs]]) {
		if (!Array.isArray(t)) continue;
		for (const n of t) {
			const t = NativeBrowserRefSchema.safeParse(n);
			if (!t.success || o.has(t.data.ref)) continue;
			const { ref: r, ...s } = t.data;
			o.add(r);
			a.push({
				elementRef: issueBrowserElementRef(i, r),
				kind: e,
				...s
			});
		}
	}
	const s = a.slice(0, MAX_BROWSER_ELEMENTS);
	const c = asOptionalRecord(r.page);
	return {
		ok: true,
		observation: {
			kind: "browser",
			...observationImage(e, r.screenshot_width, r.screenshot_height),
			observationId: i.id
		},
		details: {
			browserRef: n.browserRef,
			pageRef: n.pageRef,
			elements: s,
			...a.length > MAX_BROWSER_ELEMENTS ? { truncatedElements: a.length - MAX_BROWSER_ELEMENTS } : {},
			...typeof r.snapshot_id === "string" ? { snapshot: { format: "dom_refs_v1" } } : isRecord(r.snapshot) ? { snapshot: projectSemanticBrowserSnapshot(r.snapshot) } : {},
			...typeof r.url === "string" ? { url: r.url } : {},
			...c ? { page: {
				...typeof c.url === "string" ? { url: c.url } : {},
				...typeof c.title === "string" ? { title: c.title } : {}
			} } : {},
			...typeof r.truncated === "boolean" ? { truncated: r.truncated } : {}
		}
	};
}
function browserToolEnvelope(e, t) {
	if (t === "browser_click" || t === "browser_type" || t === "browser_pointer") return actionEnvelope(e);
	const n = projectedToolDetails(e, t);
	const r = {};
	if (t === "browser_prepare") {
		for (const [e, t] of [
			["prepared", "prepared"],
			["action", "action"],
			["message", "message"],
			["side_effects", "sideEffects"]
		]) if (n[e] !== void 0) r[t] = n[e];
		const e = n.endpoint_ownership;
		if (isRecord(e) && typeof e.method === "string") r.endpointOwnership = { method: e.method };
	} else if (t === "browser_navigate") {
		if (typeof n.url === "string") r.url = n.url;
		if (typeof n.refs_invalidated === "boolean") r.refsInvalidated = n.refs_invalidated;
	} else if (t === "browser_set_input_files") {
		if (typeof n.file_count === "number") r.fileCount = n.file_count;
		if (typeof n.frame === "string") r.frame = n.frame;
	} else if (t === "browser_download") {
		if (typeof n.status === "string") r.status = n.status;
		if (typeof n.bytes === "number") r.bytes = n.bytes;
	}
	return {
		ok: true,
		...Object.keys(r).length ? { details: r } : {}
	};
}
function projectSemanticBrowserSnapshot(e) {
	return {
		format: "semantic_v2",
		...typeof e.complete === "boolean" ? { complete: e.complete } : {},
		...typeof e.selected_nodes === "number" ? { selectedNodes: e.selected_nodes } : {},
		...typeof e.total_nodes === "number" ? { totalNodes: e.total_nodes } : {},
		...isRecord(e.omitted) ? { omitted: e.omitted } : {},
		...typeof e.continuation === "string" ? { continuation: e.continuation } : {}
	};
}
function browserDialogEnvelope(e, t, n) {
	const r = projectedToolDetails(e, "browser_dialog");
	const i = r.present === true;
	if (!i) t.dialog = void 0;
	const a = { present: i };
	if (typeof r.kind === "string") a.kind = r.kind;
	if (i && typeof r.dialog_id === "string") a.dialogRef = issueDialogRef(t, r.dialog_id, n.browserRef, n.pageRef);
	if (typeof r.action === "string") a.action = r.action;
	return {
		ok: true,
		details: a
	};
}
//#endregion
//#region extensions/cua-computer/src/execution-resources.ts
const RESOURCE_HANDLE_PREFIX = "openclaw:computer-resource:v1:";
const RESOURCE_ROOT_NAME = "cua-computer-resources";
const MAX_RESOURCE_TREE_ENTRIES = 1e4;
function createLazyCuaExecutionResources() {
	let e;
	const resources = () => e ??= createCuaExecutionResources().catch((t) => {
		e = void 0;
		throw t;
	});
	return {
		createDirectory: async (e) => await (await resources()).createDirectory(e),
		resolveFiles: async (e) => await (await resources()).resolveFiles(e),
		validateDirectoryTree: async (e) => await (await resources()).validateDirectoryTree(e),
		captureFiles: async (e) => await (await resources()).captureFiles(e),
		discard: async (e) => await (await resources()).discard(e),
		dispose: async (t) => {
			if (e) await (await e).dispose(t);
		}
	};
}
function resourceError(e) {
	return /* @__PURE__ */ new Error(`COMPUTER_INVALID_RESOURCE: ${e}`);
}
async function requireEntry(e, t, n, r) {
	if (!n.startsWith(RESOURCE_HANDLE_PREFIX)) throw resourceError("malformed resource handle");
	const i = e.get(n);
	if (!i || i.kind !== r) throw resourceError("resource handle is unknown in this provider execution");
	let a;
	let o;
	try {
		a = await t.stat(i.relativePath);
		o = await t.resolve(i.relativePath);
	} catch (e) {
		throw resourceError(`resource is no longer a safe ${r}: ${String(e)}`);
	}
	if (a.isSymbolicLink || (r === "file" ? !a.isFile : !a.isDirectory)) throw resourceError(`resource is no longer a regular ${r}`);
	return {
		entry: i,
		path: o
	};
}
async function createCuaExecutionResources() {
	const e = await root(resolvePreferredOpenClawTmpDir(), {
		hardlinks: "reject",
		mode: 448,
		symlinks: "reject"
	});
	await e.mkdir(RESOURCE_ROOT_NAME);
	const t = await root(await e.resolve(RESOURCE_ROOT_NAME), {
		hardlinks: "reject",
		mode: 448,
		symlinks: "reject"
	});
	const n = `execution-${randomUUID()}`;
	await t.mkdir(n);
	const r = await t.resolve(n);
	const i = await root(r, {
		hardlinks: "reject",
		mode: 448,
		symlinks: "reject"
	});
	const a = /* @__PURE__ */ new Map();
	const o = /* @__PURE__ */ new Map();
	let s = false;
	const assertActive = () => {
		if (s) throw resourceError("provider execution is closed");
	};
	const register = (e, t) => {
		const n = o.get(t);
		if (n) return n;
		const r = `${RESOURCE_HANDLE_PREFIX}${randomUUID()}`;
		a.set(r, {
			kind: e,
			relativePath: t
		});
		o.set(t, r);
		return r;
	};
	return {
		async createDirectory(e) {
			assertActive();
			const t = `${e}-${randomUUID()}`;
			await i.mkdir(t);
			return {
				handle: register(e, t),
				path: await i.resolve(t)
			};
		},
		async resolveFiles(e) {
			assertActive();
			return await Promise.all(e.map(async (e) => (await requireEntry(a, i, e, "file")).path));
		},
		async validateDirectoryTree(e) {
			assertActive();
			const t = await requireEntry(a, i, e, "recording");
			let n = 0;
			const visit = async (e) => {
				for (const t of await i.list(e, { withFileTypes: true })) {
					n += 1;
					if (n > MAX_RESOURCE_TREE_ENTRIES) throw resourceError("resource tree is too large");
					if (t.isSymbolicLink || !t.isDirectory && !t.isFile) throw resourceError("resource tree contains an unsupported entry");
					const r = path.join(e, t.name);
					await i.resolve(r);
					if (t.isDirectory) await visit(r);
				}
			};
			await visit(t.entry.relativePath);
			return t.path;
		},
		async captureFiles(e) {
			assertActive();
			const t = await requireEntry(a, i, e, "browser-download");
			const n = [];
			for (const e of await i.list(t.entry.relativePath, { withFileTypes: true })) {
				if (e.isSymbolicLink || !e.isFile) continue;
				const r = path.join(t.entry.relativePath, e.name);
				await i.resolve(r);
				n.push(register("file", r));
			}
			return n;
		},
		async discard(e) {
			assertActive();
			const t = a.get(e);
			if (!t) return;
			await removePathWithinRoot({
				rootDir: i.rootReal,
				relativePath: t.relativePath,
				recursive: true,
				force: true
			});
			a.delete(e);
			o.delete(t.relativePath);
		},
		async dispose(e) {
			if (s) return;
			s = true;
			a.clear();
			o.clear();
			if (e) await removePathWithinRoot({
				rootDir: t.rootReal,
				relativePath: n,
				recursive: true,
				force: true
			});
		}
	};
}
//#endregion
//#region extensions/cua-computer/src/mcp-driver-client.ts
const MCP_PROTOCOL_VERSION = "2025-06-18";
const MCP_STARTUP_TIMEOUT_MS = 1e4;
const MCP_REQUEST_TIMEOUT_MS = 12e4;
const MAX_PENDING_REQUESTS = 64;
const MAX_MCP_LINE_BYTES = 268435456;
const MCP_DESKTOP_TARGET = {
	kind: "desktop",
	display_id: "primary"
};
const ACTION_RESULT_TOOLS = /* @__PURE__ */ new Set([
	"click",
	"double_click",
	"right_click",
	"scroll",
	"drag",
	"mouse_drag",
	"parallel_mouse_drag",
	"move_cursor",
	"mouse_button_down",
	"mouse_button_up",
	"type_text",
	"type_text_chars",
	"press_key",
	"hotkey",
	"set_value",
	"set_window_frame",
	"invoke_menu",
	"browser_click",
	"browser_pointer",
	"browser_type"
]);
function driverUnavailable(e, t) {
	return new Error(`COMPUTER_DRIVER_UNAVAILABLE: ${e}`, { cause: t });
}
function driverProtocolError(e, t) {
	return new Error(`COMPUTER_DRIVER_ERROR: ${e}`, { cause: t });
}
function mappedEnum(e, t, n) {
	if (typeof e !== "string") throw driverProtocolError(`CUA MCP ${n} is missing`);
	const r = t.indexOf(e);
	if (r < 0) throw driverProtocolError(`CUA MCP ${n} is invalid`);
	return r;
}
function mcpActionResult(e, t) {
	if (!ACTION_RESULT_TOOLS.has(e)) return;
	const n = asOptionalRecord(t);
	if (!n) throw driverProtocolError(`CUA MCP ${e} returned no ActionResult`);
	const r = asOptionalRecord(n.delivery);
	const i = asOptionalRecord(n.escalation);
	const a = Array.isArray(n.evidence) ? n.evidence : void 0;
	return {
		effect: mappedEnum(n.effect, [
			"confirmed",
			"partial",
			"unverifiable",
			"suspected_noop",
			"refused"
		], "action effect"),
		route: mappedEnum(n.route, [
			"accessibility",
			"synthetic_events",
			"global_input",
			"system_api",
			"dom",
			"trusted_input"
		], "action route"),
		...r ? { delivery: {
			mode: mappedEnum(r.mode, [
				"background",
				"foreground",
				"not_applicable",
				"unknown"
			], "delivery mode"),
			...typeof r.delivered_count === "number" ? { deliveredCount: r.delivered_count } : {}
		} } : {},
		...a ? { evidence: a.map((e) => ({ kind: mappedEnum(asOptionalRecord(e)?.kind, ["value_readback", "window_change"], "evidence kind") })) } : {},
		...i ? { escalation: {
			target: mappedEnum(i.target, [
				"pixel",
				"foreground",
				"page",
				"session"
			], "escalation target"),
			reason: mappedEnum(i.reason, [
				"route_unavailable",
				"delivery_failed",
				"effect_unconfirmed",
				"suspected_noop",
				"permission_required"
			], "escalation reason")
		} } : {}
	};
}
function normalizeMcpToolResult(e, t) {
	const n = asOptionalRecord(t);
	if (!n) throw driverProtocolError(`CUA MCP ${e} returned a non-object result`);
	const r = Array.isArray(n.content) ? n.content : [];
	const i = r.flatMap((e) => e?.type === "text" && typeof e.text === "string" ? [e.text] : []);
	const a = r.flatMap((e) => e?.type === "image" && typeof e.data === "string" && typeof e.mimeType === "string" ? [{
		dataBase64: e.data,
		mimeType: e.mimeType
	}] : []);
	const o = asOptionalRecord(n.structuredContent);
	const s = readStringField(o, "code") ?? readStringField(asOptionalRecord(o?.refusal), "code");
	const c = n.isError === true;
	return {
		text: i.join("\n"),
		images: a,
		...o ? { structuredContent: o } : {},
		isError: c,
		...s ? { errorCode: s } : {},
		...!c ? { action: mcpActionResult(e, o) } : {},
		degraded: o?.degraded === true,
		rawJson: "{}"
	};
}
function createClient(e, t, n) {
	const r = { ...n };
	for (const e of Object.keys(r)) if (e.startsWith("CUA_DRIVER_") || e === "CUA_TELEMETRY_ENABLED") delete r[e];
	return import("../../plugin-sdk/agent-harness-runtime.js").then(({ mcpStdioRuntime: e }) => e.load()).then(({ createMcpStdioClient: n }) => n({
		command: e,
		args: [
			"mcp",
			"--embedded",
			"--socket",
			t
		],
		env: {
			...r,
			CUA_DRIVER_RS_TELEMETRY_ENABLED: "false",
			CUA_DRIVER_RS_UPDATE_CHECK: "false"
		},
		clientInfo: {
			name: "openclaw-cua-computer",
			version: "1"
		},
		protocolVersion: MCP_PROTOCOL_VERSION,
		startupTimeoutMs: MCP_STARTUP_TIMEOUT_MS,
		maxPendingRequests: MAX_PENDING_REQUESTS,
		maxFrameBytes: MAX_MCP_LINE_BYTES,
		errors: {
			unavailable: (e, t) => driverUnavailable(`CUA MCP ${e}`, t),
			protocol: (e, t) => driverProtocolError(`CUA MCP ${e}`, t)
		}
	}));
}
function sessionState(e) {
	if (e.isError || !e.structuredContent) throw driverProtocolError(e.text || "CUA MCP session operation failed");
	const t = e.structuredContent;
	return {
		captureScope: mappedEnum(t.capture_scope, [
			"auto",
			"window",
			"desktop"
		], "capture scope"),
		effectiveScope: mappedEnum(t.effective_scope, ["window", "desktop"], "effective scope"),
		desktopUnlocked: t.desktop_unlocked === true
	};
}
var McpCuaDriverSession = class {
	constructor(e) {
		this.client = e;
		this.generation = randomUUID();
		this.publicSession = `openclaw-${randomUUID()}`;
		this.started = false;
		this.disposed = false;
		e.then((e) => {
			this.resolved = e;
		}).catch(() => {});
	}
	isAvailable() {
		return !this.disposed && this.resolved?.isAvailable() === true;
	}
	resetAvailabilityCache() {}
	async callTool(e, t, n) {
		return await this.sessionTool(e, t, n);
	}
	async getCursorPosition(e) {
		return await this.sessionTool("get_cursor_position", {}, e);
	}
	async getSessionState(e) {
		return sessionState(await this.sessionTool("get_session_state", {}, e));
	}
	async getDesktopState(e) {
		return await this.sessionTool("get_desktop_state", {}, e);
	}
	async getScreenSize(e) {
		return await this.sessionTool("get_screen_size", {}, e);
	}
	async click(e, t) {
		return await this.sessionTool("click", {
			x: e.x,
			y: e.y,
			button: [
				"left",
				"right",
				"middle"
			][e.button],
			count: e.count,
			target: MCP_DESKTOP_TARGET
		}, t);
	}
	async drag(e, t) {
		return await this.sessionTool("drag", {
			from_x: e.fromX,
			from_y: e.fromY,
			to_x: e.toX,
			to_y: e.toY,
			...e.durationMs === void 0 ? {} : { duration_ms: Number(e.durationMs) },
			target: MCP_DESKTOP_TARGET
		}, t);
	}
	async moveCursor(e, t) {
		return await this.sessionTool("move_cursor", {
			x: e.x,
			y: e.y,
			target: MCP_DESKTOP_TARGET
		}, t);
	}
	async scroll(e, t) {
		return await this.sessionTool("scroll", {
			x: e.x,
			y: e.y,
			direction: [
				"up",
				"down",
				"left",
				"right"
			][e.direction],
			by: "line",
			amount: Number(e.amount),
			target: MCP_DESKTOP_TARGET
		}, t);
	}
	async typeText(e, t) {
		return await this.sessionTool("type_text", {
			text: e,
			target: MCP_DESKTOP_TARGET
		}, t);
	}
	async pressKey(e, t) {
		return await this.sessionTool("press_key", {
			key: e.key,
			modifiers: e.modifiers,
			target: MCP_DESKTOP_TARGET
		}, t);
	}
	async dispose() {
		if (this.disposed) return;
		this.disposed = true;
		let e = await this.startPromise?.catch((e) => e);
		try {
			const t = await this.client;
			if (t.isAvailable() && this.started) try {
				await this.tool("end_session", {});
			} catch (t) {
				e ??= t;
			}
			await t.stop();
		} catch (t) {
			e ??= t;
		}
		if (e) throw e instanceof Error ? e : driverUnavailable("CUA MCP cleanup failed", e);
	}
	async sessionTool(e, t, n) {
		await this.ensureStarted(n);
		return await this.tool(e, t, n);
	}
	async tool(e, t, n) {
		return normalizeMcpToolResult(e, await (await this.client).request("tools/call", {
			name: e,
			arguments: {
				...t,
				session: this.publicSession
			}
		}, {
			timeoutMs: MCP_REQUEST_TIMEOUT_MS,
			signal: n
		}));
	}
	async ensureStarted(e) {
		if (this.disposed) throw driverUnavailable("cua-computer is stopping");
		this.startPromise ??= this.tool("start_session", {}, e).then((e) => {
			if (e.isError) throw driverProtocolError(e.text || "CUA MCP start_session failed");
			this.started = true;
		}).catch((e) => {
			this.startPromise = void 0;
			throw e;
		});
		await this.startPromise;
	}
};
function createCuaMcpDriver(e) {
	return new McpCuaDriverSession(createClient(e.binaryPath, e.socketPath, e.env ?? process.env));
}
//#endregion
//#region extensions/cua-computer/src/recording-actions.ts
const RecordingStateSchema = object({
	recording: boolean(),
	enabled: boolean(),
	output_dir: string().nullable(),
	next_turn: number().int().nonnegative(),
	last_error: string().nullable(),
	video_active: boolean(),
	last_video_path: string().nullable(),
	owner: string().nullable()
});
const ReplayTurnSchema = object({
	turn: string(),
	tool: string().optional(),
	ok: boolean(),
	result_summary: string().optional(),
	parse_error: string().optional()
});
const ReplayResultSchema = object({
	directory: string(),
	attempted: number().int().nonnegative(),
	succeeded: number().int().nonnegative(),
	failed: number().int().nonnegative(),
	stop_on_error: boolean(),
	turns: array(ReplayTurnSchema),
	first_failure: object({
		turn: string(),
		tool: string(),
		error: string()
	}).optional()
});
const MAX_REPLAY_TURNS = 200;
function driverError(e, t) {
	const n = e.errorCode ? `COMPUTER_REFUSED_${e.errorCode}` : "COMPUTER_DRIVER_ERROR";
	return /* @__PURE__ */ new Error(`${n}: ${t} failed; inspect node logs and resource state before retrying`);
}
function structured(e, t) {
	if (e.isError) throw driverError(e, t);
	return projectedToolDetails(e, t);
}
function projectRecordingState(e, t) {
	return {
		recording: e.enabled,
		nextTurn: e.next_turn,
		videoActive: e.video_active,
		...e.last_error ? { videoError: "video unavailable; per-turn trajectory capture remains active" } : {},
		...t ? { resourceHandle: t } : {}
	};
}
async function closeRecordingExecution(e) {
	const t = e.state.active;
	e.state.active = void 0;
	if (!t) return;
	let n;
	try {
		const t = await e.driver.callTool("stop_recording", {});
		if (t.isError) n = driverError(t, "stop_recording");
	} catch (e) {
		n = e;
	}
	if (e.reason !== "completion") try {
		await e.resources.discard(t.resourceHandle);
	} catch (e) {
		n ??= e;
	}
	if (n) throw n instanceof Error ? n : new Error("CUA recording cleanup failed", { cause: n });
}
function projectReplayTurn(e) {
	const t = {
		turn: e.turn,
		ok: e.ok
	};
	if (e.tool) t.tool = e.tool;
	if (e.parse_error) t.parseError = true;
	return t;
}
async function handleRecordingAct(e, t, n, r, i) {
	switch (r.action) {
		case "get_recording_state": {
			if (!t.active) return JSON.stringify({
				ok: true,
				details: { recording: false }
			});
			const n = RecordingStateSchema.parse(structured(await e.callTool("get_recording_state", {}, i), "get_recording_state"));
			return JSON.stringify({
				ok: true,
				details: projectRecordingState(n, t.active.resourceHandle)
			});
		}
		case "start_recording": {
			if (t.active) throw new Error("COMPUTER_RECORDING_ACTIVE: stop the current recording before starting another");
			const a = await n.createDirectory("recording");
			try {
				const n = await e.callTool("start_recording", {
					output_dir: a.path,
					record_video: r.recordVideo ?? false
				}, i);
				const o = RecordingStateSchema.parse(structured(n, "start_recording"));
				if (!o.enabled) throw new Error("COMPUTER_DRIVER_ERROR: start_recording returned disabled state");
				t.active = { resourceHandle: a.handle };
				return JSON.stringify({
					ok: true,
					details: projectRecordingState(o, a.handle)
				});
			} catch (t) {
				await e.dispose().catch(() => {});
				await n.discard(a.handle).catch(() => {});
				throw t;
			}
		}
		case "stop_recording": {
			const n = t.active;
			if (!n) return JSON.stringify({
				ok: true,
				details: { recording: false }
			});
			t.active = void 0;
			const r = RecordingStateSchema.parse(structured(await e.callTool("stop_recording", {}, i), "stop_recording"));
			return JSON.stringify({
				ok: true,
				details: projectRecordingState(r, n.resourceHandle)
			});
		}
		case "replay_trajectory": {
			const t = r.resourceHandle;
			if (!t) throw new Error("COMPUTER_INVALID_REQUEST: resourceHandle is required for replay_trajectory");
			const a = await n.validateDirectoryTree(t);
			const o = ReplayResultSchema.parse(structured(await e.callTool("replay_trajectory", {
				dir: a,
				...r.delayMs !== void 0 ? { delay_ms: r.delayMs } : {},
				...r.stopOnError !== void 0 ? { stop_on_error: r.stopOnError } : {}
			}, i), "replay_trajectory"));
			return JSON.stringify({
				ok: true,
				details: {
					resourceHandle: t,
					attempted: o.attempted,
					succeeded: o.succeeded,
					failed: o.failed,
					stopOnError: o.stop_on_error,
					turns: o.turns.slice(0, MAX_REPLAY_TURNS).map(projectReplayTurn),
					...o.turns.length > MAX_REPLAY_TURNS ? { truncatedTurns: o.turns.length - MAX_REPLAY_TURNS } : {},
					...o.first_failure ? { firstFailure: {
						turn: o.first_failure.turn,
						tool: o.first_failure.tool
					} } : {}
				}
			});
		}
		default: return;
	}
}
//#endregion
//#region extensions/cua-computer/src/action-targets.ts
function requireWindowTarget(e, t, n) {
	verifyGeneration(t, e.generation);
	if (!n.windowRef) throw new Error(`COMPUTER_INVALID_REQUEST: windowRef is required for ${n.action}`);
	return {
		ref: n.windowRef,
		target: resolveWindowRef(t, n.windowRef)
	};
}
function observationTarget(e, t, n) {
	if (!t.observationId) throw new Error(`COMPUTER_STALE_OBSERVATION: observationId is required for ${t.action}`);
	return resolveObservation(e, t.observationId, n);
}
function elementArgs(e, t, n) {
	if (!t.elementRef) return;
	const r = observationTarget(e, t, n);
	const i = resolveElementRef(r, t.elementRef);
	return i.elementToken ? { element_token: i.elementToken } : {
		element_index: i.elementIndex,
		...i.snapshotId ? { snapshot_id: i.snapshotId } : {}
	};
}
function browserTarget(e, t, n) {
	verifyGeneration(t, e.generation);
	if (!n.browserRef || !n.pageRef) throw new Error(`COMPUTER_INVALID_REQUEST: browserRef and pageRef are required for ${n.action}`);
	const r = resolveBrowserRef(t, n.browserRef);
	const i = resolvePageRef(t, n.browserRef, n.pageRef);
	return {
		browserRef: n.browserRef,
		pageRef: n.pageRef,
		targetId: r.targetId,
		tabId: i.tabId
	};
}
function browserElement(e, t, n, r = t.elementRef) {
	if (!r) return;
	if (!t.observationId) throw new Error(`COMPUTER_STALE_OBSERVATION: observationId is required for ${t.action}`);
	const i = resolveBrowserObservation(e, t.observationId, n.browserRef, n.pageRef);
	return resolveBrowserElementRef(i, r);
}
function windowPointArgs(e, t, n, r, i) {
	if (r.x === void 0 || r.y === void 0) throw new Error(`COMPUTER_INVALID_REQUEST: ${i} coordinates are required`);
	const a = observationTarget(e, t, n);
	return {
		x: r.x,
		y: r.y,
		...a.fromZoom ? { from_zoom: true } : {}
	};
}
//#endregion
//#region extensions/cua-computer/src/window-actions.ts
const CUA_TARGETED_ACTION_NAMES = /* @__PURE__ */ new Set([
	"left_click",
	"right_click",
	"middle_click",
	"double_click",
	"triple_click",
	"left_click_drag",
	"left_mouse_down",
	"left_mouse_up",
	"scroll",
	"type",
	"key"
]);
async function handleTargetedAct(e, t, n, r, i) {
	const { ref: a, target: o } = requireWindowTarget(t, n, r);
	const s = {
		pid: o.pid,
		window_id: o.windowId
	};
	const c = r.deliveryMode ? { delivery_mode: r.deliveryMode } : {};
	const l = elementArgs(n, r, a);
	const optionalTarget = (e) => l ?? (r.x !== void 0 || r.y !== void 0 ? windowPointArgs(n, r, a, r, e) : {});
	let u;
	let d;
	switch (r.action) {
		case "left_click":
		case "right_click":
		case "middle_click":
		case "double_click":
		case "triple_click": {
			u = "click";
			const { button: t, count: i } = CLICK_ACTIONS[r.action];
			const o = normalizeModifiers(r.modifiers, e);
			d = {
				...s,
				...l ?? windowPointArgs(n, r, a, r, "click"),
				button: t,
				count: i,
				...o.length ? { modifier: o } : {},
				...c
			};
			break;
		}
		case "left_click_drag": {
			if (l) throw new Error("COMPUTER_UNSUPPORTED_ACTION: cua-driver drag has no element target");
			u = "drag";
			const e = windowPointArgs(n, r, a, {
				x: r.fromX,
				y: r.fromY
			}, "drag start");
			const t = windowPointArgs(n, r, a, r, "drag end");
			d = {
				...s,
				from_x: e.x,
				from_y: e.y,
				to_x: t.x,
				to_y: t.y,
				...e.from_zoom || t.from_zoom ? { from_zoom: true } : {},
				...r.durationMs === void 0 ? {} : { duration_ms: Math.min(1e4, r.durationMs) },
				...c
			};
			break;
		}
		case "left_mouse_down":
		case "left_mouse_up": {
			const t = r.action === "left_mouse_down";
			if (e !== "linux") throw new Error(`COMPUTER_UNSUPPORTED_ACTION: ${r.action} is Linux-only`);
			if (l || r.deliveryMode === "foreground") throw new Error(`COMPUTER_UNSUPPORTED_ACTION: ${r.action} supports only background window pixels`);
			u = t ? "mouse_button_down" : "mouse_button_up";
			d = {
				...s,
				...t ? {
					...windowPointArgs(n, r, a, r, "mouse down"),
					button: "left"
				} : optionalTarget("mouse up")
			};
			break;
		}
		case "scroll":
			if (!r.scrollDirection) throw new Error("COMPUTER_INVALID_REQUEST: scrollDirection is required for scroll");
			if (normalizeModifiers(r.modifiers, e).length) throw new Error("COMPUTER_UNSUPPORTED_ACTION: modifier-held scroll is unsupported by cua-driver");
			u = "scroll";
			d = {
				...s,
				...optionalTarget("scroll"),
				direction: r.scrollDirection,
				by: "line",
				amount: Math.min(50, r.scrollAmount ?? 3),
				...c
			};
			break;
		case "type":
			if (!r.text) throw new Error("COMPUTER_INVALID_REQUEST: text is required for type");
			u = "type_text";
			d = {
				...s,
				...optionalTarget("type"),
				text: r.text,
				...c
			};
			break;
		case "key": {
			const t = parseKeyChord(r.keys, e);
			u = "press_key";
			d = {
				...s,
				...optionalTarget("key"),
				...t,
				...c
			};
			break;
		}
		default: throw new Error(`COMPUTER_UNSUPPORTED_ACTION: ${r.action}`);
	}
	const f = await callWindowTool(t, n, u, d, i);
	return JSON.stringify(actionEnvelope(f));
}
async function handleWindowAct(e, t, n, r, i, a, o) {
	const s = i;
	if (CUA_TARGETED_ACTION_NAMES.has(s.action) && (s.windowRef || s.elementRef)) return await handleTargetedAct(e, t, n, s, o);
	if (CUA_WIRE_ACTION_NAMES.includes(s.action)) return await a(e, t, n, i, o);
	const c = await handleRecordingAct(t, r.recording, r.resources, s, o);
	if (c !== void 0) return c;
	const l = r.resources;
	switch (s.action) {
		case "get_browser_state": {
			verifyGeneration(n, t.generation);
			if (s.windowRef) {
				const e = resolveWindowRef(n, s.windowRef);
				const r = await callWindowTool(t, n, "get_browser_state", {
					pid: e.pid,
					window_id: e.windowId
				}, o);
				return JSON.stringify(browserBinding(r, n, s.windowRef));
			}
			const e = browserTarget(t, n, s);
			const r = s.snapshotFormat ?? "dom_refs_v1";
			if (r === "dom_refs_v1" && (s.elementRef || s.query || s.continuation)) throw new Error("COMPUTER_INVALID_REQUEST: elementRef, query, and continuation require snapshotFormat=semantic_v2");
			const i = browserElement(n, s, e);
			const a = await callWindowTool(t, n, "get_browser_state", {
				target_id: e.targetId,
				tab_id: e.tabId,
				snapshot_format: r,
				include_screenshot: s.includeScreenshot ?? true,
				...i ? { scope_ref: i } : {},
				...s.query ? { query: s.query } : {},
				...s.continuation ? { continuation: s.continuation } : {}
			}, o);
			return JSON.stringify(browserObservation(a, n, e));
		}
		case "browser_prepare": {
			const { target: e } = requireWindowTarget(t, n, s);
			const r = s.profile ?? "isolated_new";
			if (r === "isolated_named" && !s.profileName) throw new Error("COMPUTER_INVALID_REQUEST: profileName is required for an isolated_named browser profile");
			if (r === "isolated_new" && s.profileName) throw new Error("COMPUTER_INVALID_REQUEST: profileName is valid only for an isolated_named browser profile");
			const i = await callWindowTool(t, n, "browser_prepare", {
				pid: e.pid,
				allow_launch: true,
				profile: {
					mode: r,
					...s.profileName ? { name: s.profileName } : {}
				}
			}, o);
			return JSON.stringify(browserToolEnvelope(i, "browser_prepare"));
		}
		case "browser_navigate":
		case "browser_click":
		case "browser_type":
		case "browser_pointer": {
			const e = browserTarget(t, n, s);
			const r = {
				target_id: e.targetId,
				tab_id: e.tabId
			};
			if (s.action === "browser_navigate") r.url = s.url;
			else if (s.action === "browser_type") Object.assign(r, {
				ref: browserElement(n, s, e),
				text: s.text,
				...s.mode ? { mode: s.mode } : {},
				...s.replace !== void 0 ? { replace: s.replace } : {}
			});
			else {
				resolveBrowserObservation(n, s.observationId, e.browserRef, e.pageRef);
				const t = browserElement(n, s, e);
				if (s.action === "browser_pointer") {
					const t = browserElement(n, s, e, s.destinationElementRef);
					Object.assign(r, {
						action: s.pointerAction,
						...t ? { destination_ref: t } : {},
						...s.toX !== void 0 ? { to_x: s.toX } : {},
						...s.toY !== void 0 ? { to_y: s.toY } : {},
						...s.deltaX !== void 0 ? { delta_x: s.deltaX } : {},
						...s.deltaY !== void 0 ? { delta_y: s.deltaY } : {}
					});
				}
				Object.assign(r, {
					...t ? { ref: t } : {},
					...s.x !== void 0 ? { x: s.x } : {},
					...s.y !== void 0 ? { y: s.y } : {},
					...s.inputRoute ? { input_route: s.inputRoute } : {}
				});
			}
			const i = await callWindowTool(t, n, s.action, r, o);
			if (s.action === "browser_navigate") invalidateBrowserObservation(n);
			return JSON.stringify(browserToolEnvelope(i, s.action));
		}
		case "browser_dialog": {
			const e = browserTarget(t, n, s);
			const r = s.dialogAction === "inspect" ? void 0 : resolveDialogRef(n, s.dialogRef, e.browserRef, e.pageRef);
			const i = await callWindowTool(t, n, "browser_dialog", {
				target_id: e.targetId,
				tab_id: e.tabId,
				action: s.dialogAction,
				...r ? { dialog_id: r } : {},
				...s.promptText !== void 0 ? { prompt_text: s.promptText } : {},
				...s.deliveryMode ? { delivery_mode: s.deliveryMode } : {}
			}, o);
			if (s.dialogAction !== "inspect") n.dialog = void 0;
			return JSON.stringify(browserDialogEnvelope(i, n, e));
		}
		case "browser_set_input_files":
		case "browser_download": {
			const e = browserTarget(t, n, s);
			const r = browserElement(n, s, e);
			const i = s.action === "browser_download" ? await l.createDirectory("browser-download") : void 0;
			const a = i ? { destination_root: i.path } : { files: await l.resolveFiles(s.resourceHandles ?? []) };
			let c;
			try {
				c = await callWindowTool(t, n, s.action, {
					target_id: e.targetId,
					tab_id: e.tabId,
					ref: r,
					...a
				}, o);
			} catch (e) {
				if (i) await l.discard(i.handle).catch(() => {});
				o?.throwIfAborted();
				throw new Error(`COMPUTER_DRIVER_ERROR: ${s.action} failed; inspect node logs and resource state before retrying`, { cause: e });
			}
			const u = browserToolEnvelope(c, s.action);
			if (!i) return JSON.stringify(u);
			const d = await l.captureFiles(i.handle);
			return JSON.stringify({
				...u,
				details: {
					...u.details,
					resourceHandle: i.handle,
					fileResourceHandles: d
				}
			});
		}
		case "list_apps": {
			const e = await callWindowTool(t, n, "list_apps", {}, o);
			n.apps = /* @__PURE__ */ new Map();
			const r = projectedToolDetails(e, "list_apps");
			return JSON.stringify({
				ok: true,
				details: projectApps(n, r.apps)
			});
		}
		case "list_windows": {
			const e = await callWindowTool(t, n, "list_windows", {}, o);
			const r = projectedToolDetails(e, "list_windows");
			return JSON.stringify({
				ok: true,
				details: projectWindows(n, nativeWindows(r.windows))
			});
		}
		case "get_accessibility_tree": {
			if (s.windowRef || s.query || s.depth !== void 0 || s.maxElements) throw new Error("COMPUTER_UNSUPPORTED_ACTION: CUA Driver exposes get_accessibility_tree only as unfiltered desktop discovery; use get_window_state for a window tree");
			const e = await callWindowTool(t, n, "get_accessibility_tree", {}, o);
			const r = projectedToolDetails(e, "get_accessibility_tree");
			return JSON.stringify({
				ok: true,
				details: {
					...projectWindows(n, nativeWindows(r.windows)),
					...projectProcesses(r.processes)
				}
			});
		}
		case "get_cursor_position": {
			const e = await t.getCursorPosition(o);
			return JSON.stringify({
				ok: true,
				details: projectedToolDetails(e, "get_cursor_position")
			});
		}
		case "get_window_state": {
			verifyGeneration(n, t.generation);
			const e = resolveWindowRef(n, s.windowRef);
			const r = await callWindowTool(t, n, "get_window_state", {
				pid: e.pid,
				window_id: e.windowId,
				tree_format: "elements",
				include_screenshot: s.includeScreenshot ?? true,
				max_elements: s.maxElements ?? 2e3,
				...s.depth !== void 0 ? { max_depth: Math.max(1, s.depth) } : {},
				...s.query ? { query: s.query } : {}
			}, o);
			return JSON.stringify(windowObservation(r, n, s.windowRef));
		}
		case "launch_app": {
			verifyGeneration(n, t.generation);
			const r = s.app;
			const i = n.apps?.get(r);
			if (!i) throw new Error("COMPUTER_STALE_OBSERVATION: refresh list_apps and retry");
			const a = await callWindowTool(t, n, "launch_app", e !== "darwin" && i.launchPath ? { launch_path: i.launchPath } : i.bundleId ? { bundle_id: i.bundleId } : { name: i.name }, o);
			const c = projectedToolDetails(a, "launch_app");
			return JSON.stringify({
				...actionEnvelope(a),
				details: {
					app: projectApps(n, [c]).apps,
					...projectWindows(n, nativeWindows(c.windows))
				}
			});
		}
		case "kill_app": {
			verifyGeneration(n, t.generation);
			const e = s.app;
			const r = n.apps?.get(e);
			if (!r?.pid) throw new Error("COMPUTER_INVALID_REQUEST: kill_app requires a running app reference from list_apps");
			const i = await callWindowTool(t, n, "kill_app", { pid: r.pid }, o);
			return JSON.stringify(actionEnvelope(i, { app: e }));
		}
		case "bring_to_front":
		case "set_value":
		case "invoke_menu":
		case "zoom": {
			const { ref: e, target: r } = requireWindowTarget(t, n, s);
			const i = {
				pid: r.pid,
				window_id: r.windowId
			};
			if ((s.action === "set_value" || s.action === "invoke_menu") && s.deliveryMode === "foreground") throw new Error(`COMPUTER_UNSUPPORTED_ACTION: cua-driver ${s.action} is background accessibility delivery`);
			if (s.action === "set_value") {
				const t = elementArgs(n, s, e);
				if (!t) throw new Error("COMPUTER_INVALID_REQUEST: elementRef is required for set_value");
				Object.assign(i, t, { value: s.value });
			} else if (s.action === "invoke_menu") i.path = s.path;
			else if (s.action === "zoom") {
				resolveObservation(n, s.observationId, e);
				Object.assign(i, {
					x1: s.x1,
					y1: s.y1,
					x2: s.x2,
					y2: s.y2
				});
			}
			const a = await callWindowTool(t, n, s.action, i, o);
			return JSON.stringify(s.action === "zoom" ? windowObservation(a, n, e, { fromZoom: true }) : actionEnvelope(a));
		}
		case "escalate_scope": {
			const e = await t.getSessionState(o);
			adoptGeneration(n, t.generation);
			return JSON.stringify({
				ok: true,
				details: {
					captureScope: e.captureScope,
					effectiveScope: e.effectiveScope,
					desktopUnlocked: e.desktopUnlocked
				}
			});
		}
		default: throw new Error(`COMPUTER_UNSUPPORTED_ACTION: ${s.action}`);
	}
}
//#endregion
//#region extensions/cua-computer/src/commands.ts
const AVAILABILITY_POLL_MS = 5e3;
const MAX_IMAGE_PIXELS = 4e7;
const CUA_DRIVER_ENDPOINT_ENV = "OPENCLAW_CUA_DRIVER_ENDPOINT";
const CuaDriverEndpointSchema = strictObject({
	v: literal(1),
	socketPath: string(),
	binaryPath: string()
});
const DesktopStateSchema = object({
	platform: string().min(1),
	display: string().min(1),
	screenshot_width: number().int().positive(),
	screenshot_height: number().int().positive(),
	screen_width: number().int().positive(),
	screen_height: number().int().positive(),
	scale_factor: number().positive()
});
const ScreenSizeSchema = object({
	width: number().int().positive(),
	height: number().int().positive(),
	scale_factor: number().positive()
});
function resolveMacOsMcpEndpoint(e) {
	const t = e[CUA_DRIVER_ENDPOINT_ENV];
	if (!t || Buffer.byteLength(t, "utf8") > 4096) return;
	try {
		const e = JSON.parse(t);
		const n = CuaDriverEndpointSchema.safeParse(e);
		if (!n.success) return;
		const { socketPath: r, binaryPath: i } = n.data;
		if (r.includes("\0") || i.includes("\0") || !path.isAbsolute(r) || !path.isAbsolute(i)) return;
		fs.accessSync(i, fs.constants.X_OK);
		return {
			socketPath: r,
			binaryPath: i
		};
	} catch {
		return;
	}
}
function assertPrimaryDisplay(e) {
	if (e !== void 0 && e !== 0) throw new Error("COMPUTER_UNSUPPORTED_DISPLAY: cua-driver controls only the primary display (screenIndex 0)");
}
function assertToolSuccess(e, t) {
	if (e.isError) {
		const n = e.errorCode ? `COMPUTER_REFUSED_${e.errorCode}` : "COMPUTER_DRIVER_ERROR";
		throw new Error(`${n}: ${e.text || `${t} failed`}`);
	}
	return e;
}
function structuredContent(e, t) {
	return projectedToolDetails(assertToolSuccess(e, t), t);
}
function desktopGeometry(e) {
	const t = DesktopStateSchema.safeParse(structuredContent(e, "get_desktop_state"));
	if (!t.success) throw new Error("COMPUTER_DRIVER_ERROR: invalid get_desktop_state geometry");
	return {
		platform: t.data.platform,
		display: t.data.display,
		screenWidth: t.data.screen_width,
		screenHeight: t.data.screen_height,
		scaleFactor: t.data.scale_factor,
		screenshotWidth: t.data.screenshot_width,
		screenshotHeight: t.data.screenshot_height
	};
}
function desktopPng(e) {
	const t = e.images.find((e) => e.mimeType === "image/png");
	if (!t) throw new Error("COMPUTER_DRIVER_ERROR: get_desktop_state returned no PNG image");
	const n = canonicalizeBase64(t.dataBase64);
	if (!n) throw new Error("COMPUTER_DRIVER_ERROR: get_desktop_state returned malformed PNG base64");
	return Buffer.from(n, "base64");
}
function screenSize(e) {
	const t = ScreenSizeSchema.safeParse(structuredContent(e, "get_screen_size"));
	if (!t.success) throw new Error("COMPUTER_DRIVER_ERROR: invalid get_screen_size geometry");
	return {
		width: t.data.width,
		height: t.data.height,
		scaleFactor: t.data.scale_factor
	};
}
function resolveImageCommand(e, t) {
	const n = process.platform === "win32" && !path.extname(e) ? [
		e,
		`${e}.exe`,
		`${e}.cmd`
	] : [e];
	for (const e of (t.PATH ?? "").split(path.delimiter).filter(Boolean)) for (const t of n) {
		const n = path.resolve(e, t);
		try {
			fs.accessSync(n, fs.constants.X_OK);
			return n;
		} catch {}
	}
	return null;
}
function createImageProcessor(e) {
	return createRastermill({
		execution: "auto",
		limits: {
			inputPixels: MAX_IMAGE_PIXELS,
			outputPixels: MAX_IMAGE_PIXELS
		},
		temp: {
			rootDir: resolvePreferredOpenClawTmpDir(),
			prefix: "openclaw-cua-computer-"
		},
		commandResolver: (t) => resolveImageCommand(t, e)
	});
}
function clickArgs(e, t, n, r, i) {
	const a = scalePoint(t, n.x, n.y, n.action);
	if (normalizeModifiers(n.modifiers, e).length > 0) throw new Error("COMPUTER_UNSUPPORTED_ACTION: modifier-held desktop clicks are unsupported by cua-driver");
	return {
		...a,
		button: {
			left: ClickButton.Left,
			right: ClickButton.Right,
			middle: ClickButton.Middle
		}[r],
		count: i
	};
}
async function currentFrame(e, t, n, r) {
	const i = screenSize(await e.getScreenSize(r));
	if (e.generation !== t.generation) {
		t.lastFrame = void 0;
		throw new Error("COMPUTER_STALE_FRAME: the computer driver reconnected; take a new screenshot");
	}
	return verifyFrame(t, n.displayFrameId, i, n.refWidth);
}
async function handleDesktopAct(e, t, n, r, i) {
	if (!CUA_WIRE_ACTION_NAMES.includes(r.action)) throw new Error(`COMPUTER_UNSUPPORTED_ACTION: ${r.action}`);
	const a = r;
	assertPrimaryDisplay(a.screenIndex);
	if (a.action === "hold_key") throw new Error("COMPUTER_UNSUPPORTED_ACTION: hold_key; this driver supports key taps only");
	if (a.action === "left_mouse_down" || a.action === "left_mouse_up") throw new Error(`COMPUTER_UNSUPPORTED_ACTION: ${a.action}; ` + (e === "linux" ? "requires a background window pixel target with windowRef and observationId" : "held mouse buttons are unavailable on this platform"));
	let o;
	switch (a.action) {
		case "type":
			if (!a.text) throw new Error("COMPUTER_INVALID_REQUEST: text is required for type");
			o = assertToolSuccess(await t.typeText(a.text, i), "type_text");
			break;
		case "key": {
			const n = parseKeyChord(a.keys, e);
			o = assertToolSuccess(await t.pressKey(n, i), "press_key");
			break;
		}
		case "scroll": {
			if (!a.scrollDirection) throw new Error("COMPUTER_INVALID_REQUEST: scrollDirection is required for scroll");
			if (normalizeModifiers(a.modifiers, e).length > 0) throw new Error("COMPUTER_UNSUPPORTED_ACTION: modifier-held scroll is unsupported by cua-driver");
			const r = await currentFrame(t, n, a, i);
			const s = scalePoint(r, a.x, a.y, a.action);
			const c = {
				up: ScrollDirection.Up,
				down: ScrollDirection.Down,
				left: ScrollDirection.Left,
				right: ScrollDirection.Right
			}[a.scrollDirection];
			o = assertToolSuccess(await t.scroll({
				direction: c,
				amount: BigInt(Math.min(50, a.scrollAmount ?? 3)),
				...s
			}, i), "scroll");
			break;
		}
		default: {
			const r = await currentFrame(t, n, a, i);
			switch (a.action) {
				case "left_click":
				case "right_click":
				case "middle_click":
				case "double_click":
				case "triple_click": {
					const { button: n, count: s } = CLICK_ACTIONS[a.action];
					o = assertToolSuccess(await t.click(clickArgs(e, r, a, n, s), i), "click");
					break;
				}
				case "mouse_move": {
					const e = scalePoint(r, a.x, a.y, a.action);
					o = assertToolSuccess(await t.moveCursor(e, i), "move_cursor");
					break;
				}
				case "left_click_drag": {
					const e = scalePoint(r, a.fromX, a.fromY, "drag start");
					const n = scalePoint(r, a.x, a.y, "drag end");
					o = assertToolSuccess(await t.drag({
						fromX: e.x,
						fromY: e.y,
						toX: n.x,
						toY: n.y,
						...a.durationMs === void 0 ? {} : { durationMs: BigInt(Math.min(1e4, a.durationMs)) }
					}, i), "drag");
					break;
				}
				default: throw new Error("COMPUTER_UNSUPPORTED_ACTION: unknown action");
			}
		}
	}
	return JSON.stringify(actionEnvelope(o, {
		scope: "desktop",
		...a.deliveryMode ? { deliveryModeApplicable: false } : {}
	}));
}
function createCuaComputerProvider() {
	const e = process.platform;
	const t = process.env;
	const n = e === "darwin" ? resolveMacOsMcpEndpoint(t) : void 0;
	const r = `cua-computer-v2:${randomUUID()}`;
	let i;
	let a;
	let o = false;
	const s = n ? () => createCuaMcpDriver({
		...n,
		env: t
	}) : createCuaDriver;
	const availabilityDriver = () => {
		if (o) throw new Error("COMPUTER_DRIVER_UNAVAILABLE: cua-computer is stopping");
		return i ??= s();
	};
	const disposeAvailabilityDriver = () => {
		o = true;
		return a ??= Promise.resolve().then(async () => {
			const e = i;
			i = void 0;
			await e?.dispose();
		});
	};
	const c = createImageProcessor(t);
	const l = e === "linux" || e === "win32" || n !== void 0;
	const isAvailable = () => n !== void 0 || l && availabilityDriver().isAvailable();
	return {
		id: "cua-computer",
		label: "CUA Computer",
		capabilities: () => ({
			contractVersion: 2,
			provider: {
				id: "cua-computer",
				label: "CUA Computer",
				generation: r
			},
			actions: platformActions(e),
			targets: [
				"screen",
				"window",
				"element",
				"browser"
			],
			deliveryModes: ["background", "foreground"],
			observations: [
				"image",
				"accessibility",
				"browser"
			],
			features: {
				recording: true,
				agentCursor: false,
				multiDisplay: false
			}
		}),
		isAvailable,
		prepare: async () => {
			if (l && n === void 0 && !o) await availabilityDriver().prepareAvailability?.();
		},
		watchAvailability: (e, t) => {
			let n = isAvailable();
			const r = setInterval(() => {
				availabilityDriver().resetAvailabilityCache();
				const e = isAvailable();
				if (e !== n) {
					n = e;
					t();
				}
			}, AVAILABILITY_POLL_MS);
			r.unref?.();
			return () => {
				clearInterval(r);
				return disposeAvailabilityDriver();
			};
		},
		openExecution: async () => {
			if (o) throw new Error("COMPUTER_DRIVER_UNAVAILABLE: cua-computer is stopping");
			const t = s();
			const n = createLazyCuaExecutionResources();
			const r = {
				resources: n,
				recording: {}
			};
			const i = new KeyedAsyncQueue();
			const a = { generation: t.generation };
			const prepareExecution = async (e) => {
				const assertAuthority = () => {
					e?.throwIfAborted();
					assertOpen();
				};
				assertAuthority();
				try {
					await t.prepareExecution?.(e, assertAuthority);
				} finally {
					if (a.generation !== t.generation) r.recording.active = void 0;
				}
				assertAuthority();
				adoptGeneration(a, t.generation);
			};
			let u = false;
			let d;
			const assertOpen = () => {
				if (u) throw new Error("COMPUTER_DRIVER_UNAVAILABLE: provider execution is closing");
				if (!l) throw new Error(e === "darwin" ? `COMPUTER_DRIVER_UNAVAILABLE: cua-computer requires app-provided ${CUA_DRIVER_ENDPOINT_ENV}` : "COMPUTER_DRIVER_UNAVAILABLE: cua-computer supports macOS, Windows, and Linux");
			};
			return {
				snapshot: async (n, r) => await i.enqueue("execution", async () => {
					assertOpen();
					const i = parseScreenSnapshotParamsJSON(n);
					assertPrimaryDisplay(i.screenIndex);
					await prepareExecution(r);
					const o = i.format ?? "jpeg";
					const s = i.maxWidth ?? (o === "png" ? 900 : 1600);
					const l = Math.min(1, Math.max(.05, i.quality ?? .72));
					const u = await t.getDesktopState(r);
					const d = desktopGeometry(u);
					if (e !== "darwin" && (d.screenWidth !== d.screenshotWidth || d.screenHeight !== d.screenshotHeight)) throw new Error("COMPUTER_UNSUPPORTED_DISPLAY: cua-driver reported capture and screen geometry in different pixel spaces");
					const f = desktopPng(u);
					let p = f;
					let m = d.screenshotWidth;
					let h = d.screenshotHeight;
					if (o === "jpeg" || Math.max(m, h) > s) {
						const e = await c.encode(f, {
							format: o,
							...o === "jpeg" ? { quality: Math.round(l * 100) } : {},
							resize: {
								maxSide: s,
								enlarge: false
							}
						});
						p = e.data;
						m = e.width;
						h = e.height;
					}
					adoptGeneration(a, t.generation);
					const g = issueFrame(a, d, {
						width: m,
						height: h,
						referenceWidth: s
					});
					return JSON.stringify({
						format: o,
						base64: p.toString("base64"),
						displayFrameId: g,
						screenIndex: 0,
						width: m,
						height: h
					});
				}),
				act: async (n, o) => await i.enqueue("execution", async () => {
					assertOpen();
					const i = parseComputerActParamsJSON(n);
					await prepareExecution(o);
					return await handleWindowAct(e, t, a, r, i, handleDesktopAct, o);
				}),
				close: async (e) => {
					if (d) return await d;
					u = true;
					d = i.enqueue("execution", async () => {
						let i;
						try {
							await closeRecordingExecution({
								driver: t,
								state: r.recording,
								resources: n,
								reason: e
							});
						} catch (e) {
							i = e;
						}
						await n.dispose(e !== "completion").catch((e) => {
							i ??= e;
						});
						await t.dispose().catch((e) => {
							i ??= e;
						});
						if (i) throw i instanceof Error ? i : new Error("CUA Computer cleanup failed", { cause: i });
					});
					return await d;
				}
			};
		}
	};
}
//#endregion
//#region extensions/cua-computer/index.ts
const COMPUTER_ACT_COMMAND = "computer.act";
const HIGH_RISK_FAMILIES = /* @__PURE__ */ new Map([
	["kill_app", "process_termination"],
	["browser_navigate", "browser_navigation"],
	["browser_download", "browser_download"],
	["browser_set_input_files", "browser_file_input"],
	["start_recording", "recording_start"],
	["replay_trajectory", "recording_replay"],
	["escalate_scope", "desktop_scope_escalation"]
]);
const OBSERVATION_ACTIONS = /* @__PURE__ */ new Set([
	"list_apps",
	"list_windows",
	"get_accessibility_tree",
	"get_cursor_position",
	"get_window_state",
	"zoom",
	"get_browser_state",
	"get_recording_state"
]);
const CuaComputerConfigSchema = strictObject({ driverPath: string().optional() });
var cua_computer_default = definePluginEntry({
	id: "cua-computer",
	name: "CUA Computer",
	description: "Experimental CUA Driver computer control for macOS, Windows, and Linux node hosts.",
	configSchema: buildPluginConfigSchema(CuaComputerConfigSchema),
	register(e) {
		const t = CuaComputerConfigSchema.safeParse(e.pluginConfig ?? {});
		if (!t.success) throw new Error(`Invalid cua-computer plugin config: ${t.error.issues[0]?.message ?? "invalid config"}`);
		e.registerNodeInvokePolicy({
			commands: [COMPUTER_ACT_COMMAND],
			dangerous: true,
			classifyRisk: ({ command: e, params: t }) => {
				if (e !== COMPUTER_ACT_COMMAND) throw new Error("unsupported CUA Computer node command");
				if (isRecord(t) && t.action === "__close_execution") return {
					level: "ordinary",
					family: "execution_lifecycle"
				};
				const n = JSON.stringify(t);
				if (n === void 0) throw new Error("computer action arguments are not serializable");
				const r = parseComputerActParamsJSON(n);
				const i = HIGH_RISK_FAMILIES.get(r.action);
				if (i) return {
					level: "high",
					family: i
				};
				if (r.action === "browser_dialog" && "dialogAction" in r && r.dialogAction === "inspect") return {
					level: "ordinary",
					family: "observation"
				};
				return {
					level: "ordinary",
					family: OBSERVATION_ACTIONS.has(r.action) ? "observation" : "input"
				};
			},
			handle: async (e) => {
				if (!e.risk) return {
					ok: false,
					code: "COMPUTER_RISK_UNCLASSIFIED",
					message: "computer.act arguments were not classified before dispatch"
				};
				return await e.invokeNode();
			}
		});
		if (process.platform !== "darwin" && createNormalizedPluginsConfig(e.config.plugins).entries[e.id]?.enabled !== true) return;
		registerCuaDriverDoctorChecks();
		const n = verifyInstalledCuaDriverArtifacts();
		if (!n.ok) e.logger.error(n.diagnostic);
		registerComputerUseProvider(e, createCuaComputerProvider());
	}
});
//#endregion
export { cua_computer_default as default };