UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

4,630 lines • 211 kB
import { l as normalizeOptionalString } from "../../string-coerce-CCIiB4H7.mjs";
import { l as isRecord, u as isStringArray } from "../../record-coerce-CVPuDqcc.mjs";
import { n as coerceErrorMessage, p as toErrorObject } from "../../error-coercion-hDrHOSGy.mjs";
import { r as truncateUtf16Safe } from "../../utf16-slice-CuDyEXgS.mjs";
import { s as redactSensitiveText, u as redactToolPayloadText } from "../../redact-Mj7pppxC.mjs";
import { d as sleepWithAbort, o as racePromiseWithAbortSignal } from "../../src-BPmQBLJp.mjs";
import { n as resolvePreferredOpenClawTmpDir } from "../../tmp-openclaw-dir-Bf0oU1Cn.mjs";
import { t as createSubsystemLogger } from "../../subsystem-BHJiy01V.mjs";
import { t as truncateUtf8Prefix } from "../../utf8-truncate-BH7Ecfuh.mjs";
import { r as textResult } from "../../tool-results-CcV0sxnb.mjs";
import { m as readToolStringParam, u as readPositiveIntegerParam } from "../../common-njQNtpnW.mjs";
import { n as shellEscapeBackslash } from "../../shell-quote-DeRN90_2.mjs";
import { t as WorkerProviderError } from "../../capability-provider.types-qOxhG-PT.mjs";
import { n as resolveCrabboxBinary } from "../../crabbox-binary-B74dQeJ2.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import "../../logging-core-DxpUImpb.mjs";
import "../../text-utility-runtime-Ds8jsG0J.mjs";
import "../../retry-runtime-DOUvdfOa.mjs";
import "../../time-runtime-DoAwjF0T.mjs";
import "../../error-runtime-BM740gJj.mjs";
import { t as definePluginEntry } from "../../plugin-entry-CiJdaHtx.mjs";
import { a as createRemoteShellSandboxBackend, p as createRemoteShellSandboxSession } from "../../ssh-backend-BMXCHhdQ.mjs";
import { a as getSandboxBackendWorkdirResolver, o as registerSandboxBackend } from "../../backend-CR3qLOqu.mjs";
import { t as SandboxRuntimeRetiredError } from "../../provisioning-error-19aGMcmG.mjs";
import "../../sandbox-Cq8qURAL.mjs";
import { n as withSetupSecretEgress } from "../../secret-egress-runtime-DG90n7eD.mjs";
import "../../temp-path-CW7QMeae.mjs";
import "../../param-readers-CVZN1591.mjs";
import { a as isUnrecognizedLease, c as runCrabboxCommand, d as stopCrabboxLease, f as runCrabboxProcess, i as isFixedLeaseIdUnsupported, l as runCrabboxCommandWithCoordinatorRetry, n as crabboxCommandOutput, o as leaseRunArgs, s as parseCrabboxJson, t as crabboxCommandError, u as sanitizeCrabboxNotice } from "../../crabbox-worker-command-C6ki_dj6.mjs";
import { S as resolveCrabboxWarmImageCaptureTimeoutMs, _ as resolveCrabboxLifecycleTimeoutMs, b as resolveCrabboxProvisionCallTimeoutMs, c as CRABBOX_SETUP_TIMEOUT_MS, d as WARM_IMAGE_COMMAND_ROUND_TRIP_TIMEOUT_MS, f as WARM_IMAGE_COMMAND_TIMEOUT_MS, g as resolveCrabboxDestroyTimeoutMs, h as resolveCrabboxCheckpointCaptureTimeoutMs, i as CRABBOX_LIFECYCLE_TIMEOUT_MS, m as countCrabboxProvisionSetupPhases, n as CRABBOX_DESKTOP_WARMUP_TIMEOUT_MS, o as CRABBOX_NODE_ENROLLMENT_DIAGNOSTIC_TIMEOUT_MS, p as WARM_IMAGE_NATIVE_WAIT_TIMEOUT_MS, r as CRABBOX_HEARTBEAT_TIMEOUT_MS, s as CRABBOX_PROJECT_PREPARATION_TIMEOUT_MS, u as CRABBOX_WARMUP_TIMEOUT_MS, v as resolveCrabboxNodeEnrollmentTimeoutMs, x as resolveCrabboxReadyPollIntervalMs, y as resolveCrabboxProvisionBaseTimeoutMs } from "../../crabbox-worker-timeouts-pTo1LSUy.mjs";
import { a as isCrabboxVersionAtLeast, n as CRABBOX_NONBLOCKING_CAPTURE_VERSION, r as ensureManagedCrabboxBinary } from "../../crabbox-managed-binary-Bk-CKD5f.mjs";
import { _ as resolveCrabboxProvisionProfile, a as buildCrabboxAllocationArgs, b as resolveOpenClawRoot, d as parseCrabboxCleanupProfile, f as parseCrabboxDurationMs, g as resolveCrabboxPreparedIdleTimeoutMs, h as resolveCrabboxPreparationTarget, i as assertCrabboxLeaseId, l as operationLeaseId, o as heartbeatIntervalMs, p as parseCrabboxProfile, r as CRABBOX_WORKER_PROVIDER_ID, u as operationSlug, v as resolveCrabboxWarmImageProfile, x as supportsCrabboxProjectPreparation, y as resolveCrabboxWarmImageProfileKey } from "../../crabbox-worker-profile-Ckeez-8x.mjs";
import { a as createCrabboxMachineOptionsResolver, n as assertHetznerDesktopHasManagedCoordinator, t as assertAwsWorkerHasNoInstanceProfile } from "../../crabbox-worker-preflight-6kY6qrGD.mjs";
import { a as assertCrabboxWarmImageReplay, c as isCrabboxCaptureRefusalRetained, d as openCrabboxWarmImageStore, f as projectCrabboxWarmImage, g as withCrabboxWarmImageGeneration, h as withCrabboxWarmImageDisplayFacts, i as assertCrabboxWarmImagePreparation, m as sameCrabboxWarmImageGeneration, o as clearCrabboxWarmImageCapture, r as assertCrabboxWarmImageMigrationReady, s as crabboxCaptureUnsupportedSentence, t as CrabboxWarmImageRequestError } from "../../crabbox-worker-warm-image-store-gdxNPzY8.mjs";
import { a as crabboxWarmImageRecoveryHint, i as crabboxWarmImageHoldingLeaseIds, l as withoutCrabboxWarmImageOperation, o as isCrabboxWarmImageHeld, r as crabboxWarmImageCaptureStatus, t as CRABBOX_WARM_IMAGE_WAIT_HINT } from "../../crabbox-worker-warm-image-records-DeuyTta3.mjs";
import fs from "node:fs";
import { fileURLToPath } from "node:url";
import { join } from "node:path";
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { isDeepStrictEqual } from "node:util";
import { setTimeout as setTimeout$1 } from "node:timers/promises";
//#region extensions/crabbox/src/crabbox-sandbox-lease.ts
const CRABBOX_SANDBOX_LEASE_ID_PATTERN = /^cbx_[a-f0-9]{12}$/u;
/** The sandbox registry persists this generation before Crabbox provisioning starts. */
function mintCrabboxSandboxLeaseId() {
	return `cbx_${randomBytes(6).toString("hex")}`;
}
//#endregion
//#region extensions/crabbox/src/crabbox-sandbox-backend.ts
const CRABBOX_SANDBOX_BACKEND_ID = "crabbox";
const CRABBOX_SANDBOX_SLUG = "openclaw-sandbox";
const READY_STATES = /* @__PURE__ */ new Set([
	"started",
	"running",
	"ready"
]);
function configLabel(e) {
	return `${e.provider ?? "configured"}/${e.class ?? "default"}`;
}
function createClient(e) {
	return {
		binary: resolveCrabboxBinary({
			explicit: e.pluginConfig.binary,
			openclawRoot: e.openclawRoot
		}),
		pluginConfig: e.pluginConfig
	};
}
async function runCrabbox(e, t, n, r, i) {
	e.acquisition ??= ensureManagedCrabboxBinary({
		binary: e.binary,
		cwd: r
	}).then(({ binary: t }) => {
		e.binary = t;
	}).catch((t) => {
		e.acquisition = void 0;
		throw t;
	});
	await e.acquisition;
	try {
		return await runCrabboxProcess([e.binary, ...n], {
			...r ? { cwd: r } : {},
			killProcessTree: true,
			maxOutputBytes: 65536,
			timeoutMs: i
		});
	} catch (e) {
		throw new Error(`Crabbox sandbox ${t} could not start: ${coerceErrorMessage(e)}`, { cause: e });
	}
}
function assertCrabboxSuccess(e, t) {
	if (t.code !== 0) {
		const n = e === "warmup" ? `exit ${String(t.code)}` : t.stderr.trim() || t.stdout.trim() || `exit ${String(t.code)}`;
		throw new Error(`Crabbox sandbox ${e} failed: ${n}`);
	}
}
async function requireExecSupport(e, t) {
	e.execSupport ??= runCrabbox(e, "exec capability", [
		"exec",
		"--check",
		...e.pluginConfig.provider ? ["--provider", e.pluginConfig.provider] : []
	], t, 1e4).then((e) => {
		assertCrabboxSuccess("exec capability", e);
		const t = JSON.parse(e.stdout);
		if (!isRecord(t) || t.execution !== true || t.currentRepoStop !== true) throw new Error("The configured provider lacks repository-owned execution or cleanup.");
	}).catch((t) => {
		e.execSupport = void 0;
		throw new Error("Crabbox sandbox requires a build with claim-owned `crabbox exec` and repository-scoped cleanup for the configured provider. Upgrade Crabbox or select a supported provider before provisioning.", { cause: t });
	});
	await e.execSupport;
}
function inspectLease(e, t, n) {
	return runCrabbox(e, "inspect", [
		"inspect",
		"--id",
		t,
		"--json"
	], n, CRABBOX_LIFECYCLE_TIMEOUT_MS);
}
function parseLeaseInspection(e, t) {
	assertCrabboxSuccess("inspect", e);
	let n;
	try {
		n = JSON.parse(e.stdout);
	} catch {
		throw new Error(`Crabbox sandbox inspect returned invalid JSON for ${t}`);
	}
	if (!isRecord(n) || n.id !== t) throw new Error(`Crabbox sandbox inspect did not return the requested lease ${t}`);
	const r = typeof n.state === "string" ? n.state : "";
	return {
		state: r,
		ready: n.ready === true || READY_STATES.has(r)
	};
}
async function ensureLease(e, t, n) {
	await requireExecSupport(e, n);
	const r = e.pluginConfig;
	assertCrabboxSuccess("warmup", await runCrabbox(e, "warmup", [
		"warmup",
		...r.provider ? ["--provider", r.provider] : [],
		...r.class ? ["--class", r.class] : [],
		"--lease-id",
		t,
		"--slug",
		CRABBOX_SANDBOX_SLUG,
		"--keep",
		...r.ttl ? ["--ttl", r.ttl] : [],
		...r.idleTimeout ? ["--idle-timeout", r.idleTimeout] : []
	], n, 6e5));
	const i = parseLeaseInspection(await inspectLease(e, t, n), t);
	if (!i.ready) throw new Error(`Crabbox lease ${t} is not ready (state=${i.state || "unknown"})`);
}
async function stopLease(e, t, n) {
	assertCrabboxSuccess("stop", await runCrabbox(e, "stop", [
		"stop",
		"--current-repo",
		"--id",
		t
	], n, 3e5));
}
function createCrabboxSandboxBackendFactory(e) {
	const t = createClient(e);
	return async (e) => {
		if ((e.cfg.docker.binds?.length ?? 0) > 0) throw new Error("Crabbox sandbox backend does not support sandbox.docker.binds.");
		const { runtimeId: n, assertRuntimeCurrent: r, workspaceDir: i } = e;
		if (!CRABBOX_SANDBOX_LEASE_ID_PATTERN.test(n)) throw new Error("Crabbox sandbox requires a fixed lease runtime ID.");
		r();
		await requireExecSupport(t, i);
		r();
		try {
			await ensureLease(t, n, i);
		} catch (e) {
			if ((await inspectLease(t, n, i).then((e) => parseLeaseInspection(e, n)).catch(() => void 0))?.state === "released") throw new SandboxRuntimeRetiredError(n);
			throw e;
		}
		r();
		return createRemoteShellSandboxBackend(e, {
			backendId: CRABBOX_SANDBOX_BACKEND_ID,
			runtimeId: n,
			configLabel: configLabel(t.pluginConfig),
			configLabelKind: "Lease",
			createSession: async () => createRemoteShellSandboxSession({
				assertCurrent: r,
				buildCommand: ({ remoteCommand: e, tty: r }) => ({
					argv: [
						t.binary,
						"exec",
						"--id",
						n,
						...r ? ["--pty"] : [],
						"--",
						"/bin/sh",
						"-c",
						e
					],
					env: process.env,
					cwd: i
				})
			})
		});
	};
}
function createCrabboxSandboxBackendManager(e) {
	const t = createClient(e);
	const n = configLabel(t.pluginConfig);
	return {
		async describeRuntime({ entry: e }) {
			if (!CRABBOX_SANDBOX_LEASE_ID_PATTERN.test(e.containerName)) return {
				running: false,
				configLabelMatch: false
			};
			const r = await inspectLease(t, e.containerName, e.workspaceDir);
			if (isUnrecognizedLease(r, e.containerName, "inspect")) return {
				running: false,
				actualConfigLabel: e.image,
				configLabelMatch: false
			};
			return {
				running: parseLeaseInspection(r, e.containerName).ready,
				actualConfigLabel: e.image,
				configLabelMatch: e.image === n
			};
		},
		async removeRuntime({ entry: e }) {
			if (!CRABBOX_SANDBOX_LEASE_ID_PATTERN.test(e.containerName)) throw new Error(`Crabbox sandbox runtime ${e.containerName} is not a fixed lease id`);
			try {
				await stopLease(t, e.containerName, e.workspaceDir);
			} catch (n) {
				if (e.runtimeState !== "removing-pending" || !e.workspaceDir) throw n;
				await ensureLease(t, e.containerName, e.workspaceDir);
				await stopLease(t, e.containerName, e.workspaceDir);
			}
		}
	};
}
function resolveCrabboxSandboxWorkdir(e) {
	const t = getSandboxBackendWorkdirResolver("ssh");
	if (!t) throw new Error("Crabbox sandbox backend requires the shared remote workspace layout");
	return t({
		...e,
		cfg: {
			...e.cfg,
			backend: "ssh"
		}
	});
}
//#endregion
//#region extensions/crabbox/src/crabbox-sandbox-config.ts
const FIELDS = [
	"provider",
	"class",
	"binary",
	"ttl",
	"idleTimeout"
];
/** Returns undefined when no sandbox block is configured; the backend then stays unregistered. */
function resolveCrabboxSandboxConfig(e) {
	const t = e?.sandbox;
	if (t === void 0) return;
	if (!isRecord(t)) throw new Error("Crabbox sandbox must be an object.");
	const n = {};
	for (const e of FIELDS) {
		const r = t[e];
		if (r === void 0) continue;
		const i = normalizeOptionalString(r);
		if (!i) throw new Error(`Crabbox sandbox.${e} must be a non-empty string.`);
		n[e] = i;
	}
	return n;
}
//#endregion
//#region extensions/crabbox/src/crabbox-tool.ts
function crabboxEnvironmentText(e) {
	return `Environment: ${e.status} (${e.worker.state}).${e.worker.error ? `\n${e.worker.error}` : ""}`;
}
function crabboxExecResult(e) {
	const t = e.process;
	const n = [
		t ? `Process ${t.processId}: ${t.state}.` + (t.state === "running" ? " App readiness has not been checked." : "") : e.code === 0 && e.termination === "exit" ? "Command completed." : "Command failed.",
		`exit code: ${e.code}; termination: ${e.termination}; signal: ${e.signal}; killed: ${e.killed}`,
		`Environment: ${e.environmentId}; workspace: ${e.workspaceDir}`
	];
	if (e.stdoutTruncatedBytes) n.push(`stdout truncated: ${e.stdoutTruncatedBytes} bytes`);
	if (e.stderrTruncatedBytes) n.push(`stderr truncated: ${e.stderrTruncatedBytes} bytes`);
	if (e.outputLimitExceeded) n.push(`Output limit exceeded${e.outputErrorStream ? ` (${e.outputErrorStream})` : ""}.`);
	return textResult(`${n.join("\n")}\n\nstdout:\n${e.stdout}\nstderr:\n${e.stderr}`, e);
}
const CRABBOX_TOOL_PARAMETERS = {
	type: "object",
	additionalProperties: false,
	required: ["action"],
	properties: {
		action: {
			type: "string",
			enum: [
				"profiles",
				"create",
				"status",
				"exec",
				"process_status",
				"process_stop",
				"stop"
			]
		},
		profileId: {
			type: "string",
			description: "create: configured Crabbox profile; optional when only one is configured."
		},
		environmentId: {
			type: "string",
			description: "Target attached to this conversation. Omit to use its current attachment."
		},
		os: {
			type: "string",
			description: "create: an operating system advertised by the profile."
		},
		machineClass: {
			type: "string",
			description: "create: a machine class advertised by the profile."
		},
		presentation: {
			type: "string",
			enum: ["desktop", "portal"],
			description: "create: for open-and-show requests, open the native Desktop or web Portal sidebar immediately with provisioning progress. Omit when no viewer was requested."
		},
		argv: {
			type: "array",
			items: { type: "string" },
			minItems: 1,
			maxItems: 128,
			description: "exec: executable and arguments, run in the remote workspace. Use a shell explicitly for shell syntax."
		},
		input: {
			type: "string",
			description: "exec: bounded standard input for the command."
		},
		timeoutMs: {
			type: "integer",
			minimum: 1,
			maximum: 6e5,
			description: "exec: foreground command timeout."
		},
		background: {
			type: "boolean",
			description: "exec: start an owned app/server that survives this turn. Returns processId."
		},
		processId: {
			type: "string",
			description: "process_status/process_stop: identifier returned by background exec."
		}
	}
};
function operationId(e, t, n) {
	return createHash("sha256").update(JSON.stringify(n ? [
		e,
		t,
		n
	] : [e, t])).digest("hex");
}
function createCrabboxTool({ context: e, gateway: t }) {
	const config = () => e.getRuntimeConfig?.() ?? e.runtimeConfig ?? e.config;
	const profiles = () => Object.entries(config()?.cloudWorkers?.profiles ?? {}).filter(([, e]) => e.provider === "crabbox");
	if (e.sandboxed || !e.sessionKey || !e.sessionId || profiles().length === 0) return null;
	const n = e.sessionId;
	return {
		name: "crabbox",
		label: "Crabbox",
		description: "Create and use a temporary Crabbox attached to this conversation while keeping the agent and its main workspace in place. profiles lists configured machines and desktop capability; create reuses the current attachment. For open-and-show requests, pass presentation=desktop for native apps or portal for web apps to open the sidebar during provisioning. exec runs commands there, with background=true for persistent apps and servers. Inspect/stop owned processes or stop the entire box. Desktop-enabled profiles support native app viewing and computer use. Read the crabbox-apps skill for the complete workflow.",
		parameters: CRABBOX_TOOL_PARAMETERS,
		resultContentSource: "network",
		async execute(e, r, i, a) {
			i?.throwIfAborted();
			const o = r;
			const s = readToolStringParam(o, "action", { required: true });
			const c = readToolStringParam(o, "environmentId");
			const l = c ? { environmentId: c } : {};
			const reportProgress = (e) => {
				try {
					a?.({
						...textResult(e, {
							action: s,
							status: "running"
						}),
						progress: {
							text: e,
							visibility: "channel",
							privacy: "public"
						}
					});
				} catch {}
			};
			if (s === "profiles") {
				const e = await t.request("environments.list", { projection: "profiles" });
				const n = new Map(profiles());
				const r = [];
				for (const t of e.profiles ?? []) if (t.providerId === "crabbox") r.push({
					...t,
					desktop: n.get(t.id)?.settings?.desktop === true
				});
				const i = r.map((e) => {
					const t = [
						e.desktop ? "desktop enabled" : "desktop disabled",
						...e.operatingSystems?.map((e) => e.disabledReason ? `${e.id} (unavailable: ${e.disabledReason})` : e.id) ?? [],
						...e.machines?.map((e) => `${e.id}${e.os ? ` (${e.os})` : ""}`) ?? []
					];
					return `- ${e.id}: ${t.join("; ")}`;
				});
				return textResult(i.length ? `Crabbox profiles:\n${i.join("\n")}\nUse action=create with a profileId to create or reuse a Crabbox.` : "No Crabbox profiles are currently available.", { profiles: r });
			}
			if (s === "create") {
				const r = profiles();
				const i = readToolStringParam(o, "profileId") ?? (r.length === 1 ? r[0]?.[0] : void 0);
				if (!i || !r.some(([e]) => e === i)) throw new Error("Choose a configured Crabbox profile using action=profiles, then pass its profileId to create.");
				const a = readToolStringParam(o, "os");
				const s = readToolStringParam(o, "machineClass");
				const c = readToolStringParam(o, "presentation");
				if (c !== void 0 && c !== "desktop" && c !== "portal") throw new Error("presentation must be desktop or portal");
				reportProgress("Requesting a Crabbox for this conversation (create or reuse)…");
				const l = await t.request("environments.session.status", {}, {
					timeoutMs: 3e4,
					scopes: ["operator.read"]
				});
				const u = await t.request("environments.session.create", {
					profileId: i,
					idempotencyKey: operationId(n, e, l.attachment?.environmentId),
					...a ? { os: a } : {},
					...s ? { machineClass: s } : {},
					...c ? { presentation: c } : {}
				}, {
					timeoutMs: 12e5,
					scopes: ["operator.admin"]
				});
				return textResult(`${u.reused ? "Reusing" : "Created"} Crabbox ${u.attachment.environmentId}.\n${crabboxEnvironmentText(u.environment)}`, u);
			}
			if (s === "status") {
				const e = await t.request("environments.session.status", l, {
					timeoutMs: 3e4,
					scopes: ["operator.read"]
				});
				if (!e.attachment) return textResult("No Crabbox is attached to this conversation. Use action=create to create one.", e);
				return textResult(`Crabbox ${e.attachment.environmentId} ${e.closed ? "is no longer attached. Use action=create to create one." : "is attached to this conversation."}\n${crabboxEnvironmentText(e.environment)}`, e);
			}
			if (s === "stop") {
				reportProgress("Requesting Crabbox shutdown…");
				const e = await t.request("environments.session.destroy", l, {
					timeoutMs: 6e5,
					scopes: ["operator.admin"]
				});
				return textResult(e.environment ? `Crabbox ${e.environment.id} is detached from this conversation.\n${crabboxEnvironmentText(e.environment)}` : "No Crabbox is attached to this conversation. Nothing to stop.", e);
			}
			if (s === "exec") {
				const r = o.argv;
				if (!isStringArray(r) || r.length === 0) throw new Error("argv must be a non-empty array of strings");
				const i = readToolStringParam(o, "input", {
					trim: false,
					allowEmpty: true
				});
				const a = readPositiveIntegerParam(o, "timeoutMs", { max: 6e5 });
				if (o.background !== void 0 && typeof o.background !== "boolean") throw new Error("background must be a boolean");
				const s = o.background === true ? `app-${operationId(n, e)}` : void 0;
				reportProgress(o.background === true ? "Requesting a background process in the attached Crabbox…" : "Requesting command execution in the attached Crabbox…");
				try {
					return crabboxExecResult(await t.request("environments.session.exec", {
						...l,
						action: o.background === true ? "start" : "run",
						argv: r,
						...i === void 0 ? {} : { input: i },
						...a === void 0 ? {} : { timeoutMs: a },
						...s ? { processId: s } : {}
					}, {
						timeoutMs: 18e5 + (a ?? 12e4) + 15e3,
						scopes: ["operator.admin"]
					}));
				} catch (e) {
					if (!s) throw e;
					throw new Error(`${coerceErrorMessage(e)}\nBackground processId: ${s}. Check process_status for this ID before retrying; a failed response does not prove that the app failed to start.`, { cause: e });
				}
			}
			if (s === "process_status" || s === "process_stop") {
				const e = readToolStringParam(o, "processId", { required: true });
				reportProgress(s === "process_stop" ? "Requesting background process shutdown…" : "Checking the Crabbox background process…");
				return crabboxExecResult(await t.request("environments.session.exec", {
					...l,
					action: s === "process_status" ? "status" : "stop",
					processId: e
				}, {
					timeoutMs: 6e4,
					scopes: ["operator.admin"]
				}));
			}
			throw new Error(`Unknown Crabbox action: ${s}`);
		}
	};
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-inspect.ts
function timestamp(e) {
	if (typeof e !== "string" || !e.trim()) return;
	const t = /^\d+$/u.test(e) ? Number(e) * 1e3 : Date.parse(e);
	return Number.isFinite(t) && t > 0 ? t : void 0;
}
function parseCrabboxLeaseLifetime(e) {
	const t = isRecord(e.leasePolicy) ? e.leasePolicy : {};
	const n = isRecord(e.labels) ? e.labels : {};
	const positiveSeconds = (e) => {
		const t = typeof e === "string" ? Number(e) : e;
		return typeof t === "number" && Number.isFinite(t) && t > 0 ? t * 1e3 : void 0;
	};
	const r = {
		expiresAtMs: timestamp(e.expiresAt),
		idleTimeoutMs: parseCrabboxDurationMs(e.idleTimeout) ?? positiveSeconds(e.idleTimeoutSeconds),
		maxLifetimeMs: parseCrabboxDurationMs(e.maxLifetime) ?? positiveSeconds(t.maxTTLSeconds),
		runtimeExtension: typeof t.runtimeExtension === "boolean" ? t.runtimeExtension : void 0,
		extension: normalizeOptionalString(t.extension),
		createdAtMs: timestamp(e.createdAt) ?? timestamp(n.created_at),
		ttlMs: positiveSeconds(e.ttlSeconds) ?? positiveSeconds(n.ttl_secs),
		policyNotice: typeof e.policyNotice === "string" ? sanitizeCrabboxNotice(e.policyNotice) : void 0
	};
	return Object.fromEntries(Object.entries(r).filter(([, e]) => e !== void 0));
}
function parseInspectJson(e) {
	const t = parseCrabboxJson(e, "inspect");
	if (!isRecord(t)) throw new Error("Crabbox inspect returned invalid JSON");
	const n = normalizeOptionalString(t.id);
	const r = normalizeOptionalString(t.state)?.toLowerCase();
	if (!n || !/^\S{1,128}$/u.test(n) || !r) throw new Error("Crabbox inspect returned an invalid lease identity or state");
	if (t.ready !== void 0 && typeof t.ready !== "boolean") throw new Error("Crabbox inspect returned an invalid ready state");
	if (t.sshUser !== void 0 && typeof t.sshUser !== "string") throw new Error("Crabbox inspect returned an invalid SSH user");
	const i = normalizeOptionalString(t.sshUser);
	if (t.tailscale !== void 0 && !isRecord(t.tailscale)) throw new Error("Crabbox inspect returned invalid Tailscale state");
	const a = t.tailscale !== void 0;
	let o;
	if (t.providerMetadata !== void 0) {
		if (!isRecord(t.providerMetadata)) throw new Error("Crabbox inspect returned invalid provider metadata");
		const e = t.providerMetadata.instanceProfileAttached;
		if (e !== void 0 && typeof e !== "boolean") throw new Error("Crabbox inspect returned invalid AWS instance profile metadata");
		o = e;
	}
	const s = normalizeOptionalString(t.failureError);
	const c = parseCrabboxLeaseLifetime(t);
	return {
		id: n,
		state: r,
		tailscaleEnabled: a,
		...Object.keys(c).length ? { lifetime: c } : {},
		...s ? { failureError: truncateUtf16Safe(redactSensitiveText(s).replace(/\s+/gu, " "), 512) } : {},
		...o !== void 0 ? { awsInstanceProfileAttached: o } : {},
		...typeof t.ready === "boolean" ? { ready: t.ready } : {},
		...i && i !== "<token>" ? { sshUser: i } : {}
	};
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-heartbeat.ts
function providerDoesNotSupportHeartbeat(e) {
	const t = `${e.stderr}\n${e.stdout}`;
	return e.termination === "exit" && e.code === 2 && /\bprovider=\S+ does not support lease heartbeat\b/iu.test(t);
}
function createCrabboxHeartbeatManager(e) {
	const t = /* @__PURE__ */ new Map();
	let n = false;
	const isCurrent = (e) => !n && t.get(e.id) === e && !e.controller.signal.aborted;
	const warn = (t, n, r = true) => e.warn(t.provider === "azure-sandbox" ? `${n}; Sandbox idle activity is not being refreshed; ${r ? "OpenClaw will retry automatically; " : ""}save your work if failures persist` : `${n}; cloud worker machines may be reaped after ${t.idleTimeout} of coordinator-idle time`);
	const observe = (t, n) => {
		t.lifetime = {
			...t.lifetime,
			...n
		};
		const r = t.lifetime.idleTimeoutMs;
		if (r !== void 0) {
			t.idleTimeout = `${r}ms`;
			t.heartbeatIntervalMs = heartbeatIntervalMs(r);
			t.heartbeatTimeoutMs = Math.min(CRABBOX_HEARTBEAT_TIMEOUT_MS, Math.max(1, Math.floor(r / 2)));
		}
		const i = n?.policyNotice;
		if (i && i !== t.notice) {
			e.warn(`Crabbox worker lease ${t.id}: ${i}`);
			t.notice = i;
		}
	};
	const schedule = (e, t = e.heartbeatIntervalMs) => {
		if (!isCurrent(e)) return;
		e.timer = setTimeout(() => {
			e.timer = void 0;
			e.pending = heartbeat(e);
		}, t);
		e.timer.unref?.();
	};
	const heartbeat = async (e) => {
		if (!isCurrent(e)) return;
		let t;
		const n = Date.now();
		try {
			t = await runCrabboxCommandWithCoordinatorRetry({
				action: "heartbeat",
				args: [
					"heartbeat",
					"--provider",
					e.provider,
					"--id",
					e.id,
					...e.provider === "azure-sandbox" ? [] : ["--idle-timeout", e.idleTimeout],
					"--json"
				],
				binary: e.binary,
				signal: e.controller.signal,
				timeoutMs: e.heartbeatTimeoutMs
			});
		} catch (t) {
			if (isCurrent(e) && !e.failureWarned) {
				e.failureWarned = true;
				warn(e, t instanceof Error ? t.message : "Crabbox heartbeat failed");
			}
			schedule(e);
			return;
		}
		if (!isCurrent(e)) return;
		if (t.termination === "exit" && t.code === 0) {
			try {
				if (t.stdout.trim()) {
					const n = parseInspectJson(t.stdout);
					if (n.id !== e.id) throw new Error("Crabbox heartbeat returned a different lease id");
					observe(e, n.lifetime);
				}
				const n = sanitizeCrabboxNotice(t.stderr);
				if (n) observe(e, { policyNotice: n });
			} catch (t) {
				if (!e.failureWarned) warn(e, t instanceof Error ? t.message : "Invalid Crabbox heartbeat response");
				e.failureWarned = true;
				schedule(e);
				return;
			}
			e.failureWarned = false;
			schedule(e);
			return;
		}
		if (providerDoesNotSupportHeartbeat(t)) {
			warn(e, `Crabbox provider ${e.provider} does not support heartbeat for worker lease ${e.id}`, false);
			return;
		}
		if (!e.failureWarned) {
			e.failureWarned = true;
			const r = crabboxCommandError("heartbeat", t).message;
			warn(e, r.replace("(timeout)", `(timeout after ${Date.now() - n} ms)`));
		}
		schedule(e);
	};
	const stop = async (e) => {
		const n = t.get(e);
		if (!n) return;
		n.controller.abort();
		clearTimeout(n.timer);
		try {
			await n.pending;
		} finally {
			if (t.get(e) === n) t.delete(e);
		}
	};
	return {
		start(e) {
			if (n) return;
			const r = t.get(e.id);
			if (r) {
				if (isCurrent(r)) {
					const t = r.heartbeatIntervalMs;
					observe(r, e.lifetime);
					if (r.timer && r.heartbeatIntervalMs < t) {
						clearTimeout(r.timer);
						schedule(r);
					}
				}
				return;
			}
			const i = {
				...e,
				failureWarned: false,
				controller: new AbortController()
			};
			observe(i, e.lifetime);
			t.set(e.id, i);
			schedule(i, 0);
		},
		stop,
		async dispose() {
			n = true;
			await Promise.all([...t.keys()].map(stop));
		}
	};
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-desktop-macos.ts
const CRABBOX_MACOS_APP_PATH = "/Applications/OpenClawCloudWorker.app";
const CRABBOX_MACOS_HOST_VERSION = 1;
const MACOS_DESKTOP_ROOT = "/var/db/crabbox/openclaw-workers";
const MACOS_CDP_PORT = 9222;
function crabboxMacosDesktopDirectory(e) {
	assertCrabboxLeaseId(e);
	return `${MACOS_DESKTOP_ROOT}/${e}`;
}
function desktopRoot(e, t) {
	if (typeof t !== "string" || !/^[A-Za-z0-9_][A-Za-z0-9._-]{0,62}$/u.test(t)) throw new Error("Crabbox macOS desktop requires its inspected SSH account username");
	return crabboxMacosDesktopDirectory(e);
}
function requireGuiAccount(e) {
	return `worker_user=$(/usr/bin/id -un)
worker_uid=$(/usr/bin/id -u)
[ "$worker_user" = ${shellEscapeBackslash(e)} ] && [ "$worker_uid" -ne 0 ] || { echo 'Cloud desktop must run as its inspected macOS account' >&2; exit 1; }
[ "$(/usr/bin/stat -f '%u' /dev/console)" = "$worker_uid" ] || { echo 'Sign in to the worker macOS account before dispatching a desktop session' >&2; exit 1; }
/bin/launchctl print "gui/$worker_uid" >/dev/null 2>&1 || { echo 'The worker macOS GUI session is unavailable; sign in before dispatch' >&2; exit 1; }`;
}
/** SSH needs root to adopt another audit session; GUI commands still run as the lease account. */
function createCrabboxMacosGuiLaunchScript() {
	return `set -euo pipefail
worker_uid=$(/usr/bin/id -u)
worker_user=$(/usr/bin/id -un)
[ "$worker_uid" -ne 0 ] && [ "$(/usr/bin/stat -f '%u' /dev/console)" = "$worker_uid" ] || { echo 'The worker account no longer owns the macOS desktop' >&2; exit 1; }
worker_home=$(/usr/bin/dscl . -read "/Users/$worker_user" NFSHomeDirectory | sed 's/^NFSHomeDirectory: //')
worker_tmp=$(/usr/bin/getconf DARWIN_USER_TEMP_DIR)
case "$worker_home:$worker_tmp" in /*:/*) ;; *) echo 'The worker account home or temporary directory is unavailable' >&2; exit 1 ;; esac
exec /usr/bin/sudo -n -- /bin/launchctl asuser "$worker_uid" /usr/bin/sudo -n -u "#$worker_uid" -- /usr/bin/env -i HOME="$worker_home" USER="$worker_user" LOGNAME="$worker_user" PATH="$PATH" TMPDIR="$worker_tmp" LC_ALL=C /bin/sh -c 'cd -- "$1"; shift; exec "$@"' openclaw-gui "$PWD" "$@"`;
}
function browserLauncher$2(e, t) {
	return `#!/bin/bash
set -euo pipefail
[ "$#" -eq 0 ] || { echo 'Cloud browser launcher does not accept arguments' >&2; exit 64; }
${requireGuiAccount(t)}
exec /bin/bash -c ${shellEscapeBackslash(createCrabboxMacosGuiLaunchScript())} openclaw-gui /usr/bin/lockf -k -t 25 ${shellEscapeBackslash(`${e}/browser-profile/.launch.lock`)} /bin/bash <<'CRABBOX_BROWSER_LOCKED'
set -euo pipefail
profile=${shellEscapeBackslash(`${e}/browser-profile`)}
browser='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
[ -x "$browser" ] || { echo 'Install Google Chrome in the macOS worker image' >&2; exit 1; }
cdp_url=http://127.0.0.1:${MACOS_CDP_PORT}/json/version
owned_browser() {
  [ -f "$profile/browser.pid" ] || return 1
  browser_pid=$(cat "$profile/browser.pid")
  case "$browser_pid" in ''|*[!0-9]*) return 1 ;; esac
  [ "$(/bin/ps -p "$browser_pid" -o uid= | tr -d ' ')" = "$(/usr/bin/id -u)" ] || return 1
  browser_command=$(/bin/ps -ww -p "$browser_pid" -o command=) || return 1
  case "$browser_command" in "$browser "*) ;; *) return 1 ;; esac
  case "$browser_command" in *"--user-data-dir=$profile "*) ;; *) return 1 ;; esac
}
cdp_ready() { /usr/bin/curl --fail --silent --max-time 1 "$cdp_url" >/dev/null; }
owned_cdp() {
  owned_browser || return 1
  /usr/sbin/lsof -nP -a -p "$browser_pid" -iTCP:${MACOS_CDP_PORT} -sTCP:LISTEN -Fn | grep -Fx 'n127.0.0.1:${MACOS_CDP_PORT}' >/dev/null
}
if cdp_ready; then
  owned_cdp || { echo 'CDP port belongs to another browser; reprovision the desktop worker' >&2; exit 1; }
  exit 0
fi
if ! owned_browser; then
  /usr/bin/nohup "$browser" "--user-data-dir=$profile" --remote-debugging-address=127.0.0.1 --remote-debugging-port=${MACOS_CDP_PORT} --no-first-run --no-default-browser-check about:blank >>"$profile/launch.log" 2>&1 </dev/null &
  printf '%s\\n' "$!" >"$profile/browser.pid"
fi
for ((attempt=0; attempt<40; attempt++)); do
  if cdp_ready; then owned_cdp && exit 0; fi
  sleep 0.5
done
echo 'Cloud browser CDP did not become ready within 20 seconds' >&2
exit 1
CRABBOX_BROWSER_LOCKED`;
}
function terminalLauncher$1(e) {
	return `#!/bin/bash
set -euo pipefail
[ "$#" -eq 0 ] || { echo 'Cloud terminal launcher does not accept arguments' >&2; exit 64; }
${requireGuiAccount(e)}
exec /bin/bash -c ${shellEscapeBackslash(createCrabboxMacosGuiLaunchScript())} openclaw-gui /usr/bin/open -a /System/Applications/Utilities/Terminal.app`;
}
function createCrabboxMacosDesktopSetup(e, t, n) {
	const r = desktopRoot(e, n);
	if (!/^[A-Za-z0-9+/]+={0,2}$/u.test(t)) throw new Error("Crabbox macOS desktop wallpaper must be base64");
	return `set +x
set -euo pipefail
umask 077
${requireGuiAccount(n)}
app=${shellEscapeBackslash(CRABBOX_MACOS_APP_PATH)}
plist="$app/Contents/Info.plist"
[ -x "$app/Contents/MacOS/OpenClaw" ] && [ -x "$app/Contents/Resources/cua-driver" ] || { echo 'Install the signed OpenClaw Cloud Worker app with its bundled CUA driver in the worker image' >&2; exit 1; }
/usr/bin/codesign --verify --deep --strict "$app" || { echo 'The macOS worker app signature is invalid; replace the image app' >&2; exit 1; }
signature=$(/usr/bin/codesign -dv --verbose=4 "$app" 2>&1)
grep -q '^Authority=Developer ID Application:' <<<"$signature" || { echo 'The macOS worker app needs a Developer ID Application signature' >&2; exit 1; }
grep -Eq '^TeamIdentifier=[A-Z0-9]{10}$' <<<"$signature" || { echo 'The macOS worker app signing team is missing' >&2; exit 1; }
[ "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$plist")" = OpenClaw ] || { echo 'The worker app executable identity is invalid' >&2; exit 1; }
bundle_id=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$plist")
[ "$bundle_id" = ai.openclaw.cloud-worker ] || { echo 'The desktop requires the separate OpenClaw Cloud Worker app identity' >&2; exit 1; }
[ "$(/usr/libexec/PlistBuddy -c 'Print :OpenClawCloudWorkerHostVersion' "$plist")" = ${CRABBOX_MACOS_HOST_VERSION} ] || { echo 'Update the signed OpenClaw Cloud Worker app in the worker image for cloud desktop support' >&2; exit 1; }
worker_group=$(/usr/bin/id -gn)
worker_root=${shellEscapeBackslash(r)}
sudo -n -- /usr/bin/install -d -o root -g wheel -m 0755 ${shellEscapeBackslash(MACOS_DESKTOP_ROOT)}
sudo -n -- /usr/bin/install -d -o "$worker_user" -g "$worker_group" -m 0700 "$worker_root"
[ ! -L "$worker_root" ] && [ "$(/usr/bin/stat -f '%u' "$worker_root")" = "$worker_uid" ] || { echo 'The cloud desktop directory is not owned by its worker account' >&2; exit 1; }
setup_dir=$(mktemp -d "$worker_root/.setup.XXXXXX")
trap 'rm -rf -- "$setup_dir"' EXIT
sudo -n -- /bin/cat /var/db/crabbox/vnc.password >"$setup_dir/vnc.password"
[ -s "$setup_dir/vnc.password" ] || { echo 'The managed macOS desktop credential is missing' >&2; exit 1; }
chmod 0600 "$setup_dir/vnc.password"
mv -f "$setup_dir/vnc.password" "$worker_root/vnc.password"
cat >"$setup_dir/browser" <<'CRABBOX_BROWSER_LAUNCHER'
${browserLauncher$2(r, n)}
CRABBOX_BROWSER_LAUNCHER
cat >"$setup_dir/terminal" <<'CRABBOX_TERMINAL_LAUNCHER'
${terminalLauncher$1(n)}
CRABBOX_TERMINAL_LAUNCHER
chmod 0700 "$setup_dir/browser" "$setup_dir/terminal"
mv -f "$setup_dir/browser" "$worker_root/browser"
mv -f "$setup_dir/terminal" "$worker_root/terminal"
mkdir -p "$worker_root/browser-profile"
chmod 0700 "$worker_root/browser-profile"
printf '%s' ${shellEscapeBackslash(t)} | /usr/bin/base64 -D >"$setup_dir/wallpaper.png"
mv -f "$setup_dir/wallpaper.png" "$worker_root/wallpaper.png"
"$worker_root/browser"`;
}
function createCrabboxMacosDesktopEndpoint(e, t) {
	const n = desktopRoot(e, t);
	return {
		protocol: "rfb",
		port: 5900,
		allowsResize: false,
		username: t,
		passwordFilePath: `${n}/vnc.password`,
		apps: [{
			id: "browser",
			executablePath: `${n}/browser`,
			cdpPort: MACOS_CDP_PORT
		}, {
			id: "terminal",
			executablePath: `${n}/terminal`
		}]
	};
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-desktop-windows.ts
const WINDOWS_POWERSHELL = String.raw`C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`;
const WINDOWS_DESKTOP_ROOT = String.raw`C:\ProgramData\OpenClaw\cloud-workers`;
const WINDOWS_CDP_PORT = 9222;
function quote$1(e) {
	return `'${e.replaceAll("'", "''")}'`;
}
function desktopDirectory(e) {
	return `${WINDOWS_DESKTOP_ROOT}\\${e}\\desktop`;
}
const sessionIdentity = String.raw`
if (-not ('OpenClawActiveSession' -as [type])) {
  Add-Type @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
public static class OpenClawActiveSession {
  [StructLayout(LayoutKind.Sequential)] struct Session { public int id; public IntPtr name; public int state; }
  [DllImport("wtsapi32.dll", SetLastError=true)] static extern bool WTSEnumerateSessions(IntPtr server, int reserved, int version, out IntPtr sessions, out int count);
  [DllImport("wtsapi32.dll")] static extern void WTSFreeMemory(IntPtr memory);
  [DllImport("kernel32.dll")] static extern uint WTSGetActiveConsoleSessionId();
  [DllImport("wtsapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool WTSQuerySessionInformation(IntPtr server, int session, int kind, out IntPtr value, out int bytes);
  static string Read(int session, int kind) {
    IntPtr value; int bytes;
    if (!WTSQuerySessionInformation(IntPtr.Zero, session, kind, out value, out bytes)) throw new Win32Exception(Marshal.GetLastWin32Error());
    try { return Marshal.PtrToStringUni(value); } finally { WTSFreeMemory(value); }
  }
  public static string UserSid(int session) { return new System.Security.Principal.NTAccount(Read(session, 7), Read(session, 5)).Translate(typeof(System.Security.Principal.SecurityIdentifier)).Value; }
  public static int Get() {
    IntPtr sessions; int count;
    if (!WTSEnumerateSessions(IntPtr.Zero, 0, 1, out sessions, out count)) throw new Win32Exception(Marshal.GetLastWin32Error());
    int fallback = -1; uint console = WTSGetActiveConsoleSessionId();
    try {
      int size = Marshal.SizeOf(typeof(Session));
      for (int index = 0; index < count; index++) {
        Session session = (Session)Marshal.PtrToStructure(IntPtr.Add(sessions, index * size), typeof(Session));
        if (session.state != 0) continue;
        if (session.id == (int)console) return session.id;
        if (fallback < 0) fallback = session.id;
      }
    } finally { WTSFreeMemory(sessions); }
    return fallback;
  }
}
'@
}
$consoleSession = [OpenClawActiveSession]::Get()
if ($consoleSession -le 0) { throw 'Cloud worker requires an active interactive Windows session; reprovision the desktop worker' }
$userSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
if ($userSid -ne [OpenClawActiveSession]::UserSid($consoleSession)) { throw 'Cloud worker active Windows account changed; reprovision the desktop worker' }
`;
function interactiveScript(e, t = "") {
	const n = `param([string]$ResultPath)
$ErrorActionPreference = 'Stop'
$expectedSid = '__CRABBOX_EXPECTED_SID__'
$expectedSession = __CRABBOX_EXPECTED_SESSION__
$cancelPath = $ResultPath + '.cancel'
function Assert-LaunchCurrent {
  if (Test-Path -LiteralPath $cancelPath) { throw 'Cloud desktop launch was cancelled' }
  ${sessionIdentity}
  if ($userSid -ne $expectedSid -or $consoleSession -ne $expectedSession -or [Diagnostics.Process]::GetCurrentProcess().SessionId -ne $expectedSession) { throw 'Cloud desktop active account or session changed; reprovision the worker' }
}
function Write-LaunchResult($value) {
  $temporary = $ResultPath + '.tmp'
  [IO.File]::WriteAllText($temporary, ($value | ConvertTo-Json -Compress), [Text.UTF8Encoding]::new($false))
  Move-Item -LiteralPath $temporary -Destination $ResultPath
}
try {
  Assert-LaunchCurrent
  ${e}
} catch {
  Write-LaunchResult @{ error = $_.Exception.Message }
  exit 1
}`;
	return `$ErrorActionPreference = 'Stop'
${sessionIdentity}
$service = Get-Service -Name CrabboxDesktopLauncher -ErrorAction Stop
if ($service.Status -ne 'Running') { throw 'CrabboxDesktopLauncher is not running; reprovision the Windows desktop worker' }
$base = 'C:\\ProgramData\\crabbox'
$identity = 'desktop-launch-' + [Guid]::NewGuid().ToString('N')
$scriptPath = Join-Path $base ($identity + '.ps1')
$resultPath = Join-Path $base ($identity + '.result')
$cancelPath = $resultPath + '.cancel'
$request = Join-Path (Join-Path $base 'desktop-launch-requests') ($identity + '.request')
$requestTemporary = $request + '.tmp'
$source = ${quote$1(n)}
${t}
$source = $source.Replace('__CRABBOX_EXPECTED_SID__', $userSid).Replace('__CRABBOX_EXPECTED_SESSION__', [string]$consoleSession)
$settled = $false
try {
  [IO.File]::WriteAllText($scriptPath, $source, [Text.UTF8Encoding]::new($false))
  [IO.File]::WriteAllLines($requestTemporary, @($scriptPath, $resultPath), [Text.UTF8Encoding]::new($false))
  Move-Item -LiteralPath $requestTemporary -Destination $request
  $deadline = [DateTime]::UtcNow.AddSeconds(45)
  while (-not (Test-Path -LiteralPath $resultPath) -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 100 }
  if (-not (Test-Path -LiteralPath $resultPath)) {
    [IO.File]::WriteAllText($cancelPath, 'cancelled')
    Remove-Item -LiteralPath $request -Force -ErrorAction SilentlyContinue
    $deadline = [DateTime]::UtcNow.AddSeconds(10)
    while (-not (Test-Path -LiteralPath $resultPath) -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 100 }
    if (-not (Test-Path -LiteralPath $resultPath)) { throw 'Cloud desktop launch outcome could not be confirmed; release and reprovision the worker' }
  }
  $raw = [IO.File]::ReadAllText($resultPath).Trim()
  $settled = $true
  if ($raw.StartsWith('CRABBOX_DESKTOP_ERROR message=')) { throw [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($raw.Substring('CRABBOX_DESKTOP_ERROR message='.Length))) }
  $result = $raw | ConvertFrom-Json
  if ($result.error) { throw $result.error }
  if (Test-Path -LiteralPath $cancelPath) {
    if ($result.pid) {
      $current = Get-CimInstance Win32_Process -Filter ('ProcessId=' + $result.pid)
      if ($current -and $current.CreationDate.ToUniversalTime().ToString('o') -eq $result.startTime) { Stop-Process -Id $result.pid -Force }
    }
    throw 'Cloud desktop launch was cancelled; release and reprovision the worker'
  }
  Write-Output $raw
} finally {
  Remove-Item -LiteralPath $requestTemporary -Force -ErrorAction SilentlyContinue
  Remove-Item -LiteralPath $request -Force -ErrorAction SilentlyContinue
  if ($settled) { @($scriptPath, $resultPath, $cancelPath) | ForEach-Object { Remove-Item -LiteralPath $_ -Force -ErrorAction SilentlyContinue } }
}`;
}
const vncIdentity = String.raw`
$vncExecutable = 'C:\Program Files\TightVNC\tvnserver.exe'
function Assert-VncProcess($process, [string]$argument, [int]$session, [string]$sid) {
  $command = '^"?' + [regex]::Escape($vncExecutable) + '"?\s+' + [regex]::Escape($argument) + '[ \t]*$'
  if (-not $process -or -not $process.CreationDate -or $process.ExecutablePath -ine $vncExecutable -or $process.CommandLine -notmatch $command -or $process.SessionId -ne $session -or (Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 5).Sid -ne $sid) { throw 'Cloud desktop VNC process identity changed; reprovision the worker' }
}
function Get-WorkerVnc([string]$sid, [int]$session) {
  $listeners = @(Get-NetTCPConnection -LocalPort 5900 -State Listen -ErrorAction SilentlyContinue)
  if (-not $listeners.Count) { return $null }
  $owners = @($listeners.OwningProcess | Sort-Object -Unique)
  if ($owners.Count -ne 1 -or @($listeners | Where-Object { $_.LocalAddress -ne '127.0.0.1' }).Count) { throw 'Cloud desktop VNC requires one worker-owned loopback listener' }
  $process = Get-CimInstance Win32_Process -Filter ('ProcessId=' + $owners[0]) -OperationTimeoutSec 5
  Assert-VncProcess $process '-run' $session $sid
  return $process
}
`;
const prepareVnc = `${vncIdentity}
if (-not (Test-Path -LiteralPath $vncExecutable -PathType Leaf)) { throw 'Crabbox TightVNC is unavailable; reprovision the Windows desktop worker' }
$serviceKey = Get-Item -LiteralPath 'HKLM:\\Software\\TightVNC\\Server'
if (Test-Path -LiteralPath 'HKLM:\\Software\\TightVNC\\Server\\ServiceOnly') { throw 'The Windows image forbids TightVNC application mode; prepare an image that permits interactive VNC' }
$vncSettings = @{ UseVncAuthentication = 1; UseControlAuthentication = 1; RfbPort = 5900; AcceptRfbConnections = 1; AllowLoopback = 1; LoopbackOnly = 1; AcceptHttpConnections = 0; UseD3D = 0; UseMirrorDriver = 0; RemoveWallpaper = 0 }
$credentials = @{}
foreach ($name in @('Password', 'ControlPassword')) {
  $value = $serviceKey.GetValue($name)
  if ($serviceKey.GetValueKind($name) -ne 'Binary' -or $value.Length -ne 8) { throw 'Crabbox VNC credentials are unavailable; reprovision the worker' }
  $credentials[$name] = $value
}
foreach ($name in @('UseVncAuthentication', 'UseControlAuthentication')) {
  if ($serviceKey.GetValueKind($name) -ne 'DWord' -or $serviceKey.GetValue($name) -ne 1) { throw 'Crabbox VNC authentication is not enabled; reprovision the worker' }
}
$vncService = Get-Service -Name tvnserver
$serviceCommand = (Get-ItemProperty -LiteralPath 'HKLM:\\SYSTEM\\CurrentControlSet\\Services\\tvnserver').ImagePath
if ($serviceCommand -notmatch ('^"?' + [regex]::Escape($vncExecutable) + '"?\\s+-service$')) { throw 'Crabbox VNC service executable changed; reprovision the worker' }
if ($vncService.Status -eq 'Running') {
  if (-not ('OpenClawVncService' -as [type])) {
    Add-Type @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
public static class OpenClawVncService {
  [StructLayout(LayoutKind.Sequential)] struct Status { public uint type, state, accepted, error, specificError, checkpoint, waitHint, pid, flags; }
  [DllImport("advapi32.dll", SetLastError=true)] static extern bool QueryServiceStatusEx(IntPtr service, int level, out Status status, int size, out int needed);
  public static uint ProcessId(IntPtr service) { Status status; int needed; if (!QueryServiceStatusEx(service, 0, out status, Marshal.SizeOf(typeof(Status)), out needed)) throw new Win32Exception(Marshal.GetLastWin32Error()); return status.pid; }
}
'@
  }
  $servicePid = [OpenClawVncService]::ProcessId($vncService.ServiceHandle.DangerousGetHandle())
  $serviceProcess = Get-CimInstance Win32_Process -Filter ('ProcessId=' + $servicePid) -OperationTimeoutSec 5
  Assert-VncProcess $serviceProcess '-service' 0 'S-1-5-18'
  $serviceBirth = $serviceProcess.CreationDate
  $listeners = @(Get-NetTCPConnection -LocalPort 5900 -State Listen -ErrorAction SilentlyContinue)
  if (@($listeners | Where-Object { $_.OwningProcess -ne $servicePid }).Count) { throw 'Cloud desktop VNC port belongs to another process' }
  $serviceProcess = Get-CimInstance Win32_Process -Filter ('ProcessId=' + $servicePid) -OperationTimeoutSec 5
  Assert-VncProcess $serviceProcess '-service' 0 'S-1-5-18'
  if ($serviceProcess.CreationDate -ne $serviceBirth -or [OpenClawVncService]::ProcessId($vncService.ServiceHandle.DangerousGetHandle()) -ne $servicePid -or [OpenClawActiveSession]::Get() -ne $consoleSession -or [OpenClawActiveSession]::UserSid($consoleSession) -ne $userSid) { throw 'Cloud desktop changed before VNC service handover' }
  $vncService.Stop()
  $vncService.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped, [TimeSpan]::FromSeconds(15))
} elseif ($vncService.Status -ne 'Stopped') { throw 'Crabbox VNC service is transitioning; reprovision the worker' }
$existingVnc = Get-WorkerVnc $userSid $consoleSession
if ([OpenClawActiveSession]::Get() -ne $consoleSession -or [OpenClawActiveSession]::UserSid($consoleSession) -ne $userSid) { throw 'Cloud desktop changed before VNC configuration' }
Set-Service -Name tvnserver -StartupType Disabled
$userKeyPath = 'Registry::HKEY_USERS\\' + $userSid + '\\Software\\TightVNC\\Server'
if (-not $existingVnc) {
  if (Test-Path -LiteralPath $userKeyPath) { Remove-Item -LiteralPath $userKeyPath -Recurse -Force }
  New-Item -Path $userKeyPath -Force | Out-Null
  foreach ($name in $vncSettings.Keys) { New-ItemProperty -LiteralPath $userKeyPath -Name $name -PropertyType DWord -Value $vncSettings[$name] -Force | Out-Null }
  foreach ($name in $credentials.Keys) { New-ItemProperty -LiteralPath $userKeyPath -Name $name -PropertyType Binary -Value $credentials[$name] -Force | Out-Null }
}
$userKey = Get-Item -LiteralPath $userKeyPath
foreach ($name in $vncSettings.Keys) {
  if ($userKey.GetValueKind($name) -ne 'DWord' -or $userKey.GetValue($name) -ne $vncSettings[$name]) { throw 'Cloud desktop VNC settings changed; reprovision the worker' }
}
foreach ($name in $credentials.Keys) {
  if ($userKey.GetValueKind($name) -ne 'Binary' -or [Convert]::ToBase64String($userKey.GetValue($name)) -cne [Convert]::ToBase64String($credentials[$name])) { throw 'Cloud desktop VNC credentials changed; reprovision the worker' }
}
# ConvertFrom-Json coerces ISO timestamps to DateTime; decimal text preserves exact birth ticks.
$expectedVnc = if ($existingVnc) { @{ pid = [int]$existingVnc.ProcessId; birthTicks = [string]$existingVnc.CreationDate.ToUniversalTime().Ticks } } else { $null }
$source = $source.Replace('__CRABBOX_VNC_IDENTITY__', (ConvertTo-Json -InputObject $expectedVnc -Compress))
`;
function browserLauncher$1(e) {
	return `$ErrorActionPreference = 'Stop'
if ($args.Count) { throw 'OpenClaw worker browser does not accept arguments' }
$profile = ${quote$1(`${desktopDirectory(e)}\\browser-profile`)}
$browser = '__CRABBOX_BROWSER_EXECUTABLE__'
New-Item -ItemType Directory -Force -Path $profile | Out-Null
$lock = $null
$lockDeadline = [DateTime]::UtcNow.AddSeconds(25)
while (-not $lock) {
  try { $lock = [IO.File]::Open((Join-Path $profile 'launch.lock'), [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) }
  catch [IO.IOException] { if ([DateTime]::UtcNow -ge $lockDeadline) { throw }; Start-Sleep -Milliseconds 100 }
}
try {
  $endpoint = 'http://127.0.0.1:${WINDOWS_CDP_PORT}/json/version'
  $caller = Get-CimInstance Win32_Process -Filter ('ProcessId=' + $PID)
  $callerSid = [string](Invoke-CimMethod -InputObject $caller -MethodName GetOwnerSid).Sid
  if ($caller.SessionId -le 0 -or -not $callerSid.StartsWith('S-1-')) { throw 'Cloud browser requires its interactive Windows account and session' }
  $profileValue = [regex]::Escape($profile)
  $profilePattern = '(?:^|\\s)(?:"--user-data-dir=' + $profileValue + '"|--user-data-dir="' + $profileValue + '"'
  if ($profile -notmatch '\\s') { $profilePattern += '|--user-data-dir=' + $profileValue }
  $profilePattern += ')(?=\\s|$)'
  function Get-OwnedBrowserListener {
    $listeners = @(Get-NetTCPConnection -LocalPort ${WINDOWS_CDP_PORT} -State Listen -ErrorAction SilentlyContinue)
    if (-not $listeners.Count) { return $false }
    $owners = @($listeners.OwningProcess | Sort-Object -Unique)
    if ($owners.Count -ne 1 -or @($listeners | Where-Object { $_.LocalAddress -ne '127.0.0.1' }).Count) { throw 'Cloud browser CDP must have one worker-owned loopback listener' }
    $owner = Get-CimInstance Win32_Process -Filter ('ProcessId=' + $owners[0])
    $ownerSid = [string](Invoke-CimMethod -InputObject $owner -MethodName GetOwnerSid).Sid
    if (-not $owner.ExecutablePath -or -not [string]::Equals([IO.Path]::GetFullPath($owner.ExecutablePath), [IO.Path]::GetFullPath($browser), [StringComparison]::OrdinalIgnoreCase) -or $owner.SessionId -ne $caller.SessionId -or $ownerSid -ne $callerSid -or $owner.CommandLine -notmatch $profilePattern -or $owner.CommandLine -notmatch '(?:^|\\s)"?--remote-debugging-port=${WINDOWS_CDP_PORT}"?(?=\\s|$)') { throw 'CDP port belongs to another browser, profile, or Windows session; reprovision the desktop worker' }
    return $true
  }
  if (-not (Get-OwnedBrowserListener)) {
    Start-Process -FilePath $browser -ArgumentList @('--no-first-run', '--no-default-browser-check', '--disable-default-apps', '--hide-crash-restore-bubble', ('--user-data-dir="' + $profile + '"'), '--remote-debugging-address=127.0.0.1', '--remote-debugging-port=${WINDOWS_CDP_PORT}', 'about:blank') | Out-Null
  }
  $deadline = [DateTime]::UtcNow.AddSeconds(20)
  while ([DateTime]::UtcNow -lt $deadline) {
    if (Get-OwnedBrowserListener) {
      try { Invoke-RestMethod -Uri $endpoint -TimeoutSec 1 | Out-Null; $ready = $true } catch { $ready = $false }
      if ($ready -and (Get-OwnedBrowserListener)) { exit 0 }
    }
    Start-Sleep -Milliseconds 200
  }
  throw 'Browser CDP did not become ready on 127.0.0.1:${WINDOWS_CDP_PORT} within 20 seconds'
} finally { $lock.Dispose() }`;
}
function createCrabboxWindowsDesktopSetup(e, t) {
	const n = desktopDirectory(e);
	const r = browserLauncher$1(e);
	const i = `$ErrorActionPreference = 'Stop'
if ($args.Count) { throw 'OpenClaw worker terminal does not accept arguments' }
$child = Start-Process -FilePath ${quote$1(WINDOWS_POWERSHELL)} -ArgumentList '-NoLogo -NoProfile -NoExit' -WindowStyle Normal -PassThru
Start-Sleep -Milliseconds 200
if ($child.HasExited) { throw 'Cloud worker terminal exited before becoming ready' }`;
	return interactiveScript(`$directory = ${quote$1(n)}
  New-Item -ItemType Directory -Force -Path $directory | Out-Null
  icacls.exe $directory /inheritance:r /grant ('*' + $expectedSid + ':(OI)(CI)F') /grant '*S-1-5-18:(OI)(CI)F' /grant '*S-1-5-32-544:(OI)(CI)F' | Out-Null
  if ($LASTEXITCODE -ne 0) { throw 'Cloud desktop launcher directory permissions could not be secured' }
  $browserPaths = @()
  foreach ($name in @('chrome.exe', 'msedge.exe')) {
    $command = Get-Command -Name $name -CommandType Application -ErrorAction SilentlyContinue
    if ($command) { $browserPaths += $command.Source }
  }
  $programDirectories = @($env:ProgramFiles, \${env:ProgramFiles(x86)}) | Where-Object { $_ } | Select-Object -Unique
  foreach ($relative in @('Google\\Chrome\\Application\\chrome.exe', 'Microsoft\\Edge\\Application\\msedge.exe')) {
    foreach ($root in $programDirectories) { $browserPaths += Join-Path $root $relative }
  }
  $browserExecutable = $browserPaths | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } | Select-Object -First 1
  if (-not $browserExecutable -or -not [IO.Path]::IsPathRooted($browserExecutable)) { throw 'Crabbox desktop browser is unavailable; reprovision the worker with browser support' }
  [IO.File]::WriteAllText((Join-Path $directory 'browser.ps1'), ${quote$1(r)}.Replace('__CRABBOX_BROWSER_EXECUTABLE__', $browserExecutable.Replace("'", "''")), [Text.UTF8Encoding]::new($false))
  [IO.File]::WriteAllText((Join-Path $directory 'terminal.ps1'), ${quote$1(i)}, [Text.UTF8Encoding]::new($false))
  $wallpaper = Join-Path $directory 'wallpaper.png'
  [IO.File]::WriteAllBytes($wallpaper, [Convert]::FromBase64String(${quote$1(t)}))
  if (-not ('OpenClawWallpaper' -as [type])) { Add-Type 'using System; using System.Runtime.InteropServices; public static class OpenClawWallpaper { [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)] public static extern bool SystemParametersInfo(uint action, uint parameter, string value, uint flags); }' }
  Assert-LaunchCurrent
  if (-not [OpenClawWallpaper]::SystemParametersInfo(20, 0, $wallpaper, 3)) { throw 'Cloud worker wallpaper could not be applied' }
  ${vncIdentity}
  $startedVnc = $null
  try {
    Assert-LaunchCurrent
    $expectedVnc = ConvertFrom-Json '__CRABBOX_VNC_IDENTITY__'
    $vnc = Get-WorkerVnc $expectedSid $expectedSession
    if ($expectedVnc) {
      if (-not $vnc -or $vnc.ProcessId -ne $expectedVnc.pid -or [string]$vnc.CreationDate.ToUniversalTime().Ticks -ne $expectedVnc.birthTicks) { throw 'Cloud desktop VNC changed during setup handover; reprovision the worker' }
    } elseif ($vnc) { throw 'Cloud desktop VNC appeared during setup handover; reprovision the worker' }
    if (-not $vnc) {
      Assert-LaunchCurrent
      $startedVnc = Start-Process -FilePath $vncExecutable -ArgumentList '-run' -PassThru
      $vnc = Get-CimInstance Win32_Process -Filter ('ProcessId=' + $startedVnc.Id) -OperationTimeoutSec 5
      Assert-VncProcess $vnc '-run' $expectedSession $expectedSid
    }
    $vncBirth = $vnc.CreationDate
    $deadline = [DateTime]::UtcNow.AddSeconds(15)
    do {
      Assert-LaunchCurrent
      $listener = Get-WorkerVnc $expectedSid $expectedSession
      if ($listener) {
        if ($listener.ProcessId -ne $vnc.ProcessId -or $listener.CreationDate -ne $vncBirth) { throw 'Cloud desktop VNC changed before becoming ready' }
        if ((Get-Service -Name tvnserver).Status -ne 'Stopped') { throw 'Crabbox VNC service resumed during desktop setup' }
        Assert-LaunchCurrent
        $result = @{ status = 'ready' }
        if ($startedVnc) { $result.pid = [int]$vnc.ProcessId; $result.startTime = $vncBirth.ToUniversalTime().ToString('o') }
        Write-LaunchResult $result
        break
      }
      if ($startedVnc -and $startedVnc.HasExited) { throw 'Cloud desktop VNC exited before becoming ready' }
      if ([DateTime]::UtcNow -ge $deadline) { throw 'Cloud desktop VNC did not listen on 127.0.0.1:5900 within 15 seconds' }
      Start-Sleep -Milliseconds 100
    } while ($true)
  } catch {
    if ($startedVnc -and -not $startedVnc.HasExited) { $startedVnc.Kill() }
    throw
  } finally { if ($startedVnc) { $startedVnc.Dispose() } }`, prepareVnc);
}
function createCrabboxWindowsDesktopEndpoint(e) {
	const t = desktopDirectory(e);
	const args = (e) => [
		"-NoLogo",
		"-NoProfile",
		"-NonInteractive",
		"-ExecutionPolicy",
		"Bypass",
		"-File",
		`${t}\\${e}.ps1`
	];
	return {
		protocol: "rfb",
		port: 5900,
		allowsResize: false,
		passwordFilePath: String.raw`C:\ProgramData\crabbox\vnc.password`,
		apps: [{
			id: "browser",
			executablePath: WINDOWS_POWERSHELL,
			args: args("browser"),
			cdpPort: WINDOWS_CDP_PORT
		}, {
			id: "terminal",
			executablePath: WINDOWS_POWERSHELL,
			args: args("terminal")
		}]
	};
}
function createCrabboxWindowsDesktopNodeLauncher() {
	const e = interactiveScript(`$options = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__CRABBOX_NODE_OPTIONS__')))
  $nodeScript = $PSCommandPath + '.cjs'
  try {
    [IO.File]::WriteAllText($nodeScript, [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__CRABBOX_NODE_SOURCE__')), [Text.UTF8Encoding]::new($false))
    $env:OPENCLAW_STATE_DIR = $options.stateDir
    Assert-LaunchCurrent
    $nodeResult = & $options.nodePath $nodeScript $cancelPath $expectedSession $expectedSid
    if ($LASTEXITCODE -ne 0) { throw 'Cloud worker interactive node launcher failed' }
    Write-LaunchResult ($nodeResult | ConvertFrom-Json)
  } finally { Remove-Item -LiteralPath $nodeScript -Force -ErrorAction SilentlyContinue }`);
	const t = String.raw`const fs = require("node:fs");
const { spawn, spawnSync } = require("node:child_process");
const options = __CRABBOX_OPTIONS__;
const [, , cancelPath, expectedSession, expectedSid] = process.argv;
if (fs.existsSync(cancelPath)) throw new Error("Cloud desktop launch was cancelled");
const log = fs.openSync(options.logPath, "a");
const child = spawn(options.nodePath, options.nodeArgs, { cwd: options.cwd, env: { ...process.env, OPENCLAW_STATE_DIR: options.stateDir }, detached: true, windowsHide: true, stdio: ["ignore", log, log] });
child.once("error", error => { fs.closeSync(log); console.error(error.message); process.exitCode = 1; });
child.once("spawn", () => {
  fs.closeSync(log);
  try {
    const script = "$ErrorActionPreference = 'Stop'; $node = Get-CimInstance Win32_Process -Filter 'ProcessId=" + child.pid + "'; if (-not $node) { throw 'Node process is unavailable' }; @{ pid = [int]$node.ProcessId; startTime = $node.CreationDate.ToUniversalTime().ToString('o'); sessionId = [int]$node.SessionId; userSid = [string](Invoke-CimMethod -InputObject $node -MethodName GetOwnerSid).Sid; executablePath = $node.ExecutablePath } | ConvertTo-Json -Compress";
    const probe = spawnSync(process.env.SystemRoot + "\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { encoding: "utf8", windowsHide: true, timeout: 10000 });
    if (probe.error || probe.status !== 0) throw new Error(probe.stderr?.trim() || "Cloud worker interactive node identity is unavailable");
    const identity = JSON.parse(probe.stdout.trim());
    if (identity.pid !== child.pid || identity.sessionId !== Number(expectedSession) || identity.userSid !== expectedSid || !identity.startTime || fs.realpathSync(identity.executablePath) !== fs.realpathSync(options.nodePath)) throw new Error("Cloud worker interactive node identity changed");
    if (fs.existsSync(cancelPath)) throw new Error("Cloud desktop launch was cancelled");
    delete identity.executablePath;
    process.stdout.write(JSON.stringify(identity));
    child.unref();
  } catch (error) { child.kill(); console.error(error.message); process.exitCode = 1; }
});`;
	return `function runWindowsDesktopPowerShell(script) {
  const fs = require("node:fs");
  const path = require("node:path");
  const directory = fs.mkdtempSync(path.join(require("node:os").tmpdir(), "openclaw-desktop-"));
  try {
    const scriptPath = path.join(directory, "launch.ps1");
    fs.writeFileSync(scriptPath, script, "utf8");
    const result = require("node:child_process").spawnSync(${JSON.stringify(WINDOWS_POWERSHELL)}, ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", scriptPath], { encoding: "utf8", windowsHide: true, timeout: 95000, maxBuffer: 1024 * 1024 });
    if (result.error || result.status !== 0) throw new Error(result.error?.message || result.stderr?.trim() || "Cloud worker Windows desktop launch failed");
    return JSON.parse(result.stdout.trim());
  } finally { fs.rmSync(directory, { recursive: true, force: true }); }
}
function readWindowsDesktopSessionIdentity() {
  const result = runWindowsDesktopPowerShell(${JSON.stringify(`$ErrorActionPreference = 'Stop'
${sessionIdentity}
@{ sessionId = [int]$consoleSession; userSid = $userSid } | ConvertTo-Json -Compress`)});
  if (!Number.isSafeInteger(result.sessionId) || result.sessionId < 1 || typeof result.userSid !== "string" || !/^S-1-/.test(result.userSid)) throw new Error("Cloud worker interactive session identity is invalid");
  return result;
}
async function launchWindowsDesktopNode(options) {
  const source = ${JSON.stringify(t)}.replace("__CRABBOX_OPTIONS__", () => JSON.stringify(options));
  const result = runWindowsDesktopPowerShell(${JSON.stringify(e)}.replace("__CRABBOX_NODE_OPTIONS__", Buffer.from(JSON.stringify(options)).toString("base64")).replace("__CRABBOX_NODE_SOURCE__", Buffer.from(source).toString("base64")));
  if (!Number.isSafeInteger(result.pid) || result.pid < 1 || !Number.isSafeInteger(result.sessionId) || result.sessionId < 1 || typeof result.startTime !== "string" || !result.startTime || typeof result.userSid !== "string" || !/^S-1-/.test(result.userSid)) throw new Error("Cloud worker interactive node identity is invalid");
  return result;
}`;
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-desktop-setup.ts
const CRABBOX_WORKER_BROWSER_PATH = "/usr/local/bin/openclaw-worker-browser";
const CRABBOX_WORKER_TERMINAL_PATH = "/usr/local/bin/openclaw-worker-terminal";
const CRABBOX_WORKER_BROWSER_CDP_PORT = 9222;
function xfceDesktopEnvironment() {
	return [
		"[ -r /var/lib/crabbox/desktop.env ] || { echo \"Crabbox desktop environment is unavailable\" >&2; exit 1; }",
		"grep -Fx 'CRABBOX_DESKTOP_ENV=xfce' /var/lib/crabbox/desktop.env >/dev/null || { echo \"Crabbox desktop environment is not XFCE\" >&2; exit 1; }",
		"grep -Fx 'DISPLAY=:99' /var/lib/crabbox/desktop.env >/dev/null || { echo \"Crabbox XFCE display is not :99\" >&2; exit 1; }",
		"export DISPLAY=:99"
	];
}
function createCrabboxXfceSessionEnvironment() {
	return [
		...xfceDesktopEnvironment(),
		"worker_uid=$(id -u)",
		"read_xfce_process_environment() {",
		"  local process_pid=\"$1\"",
		"  exec 8<\"/proc/$process_pid/environ\" || return 1",
		"  process_display=",
		"  process_dbus=",
		"  process_runtime_dir=",
		"  while IFS= read -r -d '' process_variable; do",
		"    case \"$process_variable\" in",
		"      DISPLAY=*) process_display=\"${process_variable#*=}\" ;;",
		"      DBUS_SESSION_BUS_ADDRESS=*) process_dbus=\"${process_variable#*=}\" ;;",
		"      XDG_RUNTIME_DIR=*) process_runtime_dir=\"${process_variable#*=}\" ;;",
		"    esac",
		"  done <&8",
		"  exec 8<&-",
		"}",
		"# XFCE owns the D-Bus session; the image's original renderer may have been launched outside it.",
		"mapfile -t session_pids < <(pgrep -u \"$worker_uid\" -x xfce4-session || true)",
		"[ \"${#session_pids[@]}\" -eq 1 ] || { echo \"Expected exactly one worker-owned XFCE session; restart crabbox-desktop.service and retry\" >&2; exit 1; }",
		"session_pid=\"${session_pids[0]}\"",
		"read_xfce_process_environment \"$session_pid\" || { echo \"XFCE session changed while it was inspected; restart crabbox-desktop.service and retry\" >&2; exit 1; }",
		"[ \"$process_display\" = \":99\" ] || { echo \"XFCE session does not use DISPLAY=:99; restart crabbox-desktop.service and retry\" >&2; exit 1; }",
		"DBUS_SESSION_BUS_ADDRESS=\"$process_dbus\"",
		"unset XDG_RUNTIME_DIR",
		"XDG_RUNTIME_DIR=\"$process_runtime_dir\"",
		"[ -n \"$DBUS_SESSION_BUS_ADDRESS\" ] || { echo \"XFCE session is missing its D-Bus binding; restart crabbox-desktop.service and retry\" >&2; exit 1; }",
		"case \"$XDG_RUNTIME_DIR\" in \"\"|/*) ;; *) echo \"XFCE session has an invalid XDG_RUNTIME_DIR\" >&2; exit 1 ;; esac",
		"export DBUS_SESSION_BUS_ADDRESS",
		"[ -z \"$XDG_RUNTIME_DIR\" ] || export XDG_RUNTIME_DIR"
	];
}
function browserLauncher(e) {
	return [
		"#!/bin/bash",
		"set -euo pipefail",
		"[ \"$#\" -eq 0 ] || { echo \"openclaw-worker-browser does not accept arguments\" >&2; exit 64; }",
		...xfceDesktopEnvironment(),
		"[ -x /usr/local/bin/crabbox-browser ] || { echo \"Crabbox browser is unavailable\" >&2; exit 1; }",
		"worker_home=$(getent passwd \"$(id -u)\" | cut -d: -f6)",
		"case \"$worker_home\" in /*) ;; *) echo \"Crabbox worker home is invalid\" >&2; exit 1 ;; esac",
		"export HOME=\"$worker_home\"",
		`export CRABBOX_BROWSER_PROFILE="$worker_home/.cache/openclaw/worker-browser/${e}"`,
		"mkdir -p \"$CRABBOX_BROWSER_PROFILE\"",
		"chmod 700 \"$CRABBOX_BROWSER_PROFILE\"",
		"exec 9>\"$CRABBOX_BROWSER_PROFILE/.openclaw-launch.lock\"",
		"flock -x 9",
		`cdp_url=http://127.0.0.1:${CRABBOX_WORKER_BROWSER_CDP_PORT}/json/version`,
		"if curl --fail --silent --show-error --max-time 1 \"$cdp_url\" >/dev/null; then",
		"  exit 0",
		"fi",
		"launch_log=\"$CRABBOX_BROWSER_PROFILE/launch.log\"",
		": >\"$launch_log\"",
		`nohup /usr/local/bin/crabbox-browser --remote-debugging-address=127.0.0.1 --remote-debugging-port=${CRABBOX_WORKER_BROWSER_CDP_PORT} about:blank >>"$launch_log" 2>&1 </dev/null 9>&- &`,
		"for _attempt in $(seq 1 40); do",
		"  if curl --fail --silent --show-error --max-time 1 \"$cdp_url\" >/dev/null; then",
		"    exit 0",
		"  fi",
		"  sleep 0.5",
		"done",
		`echo "Browser CDP did not become ready on 127.0.0.1:${CRABBOX_WORKER_BROWSER_CDP_PORT} within 20 seconds" >&2`,
		"exit 1"
	];
}
function terminalLauncher() {
	return [
		"#!/bin/bash",
		"set -euo pipefail",
		"[ \"$#\" -eq 0 ] || { echo \"openclaw-worker-terminal does not accept arguments\" >&2; exit 64; }",
		...xfceDesktopEnvironment(),
		"nohup /usr/bin/xfce4-terminal >/dev/null 2>&1 </dev/null &",
		"terminal_pid=$!",
		"sleep 0.2",
		"if kill -0 \"$terminal_pid\" 2>/dev/null; then",
		"  exit 0",
		"fi",
		"wait \"$terminal_pid\""
	];
}
function heredoc(e, t, n) {
	return [
		`cat >"$setup_dir/${e}" <<'${t}'`,
		...n,
		t
	];
}
function createCrabboxWorkerDesktopSetup(e, t, n, r) {
	switch (n) {
		case "linux": break;
		case "windows/normal": return createCrabboxWindowsDesktopSetup(e, t);
		case "macos": return createCrabboxMacosDesktopSetup(e, t, requireDesktopUser(r));
		case "windows/wsl2": throw new Error("Crabbox desktop requires native Windows");
	}
	return createCrabboxLinuxDesktopSetup(e, t);
}
function requireDesktopUser(e) {
	if (!e || e === "<token>") throw new Error("Crabbox macOS desktop inspection must identify the worker account");
	return e;
}
function createCrabboxLinuxDesktopSetup(e, t) {
	return [
		"set -euo pipefail",
		...createCrabboxXfceSessionEnvironment(),
		"worker_user=$(id -un)",
		"worker_group=$(id -gn)",
		"worker_home=$(getent passwd \"$worker_uid\" | cut -d: -f6)",
		"case \"$worker_home\" in /*) ;; *) echo \"Crabbox worker home is invalid\" >&2; exit 1 ;; esac",
		"as_root() { if [ \"$worker_uid\" -eq 0 ]; then \"$@\"; else sudo -n -- \"$@\"; fi; }",
		"for required_command in xfconf-query xfdesktop xrandr awk cmp curl flock getent pgrep pkill python3; do command -v \"$required_command\" >/dev/null 2>&1 || { echo \"Required Crabbox desktop command is unavailable: $required_command\" >&2; exit 1; }; done",
		"bind_xfdesktop_renderer() {",
		"  mapfile -t renderer_pids < <(pgrep -u \"$worker_uid\" -x xfdesktop || true)",
		"  [ \"${#renderer_pids[@]}\" -eq 1 ] || return 1",
		"  renderer_pid=\"${renderer_pids[0]}\"",
		"  read_xfce_process_environment \"$renderer_pid\" || return 1",
		"  [ \"$process_display\" = \"$DISPLAY\" ] && [ \"$process_dbus\" = \"$DBUS_SESSION_BUS_ADDRESS\" ]",
		"}",
		"setup_dir=$(mktemp -d)",
		"trap 'rm -rf -- \"$setup_dir\"' EXIT",
		...heredoc("browser", "WORKER_BROWSER_LAUNCHER_EOF", browserLauncher(e)),
		...heredoc("terminal", "WORKER_TERMINAL_LAUNCHER_EOF", terminalLauncher()),
		`python3 -c 'import base64,pathlib,sys;pathlib.Path(sys.argv[1]).write_bytes(base64.b64decode(sys.stdin.buffer.read().strip(),validate=True))' "$setup_dir/wallpaper.png" <<'WORKER_WALLPAPER_B64_EOF'`,
		t,
		"WORKER_WALLPAPER_B64_EOF",
		`as_root install -o root -g root -m 0755 "$setup_dir/browser" ${CRABBOX_WORKER_BROWSER_PATH}`,
		`as_root install -o root -g root -m 0755 "$setup_dir/terminal" ${CRABBOX_WORKER_TERMINAL_PATH}`,
		"as_root install -d -o \"$worker_user\" -g \"$worker_group\" -m 0755 \"$worker_home/.cache\" \"$worker_home/.cache/openclaw\" \"$worker_home/.cache/openclaw/worker-browser\"",
		`as_root install -d -o "$worker_user" -g "$worker_group" -m 0700 "$worker_home/.cache/openclaw/worker-browser/${e}"`,
		"as_root install -d -o \"$worker_user\" -g \"$worker_group\" -m 0755 \"$worker_home/.local\" \"$worker_home/.local/share\" \"$worker_home/.local/share/backgrounds\"",
		"wallpaper_path=\"$worker_home/.local/share/backgrounds/openclaw-worker.png\"",
		"# XFCE caches wallpaper bytes across reloads. Reuse only unchanged assets on the authoritative bus.",
		"wallpaper_matches=false",
		"cmp -s \"$setup_dir/wallpaper.png\" \"$wallpaper_path\" && wallpaper_matches=true",
		"as_root install -o \"$worker_user\" -g \"$worker_group\" -m 0644 \"$setup_dir/wallpaper.png\" \"$wallpaper_path\"",
		"if [ \"$wallpaper_matches\" != true ] || ! bind_xfdesktop_renderer; then",
		"  pkill -TERM -u \"$worker_uid\" -x xfdesktop || true",
		"  for _attempt in $(seq 1 20); do pgrep -u \"$worker_uid\" -x xfdesktop >/dev/null || break; sleep 0.1; done",
		"  pkill -KILL -u \"$worker_uid\" -x xfdesktop || true",
		"  nohup xfdesktop >\"$worker_home/.cache/openclaw/xfdesktop.log\" 2>&1 </dev/null &",
		"  for _attempt in $(seq 1 40); do bind_xfdesktop_renderer && break; sleep 0.1; done",
		"fi",
		"bind_xfdesktop_renderer || { echo \"XFCE desktop renderer did not converge on the worker session\" >&2; exit 1; }",
		"mapfile -t backdrop_roots < <(",
		"  {",
		"    xfconf-query -c xfce4-desktop -l | sed -n 's#\\(/backdrop/[^/]*/[^/]*/workspace[^/]*\\)/.*#\\1#p'",
		"    while read -r monitor; do for workspace in 0 1 2 3; do printf \"/backdrop/screen0/monitor%s/workspace%s\\n\" \"$monitor\" \"$workspace\"; done; done < <(xrandr --listmonitors | awk 'NR > 1 { print $NF }')",
		"  } | sort -u",
		")",
		"[ \"${#backdrop_roots[@]}\" -gt 0 ] || { echo \"XFCE did not advertise any desktop backdrops\" >&2; exit 1; }",
		"for backdrop in \"${backdrop_roots[@]}\"; do",
		"  xfconf-query -c xfce4-desktop -p \"$backdrop/last-image\" -s \"$wallpaper_path\" || xfconf-query -c xfce4-desktop -p \"$backdrop/last-image\" -n -t string -s \"$wallpaper_path\"",
		"  xfconf-query -c xfce4-desktop -p \"$backdrop/image-style\" -s 5 || xfconf-query -c xfce4-desktop -p \"$backdrop/image-style\" -n -t int -s 5",
		"done",
		"renderer_pid_before_reload=\"$renderer_pid\"",
		"xfdesktop --reload",
		"bind_xfdesktop_renderer || { echo \"XFCE desktop renderer lost its worker session during reload\" >&2; exit 1; }",
		"[ \"$renderer_pid\" = \"$renderer_pid_before_reload\" ] || { echo \"XFCE desktop renderer changed during reload; restart crabbox-desktop.service and retry\" >&2; exit 1; }"
	].join("\n");
}
function createCrabboxWorkerDesktopEndpoint(e, t, n) {
	switch (t) {
		case "windows/normal": return createCrabboxWindowsDesktopEndpoint(e);
		case "macos": return createCrabboxMacosDesktopEndpoint(e, requireDesktopUser(n));
		case "windows/wsl2": throw new Error("Crabbox desktop requires native Windows");
	}
	return {
		protocol: "rfb",
		port: 5900,
		passwordFilePath: "/var/lib/crabbox/vnc.password",
		apps: [{
			id: "browser",
			executablePath: CRABBOX_WORKER_BROWSER_PATH,
			cdpPort: CRABBOX_WORKER_BROWSER_CDP_PORT
		}, {
			id: "terminal",
			executablePath: CRABBOX_WORKER_TERMINAL_PATH
		}]
	};
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-env-profile.ts
async function withCrabboxWorkerEnvProfile(e, t) {
	const n = Object.entries(e ?? {});
	const r = n.map(([e]) => e);
	let i;
	try {
		let e;
		if (n.length > 0) {
			const t = n.map(([e, t]) => {
				if ([
					"\0",
					"\r",
					"\n",
					"`",
					"$("
				].some((e) => t.includes(e))) throw new WorkerProviderError(`Crabbox setup environment value cannot be represented safely: ${e}`);
				return `${e}="${t.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
			}).join("\n");
			i = await mkdtemp(join(resolvePreferredOpenClawTmpDir(), "openclaw-crabbox-env-"));
			e = join(i, "setup.env");
			await writeFile(e, `${t}\n`, {
				mode: 384,
				flag: "wx"
			});
		}
		return await t(r, e, {
			...Object.fromEntries(r.map((e) => [e, void 0])),
			CRABBOX_ENV_ALLOW: ","
		});
	} finally {
		if (i) await rm(i, {
			force: true,
			recursive: true
		});
	}
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-setup-egress.ts
const UPSTREAM_PROXY_ENV = "CRABBOX_SETUP_PROXY";
function quote(e) {
	if (e.includes("\0")) throw new Error("Cloud setup environment cannot contain NUL");
	return `'${e.replaceAll("'", `'"'"'`)}'`;
}
async function assertCrabboxSetupEgressSupport(e) {
	e.assertCurrent();
	if (e.target !== "linux") throw new Error("Setup secrets require a coordinator-owned Linux lease; select Linux");
	if (e.projectPrepared === false) throw new WorkerProviderError("Protected repository setup requires a prepared Linux workspace; configure or select a machine class before retrying");
	const t = await runCrabboxCommand({
		...e,
		action: "setup egress preflight",
		args: [
			"egress",
			"run",
			"--help"
		],
		timeoutMs: 3e4
	});
	e.assertCurrent();
	const n = `${t.stdout}\n${t.stderr}`;
	if (t.termination !== "exit" || t.code !== 0 || !/(?:^|\n)\s+-{1,2}allow-public-destinations(?:\s|$)/u.test(n) || !/(?:^|\n)\s+-{1,2}upstream-proxy-env(?:\s|$)/u.test(n)) throw new Error("Setup secrets require native egress; update Crabbox to 0.79.2 or newer");
}
function createCrabboxSetupCommandRunner(e) {
	return async (t, n) => {
		n.assertCurrent();
		const r = parseCrabboxProfile(t.profile);
		if (!Object.keys(r.setupSecrets ?? {}).length) return;
		assertCrabboxLeaseId(t.leaseId);
		const i = await e.resolveBinary(r.binary, n.signal);
		const createScript = (e) => `set -eu\ncd -- ${quote(n.workspaceDir)}\nexport HOME=${quote(n.homeDir)}\nnode -e ${quote(n.createScript(e))}`;
		await assertCrabboxSetupEgressSupport({
			binary: i,
			target: r.target,
			assertCurrent: n.assertCurrent,
			signal: n.signal
		});
		return await runCrabboxSetupEgress({
			binary: i,
			provider: r.provider,
			id: t.leaseId,
			secrets: r.setupSecrets ?? {},
			createScript,
			timeoutMs: n.timeoutMs,
			assertCurrent: n.assertCurrent,
			signal: n.signal
		});
	};
}
/** The lease receives sentinels and public trust only; the upstream grant stays in the host child. */
async function runCrabboxSetupEgress(e) {
	const t = AbortSignal.any([AbortSignal.timeout(e.timeoutMs), ...e.signal ? [e.signal] : []]);
	e.assertCurrent();
	return await withSetupSecretEgress({
		secrets: e.secrets,
		signal: t
	}, async (n) => {
		t.throwIfAborted();
		e.assertCurrent();
		const r = `/tmp/openclaw-setup-egress.${randomBytes(16).toString("hex")}`;
		const i = `${r}/ca.pem`;
		const a = {
			...n.remoteEnv,
			HTTPS_PROXY: "http://127.0.0.1:3128",
			https_proxy: "http://127.0.0.1:3128",
			NO_PROXY: "localhost,127.0.0.1,::1",
			no_proxy: "localhost,127.0.0.1,::1",
			NODE_USE_ENV_PROXY: "1",
			NODE_EXTRA_CA_CERTS: i,
			SSL_CERT_FILE: i,
			CURL_CA_BUNDLE: i,
			REQUESTS_CA_BUNDLE: i,
			GIT_SSL_CAINFO: i
		};
		const o = `SETUP_EGRESS_CA_${randomBytes(12).toString("hex")}`;
		const s = `#!/bin/bash
set -euo pipefail
umask 077
mkdir -- ${quote(r)}
trap 'rm -rf -- ${quote(r)}' EXIT
cat > ${quote(i)} <<'${o}'
${n.caBundle}
${o}
unset HTTP_PROXY http_proxy ALL_PROXY all_proxy
${Object.entries(a).map(([e, t]) => `export ${e}=${quote(t)}`).join("\n")}
${e.createScript(a)}
`;
		const c = new AbortController();
		const abort = () => {
			n.revoke();
			c.abort(t.reason);
		};
		t.addEventListener("abort", abort, { once: true });
		try {
			t.throwIfAborted();
			e.assertCurrent();
			const r = await runCrabboxProcess([
				e.binary,
				"egress",
				"run",
				"--id",
				e.id,
				"--provider",
				e.provider,
				"--allow-public-destinations",
				"--upstream-proxy-env",
				UPSTREAM_PROXY_ENV,
				"--no-sync",
				"--no-hydrate",
				"--script-stdin"
			], {
				env: {
					CRABBOX_ENV_ALLOW: ",",
					[UPSTREAM_PROXY_ENV]: n.hostEnv.HTTPS_PROXY
				},
				input: s,
				timeoutMs: e.timeoutMs,
				maxOutputBytes: 65536,
				killProcessTree: true,
				requireProcessTreeExtinction: true,
				killGraceMs: 75e3,
				signal: c.signal
			});
			t.throwIfAborted();
			e.assertCurrent();
			if (r.cleanup === "uncertain") throw new Error("Setup egress cleanup is uncertain; stop the owned lease before retrying");
			return r;
		} finally {
			n.revoke();
			t.removeEventListener("abort", abort);
		}
	});
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-provision-commands.ts
const bootstrapLog = createSubsystemLogger("gateway/worker-environments");
/** Allocation retains host and project authority independently of cancellation or cleanup. */
function createCrabboxProvisionAuthority(e) {
	const t = e?.assertCurrent;
	if (!t) throw new WorkerProviderError("Crabbox provisioning requires current Gateway allocation authority");
	const n = e?.signal;
	const r = e?.project;
	const assertCurrent = () => {
		n?.throwIfAborted();
		t();
		r?.assertCurrent();
	};
	assertCurrent();
	return {
		signal: n,
		assertCurrent
	};
}
const NON_RUNNABLE_STATES = /* @__PURE__ */ new Set([
	"archived",
	"cleanup",
	"deleted",
	"deleting",
	"destroyed",
	"expired",
	"failed",
	"missing",
	"released",
	"stopped",
	"stopped_with_code",
	"terminated"
]);
async function inspectWithContext(e) {
	const t = e.waitForReady ? "status" : "inspect";
	const n = await runCrabboxCommandWithCoordinatorRetry({
		action: t,
		args: [
			t,
			"--provider",
			e.provider,
			"--network",
			"public",
			"--id",
			e.id,
			...e.waitForReady ? [
				"--wait",
				"--wait-timeout",
				"4m"
			] : [],
			"--json"
		],
		binary: e.binary,
		signal: e.signal,
		timeoutMs: e.timeoutMs ?? resolveCrabboxLifecycleTimeoutMs(e.provider)
	});
	if (n.termination === "exit" && n.code === 0) {
		let t;
		try {
			t = parseInspectJson(n.stdout);
			const e = sanitizeCrabboxNotice(n.stderr);
			if (e) t.lifetime = {
				...t.lifetime,
				policyNotice: e
			};
		} catch (e) {
			throw new WorkerProviderError(e instanceof Error ? e.message : "Crabbox inspect returned invalid output");
		}
		if (t.id !== e.id) throw new WorkerProviderError("Crabbox inspect returned a different lease id");
		return t;
	}
	if (n.termination === "exit" && n.stdout.trim() === "" && (e.provider === "digitalocean" && n.code === 4 && n.stderr.trim() === "DigitalOcean fixed lease is terminal" || e.provider === "ascii-box" && n.code === 1 && /^ascii-box bx_[A-Za-z0-9_-]+ not found \(404\)$/u.test(n.stderr.trim())) && !e.requireConfirmedAbsence || isUnrecognizedLease(n, e.id, "inspect", e.requireConfirmedAbsence)) return;
	throw crabboxCommandError(t, {
		...n,
		stdout: /^\s*[[{]/u.test(n.stdout) ? "" : n.stdout
	});
}
function remainingProvisionTimeout(e, t) {
	const n = e - performance.now();
	if (n <= 0) throw new Error("Crabbox provision exceeded its provider deadline");
	return Math.min(t, n);
}
const isNonRunnableState = (e) => NON_RUNNABLE_STATES.has(e.toLowerCase());
async function runProvisionWarmup(e) {
	const t = await runCrabboxCommand({
		...e,
		action: "warmup",
		args: ["warmup", ...buildCrabboxAllocationArgs(e.profile, e.id, e.slug)],
		timeoutMs: e.timeoutMs()
	});
	if (t.termination === "exit" && t.code === 0) return;
	if (isFixedLeaseIdUnsupported(t, e.provider)) throw new WorkerProviderError(`Crabbox backend ${e.provider} does not support fixed lease IDs that are safe to reuse. OpenClaw cloud workers need a Crabbox backend with fixed lease ID support.`);
	const n = crabboxCommandError("warmup", t);
	if (t.termination === "exit" && t.code !== null) try {
		const t = await inspectWithContext({
			...e,
			timeoutMs: Math.min(e.timeoutMs(), resolveCrabboxLifecycleTimeoutMs(e.provider))
		});
		if (t && isNonRunnableState(t.state) && t.failureError) n.message += `; lease failure: ${t.failureError}`;
	} catch {
		e.signal?.throwIfAborted();
	}
	throw n;
}
function assertProvisionSecurityPolicy(e) {
	if (e.inspect.tailscaleEnabled) throw new WorkerProviderError("Crabbox cloud worker lease must not have Tailscale enabled");
	const t = e.inspect.awsInstanceProfileAttached;
	const n = !e.inspect.ready && !isNonRunnableState(e.inspect.state);
	if (e.provider === "aws" && t !== false && (t || !n)) throw new WorkerProviderError("Crabbox AWS inspect must attest that no instance profile is attached");
}
async function waitForProvisionReady(e) {
	let t = e.inspect;
	const inspectAgain = async () => {
		e.signal?.throwIfAborted();
		const n = await inspectWithContext({
			...e,
			id: t.id,
			timeoutMs: remainingProvisionTimeout(e.deadline, resolveCrabboxLifecycleTimeoutMs(e.provider)),
			waitForReady: e.provider === "machine0"
		});
		if (!n) throw new Error("Crabbox operation lease disappeared while waiting for SSH readiness");
		e.signal?.throwIfAborted();
		return n;
	};
	try {
		t = e.refresh ? await inspectAgain() : e.inspect;
		e.signal?.throwIfAborted();
		assertProvisionSecurityPolicy({
			inspect: t,
			provider: e.provider
		});
		while (t.ready !== true && !isNonRunnableState(t.state)) {
			e.signal?.throwIfAborted();
			const n = remainingProvisionTimeout(e.deadline, CRABBOX_LIFECYCLE_TIMEOUT_MS);
			await setTimeout$1(Math.min(resolveCrabboxReadyPollIntervalMs(e.provider), n), void 0, { signal: e.signal });
			e.signal?.throwIfAborted();
			t = await inspectAgain();
			assertProvisionSecurityPolicy({
				inspect: t,
				provider: e.provider
			});
		}
		if (isNonRunnableState(t.state)) throw new WorkerProviderError(`Crabbox operation lease entered a terminal state while waiting for SSH${t.failureError ? `: ${t.failureError}` : ""}`);
		return t;
	} catch (n) {
		e.signal?.throwIfAborted();
		if (n instanceof WorkerProviderError) return await failProvisionAfterCleanup({
			...e,
			id: t.id
		}, n);
		throw n;
	}
}
async function runProvisionSetup(e) {
	try {
		const t = e.phase === "profile setup" || e.phase === "node runtime preparation" || e.phase === "node enrollment setup" ? runCrabboxCommandWithCoordinatorRetry : runCrabboxCommand;
		const n = e.phase === "profile setup" && Object.keys(e.profile.setupSecrets ?? {}).length ? await runCrabboxSetupEgress({
			...e,
			id: e.inspect.id,
			secrets: e.profile.setupSecrets ?? {},
			createScript: () => e.setup,
			assertCurrent: () => {
				e.signal?.throwIfAborted();
				if (!e.assertCurrent) throw new Error("Setup secrets require current provisioning authority");
				e.assertCurrent();
			},
			timeoutMs: remainingProvisionTimeout(e.deadline, e.timeoutMs ?? 9e5)
		}) : await withCrabboxWorkerEnvProfile(e.forwardedEnv, (n, r, i) => t({
			action: e.phase,
			args: leaseRunArgs({
				...e,
				id: e.inspect.id
			}, n, r),
			binary: e.binary,
			env: i,
			input: e.setup,
			signal: e.signal,
			timeoutMs: remainingProvisionTimeout(e.deadline, e.timeoutMs ?? 9e5)
		}));
		crabboxCommandOutput(e.phase, n);
		const r = `${n.stdout}\n${n.stderr}`;
		for (const t of r.matchAll(/^CRABBOX_TIMING:(openclaw-bootstrap-[a-z-]+):(\d+)\r?$/gmu)) bootstrapLog.info(`Cloud worker ${e.inspect.id}: ${t[1]} ${t[2]}ms`);
		for (const t of r.matchAll(/^CRABBOX_WARNING:openclaw-bootstrap-unlocked-install:([a-zA-Z0-9 _-]+)\r?$/gmu)) bootstrapLog.warn(`Cloud worker ${e.inspect.id}: using unlocked runtime install (${t[1]})`);
	} catch (t) {
		e.signal?.throwIfAborted();
		return await failProvisionAfterCleanup({
			...e,
			id: e.inspect.id
		}, t);
	}
	e.signal?.throwIfAborted();
}
async function prepareProvisionDesktop(e) {
	if (!e.profile.desktop) return;
	let t;
	try {
		const { id: n, sshUser: r } = e.inspect;
		t = {
			setup: createCrabboxWorkerDesktopSetup(n, e.wallpaperBase64, e.profile.target, r),
			endpoint: createCrabboxWorkerDesktopEndpoint(n, e.profile.target, r)
		};
	} catch (t) {
		e.signal?.throwIfAborted();
		return await failProvisionAfterCleanup({
			...e,
			id: e.inspect.id
		}, t);
	}
	if (e.prepareBeforeEnrollment) await runProvisionSetup({
		...e,
		phase: "desktop setup",
		setup: t.setup
	});
	return t;
}
async function failProvisionAfterCleanup(e, t) {
	try {
		await e.stopLease(e);
	} catch (n) {
		throw WorkerProviderError.cleanupIndeterminate(e.id, t, n);
	}
	throw WorkerProviderError.cleanupComplete(e.id, t);
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-lifetime.ts
async function prepareCrabboxCaptureLifetime(e, t) {
	const assertCurrent = () => {
		e.signal?.throwIfAborted();
		e.assertCurrent?.();
	};
	const command = (t, n) => {
		assertCurrent();
		return runCrabboxCommand({
			...e,
			action: t,
			args: n,
			timeoutMs: resolveCrabboxLifecycleTimeoutMs(e.provider)
		});
	};
	const inspect = async () => {
		assertCurrent();
		const n = await inspectWithContext(e);
		assertCurrent();
		if (!n || isNonRunnableState(n.state)) throw new Error("Crabbox capture preparation failed: lease_not_active; the source lease is no longer active");
		t.observe(n);
		return n;
	};
	const n = e.sourcePreparationTimeoutMs + WARM_IMAGE_COMMAND_ROUND_TRIP_TIMEOUT_MS + resolveCrabboxCheckpointCaptureTimeoutMs(e.provider);
	const failure = (e, t) => {
		const n = t.lifetime?.expiresAtMs;
		throw new Error(`Crabbox capture preparation failed: ${e}; source expiry ${n ? new Date(n).toISOString() : "unknown"}. Request sufficient TTL at creation or finish without a new image.`);
	};
	await inspect();
	const r = await command("capture heartbeat", [
		"heartbeat",
		"--provider",
		e.provider,
		"--id",
		e.id,
		"--json"
	]);
	crabboxCommandOutput("capture heartbeat", r);
	let i = await inspect();
	const a = sanitizeCrabboxNotice(r.stderr);
	if (a) t.observe({
		...i,
		lifetime: {
			...i.lifetime,
			policyNotice: a
		}
	});
	if ((i.lifetime?.expiresAtMs ?? 0) - Date.now() >= n) return;
	const totalDeadline = async (n) => {
		const r = n.lifetime;
		if (r?.createdAtMs !== void 0 && r.ttlMs !== void 0) return r.createdAtMs + Math.min(r.ttlMs, r.maxLifetimeMs ?? r.ttlMs);
		const a = await command("capture lifetime", [
			"list",
			"--provider",
			e.provider,
			"--json"
		]);
		if (a.termination !== "exit" || a.code !== 0) throw crabboxCommandError("capture lifetime", {
			...a,
			stdout: ""
		});
		const o = parseCrabboxJson(a.stdout, "list");
		assertCurrent();
		if (!Array.isArray(o)) return;
		const s = o.filter((t) => isRecord(t) && t.id === e.id && t.provider === e.provider);
		if (s.length !== 1 || !isRecord(s[0])) return;
		const c = parseCrabboxLeaseLifetime(s[0]);
		const l = {
			...n.lifetime,
			...c
		};
		i = {
			...n,
			lifetime: l
		};
		t.observe(i);
		return l.createdAtMs !== void 0 && l.ttlMs !== void 0 ? l.createdAtMs + Math.min(l.ttlMs, l.maxLifetimeMs ?? l.ttlMs) : void 0;
	};
	let o = await totalDeadline(i);
	assertCurrent();
	if (o === void 0) o = i.lifetime?.expiresAtMs;
	if (o !== void 0 && o - Date.now() >= n) return;
	const s = i.lifetime;
	if (s?.runtimeExtension === false || e.provider === "daytona") failure("lease_extension_unsupported_provider (creation-fixed lifetime)", i);
	if (s?.extension === "deny") failure("lease_extension_denied", i);
	if (s?.createdAtMs === void 0 || s.ttlMs === void 0) return failure("cannot establish the remaining total lifetime", i);
	const c = parseCrabboxDurationMs(e.profile.ttl);
	const l = 4 * resolveCrabboxLifecycleTimeoutMs(e.provider);
	const u = Math.ceil((Date.now() + n + l - s.createdAtMs) / 1e3) * 1e3;
	if (u > c || s.maxLifetimeMs !== void 0 && u > s.maxLifetimeMs) failure("the required source window exceeds the configured TTL or effective maximum", i);
	const d = [
		"extend",
		e.id,
		"--provider",
		e.provider,
		"--ttl",
		`${u / 1e3}s`,
		"--json"
	];
	for (let t = 0; t < 2; t++) {
		let r;
		try {
			r = await command("capture extension", d);
		} catch (e) {
			assertCurrent();
			i = await inspect();
			await totalDeadline(i);
			return failure(e instanceof Error ? e.message : "extension outcome is uncertain", i);
		}
		assertCurrent();
		let a = false;
		if (r.stdout.trim()) {
			let t;
			try {
				t = JSON.parse(r.stdout);
			} catch {}
			if (isRecord(t)) {
				if (t.id !== e.id) failure("extension returned a different lease id", i);
				a = t.guestExpiryRefreshPending === true || Boolean(t.error);
			}
		}
		if (a) {
			if (t === 0) continue;
			failure(`direct guest expiry refresh remains unconfirmed; reconcile with crabbox extend ${e.id} --provider ${e.provider} --ttl ${u / 1e3}s --json using the same Crabbox state`, i);
		}
		if (r.termination !== "exit" || r.code !== 0) {
			const e = crabboxCommandError("capture extension", r).message;
			const t = [
				"lease_extension_denied",
				"lease_extension_budget_exceeded",
				"lease_extension_unsupported_provider",
				"lease_extension_not_advancing",
				"lease_not_active"
			].find((t) => e.includes(t));
			i = await inspect();
			await totalDeadline(i);
			failure(t ?? e, i);
		}
		i = await inspect();
		o = await totalDeadline(i);
		assertCurrent();
		if (o !== void 0 && o - Date.now() >= n) return;
		failure("extension did not confirm sufficient remaining total lifetime", i);
	}
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-script.ts
const CRABBOX_RUNTIME_NODE_PATH = "export PATH=\"$HOME/.openclaw-worker/runtime-node:$PATH\"";
/** Guest expression evaluated with fs, path, and the canonical home directory. */
function createCrabboxWorkerStateDirScript(e) {
	return `(() => {
  const previous = path.join(home, ".openclaw", ${JSON.stringify(`cloud-workers/${e}`)});
  // Retained leases keep their state, workspace identities, and process receipts.
  if (process.platform !== "win32" || fs.existsSync(previous)) return previous;
  const key = require("node:crypto").createHash("sha256").update(home).update("\\0").update(${JSON.stringify(e)}).digest("hex").slice(0, 32);
  return path.join(path.parse(home).root, "ocw", key);
})()`;
}
const BIND_RUNTIME_NODE = `node <<'CRABBOX_BIND_RUNTIME_NODE'
const fs = require("node:fs");
const path = require("node:path");
try {
  const directory = path.join(require("node:os").homedir(), ".openclaw-worker", "runtime-node");
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
  const link = path.join(directory, "node");
  let previous;
  try { previous = fs.readlinkSync(link); }
  catch (error) { if (error.code !== "ENOENT") throw error; }
  if (previous !== process.execPath) {
    if (previous !== undefined) fs.unlinkSync(link);
    fs.symlinkSync(process.execPath, link);
  }
} catch (error) {
  console.error("Cannot retain cloud runtime Node: " + error.message + "; repair ~/.openclaw-worker/runtime-node and reprovision the worker");
  process.exitCode = 1;
}
CRABBOX_BIND_RUNTIME_NODE`;
/** Crabbox executes script-stdin with the target's native shell. */
function wrapCrabboxNodeScript(e, t = "linux", n = "CRABBOX_NODE_SCRIPT", r = "runtime") {
	if (t !== "windows/normal") return `set -eu\n${t === "linux" ? `${r === "bootstrap" ? `${BIND_RUNTIME_NODE}\n` : ""}${CRABBOX_RUNTIME_NODE_PATH}\n` : ""}node <<'${n}'\n${e}\n${n}`;
	return `$ErrorActionPreference = 'Stop'
$node = Get-Command node -CommandType Application -ErrorAction SilentlyContinue
if (-not $node) { throw 'Cloud worker requires Node.js on PATH; update the Crabbox Windows bootstrap image and reprovision the worker' }
$scriptPath = Join-Path $env:TEMP ('openclaw-' + [Guid]::NewGuid().ToString('N') + '.cjs')
try {
  $source = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(e).toString("base64")}'))
  [IO.File]::WriteAllText($scriptPath, $source, [Text.UTF8Encoding]::new($false))
  & $node.Source $scriptPath
  $code = $LASTEXITCODE
} finally {
  Remove-Item -LiteralPath $scriptPath -Force -ErrorAction SilentlyContinue
}
exit $code`;
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-node-enrollment-diagnostics.ts
const MAX_NODE_ENROLLMENT_EVIDENCE_BYTES = 2048;
async function collectCrabboxNodeEnrollmentEvidence(e) {
	let t = "box evidence";
	let n;
	try {
		const t = await runCrabboxCommand({
			action: "enrollment diagnostics",
			args: leaseRunArgs(e),
			binary: e.binary,
			input: wrapCrabboxNodeScript(`const fs = require("node:fs");
const path = require("node:path");
const home = fs.realpathSync(require("node:os").homedir());
const state = ${createCrabboxWorkerStateDirScript(e.id)};
let runtime = "absent";
let alive = false;
let tail = "absent";
try { runtime = fs.readlinkSync(path.join(state, "runtime")); } catch { /* Unavailable runtime diagnostics retain the absent marker. */ }
try {
  const text = fs.readFileSync(path.join(state, "node.pid"), "utf8").trim();
  if (/^[1-9][0-9]*$/.test(text)) { process.kill(Number(text), 0); alive = true; }
} catch { /* An unconfirmed process remains dead-or-absent in this best-effort diagnostic. */ }
try {
  const fd = fs.openSync(path.join(state, "node.log"), "r");
  try {
    const size = fs.fstatSync(fd).size;
    const bom = Buffer.alloc(2);
    fs.readSync(fd, bom, 0, 2, 0);
    // Windows PowerShell 5.1 redirects to UTF-16LE, POSIX Node writes UTF-8.
    const utf16 = bom[0] === 0xff && bom[1] === 0xfe;
    const start = Math.max(0, size - 2000);
    const buffer = Buffer.alloc(Math.min(2000, size));
    const bytes = fs.readSync(fd, buffer, 0, buffer.length, utf16 ? start - start % 2 : start);
    let offset = 0;
    if (utf16 && bytes >= 2 && buffer.readUInt16LE(0) >= 0xdc00 && buffer.readUInt16LE(0) <= 0xdfff) offset = 2;
    if (!utf16) while (offset < bytes && (buffer[offset] & 0xc0) === 0x80) offset++;
    tail = buffer.subarray(offset, bytes).toString(utf16 ? "utf16le" : "utf8");
  } finally { fs.closeSync(fd); }
} catch { /* Missing logs must not replace the original enrollment failure. */ }
process.stdout.write("node-runtime=" + runtime + " node-pid=" + (alive ? "alive" : "dead-or-absent") + " node.log tail: " + tail);`, e.target),
			...e.signal ? { signal: e.signal } : {},
			timeoutMs: CRABBOX_NODE_ENROLLMENT_DIAGNOSTIC_TIMEOUT_MS
		});
		n = crabboxCommandOutput("enrollment diagnostics", t).trim();
		if (!n) throw new Error("diagnostic command returned no output");
	} catch (e) {
		t = "box evidence unavailable";
		n = e instanceof Error ? e.message : "diagnostic command failed";
	}
	let r = `${t}: `;
	const i = redactToolPayloadText(n).replace(/\s+/gu, " ").trim();
	const a = t === "box evidence" ? /^node-runtime=(.*?) node-pid=(alive|dead-or-absent) node\.log tail: (.*)$/u.exec(i) : null;
	if (a) r += `node-runtime=${truncateUtf8Prefix(a[1], 256)} node-pid=${a[2]} node.log tail: `;
	const o = Buffer.from(a?.[3] ?? i);
	let s = Math.max(0, o.length - (MAX_NODE_ENROLLMENT_EVIDENCE_BYTES - Buffer.byteLength(r)));
	while (s < o.length && (o[s] & 192) === 128) s++;
	return `${r}${o.subarray(s).toString("utf8")}`;
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-node-process.ts
/** The enrollment script and native desktop host share one process receipt contract. */
function createCrabboxNodeProcessRuntime(e, t) {
	return `const desktopTarget = ${JSON.stringify(e)};
${e === "windows/normal" ? createCrabboxWindowsDesktopNodeLauncher() : ""}
  // The watchdog only stops a hung tool; enrollment owns total time. CPU-starved macOS
  // hosts measured ps/lsof identity probes at up to 27 s, so Darwin gets the 60 s subprocess budget.
  const probeProcess = (binary, args, timeout = process.platform === "win32" ? 10000 : 60000) => {
    const result = spawnSync(binary, args, { env: nodeEnv, encoding: "utf8", windowsHide: true, timeout, killSignal: "SIGKILL", maxBuffer: 1024 * 1024 });
    return result.status === 0 && !result.error ? result.stdout.trim() : null;
  };
  const processStartTime = (pid) => probeProcess("ps", ["-o", "lstart=", "-p", String(pid)])?.replace(/\\s+/g, " ");
  const processCwdMatches = (pid) => {
    const args = ["-a", "-p", String(pid), "-d", "cwd", "-Fn"];
    const output = probeProcess("lsof", args) ?? probeProcess("/usr/sbin/lsof", args);
    const cwd = output?.split("\\n").filter((line) => line.startsWith("n"));
    return cwd?.length === 1 && fs.realpathSync(cwd[0].slice(1)) === runtimeDir;
  };
  const macosHostPath = ${JSON.stringify(`${CRABBOX_MACOS_APP_PATH}/Contents/MacOS/OpenClaw`)};
  const macosDesktopDirectory = ${JSON.stringify(e === "macos" ? crabboxMacosDesktopDirectory(t) : void 0)};
  const macosGuiLaunchScript = ${JSON.stringify(e === "macos" ? createCrabboxMacosGuiLaunchScript() : void 0)};
  const macosHostArgs = (enrollmentMode) => ["--cloud-worker-host", "--node-executable", process.execPath, "--runtime-dir", runtimeDir, "--state-dir", stateDir, "--desktop-dir", macosDesktopDirectory, "--lease-id", leaseId, "--display-name", displayName, "--enrollment-mode", enrollmentMode];
  const inspectMacosHost = (launch, nodePid) => {
    if (!launch || !Number.isSafeInteger(launch.hostPid) || launch.hostPid < 1 || typeof launch.hostStartTime !== "string" || !launch.hostStartTime) return null;
    let actual;
    try { actual = JSON.parse(probeProcess(macosHostPath, ["--cloud-worker-inspect-process", String(launch.hostPid), ...(nodePid === undefined ? [] : [String(nodePid)])]) ?? "null"); }
    catch { return null; }
    if (actual?.state === "gone" && Object.keys(actual).length === 1) return actual;
    return actual?.state === "active" && actual.host ? actual : null;
  };
  const macosRuntimeDirectory = () => {
    const stat = fs.statSync(runtimeDir, { bigint: true });
    return { device: BigInt.asUintN(32, stat.dev).toString(), inode: stat.ino.toString() };
  };
  const macosCwdMatches = (actual, expected) => actual?.device === expected.device && actual?.inode === expected.inode;
  const macosHostMatches = (launch, host, directory) => {
    if (!host || host.pid !== launch.hostPid || host.startTime !== launch.hostStartTime || host.uid !== process.getuid() || !macosCwdMatches(host.cwd, directory) || !Array.isArray(host.arguments)) return false;
    return ["connect", "resume"].some((value) => {
      const expected = [macosHostPath, ...macosHostArgs(value)];
      return expected.length === host.arguments.length && expected.every((argument, index) => argument === host.arguments[index]);
    });
  };
  const verifyMacosHost = (launch) => {
    const actual = inspectMacosHost(launch);
    return actual?.state === "active" && macosHostMatches(launch, actual.host, macosRuntimeDirectory());
  };
  const verifyMacosNode = (launch, pid) => {
    if (launch.pid !== pid || launch.runtimeDir !== runtimeDir || launch.stateDir !== stateDir || launch.cli !== cli) return false;
    const actual = inspectMacosHost(launch, pid);
    const directory = macosRuntimeDirectory();
    const node = actual?.node;
    if (actual?.state !== "active" || !macosHostMatches(launch, actual.host, directory) || !node || node.pid !== pid || node.startTime !== launch.startTime || node.uid !== process.getuid() || node.parentPid !== launch.hostPid || !macosCwdMatches(node.cwd, directory) || !Array.isArray(node.arguments) || fs.realpathSync(node.executablePath) !== fs.realpathSync(process.execPath)) return false;
    return ["openclaw", "openclaw-connect", "openclaw-node"].includes(node.arguments[0]) || (node.arguments.length >= 2 && fs.realpathSync(node.arguments[0]) === fs.realpathSync(process.execPath) && node.arguments[1] === cli);
  };
  const verifyDarwinNode = (launch, pid) => {
    const startTime = processStartTime(pid);
    const command = probeProcess("ps", ["-ww", "-o", "command=", "-p", String(pid)]);
    const invocation = process.execPath + " " + cli;
    const nodeInvocation = command !== null && (["openclaw", "openclaw-connect", "openclaw-node"].includes(command) || command === invocation || command.startsWith(invocation + " "));
    return launch.pid === pid && Boolean(startTime) && launch.startTime === startTime && launch.runtimeDir === runtimeDir && launch.stateDir === stateDir && launch.cli === cli && nodeInvocation && processCwdMatches(pid);
  };
  const windowsProcesses = (filter) => {
    const desktopFields = desktopTarget === "windows/normal" ? "; sessionId = $_.SessionId; userSid = [string](Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid" : "";
    const output = probeProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", "$ErrorActionPreference = 'Stop'; @(Get-CimInstance Win32_Process -Filter '" + filter + "' | ForEach-Object { @{ pid = $_.ProcessId; startTime = $_.CreationDate.ToUniversalTime().ToString('o'); executablePath = $_.ExecutablePath; commandLine = $_.CommandLine" + desktopFields + " } }) | ConvertTo-Json -Compress"]);
    if (!output) return [];
    const parsed = JSON.parse(output);
    return Array.isArray(parsed) ? parsed : [parsed];
  };
  const isWindowsNode = (entry) => {
    if (!entry || !Number.isSafeInteger(entry.pid) || entry.pid < 1 || typeof entry.startTime !== "string" || !entry.startTime || typeof entry.executablePath !== "string" || typeof entry.commandLine !== "string") return false;
    // Our invocation has exactly executable + CLI before its options. Windows paths
    // cannot contain quotes; accept quoted or unquoted path tokens in those positions.
    // CIM retains this command line even when Node changes the console title.
    const invocation = entry.commandLine.match(/^(?:"([^"]+)"|([^\\s"]+))\\s+(?:"([^"]+)"|([^\\s"]+))(?:\\s|$)/);
    return invocation !== null && (invocation[3] ?? invocation[4]) === cli && fs.realpathSync(invocation[1] ?? invocation[2]) === fs.realpathSync(process.execPath) && fs.realpathSync(entry.executablePath) === fs.realpathSync(process.execPath);
  };
  const reuseNodeProcess = () => {
  const hasPid = mode && fs.existsSync(pidFile);
  if (mode && !hasPid) {
    // The runtime pointer precedes detached launch; a lost PID cannot prove no process survived.
    for (const previous of [runtimeLink, launchFile]) {
      try {
        const entry = fs.lstatSync(previous);
        if (previous === runtimeLink && !entry.isSymbolicLink()) throw new Error("Cloud worker runtime pointer is occupied");
        throw new Error("Cloud worker node launch is incomplete; release and reprovision the worker");
      } catch (error) { if (error.code !== "ENOENT") throw error; }
    }
  }
  if (hasPid) {
    const pidText = fs.readFileSync(pidFile, "utf8").trim();
    if (!/^[1-9][0-9]*$/.test(pidText)) throw new Error("Cloud worker node PID is invalid; release and reprovision the worker");
    const pid = Number(pidText);
    let alive = true;
    try { process.kill(pid, 0); } catch (error) { if (error.code !== "ESRCH") throw error; alive = false; }
    if (alive) {
      let verified = false;
      if (process.platform === "linux") {
        const args = fs.readFileSync(path.join("/proc", pidText, "cmdline"), "utf8").split("\\0");
        const env = fs.readFileSync(path.join("/proc", pidText, "environ"), "utf8").split("\\0");
        // OpenClaw changes process.title; the immutable install cwd survives that argv rewrite.
        const title = args[0];
        const nodeInvocation = args[1] === cli || ["openclaw", "openclaw-connect", "openclaw-node"].includes(title);
        verified = nodeInvocation && fs.realpathSync(path.join("/proc", pidText, "cwd")) === runtimeDir && env.includes("OPENCLAW_STATE_DIR=" + stateDir);
      } else if (process.platform === "win32") {
        try {
          const launch = JSON.parse(fs.readFileSync(launchFile, "utf8"));
          const entries = windowsProcesses("ProcessId=" + pidText);
          const entry = entries.length === 1 ? entries[0] : undefined;
          // Windows exposes no cheap cwd probe. Bind launch-owned cwd/state to the
          // actual node.exe creation time and independently inspect its executable/argv.
          verified = isWindowsNode(entry) && entry.pid === pid && launch.pid === pid && launch.startTime === entry.startTime && launch.runtimeDir === runtimeDir && launch.stateDir === stateDir && launch.cli === cli;
          if (verified && desktopTarget === "windows/normal") {
            const session = readWindowsDesktopSessionIdentity();
            verified = entry.sessionId > 0 && entry.sessionId === session.sessionId && entry.userSid === session.userSid && launch.sessionId === session.sessionId && launch.userSid === session.userSid;
          }
        } catch { verified = false; }
      } else {
        try {
          // Darwin loses ps-visible environment when process.title changes. Bind the launch
          // facts to this live process's start time, then independently verify argv and cwd.
          const launch = JSON.parse(fs.readFileSync(launchFile, "utf8"));
          verified = desktopTarget === "macos" ? verifyMacosNode(launch, pid) : verifyDarwinNode(launch, pid);
        } catch { /* Missing launch or process identity must never authorize replay. */ }
      }
      if (!verified) {
        throw new Error("Cloud worker node is running a different bootstrap artifact or invocation; release and reprovision the worker");
      }
      return true;
    }
    if (desktopTarget === "macos") {
      const launch = JSON.parse(fs.readFileSync(launchFile, "utf8"));
      if (inspectMacosHost(launch)?.state !== "gone") throw new Error("Cloud worker desktop host is still running or could not be verified; release and reprovision the worker");
    }
    fs.unlinkSync(pidFile);
  }
  return false;
  };
  const launchNodeProcess = async () => {
  const args = mode === "connect" ? ["connect", "--target-file", setupFile] : ["node", "run"];
  setPhase("node launch");
  const logPath = path.join(stateDir, "node.log");
  const log = process.platform === "win32" ? undefined : fs.openSync(logPath, "a", 0o600);
  let child;
  let pid;
  let parentPid;
  let startTime;
  let desktopIdentity;
  try {
    const nodeArgs = [cli, ...args, "--ephemeral", "--display-name", displayName];
    if (desktopTarget === "macos") {
      // LaunchServices makes the signed host its own TCC responsibility owner.
      // open is only a waiter; the host's inspected receipt identifies the actual processes.
      child = spawn("/bin/bash", ["-c", macosGuiLaunchScript, "openclaw-gui", "/usr/bin/open", "-n", "-g", "-W", "-a", ${JSON.stringify(CRABBOX_MACOS_APP_PATH)}, "--stdin", "/dev/null", "--stdout", logPath, "--stderr", logPath, "--args", ...macosHostArgs(mode)], { cwd: runtimeDir, env: nodeEnv, detached: true, stdio: ["ignore", log, log] });
      await once(child, "spawn");
      const deadline = Date.now() + 90000;
      while (Date.now() < deadline) {
        if (fs.existsSync(pidFile)) {
          const launch = JSON.parse(fs.readFileSync(launchFile, "utf8"));
          const actualPid = Number(fs.readFileSync(pidFile, "utf8").trim());
          if (!verifyMacosNode(launch, actualPid)) throw new Error("Cloud worker native desktop host published a mismatched process receipt; release and reprovision the worker");
          child.unref();
          return;
        }
        if ((child.exitCode !== null && child.exitCode !== undefined) || child.signalCode) throw new Error("Cloud worker native desktop host exited before enrollment; inspect node.log and reprovision the worker");
        await new Promise((resolve) => setTimeout(resolve, 250));
      }
      throw new Error("Cloud worker native desktop host did not become ready; inspect node.log and reprovision the worker");
    } else if (desktopTarget === "windows/normal") {
      desktopIdentity = await launchWindowsDesktopNode({ nodePath: process.execPath, nodeArgs, cwd: runtimeDir, stateDir, logPath });
      ({ pid, startTime } = desktopIdentity);
    } else if (process.platform === "win32") {
      const quote = (value) => "'" + value.replaceAll("'", "''") + "'";
      // The managed launcher owns OpenSSH job breakaway. Its hidden PowerShell child
      // owns logging because detached processes must not inherit SSH stdio handles.
      const launchScript = "$env:OPENCLAW_STATE_DIR = " + quote(stateDir) + "; & " + [process.execPath, ...nodeArgs].map(quote).join(" ") + " *>> " + quote(logPath) + "; exit $LASTEXITCODE";
      const argumentList = "-NoLogo -NoProfile -NonInteractive -EncodedCommand " + Buffer.from(launchScript, "utf16le").toString("base64");
      const launched = probeProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", launcher, "-FilePath", "powershell.exe", "-ArgumentList", argumentList, "-WorkingDirectory", runtimeDir]);
      if (!/^[1-9][0-9]*$/.test(launched || "")) throw new Error("Cloud worker managed Windows launcher failed; release and reprovision the worker");
      parentPid = Number(launched);
      const deadline = Date.now() + 30000;
      while (!pid && Date.now() < deadline) {
        const entries = windowsProcesses("ParentProcessId=" + parentPid).filter(isWindowsNode);
        if (entries.length > 1) throw new Error("Cloud worker node invocation is ambiguous; release and reprovision the worker");
        if (entries.length === 1) { pid = entries[0].pid; startTime = entries[0].startTime; }
        else await new Promise((resolve) => setTimeout(resolve, 250));
      }
      if (!pid) throw new Error("Cloud worker node start time is unavailable; release and reprovision the worker");
    } else {
      child = spawn(process.execPath, nodeArgs, { cwd: runtimeDir, env: nodeEnv, detached: true, windowsHide: true, stdio: ["ignore", log, log] });
      await once(child, "spawn");
      pid = child.pid;
      if (process.platform !== "linux") startTime = processStartTime(pid);
    }
      if (process.platform !== "linux") {
        if (!startTime) throw new Error("Cloud worker node start time is unavailable; release and reprovision the worker");
        const temporary = launchFile + "." + crypto.randomUUID();
        try {
          fs.writeFileSync(temporary, JSON.stringify({ pid, startTime, runtimeDir, stateDir, cli, ...(desktopIdentity ? { sessionId: desktopIdentity.sessionId, userSid: desktopIdentity.userSid } : {}) }), { mode: 0o600, flag: "wx" });
          fs.renameSync(temporary, launchFile);
        } finally { fs.rmSync(temporary, { force: true }); }
      }
      fs.writeFileSync(pidFile, String(pid) + "\\n", { mode: 0o600 });
    child?.unref();
  } catch (error) {
    if (desktopTarget === "macos") {
      let confirmedStopped = !child?.pid;
      try {
        let launch;
        try {
          const receipt = JSON.parse(fs.readFileSync(launchFile, "utf8"));
          if (verifyMacosHost(receipt)) launch = receipt;
        } catch { /* A host can fail before publishing its Node receipt. */ }
        if (launch && verifyMacosHost(launch)) {
          process.kill(launch.hostPid, "SIGTERM");
          const deadline = Date.now() + 15000;
          while (Date.now() < deadline) {
            const current = inspectMacosHost(launch);
            if (current?.state === "gone" || (current?.state === "active" && current.host.pid === launch.hostPid && current.host.startTime !== launch.hostStartTime)) { confirmedStopped = true; break; }
            await new Promise((resolve) => setTimeout(resolve, 250));
          }
        }
      } catch { /* The provider's lease teardown owns an unconfirmed host launch. */ }
      child?.unref();
      if (!confirmedStopped) error.message += "; native desktop host shutdown could not be confirmed; lease teardown is required";
    } else if (desktopIdentity) {
      const entries = windowsProcesses("ProcessId=" + pid);
      if (entries.length === 1 && isWindowsNode(entries[0]) && entries[0].startTime === startTime) spawnSync("taskkill.exe", ["/PID", String(pid), "/T", "/F"], { env: nodeEnv, windowsHide: true, stdio: "ignore", timeout: 10000 });
    } else if (parentPid) spawnSync("taskkill.exe", ["/PID", String(parentPid), "/T", "/F"], { env: nodeEnv, windowsHide: true, stdio: "ignore", timeout: 10000 });
    else if (pid) process.kill(-pid, "SIGTERM");
    throw error;
  } finally { if (log !== undefined) fs.closeSync(log); }
  };
`;
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-node-enrollment.ts
const CLOUD_SETUP_CODE_ENV = "CRABBOX_WORKER_SETUP_CODE";
const CLOUD_BOOTSTRAP_TOKEN_ENV = "CRABBOX_WORKER_BOOTSTRAP_TOKEN";
const LINUX_PLATFORM_TRUST_SETUP = `set -eu
if [ -x /usr/sbin/update-ca-certificates ]; then
  (
    unset ${CLOUD_SETUP_CODE_ENV} ${CLOUD_BOOTSTRAP_TOKEN_ENV} CRABBOX_WORKER_CODEX_CONFIG
    if [ "$(id -u)" = 0 ]; then
      /usr/sbin/update-ca-certificates
    else
      sudo -n -- /usr/sbin/update-ca-certificates
    fi
  ) || {
    echo 'Cloud worker platform trust registration failed; repair system certificate setup before enrollment' >&2
    exit 1
  }
fi
`;
const CLOUD_BOOTSTRAP_DOWNLOAD_IDLE_TIMEOUT_MS = 12e4;
function createCrabboxNodeEnrollmentSetup(e) {
	return createCrabboxNodeSetup({
		...e,
		nodeBootstrap: e.enrollment.nodeBootstrap
	});
}
function createCrabboxNodeRuntimeSetup(e) {
	return createCrabboxNodeSetup(e);
}
function createCrabboxNodeSetup(e) {
	const { enrollment: t, leaseId: n } = e;
	const { token: r, linuxToolchainSetup: i, installLock: a, ...o } = e.nodeBootstrap;
	const s = a ? (({ token: e, ...t }) => t)(a) : void 0;
	const c = e.workerBundle ? (({ token: e, ...t }) => t)(e.workerBundle) : void 0;
	const l = e.desktop ? e.target ?? "linux" : void 0;
	const u = l === "linux" ? [
		"set -eu",
		...createCrabboxXfceSessionEnvironment(),
		`exec "$1" -e 'process.stdout.write(JSON.stringify({DISPLAY:process.env.DISPLAY,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS,XDG_RUNTIME_DIR:process.env.XDG_RUNTIME_DIR}))'`
	].join("\n") : null;
	const d = `const fs = require("node:fs");
const fsp = fs.promises;
const path = require("node:path");
const os = require("node:os");
const crypto = require("node:crypto");
const http = require("node:http");
const https = require("node:https");
const { spawn, spawnSync } = require("node:child_process");
const { once } = require("node:events");
const { performance } = require("node:perf_hooks");
const { setTimeout: delay } = require("node:timers/promises");
const bootstrap = ${JSON.stringify(o)};
const workerBundle = ${JSON.stringify(c)};
const installLock = ${JSON.stringify(s)};
const leaseId = ${JSON.stringify(n)};
const displayName = ${JSON.stringify(t?.displayName)};
const mode = ${JSON.stringify(t?.mode)};
const desktopEnvironment = ${JSON.stringify(u)};
const desktopSetup = ${JSON.stringify(e.desktopSetup)};
const credentials = process.env.${CLOUD_BOOTSTRAP_TOKEN_ENV};
const setupCode = process.env.${CLOUD_SETUP_CODE_ENV};
delete process.env.${CLOUD_BOOTSTRAP_TOKEN_ENV};
delete process.env.${CLOUD_SETUP_CODE_ENV};
if (process.platform !== "win32") process.umask(0o077);
let phase;
let phaseStarted = performance.now();
const failureMessage = (artifact, failedPhase, code, origin) => "Cloud worker " + artifact + " " + failedPhase + " failed" + (code ? " (" + code + ")" : "") + (origin ? " from " + origin : "");
const setPhase = (next) => {
  if (phase === next) return;
  const now = performance.now();
  if (phase) console.error("CRABBOX_TIMING:openclaw-bootstrap-" + phase.toLowerCase().replaceAll(" ", "-") + ":" + Math.round(now - phaseStarted));
  phaseStarted = now;
  phase = next;
  console.error("CRABBOX_PHASE:openclaw-bootstrap-" + next.toLowerCase().replaceAll(" ", "-"));
};
setPhase("preparation");
(async () => {
  let tokens;
  try { tokens = JSON.parse(credentials || "{}"); }
  catch { throw new Error("Cloud worker bootstrap credential format is invalid"); }
  const home = fs.realpathSync(os.homedir());
  const stateDir = ${createCrabboxWorkerStateDirScript(n)};
  const runtimeRoot = path.join(home, ".openclaw-worker", "node-runtimes");
  const runtimeDir = path.join(runtimeRoot, bootstrap.sha256);
  const cli = path.join(runtimeDir, "node_modules", "openclaw", "openclaw.mjs");
  const pidFile = path.join(stateDir, "node.pid");
  const launchFile = path.join(stateDir, "node-launch.json");
  const setupFile = path.join(stateDir, "setup-code");
  const runtimeLink = path.join(stateDir, "runtime");
  const nodeEnv = { ...process.env, ...(mode ? { OPENCLAW_STATE_DIR: stateDir } : {}) };
  // Tools travel inside the verified full-node artifact and share its preparation identity.
  if (process.platform !== "win32") {
    nodeEnv.PATH = (process.platform === "linux" ? path.dirname(process.execPath) + path.delimiter : "") + path.join(runtimeDir, "node_modules", "openclaw", "dist", "worker-tools", "bin") + path.delimiter + (nodeEnv.PATH || "");
  }
  const subprocessError = (message, result) => {
    let detail = [result.error?.message, result.stderr].filter(Boolean).join("\\n");
    // Sanitize complete values before truncation can leave an unrecognizable credential fragment.
    const privateValues = [credentials, setupCode, ...Object.values(tokens), ...Object.values(nodeEnv)]
      .filter((value) => typeof value === "string" && value.length > 0)
      .sort((a, b) => b.length - a.length);
    for (const value of privateValues) detail = detail.replaceAll(value, "[redacted]");
    detail = detail
      .replace(/\\b(?:Bearer|Basic)\\s+\\S+/gi, "[redacted]")
      .replace(/([A-Za-z_][A-Za-z0-9_]*\\s*=\\s*)(?:"[^"]*"|'[^']*'|[^\\s]+)/g, "$1[redacted]")
      .replace(/\\s+/g, " ").trim();
    const bytes = Buffer.from(detail);
    let start = Math.max(0, bytes.length - 512);
    while (start < bytes.length && (bytes[start] & 0xc0) === 0x80) start++;
    const cause = new Error("exit code " + (result.status ?? "unknown") + ", signal " + (result.signal ?? "none") + (detail ? ": " + bytes.subarray(start).toString("utf8") : ""));
    return new Error(message + ": " + cause.message, { cause });
  };
  const finishDesktopSetup = () => {
    if (!desktopSetup) return;
    setPhase("desktop setup");
    // The wallpaper can exceed the OS argument limit; stream the owned script over stdin.
    if (process.platform === "win32") {
      runWindowsDesktopPowerShell(desktopSetup);
      return;
    }
    const result = spawnSync("bash", ["-s"], { input: desktopSetup, env: nodeEnv, stdio: ["pipe", "inherit", "inherit"], timeout: ${CRABBOX_SETUP_TIMEOUT_MS}, killSignal: "SIGKILL" });
    if (result.error) throw result.error;
    if (result.status !== 0) throw new Error("Cloud worker desktop setup failed" + (result.signal ? " (" + result.signal + ")" : " with exit code " + result.status));
  };
  const directoryOptions = process.platform === "win32" ? {} : { mode: 0o700 };
  // Forks of a warm image load disk blocks lazily on first read, so a cold node start
  // spends ~30 s on serial reads. A boot-time parallel read of the current runtime
  // overlaps that with SSH readiness. Best effort: images without cron keep the cold start.
  // Only a Crabbox run on this lease edits the crontab; local executions (tests) never do.
  const installRuntimePrefetch = () => {
    if (process.platform !== "linux" || process.env.CRABBOX_LEASE_ID !== leaseId) return;
    try {
      const script = path.join(runtimeRoot, ".prefetch.sh");
      const nodeDir = path.dirname(path.dirname(fs.realpathSync(process.execPath)));
      fs.writeFileSync(path.join(runtimeRoot, ".prefetch"), runtimeDir + "\\n" + nodeDir + "\\n");
      fs.writeFileSync(script, '#!/bin/sh\\ncd "$(dirname "$0")" || exit 0\\ndate +%s.%N > .prefetch.log\\nwhile IFS= read -r dir; do find "$dir" -type f -print0; done < .prefetch | xargs -0 -n 64 -P 64 cat > /dev/null 2>&1\\ndate +%s.%N >> .prefetch.log\\n', { mode: 0o700 });
      const current = spawnSync("crontab", ["-l"], { encoding: "utf8", timeout: 10000 });
      const kept = (current.status === 0 ? current.stdout : "").split("\\n").filter((line) => line && !line.includes(script));
      spawnSync("crontab", ["-"], { input: [...kept, "@reboot /bin/sh " + script].join("\\n") + "\\n", timeout: 10000 });
    } catch { /* Prefetch is optional; failed setup keeps the ordinary cold-start path. */ }
  };
  const launcher = path.join(process.env.ProgramFiles || "C:\\\\Program Files", "Crabbox", "bin", "Start-CrabboxDetachedProcess.ps1");
  if (process.platform === "win32" && mode && !${JSON.stringify(l === "windows/normal")} && !fs.existsSync(launcher)) {
    throw new Error("Cloud worker requires " + launcher + "; update the Crabbox Windows bootstrap image and reprovision the worker");
  }
  if (desktopEnvironment) {
    // Inspect XFCE only after stripping forwarded credentials from every child environment.
    const desktop = spawnSync("bash", ["-c", desktopEnvironment, "bash", process.execPath], { env: nodeEnv, encoding: "utf8", timeout: 60000 });
    if (desktop.status !== 0) throw new Error(desktop.stderr?.trim() || "Cloud worker XFCE session is unavailable");
    delete nodeEnv.XDG_RUNTIME_DIR;
    Object.assign(nodeEnv, JSON.parse(desktop.stdout));
  }
  if (mode) {
    fs.mkdirSync(stateDir, { recursive: true, ...directoryOptions });
    if (process.platform !== "win32") fs.chmodSync(stateDir, 0o700);
    else if (path.dirname(stateDir) === path.join(path.parse(home).root, "ocw")) {
      // The drive root does not inherit the worker profile's private permissions.
      const quote = (value) => "'" + value.replaceAll("'", "''") + "'";
      const secureState = "$ErrorActionPreference = 'Stop'; $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value; icacls.exe " + quote(stateDir) + " /inheritance:r /grant:r ('*' + $sid + ':(OI)(CI)F') /grant:r '*S-1-5-18:(OI)(CI)F' /grant:r '*S-1-5-32-544:(OI)(CI)F' | Out-Null; exit $LASTEXITCODE";
      const result = spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", secureState], { env: nodeEnv, encoding: "utf8", windowsHide: true, timeout: 10000 });
      if (result.error || result.status !== 0) throw subprocessError("Cloud worker state directory permissions could not be secured", result);
    }
  }
  ${createCrabboxNodeProcessRuntime(l, n)}
  if (desktopTarget === "macos") finishDesktopSetup();
  if (reuseNodeProcess()) {
    if (desktopTarget !== "macos") finishDesktopSetup();
    setPhase("complete");
    return;
  }
  const verifyRuntime = (root) => {
    setPhase("runtime verification");
    if (!fs.lstatSync(root).isDirectory() || fs.realpathSync(root) !== root) throw new Error("Cloud worker bootstrap runtime path is unsafe");
    const packageRoot = path.join(root, "node_modules", "openclaw");
    const manifest = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"));
    if (manifest.name !== "openclaw" || manifest.version !== bootstrap.openclawVersion) throw new Error("Cloud worker bootstrap package identity does not match the Gateway");
    const probe = spawnSync(process.execPath, [path.join(packageRoot, "openclaw.mjs"), "--version"], { env: nodeEnv, encoding: "utf8", timeout: 60000 });
    const version = probe.stdout?.trim();
    const expected = "OpenClaw " + bootstrap.openclawVersion;
    if (probe.status !== 0 || (version !== expected && !version?.startsWith(expected + " "))) throw subprocessError("Cloud worker bootstrap CLI could not verify its Gateway version", probe);
  };
  const verifyArchive = async (source, artifact) => {
    const hash = crypto.createHash("sha256");
    let bytes = 0;
    for await (const chunk of source) {
      bytes += chunk.byteLength;
      if (bytes > artifact.bytes) throw new Error("Cloud worker bootstrap archive exceeds its declared size");
      hash.update(chunk);
    }
    if (bytes !== artifact.bytes || hash.digest("hex") !== artifact.sha256) throw new Error("Cloud worker bootstrap archive failed integrity verification");
  };
  const downloadAbort = new AbortController();
  const downloadAttempt = async (artifact, token, archive, offset, reportPhase) => {
    reportPhase("download connection");
    // A reset after the final bytes needs verification, not an unsatisfiable range.
    if (offset >= artifact.bytes) {
      await verifyArchive(fs.createReadStream(archive), artifact);
      return;
    }
    if (!token) throw new Error("Cloud worker bootstrap download authority is unavailable");
    const url = new URL(artifact.url);
    if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || (artifact.tlsFingerprint && url.protocol !== "https:")) throw new Error("Cloud worker bootstrap artifact transport is invalid");
    const normalizePin = (value) => value.trim().replace(/^sha256:/i, "").replaceAll(":", "").toLowerCase();
    const pin = artifact.tlsFingerprint ? normalizePin(artifact.tlsFingerprint) : undefined;
    if (pin && !/^[a-f0-9]{64}$/.test(pin)) throw new Error("Cloud worker bootstrap TLS fingerprint is invalid");
    const transport = url.protocol === "https:" ? https : http;
    const request = transport.request(url, {
      agent: false, headers: { authorization: "Bearer " + token, ...(offset ? { range: "bytes=" + offset + "-" } : {}) }, signal: downloadAbort.signal,
      ...(pin ? { rejectUnauthorized: false, session: Buffer.alloc(0) } : {}),
    });
    // The response/body readers still reject; keep errors observed between their awaits.
    request.on("error", () => {});
    request.once("response", (response) => response.on("error", () => {}));
    // Observe transport progress without changing when the pinned request may send credentials.
    request.once("socket", (socket) => {
      socket.setTimeout(${CLOUD_BOOTSTRAP_DOWNLOAD_IDLE_TIMEOUT_MS}, () => request.destroy(Object.assign(new Error("Cloud worker bootstrap download stalled"), { code: "ETIMEDOUT" })));
      socket.once("connect", () => { reportPhase(url.protocol === "https:" ? "download TLS" : "download HTTP response"); });
      socket.once("secureConnect", () => { if (!pin) reportPhase("download HTTP response"); });
    });
    const pendingResponse = once(request, "response").then(([response]) => response);
    // Pinned private certificates authenticate the socket before any bearer bytes leave.
    void (async () => {
      if (pin) {
        const [socket] = await once(request, "socket");
        await once(socket, "secureConnect");
        if (normalizePin(socket.getPeerCertificate().fingerprint256 ?? "") !== pin) throw new Error("Cloud worker bootstrap TLS fingerprint mismatch");
        reportPhase("download HTTP response");
      }
      request.end();
    })().catch((error) => request.destroy(error));
    const response = await pendingResponse;
    try {
      if (response.statusCode === 416 && offset) {
        fs.rmSync(archive, { force: true });
        throw Object.assign(new Error("Cloud worker bootstrap resume range was rejected"), { code: "ARTIFACT_RANGE_MISMATCH" });
      }
      if (response.statusCode !== 200 && response.statusCode !== 206) {
        const error = Object.assign(new Error("Cloud worker bootstrap download failed with HTTP " + response.statusCode), { statusCode: response.statusCode });
        if (response.statusCode === 503) {
          let body = "";
          for await (const chunk of response) {
            if (Buffer.byteLength(body) + chunk.byteLength > 1024) { body = ""; break; }
            body += chunk.toString("utf8");
          }
          try { if (JSON.parse(body)?.error === "transfer_in_progress") error.code = "TRANSFER_IN_PROGRESS"; }
          catch { /* Other proxy responses remain ordinary HTTP failures. */ }
        }
        throw error;
      }
      if (response.statusCode === 200) {
        // An older Gateway or proxy may ignore Range; never append its full response.
        fs.rmSync(archive, { force: true });
        offset = 0;
      } else if (response.headers["content-range"] !== "bytes " + offset + "-" + (artifact.bytes - 1) + "/" + artifact.bytes) {
        fs.rmSync(archive, { force: true });
        throw Object.assign(new Error("Cloud worker bootstrap resume range does not match the Gateway"), { code: "ARTIFACT_RANGE_MISMATCH" });
      }
      if (response.headers["content-length"] !== undefined && Number(response.headers["content-length"]) !== artifact.bytes - offset) {
        fs.rmSync(archive, { force: true });
        throw Object.assign(new Error("Cloud worker bootstrap archive length does not match the Gateway"), response.statusCode === 206 ? { code: "ARTIFACT_RANGE_MISMATCH" } : {});
      }
      reportPhase("download body");
      const output = await fsp.open(archive, offset ? "a" : "wx", 0o600);
      try {
        for await (const chunk of response) {
          offset += chunk.byteLength;
          if (offset > artifact.bytes) throw new Error("Cloud worker bootstrap archive exceeds its declared size");
          await output.writeFile(chunk);
        }
      }
      finally { await output.close(); }
      await verifyArchive(fs.createReadStream(archive), artifact);
    } finally { response.destroy(); }
  };
  const downloadArchive = async (artifact, token, archive, reportPhase = setPhase, optional = false) => {
    let downloadPhase;
    let origin;
    const downloadArtifact = artifact === workerBundle ? "archive" : "node bootstrap";
    const progress = (next) => { downloadPhase = next; reportPhase(next); };
    let attempt = 1;
    let retries = 0;
    let noProgressFailures = 0;
    // A fresh no-progress streak waits about 24-40 seconds through edge reconnects.
    const maxNoProgressFailures = 9;
    let offset = 0;
    let retainedAnyBytes = false;
    const partial = archive + ".partial";
    try {
      origin = new URL(artifact.url).origin;
      for (;;) {
        try {
          if (retries > 0) await delay(Math.round(250 * 2 ** Math.min(retries - 1, 5) * (0.75 + Math.random() * 0.5)), undefined, { signal: downloadAbort.signal });
          downloadAbort.signal.throwIfAborted();
          await downloadAttempt(artifact, token, partial, offset, progress);
          fs.renameSync(partial, archive);
          return;
        } catch (error) {
          if (downloadAbort.signal.aborted) throw downloadAbort.signal.reason;
          const busy = error.code === "TRANSFER_IN_PROGRESS";
          const transient = busy || ["ARTIFACT_RANGE_MISMATCH", "ECONNRESET", "ECONNREFUSED", "ECONNABORTED", "ENETUNREACH", "EHOSTUNREACH", "ENETDOWN", "EPIPE", "ERR_STREAM_PREMATURE_CLOSE", "ABORT_ERR", "ETIMEDOUT", "ESOCKETTIMEDOUT", "EAI_AGAIN"].includes(error.code) || [502, 503, 504, 520, 521, 522, 523, 524, 530].includes(error.statusCode);
          if (transient && !busy) {
            let retainedBytes = 0;
            try { retainedBytes = (await fsp.stat(partial)).size; }
            catch (statError) { if (statError.code !== "ENOENT") throw statError; }
            // Count retained progress, not bytes replayed by a proxy that ignores Range.
            noProgressFailures = retainedBytes > offset ? 0 : noProgressFailures + 1;
            offset = retainedBytes;
            retainedAnyBytes ||= retainedBytes > 0;
          }
          if (!transient || noProgressFailures === maxNoProgressFailures) {
            const hint = !retainedAnyBytes && ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "EHOSTUNREACH", "ENETUNREACH", "EAI_AGAIN"].includes(error.code)
              ? " The worker could not reach the Gateway public origin <" + origin + ">; verify the provider's network can reach it (for example with curl from a sandbox) or configure gateway.publicOrigin on a reachable hostname."
              : "";
            throw Object.assign(new Error(error.message + " (download attempt " + attempt + (noProgressFailures === maxNoProgressFailures ? "; " + maxNoProgressFailures + " consecutive no-progress failures" : "") + ")" + hint, { cause: error }), { code: error.code });
          }
          if (!busy) attempt++;
          retries++;
          console.error(failureMessage("bootstrap", downloadPhase, error.code || "HTTP_" + error.statusCode, origin) + "; retrying download attempt " + attempt + " (" + noProgressFailures + "/" + maxNoProgressFailures + " consecutive no-progress failures)");
        }
      }
    } catch (error) {
      if (optional) throw error;
      if (!downloadAbort.signal.aborted) {
        downloadAbort.abort(Object.assign(new Error(failureMessage(downloadArtifact, downloadPhase || phase, error.code, origin) + ": " + error.message, { cause: error }), { code: error.code, downloadPhase, downloadArtifact }));
      }
      throw downloadAbort.signal.reason;
    } finally { fs.rmSync(partial, { force: true }); }
  };
  const workerArchivePath = (root) => {
    const relative = workerBundle.packageRelativePath;
    const parts = relative.split("/");
    if (parts.length !== 2 || !/^[a-z][a-z-]*$/.test(parts[0]) || parts[1] !== workerBundle.sha256 + ".tgz" || !/^[a-f0-9]{64}$/.test(workerBundle.sha256)) throw new Error("Cloud worker archive package path is invalid");
    return path.join(root, "node_modules", "openclaw", ...parts);
  };
  const verifyWorkerArchive = async (root) => {
    setPhase("worker archive verification");
    const archive = workerArchivePath(root);
    let handle;
    // A non-regular artifact (including a FIFO) must reject without blocking preparation.
    try { handle = await fsp.open(archive, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK); }
    catch (error) { if (error.code === "ENOENT") return false; throw error; }
    try {
      const stat = await handle.stat();
      if (!stat.isFile() || stat.nlink !== 1 || stat.size !== workerBundle.bytes || fs.realpathSync(archive) !== archive) throw new Error("Cloud worker prepared archive path or length is unsafe");
      const source = handle.createReadStream({ autoClose: false });
      try { await verifyArchive(source, workerBundle); }
      finally { source.destroy(); }
    } finally { await handle.close(); }
    return true;
  };
  const publishWorkerArchive = (root, downloaded) => {
    if (!workerBundle) return;
    setPhase("worker archive publication");
    const archive = workerArchivePath(root);
    const directory = path.dirname(archive);
    fs.mkdirSync(directory, { recursive: true, ...directoryOptions });
    if (fs.realpathSync(directory) !== directory || !fs.lstatSync(directory).isDirectory()) throw new Error("Cloud worker prepared archive directory is unsafe");
    if (downloaded) fs.renameSync(downloaded, archive);
    // This package owns one immutable source archive; ordinary node installs never write here.
    for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
      if (entry.name !== path.basename(archive) && /^[a-f0-9]{64}\\.tgz$/.test(entry.name)) {
        if (!entry.isFile() || entry.isSymbolicLink()) throw new Error("Cloud worker prepared archive directory contains an unsafe artifact");
        fs.unlinkSync(path.join(directory, entry.name));
      }
    }
  };
  fs.mkdirSync(runtimeRoot, { recursive: true, ...directoryOptions });
  const existingRuntime = fs.existsSync(runtimeDir);
  if (existingRuntime) verifyRuntime(runtimeDir);
  if (existingRuntime && (!workerBundle || await verifyWorkerArchive(runtimeDir))) {
    publishWorkerArchive(runtimeDir);
  } else {
  const stage = fs.mkdtempSync(path.join(runtimeRoot, "node-bootstrap-"));
  try {
    const archive = path.join(stage, "node-runtime.tgz");
    const downloadedWorker = workerBundle ? path.join(stage, "worker.tgz") : undefined;
    const installDir = existingRuntime ? runtimeDir : path.join(stage, "runtime");
    const overlap = downloadedWorker && !existingRuntime;
    // Both capabilities expire from issuance; installation must not wait for the worker archive.
    await Promise.allSettled([
      (async () => {
        if (existingRuntime) return;
        await downloadArchive(bootstrap, tokens.nodeBootstrap, archive);
        downloadAbort.signal.throwIfAborted();
        fs.mkdirSync(installDir, directoryOptions);
        let locked = false;
        const warnUnlocked = (reason) => console.error("CRABBOX_WARNING:openclaw-bootstrap-unlocked-install:" + reason);
        if (installLock) {
          try {
            setPhase("lock download");
            await downloadArchive(installLock, tokens.installLock, path.join(installDir, "package-lock.json"), () => {}, true);
            locked = true;
          } catch (error) {
            downloadAbort.signal.throwIfAborted();
            warnUnlocked("lock download failed " + (error.code || error.statusCode || "integrity or transport error"));
          }
        } else warnUnlocked("lock unavailable from Gateway");
        const writeProject = () => fs.writeFileSync(path.join(installDir, "package.json"), JSON.stringify({
          private: true,
          // npm 12 trusts only this verified package; dependency script policy stays unchanged.
          allowScripts: { ["file:" + archive]: true },
          ...(locked ? { dependencies: { openclaw: "file:../node-runtime.tgz" } } : {}),
        }), { mode: 0o600 });
        writeProject();
        setPhase(overlap ? "installation and worker download" : "installation");
        const logPath = path.join(stage, "install.log");
        const runInstall = async () => {
          const log = fs.openSync(logPath, "w", 0o600);
          try {
            const npmCli = path.join(path.dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js");
            if (process.platform === "win32" && !fs.existsSync(npmCli)) throw new Error("Cloud worker requires npm beside node.exe; update the Crabbox Windows bootstrap image and reprovision the worker");
            return await new Promise((resolve) => {
              const child = spawn(process.platform === "win32" ? process.execPath : "npm", [...(process.platform === "win32" ? [npmCli] : []), ...(locked ? ["ci"] : ["install", "--no-save", "--package-lock=false"]), "--prefix", installDir, "--omit=dev", "--no-audit", "--no-fund", "--ignore-scripts=false", ...(locked ? [] : [archive])], { cwd: stage, env: nodeEnv, detached: process.platform !== "win32", windowsHide: true, stdio: ["ignore", log, log] });
              let error;
              const stopInstall = () => {
                if (!child.pid) return;
                // Kill the owned npm group, including lifecycle scripts, then join close below.
                try {
                  if (process.platform === "win32") {
                    const stopped = spawnSync("taskkill.exe", ["/PID", String(child.pid), "/T", "/F"], { env: nodeEnv, windowsHide: true, stdio: "ignore", timeout: 10000 });
                    if (stopped.error) error = stopped.error;
                  } else process.kill(-child.pid, "SIGKILL");
                } catch (cause) { if (cause.code !== "ESRCH") error = cause; }
              };
              const timeout = setTimeout(() => {
                error = new Error("Cloud worker bootstrap package installation timed out");
                stopInstall();
              }, 600000);
              const cancelInstall = () => downloadAbort.abort(new Error("Cloud worker bootstrap installation cancelled"));
              process.once("SIGTERM", cancelInstall);
              process.once("SIGINT", cancelInstall);
              child.once("error", (cause) => { error = cause; });
              child.once("close", (status, signal) => {
                clearTimeout(timeout);
                process.removeListener("SIGTERM", cancelInstall);
                process.removeListener("SIGINT", cancelInstall);
                downloadAbort.signal.removeEventListener("abort", stopInstall);
                resolve({ status, signal, error });
              });
              downloadAbort.signal.addEventListener("abort", stopInstall, { once: true });
              if (downloadAbort.signal.aborted) stopInstall();
            });
          } finally { fs.closeSync(log); }
        };
        let installed = await runInstall();
        downloadAbort.signal.throwIfAborted();
        if (locked && (installed.status !== 0 || installed.error)) {
          const code = /npm (?:error|ERR!) code ([A-Z0-9_]+)/.exec(fs.readFileSync(logPath, "utf8"))?.[1];
          warnUnlocked("npm ci rejected lock " + (code || installed.signal || "exit " + installed.status));
          locked = false;
          fs.rmSync(path.join(installDir, "package-lock.json"), { force: true });
          fs.rmSync(path.join(installDir, "node_modules"), { recursive: true, force: true });
          writeProject();
          installed = await runInstall();
          downloadAbort.signal.throwIfAborted();
        }
        if (installed.status !== 0 || installed.error) {
          const tail = fs.readFileSync(logPath, "utf8").slice(-2048);
          throw new Error("Cloud worker bootstrap package installation failed (" + (installed.error?.message || installed.signal || "exit code " + installed.status) + "): " + tail);
        }
        verifyRuntime(installDir);
      })().catch((error) => {
        if (!downloadAbort.signal.aborted) downloadAbort.abort(Object.assign(error, { downloadPhase: phase }));
        throw downloadAbort.signal.reason;
      }),
      // The runtime branch owns the overlap marker; downloadArchive retains the worker's error phase.
      downloadedWorker ? downloadArchive(workerBundle, tokens.workerBundle, downloadedWorker, overlap ? () => {} : setPhase) : undefined,
    ]);
    // A started npm child must close before either branch can release its staging files.
    if (downloadAbort.signal.aborted) throw downloadAbort.signal.reason;
    publishWorkerArchive(installDir, downloadedWorker);
    // Archive publication completes before a fresh runtime becomes reusable or capture can begin.
    if (!existingRuntime) fs.renameSync(installDir, runtimeDir);
  } finally { fs.rmSync(stage, { recursive: true, force: true }); }
  }
  installRuntimePrefetch();
  // A project snapshot contains only verified runtime bytes, never enrollment state.
  if (!mode) {
    setPhase("complete");
    return;
  }
  setPhase("activation");
  try {
    if (!fs.lstatSync(runtimeLink).isSymbolicLink()) throw new Error("Cloud worker runtime pointer is occupied");
    fs.unlinkSync(runtimeLink);
  } catch (error) { if (error.code !== "ENOENT") throw error; }
  setPhase("plugin activation");
  const pluginIds = [...new Set([...bootstrap.enabledPluginIds, ...${JSON.stringify(e.desktop ? ["cua-computer"] : [])}])];
  if (pluginIds.length > 0) {
    // One CLI process retains the combined per-plugin time and output allowances.
    const enabled = spawnSync(process.execPath, [cli, "plugins", "enable", ...pluginIds], { env: nodeEnv, encoding: "utf8", timeout: 60000 * pluginIds.length, maxBuffer: 1024 * 1024 * pluginIds.length });
    if (enabled.status !== 0) throw subprocessError("Cloud worker bootstrap could not enable plugins " + pluginIds.join(", "), enabled);
  }
  // Publishing this pointer earlier makes fresh state look like a legacy installation.
  fs.symlinkSync(runtimeDir, runtimeLink, process.platform === "win32" ? "junction" : "dir");
  if (mode === "connect") {
    if (!setupCode) throw new Error("Cloud worker enrollment credential is unavailable");
    fs.writeFileSync(setupFile, setupCode + "\\n", { mode: 0o600 });
  }
  await launchNodeProcess();
  if (desktopTarget !== "macos") finishDesktopSetup();
  setPhase("complete");
})().catch((error) => { console.error(error.downloadArtifact ? error.message : failureMessage("node bootstrap", error.downloadPhase || phase, error.code) + ": " + error.message); process.exitCode = 1; });
`;
	return {
		command: ((e.target ?? "linux") === "linux" ? (t ? LINUX_PLATFORM_TRUST_SETUP : "") + (i ?? "") : "") + wrapCrabboxNodeScript(d.trimEnd(), e.target, "CRABBOX_NODE_ENROLLMENT_SCRIPT", "bootstrap"),
		forwardedEnv: {
			[CLOUD_BOOTSTRAP_TOKEN_ENV]: JSON.stringify({
				nodeBootstrap: r,
				workerBundle: e.workerBundle?.token,
				installLock: a?.token
			}),
			...t?.mode === "connect" ? { [CLOUD_SETUP_CODE_ENV]: t.setupCode } : {}
		}
	};
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-project.ts
async function prepareCrabboxWorkerRuntime(e) {
	if (!e.prepareNodeRuntime) throw new Error("Crabbox project snapshots require node runtime preparation");
	const t = await e.prepareNodeRuntime();
	e.context.signal?.throwIfAborted();
	e.assertCurrent();
	const n = createCrabboxNodeRuntimeSetup({
		nodeBootstrap: t.nodeBootstrap,
		workerBundle: t.workerBundle,
		leaseId: e.leaseId,
		target: e.context.profile.target
	});
	const r = resolveCrabboxNodeEnrollmentTimeoutMs(t.bootstrapTimeoutMs);
	return {
		timeoutMs: r,
		async run(i) {
			e.context.signal?.throwIfAborted();
			t.signal?.throwIfAborted();
			e.assertCurrent();
			try {
				await runProvisionSetup({
					...e.context,
					phase: "node runtime preparation",
					setup: i ? `${n.command}\nunset ${Object.keys(n.forwardedEnv).join(" ")}\n${i}` : n.command,
					forwardedEnv: n.forwardedEnv,
					timeoutMs: r + (i ? WARM_IMAGE_COMMAND_ROUND_TRIP_TIMEOUT_MS : 0),
					signal: t.signal && e.preparationSignal ? AbortSignal.any([e.preparationSignal, t.signal]) : e.preparationSignal ?? t.signal
				});
			} catch (t) {
				e.onSetupFailure();
				throw t;
			}
		}
	};
}
/** Core owns Git contents; this adapter owns only the existing lease's transport. */
async function prepareCrabboxProjectFiles(e) {
	const run = async (t, n, r) => {
		e.project.assertCurrent();
		const i = e.timeoutMs();
		const assertCurrent = () => {
			e.signal?.throwIfAborted();
			e.project.assertCurrent();
			e.assertCurrent?.();
		};
		const a = e.signal ? AbortSignal.any([n, e.signal]) : n;
		const o = r && Object.keys(e.setupSecrets ?? {}).length ? await runCrabboxSetupEgress({
			...e,
			secrets: e.setupSecrets ?? {},
			createScript: (e) => r(i, e),
			signal: a,
			timeoutMs: i,
			assertCurrent
		}) : await runCrabboxCommand({
			action: "project preparation",
			args: t,
			binary: e.binary,
			signal: a,
			input: r?.(i),
			timeoutMs: i
		});
		e.project.assertCurrent();
		return crabboxCommandOutput("project preparation", o);
	};
	if (e.inspectPrepared) {
		if (!e.project.inspectPreparedWorkspace) throw new Error("Enrolled project cannot verify its completed workspace");
		await e.project.inspectPreparedWorkspace({ runScript: (t, n) => run(leaseRunArgs(e), n, () => t) });
		return;
	}
	return await e.project.prepare({
		...e.recordRecipePreparation ? { recordRecipePreparation: e.recordRecipePreparation } : {},
		runScript: (t, n) => run(leaseRunArgs(e), n, () => t),
		runScriptWithBudget: (t, n) => run(leaseRunArgs(e), n, t),
		upload: async (t, n, r) => {
			await run([
				"cp",
				"--provider",
				e.provider,
				"--id",
				e.id,
				t,
				`SANDBOX:${n}`
			], r);
		}
	});
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-provider-binary.ts
function createCrabboxWorkerBinaryResolver(e) {
	const t = process.env.PATH;
	const n = /* @__PURE__ */ new Map();
	const r = /* @__PURE__ */ new Set();
	let i;
	return {
		async resolve(a, o) {
			o?.throwIfAborted();
			const s = a ?? (i ??= resolveCrabboxBinary({
				openclawRoot: e.openclawRoot,
				pathEnv: t
			}));
			let c = n.get(s);
			if (!c) {
				e.signal.throwIfAborted();
				c = ensureManagedCrabboxBinary({
					binary: s,
					signal: e.signal
				}).then((t) => {
					e.signal.throwIfAborted();
					return t;
				}).catch((e) => {
					n.delete(s);
					throw e;
				});
				n.set(s, c);
			}
			const l = await racePromiseWithAbortSignal(c, o, ({ reason: e }) => toErrorObject(e, "Crabbox acquisition aborted"));
			o?.throwIfAborted();
			if (a && l.rejected && !r.has(s)) {
				r.add(s);
				e.warn(l.rejected);
			}
			return l;
		},
		async settle() {
			await Promise.allSettled(n.values());
		}
	};
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-snapshot-actions.ts
async function resolveCrabboxCheckpointBinaries(e) {
	const { profiles: t, signal: n, resolveBinary: r, warn: i } = e;
	n.throwIfAborted();
	const a = await Promise.allSettled(t.map((e) => r(parseCrabboxCleanupProfile(e).binary, n)));
	n.throwIfAborted();
	const o = [];
	const s = [];
	for (const e of a) if (e.status === "fulfilled") o.push(e.value);
	else {
		s.push(e.reason);
		i(`Crabbox maintenance binary unavailable: ${coerceErrorMessage(e.reason)}`);
	}
	if (s.length > 0 && o.length === 0) throw new AggregateError(s, "Crabbox maintenance has no supported executable");
	return [...new Set(o)].toSorted();
}
function createCrabboxSnapshotActions(e) {
	const { manager: t, signal: n, resolveBinaries: r } = e;
	const i = /* @__PURE__ */ new Set();
	const track = async (e) => {
		n.throwIfAborted();
		const t = Promise.resolve().then(() => {
			n.throwIfAborted();
			return e();
		});
		i.add(t);
		try {
			return await t;
		} finally {
			i.delete(t);
		}
	};
	return {
		images: {
			pin: (e, r) => track(() => t.pin(e, r, () => n.throwIfAborted())),
			rollback: (e) => track(() => t.rollback(e, () => n.throwIfAborted())),
			delete: (e, i) => track(async () => {
				const a = await r(i, n);
				n.throwIfAborted();
				return t.delete({
					binaries: a,
					signal: n,
					assertCurrent: () => n.throwIfAborted()
				}, e);
			})
		},
		async settle() {
			await Promise.allSettled(i);
		}
	};
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-wallpaper.ts
const WORKER_WALLPAPER_WIDTH = 1024;
const WORKER_WALLPAPER_HEIGHT = 576;
const PNG_SIGNATURE = Buffer.from([
	137,
	80,
	78,
	71,
	13,
	10,
	26,
	10
]);
function loadCrabboxWorkerWallpaperBase64(e) {
	let t;
	try {
		t = fs.readFileSync(e);
	} catch (t) {
		throw new Error(`Crabbox worker wallpaper could not be read: ${e}`, { cause: t });
	}
	if (t.length < 33 || !t.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) || t.readUInt32BE(8) !== 13 || t.toString("ascii", 12, 16) !== "IHDR") throw new Error(`Crabbox worker wallpaper is not a PNG: ${e}`);
	const n = t.readUInt32BE(16);
	const r = t.readUInt32BE(20);
	if (n !== WORKER_WALLPAPER_WIDTH || r !== WORKER_WALLPAPER_HEIGHT) throw new Error(`Crabbox worker wallpaper must be ${WORKER_WALLPAPER_WIDTH}x${WORKER_WALLPAPER_HEIGHT}; got ${n}x${r}: ${e}`);
	return t.toString("base64");
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-warm-image-checkpoint.ts
const CHECKPOINT_ID_PATTERN = /^chk_[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u;
var CrabboxCheckpointCreateError = class CrabboxCheckpointCreateError extends Error {
	static wasNotSubmitted(e, t) {
		return e instanceof CrabboxCheckpointCreateError && e.notSubmitted?.provider === t.provider && e.notSubmitted.leaseId === t.id;
	}
	static unsupportedCapture(e, t) {
		return e instanceof CrabboxCheckpointCreateError && this.wasNotSubmitted(e, t) ? e.unsupported : void 0;
	}
	constructor(e) {
		super(crabboxCommandError("checkpoint create", e).message);
		if (e.termination !== "exit" || e.code === null || e.code === 0 || e.killed || e.signal !== null || e.cleanup !== void 0 && e.cleanup !== "normal" || e.outputLimitExceeded || e.outputErrorStream || e.stdoutTruncatedBytes || e.stderrTruncatedBytes || e.stdout.length > 4096) return;
		try {
			const t = parseCheckpointJson(e.stdout, "create");
			if (Object.keys(t).length === 6 && t.schema === "crabbox.checkpoint.create.failure.v1" && t.outcome === "not_submitted" && t.localReservation === "removed" && typeof t.provider === "string" && typeof t.leaseId === "string" && typeof t.checkpointId === "string" && CHECKPOINT_ID_PATTERN.test(t.checkpointId)) this.notSubmitted = {
				provider: t.provider,
				leaseId: t.leaseId
			};
			else if (Object.keys(t).length === 7 && t.schema === "crabbox.checkpoint.create.failure.v1" && t.outcome === "not_submitted" && t.reason === "native_unsupported" && t.localReservation === "none" && typeof t.provider === "string" && typeof t.leaseId === "string" && typeof t.message === "string" && t.message.length > 0 && t.message.length <= 1024) {
				this.notSubmitted = {
					provider: t.provider,
					leaseId: t.leaseId
				};
				this.unsupported = { message: t.message };
			}
		} catch {}
	}
};
function parseCheckpointJson(e, t) {
	const n = parseCrabboxJson(e, `checkpoint ${t}`);
	if (!isRecord(n)) throw new Error(`Crabbox checkpoint ${t} returned an invalid record`);
	return n;
}
function parseCreatedCheckpoint(e, t) {
	const n = parseCheckpointJson(e, "create");
	const r = normalizeOptionalString(n.id);
	const i = normalizeOptionalString(n.kind);
	const a = isRecord(n.native) ? normalizeOptionalString(n.native.state) : void 0;
	if (!r || !CHECKPOINT_ID_PATTERN.test(r) || !i || n.leaseId !== t || !a) throw new Error("Crabbox checkpoint create returned an invalid native checkpoint");
	return {
		checkpointId: r,
		kind: i,
		captureEstablished: n.captureEstablished === true,
		state: [
			"available",
			"ready",
			"succeeded",
			"completed"
		].includes(a.toLowerCase()) ? "available" : "pending"
	};
}
function parseForkedCheckpoint(e, t) {
	const n = parseCheckpointJson(e, "fork");
	if (n.checkpointId !== t.checkpointId || n.leaseId !== t.leaseId || n.provider !== t.provider || n.slug !== t.slug || !normalizeOptionalString(n.workdir)) throw new Error("Crabbox checkpoint fork returned an invalid lease identity");
}
function parseCheckpointAvailability(e) {
	const t = parseCheckpointJson(e, "inspect");
	if (!normalizeOptionalString(t.localState) || !normalizeOptionalString(t.nextAction)) throw new Error("Crabbox checkpoint inspect returned an invalid verification record");
	if (t.providerState === void 0 || t.providerState === "missing") return "missing";
	if (typeof t.providerState !== "string") throw new Error("Crabbox checkpoint inspect returned an invalid provider state");
	return t.providerState === "available" || t.nextAction === "fork_or_delete" || t.nextAction === "fork_restore_or_delete" ? "available" : "pending";
}
function assertCurrent(e) {
	e.assertCurrent?.();
	e.signal?.throwIfAborted();
}
async function checkpointCommand(e, t, n, r = WARM_IMAGE_COMMAND_TIMEOUT_MS, i) {
	assertCurrent(e);
	const a = t === "scrub" ? t : `checkpoint ${t}`;
	const o = await runCrabboxCommand({
		action: a,
		args: n,
		binary: e.binary,
		timeoutMs: r,
		...e.signal ? { signal: e.signal } : {},
		...i === void 0 ? {} : { input: i }
	});
	if (t === "create" && (o.termination !== "exit" || o.code !== 0)) throw new CrabboxCheckpointCreateError(o);
	return crabboxCommandOutput(a, o);
}
async function deleteCheckpoint(e, t, n) {
	const r = "binary" in e ? [e.binary] : e.binaries;
	for (const [i, a] of r.entries()) {
		assertCurrent(e);
		const o = n();
		if (o <= 0) return false;
		const s = await checkpointCommand({
			...e,
			binary: a
		}, "delete", [
			"checkpoint",
			"delete",
			t
		], o);
		if (i === r.length - 1 || !s.split("\n").some((e) => e.trim() === `checkpoint absent id=${t}`)) return true;
	}
	return false;
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-warm-image-allocation.ts
function createCrabboxWarmImageAllocation({ assertMigrationReady: e, lookupLease: t, selectAllocation: n, openStore: r, verifyCheckpoint: i, policy: a, assertCurrent: o }) {
	return async (s) => {
		o(s);
		let c = {
			mode: "cold",
			reason: s.profile.target !== "linux" ? "os-unsupported" : !s.profile.class ? "class-unknown" : "warm-images-off",
			phase: "provisioning"
		};
		if (!s.profile.warmImage) {
			const e = await t(s.id);
			if (e && ((e.os ?? "linux") !== s.profile.target || e.machineClass !== s.profile.class)) throw new Error("Crabbox provision retry changed its recorded operating system or machine class.");
		}
		if (s.profile.warmImage) {
			await e();
			const t = await n(s, s.profile);
			const l = await r().lookup(t.key);
			c = t.choice.kind === "checkpoint" ? { mode: "snapshot" } : {
				mode: "cold",
				reason: t.coldReason ?? "snapshot-unavailable",
				phase: s.prepareProject && t.phase !== "enrolled" && l && !l.operation && !isCrabboxCaptureRefusalRetained(l, a.refreshAfterMs) && !(l.image?.pinned && l.previous?.pinned) ? "preparing" : "provisioning"
			};
			s.reportStartStatus?.(c);
			if (t.choice.kind === "checkpoint") {
				const e = t.choice.checkpointId;
				parseForkedCheckpoint(await checkpointCommand(s, "fork", [
					"checkpoint",
					"fork",
					e,
					...buildCrabboxAllocationArgs(s.profile, s.id, s.slug),
					"--json"
				], s.timeoutMs()).catch(async (n) => {
					await i(s, t.key, e, true);
					throw n;
				}), {
					checkpointId: e,
					leaseId: s.id,
					provider: s.provider,
					slug: s.slug
				});
				await r().update(t.key, (e) => {
					o(s);
					return withCrabboxWarmImageGeneration(e, t.imageGeneration, (e) => ({
						...e,
						state: "available",
						lastDemandAtMs: t.purpose === "session" || t.demandAtMs === null ? e.lastDemandAtMs : Math.max(e.lastDemandAtMs ?? 0, t.demandAtMs)
					}));
				});
				return t.choice;
			}
		}
		if (!s.profile.warmImage) s.reportStartStatus?.(c);
		o(s);
		await runProvisionWarmup(s);
		return { kind: "cold" };
	};
}
function createCrabboxWarmImageStartContext(e, t, n, r) {
	let i;
	return {
		binary: e,
		provider: t,
		prepareProject: r,
		reportStartStatus: (e) => {
			i = e;
			n?.reportStartStatus?.(e);
		},
		onCaptureStart: () => {
			if (i) n?.reportStartStatus?.({
				...i,
				phase: "saving"
			});
		},
		onCaptureEnd: () => {
			if (i) n?.reportStartStatus?.(i);
		}
	};
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-warm-image-scrub.ts
const SCRUB_WORKER_STATE = `set -eu
${CRABBOX_RUNTIME_NODE_PATH}
worker_root="$HOME/.openclaw/cloud-workers"
node <<'CRABBOX_SCRUB_NODE_SCRIPT'
const fs = require("node:fs");
const path = require("node:path");
const os = require("node:os");
const root = path.join(os.homedir(), ".openclaw", "cloud-workers");
const runtimeRoot = path.join(os.homedir(), ".openclaw-worker", "node-runtimes") + path.sep;
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
(async () => {
  // Setup grants never reach disk; only the runner's temporary CA files can remain.
  for (const tmpRoot of new Set(["/tmp", os.tmpdir()])) {
    for (const name of fs.readdirSync(tmpRoot)) {
      if (!name.startsWith("openclaw-setup-egress.")) continue;
      const staging = path.join(tmpRoot, name);
      const stat = fs.lstatSync(staging);
      if (stat.isDirectory() && stat.uid === process.getuid()) fs.rmSync(staging, { recursive: true });
    }
  }
  if (!fs.existsSync(root)) return;
  for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
    if (!entry.isDirectory()) continue;
    const stateDir = path.join(root, entry.name);
    const pidFile = path.join(stateDir, "node.pid");
    if (!fs.existsSync(pidFile)) continue;
    const pidText = fs.readFileSync(pidFile, "utf8").trim();
    if (!/^[1-9][0-9]*$/.test(pidText)) throw new Error("Cannot scrub a worker with an invalid node PID");
    const pid = Number(pidText);
    const owned = () => {
      let fields, cwd, env;
      try {
        const stat = fs.readFileSync(path.join("/proc", pidText, "stat"), "utf8");
        fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
        if (fields[0] === "Z") return false;
        cwd = fs.realpathSync(path.join("/proc", pidText, "cwd"));
        env = fs.readFileSync(path.join("/proc", pidText, "environ"), "utf8").split("\\0");
      } catch (error) {
        // The process may exit between reads, or its PID may belong to another user.
        if (["ENOENT", "ESRCH", "EACCES"].includes(error.code)) return false;
        throw error;
      }
      const runtime = fs.realpathSync(path.join(stateDir, "runtime"));
      if (!runtime.startsWith(runtimeRoot) || cwd !== runtime || Number(fields[2]) !== pid || !env.includes("OPENCLAW_STATE_DIR=" + stateDir)) throw new Error("Cannot scrub a worker whose live node ownership does not match");
      return true;
    };
    if (!owned()) continue;
    try { process.kill(-pid, "SIGTERM"); }
    catch (error) { if (error.code === "ESRCH") continue; throw error; }
    await delay(1000);
    if (owned()) {
      try { process.kill(-pid, "SIGKILL"); }
      catch (error) { if (error.code === "ESRCH") continue; throw error; }
    }
    for (let attempt = 0; attempt < 50 && owned(); attempt++) await delay(20);
    if (owned()) throw new Error("Cloud worker node did not exit before image capture");
  }
})().catch((error) => { console.error(error.message); process.exitCode = 1; });
CRABBOX_SCRUB_NODE_SCRIPT
rm -rf "$worker_root"
rm -rf "$HOME/.openclaw-worker/workspaces"
# Crabbox's forwarded-env cleanup only warns on failure; native images include its workdir.
# Replace the shell for this final command so deleting its uploaded script cannot interrupt cleanup.
exec rm -rf -- .crabbox/env .crabbox/env-* .crabbox/scripts
`;
//#endregion
//#region extensions/crabbox/src/crabbox-worker-warm-image-capture.ts
function createCrabboxWarmImageCapture(e) {
	const { openStore: t, lookupLease: n, assertCurrent: r, warnOnce: i, collectProfileImages: a, verifyImage: o, held: s, deleteImage: c, retireImage: l } = e;
	const warnUnsupported = (e) => i("capture unsupported", `${crabboxCaptureUnsupportedSentence(e)} Workers for this profile use an existing compatible snapshot when one is available and otherwise provision cold; capture attempts are skipped until warmImages.refreshAfter has elapsed since the refusal. Set settings.warmImage: false on the profile to stop capture attempts.`, false);
	return async function capture(u, d) {
		r(u);
		const f = randomUUID();
		const p = await n(u.id);
		if (p?.captureSkipped) return false;
		const m = p?.key;
		let h = false;
		let g = false;
		let _ = false;
		let v = false;
		let y = false;
		let b;
		const attemptCapture = async () => {
			try {
				if (m) await a(u, m, "teardown");
				if (!p || !m || !p.runtimeIdentity || p.demandAtMs === null || (p.projectKey ? p.phase !== "prepared" : p.phase !== "enrolled")) return;
				if ((p.os ?? "linux") !== u.profile.target || m !== resolveCrabboxWarmImageProfileKey({
					...u.profile,
					class: p.machineClass
				}, p.projectKey)) throw new Error("Crabbox capture profile does not match its recorded allocation.");
				let n = await t().lookup(m);
				if (n.operation) return;
				if (isCrabboxCaptureRefusalRetained(n, e.policy.refreshAfterMs)) return;
				if (n.image?.pinned && n.previous?.pinned) {
					i("capture paused", "The current and previous snapshots are pinned; unpin one before publishing another generation.");
					return;
				}
				if (n.image) {
					const r = isDeepStrictEqual(n.image.runtimeIdentity, p.runtimeIdentity);
					if ((!r || u.projectCaptureRequired || n.image.preparationKey !== p.preparationKey || n.image.cacheKey !== p.cacheKey) && (p.choice.kind !== "checkpoint" || p.choice.checkpointId !== n.image.checkpointId) && !(p.choice.kind === "cold" && sameCrabboxWarmImageGeneration(p.publicationBase, n.image))) return;
					const i = u.forkedCheckpointId === n.image.checkpointId ? "available" : await o(u, n.image.checkpointId);
					if (i === "available" && p.purpose === "session" && !u.projectCaptureReplay && p.choice.kind === "checkpoint" && p.choice.checkpointId === n.image.checkpointId && u.forkedCheckpointId === n.image.checkpointId && (n.image.pinned || Date.now() - n.image.createdAtMs < e.policy.refreshAfterMs) && p.cacheKey !== null && n.image.cacheKey === p.cacheKey && (!u.projectCaptureRequired || n.image.baseCommit && p.baseCommit && n.image.baseCommit !== p.baseCommit)) return;
					if (i === "missing" && !n.image.pinned && !s(n, n.image.checkpointId)) {
						await c(u, m, n);
						n = await t().lookup(m);
						if (n.image || n.operation) return;
					} else if (i !== "missing" && (n.image.pinned || Date.now() - n.image.createdAtMs < e.policy.refreshAfterMs) && r && n.image.preparationKey === p.preparationKey && n.image.cacheKey === p.cacheKey && !u.projectCaptureRequired && (!p.projectKey || n.image.baseCommit === p.baseCommit)) return;
				}
				const b = Boolean(u.provider === "aws" && !u.teardown && p.projectKey && p.purpose !== "reserve" && !n.image && !n.previous && isCrabboxVersionAtLeast(u.cliVersion ?? "", "0.79.0"));
				const x = Date.now();
				r(u);
				h = await t().update(m, (e) => {
					r(u);
					if (!e || JSON.stringify(e) !== JSON.stringify(n) || e.allocations[u.id]?.phase !== p.phase) return;
					return {
						...e,
						operation: {
							type: "capture",
							id: f,
							startedAtMs: x,
							leaseId: u.id,
							provider: u.provider,
							phase: "scrubbing"
						}
					};
				});
				if (!h) return;
				u.onCaptureStart?.();
				_ = true;
				const S = await d?.();
				_ = false;
				r(u);
				if (S) {
					const e = await t().lookup(m);
					if (e?.operation?.type !== "capture" || e.operation.id !== f) return;
				}
				v = true;
				await e.prepareCapture({
					...u,
					sourcePreparationTimeoutMs: S?.timeoutMs ?? 0
				});
				v = false;
				r(u);
				const C = await t().lookup(m);
				if (C?.operation?.type !== "capture" || C.operation.id !== f) return;
				r(u);
				if (S) {
					_ = true;
					await S.run(SCRUB_WORKER_STATE);
					_ = false;
				} else await checkpointCommand(u, "scrub", leaseRunArgs(u), WARM_IMAGE_COMMAND_ROUND_TRIP_TIMEOUT_MS, SCRUB_WORKER_STATE);
				r(u);
				g = await t().update(m, (e) => {
					r(u);
					return e?.operation?.type === "capture" && e.operation.id === f && e.allocations[u.id]?.phase === p.phase && e.allocations[u.id]?.machineClass === p.machineClass && e.allocations[u.id]?.os === p.os && e.allocations[u.id]?.preparationKey === p.preparationKey && e.allocations[u.id]?.cacheKey === p.cacheKey && e.allocations[u.id]?.purpose === p.purpose ? {
						...e,
						operation: {
							...e.operation,
							phase: "creating"
						}
					} : void 0;
				});
				if (!g) {
					await clearCrabboxWarmImageCapture(t(), m, f);
					return;
				}
				const { captureEstablished: w, ...T } = parseCreatedCheckpoint(await checkpointCommand(u, "create", [
					"checkpoint",
					"create",
					"--provider",
					u.provider,
					"--id",
					u.id,
					"--mode",
					"native",
					...b ? ["--wait=false"] : [
						"--wait",
						"--wait-timeout",
						`${WARM_IMAGE_NATIVE_WAIT_TIMEOUT_MS}ms`
					],
					"--json",
					...["azure", "daytona"].includes(u.provider) ? ["--no-reboot=false"] : [],
					...u.provider === "machine0" ? ["--strategy", "image"] : []
				], resolveCrabboxCheckpointCaptureTimeoutMs(u.provider)), u.id);
				const E = b && w;
				if (!E && T.state === "pending") {
					const e = performance.now() + WARM_IMAGE_NATIVE_WAIT_TIMEOUT_MS;
					while (T.state === "pending") {
						r(u);
						const t = e - performance.now();
						if (t <= 0) throw new Error("Crabbox waited checkpoint is not available");
						const n = await o(u, T.checkpointId, t);
						r(u);
						if (n === "available") T.state = "available";
						else if (!b) throw new Error("Crabbox waited checkpoint is not available");
						else await sleepWithAbort(Math.min(5e3, e - performance.now()), u.signal);
					}
				}
				y = E ? "source-running" : true;
				if (!await t().update(m, (t) => {
					if (t?.operation?.type !== "capture" || t.operation.id !== f) return;
					const n = withoutCrabboxWarmImageOperation(t);
					delete n.captureUnsupported;
					const r = t.image;
					let i;
					if (r && r.checkpointId !== T.checkpointId) {
						if (t.previous?.pinned) i = r.checkpointId;
						else if (r.pinned || e.policy.keepPrevious === 1) {
							n.previous = r;
							i = t.previous?.checkpointId;
						} else i = r.checkpointId;
					}
					const a = t.allocations[u.id];
					if (a && a.phase === p.phase && a.machineClass === p.machineClass && a.os === p.os && a.preparationKey === p.preparationKey && a.cacheKey === p.cacheKey && a.purpose === p.purpose && a.demandAtMs === p.demandAtMs) n.allocations = {
						...n.allocations,
						[u.id]: {
							...a,
							imageGeneration: {
								checkpointId: T.checkpointId,
								createdAtMs: x
							}
						}
					};
					return {
						...n,
						image: {
							...T,
							state: E ? "pending" : T.state,
							createdAtMs: x,
							preparationKey: p.preparationKey,
							cacheKey: p.cacheKey,
							purpose: p.purpose,
							lastDemandAtMs: p.purpose === "session" ? null : p.demandAtMs,
							runtimeIdentity: p.runtimeIdentity,
							...p.baseCommit ? { baseCommit: p.baseCommit } : {}
						},
						...i ? { operation: {
							type: "retire",
							checkpointId: i
						} } : {}
					};
				})) {
					i("capture ownership changed", `Checkpoint ${T.checkpointId} returned after recovery of ${f}; reconcile it in the Crabbox catalog before resuming captures.`);
					return;
				}
				g = false;
				h = false;
				u.onCaptureEnd?.();
				const D = await t().lookup(m);
				if (D) await l(u, m, D);
			} catch (e) {
				b = coerceErrorMessage(e);
				const n = g ? CrabboxCheckpointCreateError.unsupportedCapture(e, u) : void 0;
				const r = g && CrabboxCheckpointCreateError.wasNotSubmitted(e, u);
				let a = g;
				if (h && m) try {
					if (n) {
						if (await t().update(m, (e) => e?.operation?.type === "capture" && e.operation.id === f ? {
							...withoutCrabboxWarmImageOperation(e),
							captureUnsupported: {
								atMs: Date.now(),
								provider: u.provider,
								message: n.message
							}
						} : void 0)) {
							warnUnsupported(n.message);
							return;
						}
					}
					if (g && !r) await t().update(m, (e) => e?.operation?.type === "capture" && e.operation.id === f ? {
						...e,
						operation: {
							...e.operation,
							phase: "uncertain"
						}
					} : void 0);
					else {
						await clearCrabboxWarmImageCapture(t(), m, f);
						a = false;
					}
				} catch {}
				if (v) {
					if (u.projectCaptureRequired || !u.teardown && p?.projectKey) throw new Error(`Crabbox project image preparation failed: ${b}`, { cause: e });
					i("capture skipped", e, false);
					return;
				}
				if (_ || r && p?.projectKey) throw e;
				i("capture", a ? `${b}. ${crabboxWarmImageRecoveryHint(f)}` : e);
			}
		};
		await attemptCapture();
		const x = !u.teardown && m && p?.projectKey ? (await t().lookup(m))?.operation : void 0;
		if (x?.type === "capture" && x.leaseId === u.id) throw new Error(`${b ? `${b}. ` : ""}Crabbox project image capture is unresolved. ${crabboxWarmImageRecoveryHint(x.id)}`);
		r(u);
		if (h) u.onCaptureEnd?.();
		return y;
	};
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-warm-image-policy.ts
function duration(e, t, n, r) {
	const i = e === void 0 ? n : e;
	if (typeof i !== "string" || !/^[1-9][0-9]{0,7}[mhd](?![\s\S])/u.test(i)) throw new Error(`Crabbox warmImages.${t} must use 1–8 whole digits followed by m, h, or d.`);
	const a = i.endsWith("d") ? 864e5 : i.endsWith("h") ? 36e5 : 6e4;
	const o = Number(i.slice(0, -1)) * a;
	if (o < r) throw new Error(`Crabbox warmImages.${t} must be at least ${r / 36e5}h.`);
	return o;
}
function resolveCrabboxWarmImagePolicy(e) {
	const t = e?.warmImages;
	if (t !== void 0 && !isRecord(t)) throw new Error("Crabbox warmImages must be an object.");
	const n = t ?? {};
	const r = n.keepPrevious === void 0 ? 0 : n.keepPrevious;
	if (r !== 0 && r !== 1) throw new Error("Crabbox warmImages.keepPrevious must be 0 or 1.");
	return {
		refreshAfterMs: duration(n.refreshAfter, "refreshAfter", "24h", 36e5),
		retainUnusedMs: duration(n.retainUnused, "retainUnused", "14d", 864e5),
		keepPrevious: r
	};
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-warm-image-reconciliation.ts
function createCrabboxWarmImageRetirement(e) {
	const { openStore: t, warnOnce: n, deleteEmptyProfile: r } = e;
	const assertCurrent = (e) => {
		e.assertCurrent?.();
		e.signal?.throwIfAborted();
	};
	const releaseRetirementHolds = async (r, i, a, o) => {
		if (a.operation?.type !== "retire") return a;
		const s = a.operation.checkpointId;
		for (const c of crabboxWarmImageHoldingLeaseIds(a, s)) {
			if (e.isLeaseActive(c) || o() <= 0) continue;
			const s = a.allocations[c];
			try {
				await confirmCrabboxWarmImageLeaseGone(r, {
					leaseId: c,
					provider: a.backend
				}, o);
				await t().update(i, (t) => {
					assertCurrent(r);
					if (!t || e.isLeaseActive(c) || !isDeepStrictEqual(t.allocations[c], s)) return;
					const n = { ...t.allocations };
					delete n[c];
					return {
						...t,
						allocations: n
					};
				});
			} catch (e) {
				assertCurrent(r);
				n(`allocation ${c.slice(0, 128)} reconciliation`, coerceErrorMessage(e).slice(0, 1024));
			}
		}
		return t().lookup(i);
	};
	const retireImage = async (i, a, o, s = () => WARM_IMAGE_COMMAND_TIMEOUT_MS) => {
		const c = o.operation;
		const pinned = (e) => [e.image, e.previous].some((e) => c?.type === "retire" && e?.checkpointId === c.checkpointId && e.pinned);
		if (c?.type !== "retire") return;
		const l = crabboxWarmImageHoldingLeaseIds(o, c.checkpointId);
		if (l.length > 0) {
			n(`checkpoint ${c.checkpointId} retirement held`, `allocation leases: ${l.join(", ").slice(0, 1024)}`, false);
			return;
		}
		if (pinned(o)) return;
		const matches = (e) => e?.operation?.type === "retire" && e.operation.checkpointId === c.checkpointId && sameCrabboxWarmImageGeneration(e.image, o.image) && sameCrabboxWarmImageGeneration(e.previous, o.previous) && !pinned(e) && !isCrabboxWarmImageHeld(e, c.checkpointId);
		if (!matches(await t().lookup(a))) return;
		try {
			if (!await deleteCheckpoint(i, c.checkpointId, s)) return;
		} catch (n) {
			assertCurrent(i);
			if (matches(await t().lookup(a))) e.warn(`Crabbox warm image checkpoint retirement (${c.checkpointId} deletion obligation retained; retry during periodic maintenance or next warm-image-enabled worker teardown; inspect with openclaw crabbox warm-images) failed: ${coerceErrorMessage(n)}`);
			return;
		}
		await t().update(a, (e) => {
			assertCurrent(i);
			if (!e || !matches(e)) return;
			const t = withoutCrabboxWarmImageOperation(e);
			if (t.image?.checkpointId === c.checkpointId) delete t.image;
			if (t.previous?.checkpointId === c.checkpointId) delete t.previous;
			return t;
		});
		await r(a);
	};
	return {
		releaseRetirementHolds,
		retireImage
	};
}
/** Confirm source inactivity across every configured catalog; lost custody is not absence. */
async function confirmCrabboxWarmImageLeaseGone(e, t, n) {
	if (!t.leaseId || !t.provider || e.binaries.length === 0) throw new Error("source lease, provider, or executable is unavailable");
	for (const r of e.binaries) {
		e.assertCurrent?.();
		e.signal?.throwIfAborted();
		const i = n();
		if (i <= 0) throw new Error("reconciliation deadline exceeded");
		const a = await inspectWithContext({
			...e,
			binary: r,
			id: t.leaseId,
			provider: t.provider,
			requireConfirmedAbsence: true,
			timeoutMs: i
		});
		if (a && ![
			"stopped",
			"stopped_with_code",
			"terminated",
			"destroyed",
			"missing",
			"released",
			"expired"
		].includes(a.state)) throw new Error(`source lease ${t.leaseId} is still alive or unconfirmed (${a.state})`);
	}
}
async function reconcileCrabboxWarmImageCapture(e, t, n, r, i, a, o) {
	const s = /* @__PURE__ */ new Set();
	const assertCurrent = () => {
		e.assertCurrent?.();
		e.signal?.throwIfAborted();
		if (r.leaseId && o(r.leaseId)) throw new Error(`source lease ${r.leaseId} has an active dispatch`);
	};
	const timeout = () => {
		assertCurrent();
		const e = i();
		if (e <= 0) throw new Error("reconciliation deadline exceeded");
		return e;
	};
	try {
		await confirmCrabboxWarmImageLeaseGone(e, r, timeout);
		for (const t of e.binaries) {
			const n = parseCrabboxJson(await checkpointCommand({
				...e,
				binary: t
			}, "list", [
				"checkpoint",
				"list",
				"--json"
			], timeout()), "checkpoint list");
			if (n === null) continue;
			if (!Array.isArray(n)) throw new Error("checkpoint list returned an invalid catalog");
			for (const e of n) {
				if (!isRecord(e) || typeof e.id !== "string" || !CHECKPOINT_ID_PATTERN.test(e.id) || typeof e.leaseId !== "string" || !e.leaseId) throw new Error("checkpoint list returned an invalid checkpoint identity");
				if (e.leaseId === r.leaseId) {
					s.add(e.id);
					if (e.provider !== r.provider) throw new Error(`checkpoint ${e.id} has an unexpected provider`);
				}
			}
		}
		if (s.size > 1) throw new Error("multiple checkpoints match the source lease");
		const o = await t.lookup(n);
		const c = o?.operation;
		assertCurrent();
		if (c?.type !== "capture" || c.id !== r.id || c.phase !== "uncertain") throw new Error("capture ownership changed");
		const [l] = s;
		if (l && o && (o.image?.checkpointId === l || o.previous?.checkpointId === l || isCrabboxWarmImageHeld(o, l))) throw new Error(`checkpoint ${l} is already owned by a published image or allocation`);
		if (l && !await deleteCheckpoint(e, l, i)) throw new Error("checkpoint deletion did not complete");
		if (await clearCrabboxWarmImageCapture(t, n, r.id, {
			assertCurrent,
			releaseSourceAllocation: true
		})) a(`Crabbox warm image capture ${r.id} reconciled: ${l ? `deleted unvalidated checkpoint ${l}` : "no checkpoint found"}`);
		return;
	} catch (e) {
		assertCurrent();
		const i = [.../* @__PURE__ */ new Set([...r.checkpointIds ?? [], ...s])].toSorted();
		if (i.length > 0) await t.update(n, (e) => {
			assertCurrent();
			return e?.operation?.type === "capture" && e.operation.id === r.id && JSON.stringify(e.operation.checkpointIds) !== JSON.stringify(i) ? {
				...e,
				operation: {
					...e.operation,
					checkpointIds: i
				}
			} : void 0;
		});
		return `${coerceErrorMessage(e)}${i.length ? `; candidate checkpoints: ${i.join(", ")}` : ""}`;
	}
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-warm-image.ts
function createCrabboxWarmImageManager(e) {
	const t = e.policy ?? resolveCrabboxWarmImagePolicy();
	let n;
	let r = false;
	const assertMigrationReady = async () => {
		if (!r) {
			await assertCrabboxWarmImageMigrationReady(e.state);
			r = true;
		}
	};
	const i = /* @__PURE__ */ new Set();
	let a = "";
	const openStore = () => n ??= openCrabboxWarmImageStore(e.state);
	const assertCurrent = (e) => {
		e.assertCurrent?.();
		e.signal?.throwIfAborted();
	};
	const warnOnce = (t, n, r = true) => {
		const a = `Crabbox warm image ${t}${r ? " failed" : ""}: ${coerceErrorMessage(n)}`;
		if (!i.has(a)) {
			if (i.size >= 128) i.clear();
			i.add(a);
			e.warn(a);
		}
	};
	const imageExpired = (e) => !e.pinned && (e.lastDemandAtMs === null || Date.now() - e.lastDemandAtMs >= t.retainUnusedMs);
	const retiringCurrent = (e) => e.operation?.type === "retire" && e.operation.checkpointId === e.image?.checkpointId;
	const hasNoProviderObligations = (e) => !e.image && !e.previous && !e.operation && Object.keys(e.allocations).length === 0;
	const deleteEmptyProfile = (e) => openStore().deleteIf(e, (e) => hasNoProviderObligations(e) && !isCrabboxCaptureRefusalRetained(e, t.refreshAfterMs) && !(e.recipePreparationAtMs !== void 0 && Date.now() < e.recipePreparationAtMs + t.refreshAfterMs));
	const lookupLease = (e) => openStore().lookupLease(e);
	const { releaseRetirementHolds: o, retireImage: s } = createCrabboxWarmImageRetirement({
		openStore,
		isLeaseActive: e.isLeaseActive,
		warn: e.warn,
		warnOnce,
		deleteEmptyProfile
	});
	const deleteImage = async (e, t, n, r = () => WARM_IMAGE_COMMAND_TIMEOUT_MS, i = n.image?.checkpointId, a = false) => {
		const o = [n.image, n.previous].find((e) => e?.checkpointId === i);
		if (!o || !i || o.pinned || n.operation || isCrabboxWarmImageHeld(n, i) && !a) return;
		assertCurrent(e);
		const c = {
			...n,
			operation: {
				type: "retire",
				checkpointId: i
			}
		};
		if (await openStore().update(t, (t) => {
			assertCurrent(e);
			return JSON.stringify(t) === JSON.stringify(n) ? c : void 0;
		})) await s(e, t, c, r);
	};
	const collectImages = async (n, r, i) => {
		const c = performance.now() + WARM_IMAGE_COMMAND_TIMEOUT_MS;
		assertCurrent(n);
		const l = [];
		const u = i.toSorted((e, t) => Number(t.value.operation?.type === "retire") - Number(e.value.operation?.type === "retire"));
		for (const { key: i, value: a } of u) {
			assertCurrent(n);
			const u = crabboxWarmImageCaptureStatus(a);
			if (u) {
				if (u.phase === "uncertain" && "binaries" in n && a.operation?.type === "capture" && !e.isLeaseActive(a.operation.leaseId ?? "")) {
					const t = await reconcileCrabboxWarmImageCapture(n, openStore(), i, a.operation, () => c - performance.now(), e.info ?? (() => {}), e.isLeaseActive);
					if (t) l.push({
						selector: u.selector,
						reason: t
					});
				} else if (u.phase === "uncertain") warnOnce("capture paused", crabboxWarmImageRecoveryHint(u.selector), false);
				else if (u.stale) warnOnce(`capture ${u.selector} still pending`, CRABBOX_WARM_IMAGE_WAIT_HINT, false);
				continue;
			}
			if (a.operation && r === "allocation") continue;
			const remaining = () => c - performance.now();
			if (remaining() <= 0) break;
			if (hasNoProviderObligations(a)) {
				await deleteEmptyProfile(i);
				continue;
			}
			const d = r === "maintenance" && "binaries" in n ? await o(n, i, a, remaining) : a;
			if (d) await s(n, i, d, remaining);
			let f = await openStore().lookup(i);
			if (f?.previous && !f.operation && !f.previous.pinned && (t.keepPrevious === 0 || imageExpired(f.previous)) && remaining() > 0) {
				await deleteImage(n, i, f, remaining, f.previous.checkpointId);
				f = await openStore().lookup(i);
			}
			if (f?.image && sameCrabboxWarmImageGeneration(f.image, a.image) && !f.operation && imageExpired(f.image) && remaining() > 0) await deleteImage(n, i, f, remaining);
		}
		const d = JSON.stringify(l);
		if (r === "maintenance" && d !== a) {
			a = d;
			if (l.length > 0) e.warn(`Crabbox warm image capture paused (${l.length}; ${l.map(({ selector: e, reason: t }) => `${e}: ${t}`).join(", ")}): ${crabboxWarmImageRecoveryHint(l.length === 1 ? l[0].selector : "<selector>")}`);
		}
	};
	const collectProfileImages = async (e, t, n) => {
		const r = await openStore().lookup(t);
		await collectImages(e, n, r ? [{
			key: t,
			value: r
		}] : []);
	};
	const makeRoom = async (e) => {
		const t = performance.now() + WARM_IMAGE_COMMAND_TIMEOUT_MS;
		const n = await openStore().entries();
		if (n.length < 128) return;
		const r = n.filter(({ value: e }) => !e.operation && Object.keys(e.allocations).length === 0).toSorted((e, t) => (e.value.image?.lastDemandAtMs ?? 0) - (t.value.image?.lastDemandAtMs ?? 0));
		for (const n of ["previous", "image"]) for (const { key: i } of r) {
			if (await openStore().count() < 128) return;
			const remaining = () => t - performance.now();
			if (remaining() <= 0) break;
			const r = await openStore().lookup(i);
			const a = r?.[n];
			if (r && a && (n === "previous" || !r.previous)) await deleteImage(e, i, r, remaining, a.checkpointId);
			if (n === "image") await openStore().deleteIf(i, hasNoProviderObligations);
		}
		if (await openStore().count() >= 128) throw new Error("Crabbox warm-image profile capacity is full; stop outstanding workers or resolve cleanup with openclaw crabbox warm-images before retrying.");
	};
	const verifyImage = async (e, t, n = WARM_IMAGE_COMMAND_TIMEOUT_MS) => {
		return parseCheckpointAvailability(await checkpointCommand(e, "inspect", [
			"checkpoint",
			"inspect",
			t,
			"--verify",
			"--json"
		], Math.min(n, WARM_IMAGE_COMMAND_TIMEOUT_MS)));
	};
	const verifyCheckpoint = async (e, t, n, r = false) => {
		try {
			const i = await verifyImage(e, n);
			const a = await openStore().lookup(t);
			if (i === "missing" && a) await deleteImage(e, t, a, void 0, n, r);
			return i;
		} catch (t) {
			assertCurrent(e);
			warnOnce("verification", t);
			return;
		}
	};
	const selectAllocation = async (e, n) => {
		if (!e.nodeRuntimeIdentity) throw new Error("Crabbox warm-image allocation requires a prepared node runtime identity");
		const r = e.preparation?.key ?? null;
		const i = e.preparation?.cacheKey ?? null;
		const a = e.preparation?.purpose ?? null;
		assertCrabboxWarmImagePreparation(e.preparation, {
			projectKey: e.projectKey,
			target: n.target
		});
		const o = resolveCrabboxWarmImageProfileKey(n, e.projectKey);
		const s = {
			profileId: e.profileId,
			backend: n.provider,
			machineClass: n.class,
			os: n.target,
			projectLabel: e.projectLabel,
			projectRoot: e.projectRoot
		};
		const c = await lookupLease(e.id);
		if (c) {
			assertCrabboxWarmImageReplay(c, {
				key: o,
				machineClass: n.class,
				os: n.target,
				preparationKey: r,
				cacheKey: i,
				purpose: a,
				demandAtMs: e.preparation?.demandAtMs,
				runtimeIdentity: e.nodeRuntimeIdentity
			});
			assertCurrent(e);
			if (!await openStore().update(o, (t) => {
				assertCurrent(e);
				const n = t?.allocations[e.id];
				return t && n && isDeepStrictEqual({
					key: o,
					projectKey: t.projectKey,
					...n
				}, c) ? withCrabboxWarmImageDisplayFacts(t, s) : void 0;
			})) throw new Error("Crabbox allocation changed before provisioning completed; retry the worker operation.");
			return c;
		}
		await collectProfileImages(e, o, "allocation");
		const l = await openStore().lookup(o);
		let u = "no-snapshot-yet";
		if (l?.image) {
			if (retiringCurrent(l)) u = "snapshot-retiring";
			else if (i !== null ? l.image.cacheKey !== i : l.image.preparationKey !== null || l.image.cacheKey !== null) u = "setup-changed";
			else u = "snapshot-unavailable";
		} else if (l) {
			if (isCrabboxCaptureRefusalRetained(l, t.refreshAfterMs)) u = "backend-cannot-snapshot";
			else if (l.operation?.type === "capture") u = "capture-paused";
		}
		let d = Boolean(l?.image && l.image.lastDemandAtMs !== null && (i !== null ? l.image.cacheKey === i : l.image.preparationKey === null && l.image.cacheKey === null) && !retiringCurrent(l));
		if (d && l?.image?.state === "pending") {
			d = await verifyCheckpoint(e, o, l.image.checkpointId) === "available";
			if (!d) u = "snapshot-unavailable";
		}
		if (!await openStore().lookup(o)) await makeRoom(e);
		assertCurrent(e);
		return openStore().recordAllocation({
			key: o,
			id: e.id,
			projectKey: e.projectKey,
			displayFacts: s,
			assertCurrent: () => assertCurrent(e),
			availableImage: d ? l?.image : void 0,
			coldReason: d ? void 0 : u,
			allocation: {
				machineClass: n.class,
				os: n.target,
				phase: "pending",
				runtimeIdentity: e.nodeRuntimeIdentity,
				preparationKey: r,
				cacheKey: i,
				purpose: a,
				demandAtMs: e.preparation?.demandAtMs ?? Date.now()
			}
		});
	};
	const checkpointEntry = async (e) => {
		const t = (await openStore().entries()).find(({ value: t }) => t.image?.checkpointId === e || t.previous?.checkpointId === e || t.operation?.type === "retire" && t.operation.checkpointId === e);
		if (!t) throw new CrabboxWarmImageRequestError("Unknown snapshot checkpoint.");
		return t;
	};
	const updateCheckpoint = async (e, t, n) => {
		const { key: r } = await checkpointEntry(e);
		let i;
		let a;
		if (!await openStore().update(r, (e) => {
			n?.();
			i = void 0;
			a = void 0;
			if (!e) {
				i = "Snapshot changed; refresh the list and retry.";
				return;
			}
			const r = t(e);
			if (typeof r === "string") {
				i = r;
				return;
			}
			a = r;
			return r;
		}) || !a || i) throw new CrabboxWarmImageRequestError(i ?? "Snapshot changed; refresh and retry.");
		return projectCrabboxWarmImage(r, a);
	};
	return {
		pin(e, t, n) {
			return updateCheckpoint(e, (n) => {
				if (n.operation) return "Wait for the profile's capture or retirement to finish before changing a pin.";
				const r = n.image?.checkpointId === e ? "image" : "previous";
				const i = n[r];
				if (i?.checkpointId !== e) return "Unknown snapshot checkpoint.";
				const a = { ...i };
				if (t) a.pinned ??= { atMs: Date.now() };
				else delete a.pinned;
				return {
					...n,
					[r]: a
				};
			}, n);
		},
		rollback(e, n) {
			return updateCheckpoint(e, (n) => {
				if (n.operation) return "Wait for the profile's capture or retirement to finish before rolling back.";
				if (n.previous?.checkpointId !== e) return "Rollback requires a previous snapshot checkpoint.";
				const r = {
					...n,
					image: n.previous
				};
				delete r.previous;
				if (n.image) {
					if (t.keepPrevious === 1 || n.image.pinned) r.previous = n.image;
					else r.operation = {
						type: "retire",
						checkpointId: n.image.checkpointId
					};
				}
				return r;
			}, n);
		},
		async delete(e, t) {
			assertCurrent(e);
			const { key: n, value: r } = await checkpointEntry(t);
			if (r.operation?.type === "capture") throw new CrabboxWarmImageRequestError("A snapshot cannot be deleted while its profile is capturing.");
			if (isCrabboxWarmImageHeld(r, t)) throw new CrabboxWarmImageRequestError("Stop outstanding allocations before deleting this snapshot.");
			if ([r.image, r.previous].some((e) => e?.checkpointId === t && e.pinned)) throw new CrabboxWarmImageRequestError("Unpin this snapshot before deleting it.");
			if (r.operation) {
				if (r.operation.checkpointId !== t) throw new CrabboxWarmImageRequestError("Wait for the profile's current retirement to finish.");
				await s(e, n, r);
			} else await deleteImage(e, n, r, void 0, t);
			assertCurrent(e);
			const i = await openStore().lookup(n);
			if (i?.operation?.type === "retire" && i.operation.checkpointId === t) return { status: "retiring" };
			if (i?.image?.checkpointId === t || i?.previous?.checkpointId === t) throw new CrabboxWarmImageRequestError("Snapshot changed; refresh the list and retry deletion.");
			return { status: "deleted" };
		},
		maintain: async (e) => {
			assertCurrent(e);
			await assertMigrationReady();
			await collectImages({
				...e,
				binaries: [...new Set(e.binaries)].toSorted()
			}, "maintenance", await openStore().entries());
		},
		lookupLease,
		/** Runtime attested when this checkpoint was captured; undefined once its record is gone. */
		checkpointRuntimeIdentity: async (e) => {
			for (const { value: t } of await openStore().entries()) for (const n of [t.image, t.previous]) if (n?.checkpointId === e) return n.runtimeIdentity;
		},
		markPrepared: (...e) => openStore().markPrepared(...e),
		noteRecipePreparation: (...e) => openStore().noteRecipePreparation(...e),
		markEnrolled: (e, t) => openStore().markEnrolled(e, t),
		notePreparedDemand: (e, t) => openStore().notePreparedDemand(e, t),
		async release(e) {
			const t = await lookupLease(e.id);
			if (!t) return;
			await openStore().update(t.key, (t) => {
				if (!t?.allocations[e.id]) return;
				const n = { ...t.allocations };
				delete n[e.id];
				return {
					...t,
					allocations: n
				};
			});
			const n = performance.now() + WARM_IMAGE_COMMAND_TIMEOUT_MS;
			const remaining = () => n - performance.now();
			const r = await openStore().lookup(t.key);
			if (r) await s(e, t.key, r, remaining);
			const i = await openStore().lookup(t.key);
			if (i?.image?.lastDemandAtMs === null) await deleteImage(e, t.key, i, remaining);
			await deleteEmptyProfile(t.key);
		},
		capture: createCrabboxWarmImageCapture({
			policy: t,
			openStore,
			lookupLease,
			assertCurrent,
			warnOnce,
			collectProfileImages,
			verifyImage,
			held: isCrabboxWarmImageHeld,
			deleteImage,
			retireImage: s,
			prepareCapture: e.prepareCapture
		}),
		startContext: createCrabboxWarmImageStartContext,
		allocate: createCrabboxWarmImageAllocation({
			assertMigrationReady,
			lookupLease,
			selectAllocation,
			openStore,
			verifyCheckpoint,
			policy: t,
			assertCurrent
		})
	};
}
//#endregion
//#region extensions/crabbox/src/crabbox-worker-provider.ts
function createCrabboxWorkerProvider(e) {
	const t = loadCrabboxWorkerWallpaperBase64(e.wallpaperPath);
	const n = e.warn ?? (() => {});
	const r = e.openclawRoot ?? process.cwd();
	const i = createCrabboxHeartbeatManager({ warn: n });
	const a = new AbortController();
	const o = createCrabboxWorkerBinaryResolver({
		openclawRoot: r,
		signal: a.signal,
		warn: n
	});
	const s = o.resolve;
	const c = createCrabboxMachineOptionsResolver({
		resolveBinary: async (...e) => (await s(...e)).binary,
		warn: n
	});
	const l = /* @__PURE__ */ new Set();
	const u = createCrabboxWarmImageManager({
		isLeaseActive: (e) => {
			for (const t of l) if (t.leaseId === e) return true;
			return false;
		},
		state: e.state,
		warn: n,
		info: e.info,
		policy: e.warmImagePolicy,
		prepareCapture: async (e) => {
			i.start({
				...e.profile,
				...e
			});
			await prepareCrabboxCaptureLifetime(e, { observe: (t) => i.start({
				...e.profile,
				...e,
				lifetime: t.lifetime
			}) });
		}
	});
	let d;
	const resolveMaintenanceBinaries = (e, t) => resolveCrabboxCheckpointBinaries({
		profiles: e,
		signal: t,
		resolveBinary: async (...e) => (await s(...e)).binary,
		warn: n
	});
	const f = createCrabboxSnapshotActions({
		manager: u,
		signal: a.signal,
		resolveBinaries: resolveMaintenanceBinaries
	});
	const stopLease = async (e, t, r) => {
		await i.stop(e.id);
		await stopCrabboxLease({
			...e,
			warn: n,
			onCleanupAccepted: t,
			signal: r
		});
		await u.release({
			...e,
			signal: r
		});
	};
	const resolveLeaseContext = async (e) => {
		const t = parseCrabboxCleanupProfile(e.profile);
		assertCrabboxLeaseId(e.leaseId);
		return {
			context: {
				binary: (await s(t.binary, e.signal)).binary,
				heartbeatIntervalMs: t.heartbeatIntervalMs,
				heartbeatTimeoutMs: t.heartbeatTimeoutMs,
				id: e.leaseId,
				idleTimeout: t.idleTimeout,
				provider: t.provider
			},
			profile: t
		};
	};
	const resolveAllocation = async (e, t) => ({
		leaseId: operationLeaseId(t),
		sharedHost: false
	});
	const prepareProvision = async (e, n, r) => {
		const { signal: o, assertCurrent: c } = createCrabboxProvisionAuthority(r);
		const d = r?.executionMode;
		if (d !== void 0 && d !== "worker-turn" && d !== "remote-exec") throw new WorkerProviderError("Crabbox execution mode is unsupported");
		const { profile: f } = resolveCrabboxProvisionProfile(e, r?.machineClass, r?.os);
		const p = r?.nodeRuntimeIdentity;
		if (f.warmImage && !p) throw new WorkerProviderError("Crabbox warm images require a prepared node runtime identity");
		const m = f.desktop ? CRABBOX_DESKTOP_WARMUP_TIMEOUT_MS : CRABBOX_WARMUP_TIMEOUT_MS;
		const h = Object.keys(f.setupSecrets ?? {}).length > 0;
		const g = f.warmImage || h ? r?.project : void 0;
		if (r?.project?.preparation && !g) throw new WorkerProviderError("Crabbox prepared workers require warm images");
		const _ = AbortSignal.any([
			a.signal,
			...o ? [o] : [],
			...g?.signal ? [g.signal] : []
		]);
		const v = await resolveAllocation(e, n);
		o?.throwIfAborted();
		const { binary: y, version: b } = await s(f.binary, _);
		_?.throwIfAborted();
		if (h) await assertCrabboxSetupEgressSupport({
			binary: y,
			target: f.target,
			assertCurrent: c,
			signal: _,
			projectPrepared: g ? Boolean(g.preparation) : void 0
		});
		const x = performance.now() + resolveCrabboxProvisionBaseTimeoutMs(f);
		const S = resolveCrabboxNodeEnrollmentTimeoutMs(r?.nodeBootstrapTimeoutMs);
		const C = x + countCrabboxProvisionSetupPhases(f) * CRABBOX_SETUP_TIMEOUT_MS + 2 * S + (g ? CRABBOX_PROJECT_PREPARATION_TIMEOUT_MS + resolveCrabboxWarmImageCaptureTimeoutMs(f.provider) : 0);
		const w = u.startContext(y, f.provider, r, Boolean(g));
		const T = v.leaseId;
		if (f.desktop && f.provider === "hetzner") await assertHetznerDesktopHasManagedCoordinator({
			binary: y,
			signal: o
		});
		if (f.provider === "aws") await assertAwsWorkerHasNoInstanceProfile({
			binary: y,
			signal: o
		});
		const provision = async () => {
			c();
			const e = g?.preparation && await u.lookupLease(T);
			const a = e && e.phase !== "enrolled";
			const s = await u.allocate({
				...w,
				id: T,
				profile: f,
				profileId: r?.profileId,
				nodeRuntimeIdentity: p,
				...g ? {
					projectKey: g.key,
					projectLabel: g.label,
					projectRoot: g.root
				} : {},
				...g?.preparation ? { preparation: g.preparation } : {},
				assertCurrent: c,
				signal: _,
				slug: operationSlug(n),
				timeoutMs: () => remainingProvisionTimeout(x, m)
			});
			let l = false;
			try {
				let n;
				try {
					n = await inspectWithContext({
						...w,
						id: T,
						timeoutMs: remainingProvisionTimeout(x, resolveCrabboxLifecycleTimeoutMs(f.provider)),
						waitForReady: f.provider === "machine0",
						signal: _
					});
					o?.throwIfAborted();
				} catch (e) {
					o?.throwIfAborted();
					if (e instanceof WorkerProviderError) return await failProvisionAfterCleanup({
						...w,
						id: T,
						stopLease
					}, e);
					throw e;
				}
				if (!n) throw new Error("Crabbox warmup lease was not found during inspection");
				i.start({
					binary: y,
					id: T,
					provider: f.provider,
					heartbeatIntervalMs: f.heartbeatIntervalMs,
					heartbeatTimeoutMs: f.heartbeatTimeoutMs,
					idleTimeout: f.idleTimeout,
					lifetime: n.lifetime
				});
				const d = {
					...w,
					deadline: x,
					inspect: n,
					profile: f,
					stopLease,
					signal: _,
					assertCurrent: c
				};
				if (isNonRunnableState(n.state)) return await failProvisionAfterCleanup({
					...d,
					id: T
				}, new WorkerProviderError(`Crabbox warmup lease entered a terminal state${n.failureError ? `: ${n.failureError}` : ""}`));
				d.inspect = await waitForProvisionReady(d);
				d.deadline = C;
				if (f.setup && s.kind !== "checkpoint") {
					await runProvisionSetup({
						...d,
						phase: "profile setup",
						setup: f.setup
					});
					d.inspect = await waitForProvisionReady({
						...d,
						refresh: true
					});
				}
				const m = await prepareProvisionDesktop({
					...d,
					wallpaperBase64: t,
					prepareBeforeEnrollment: Boolean(g)
				});
				if (g?.preparation && (await u.lookupLease(T))?.phase === "enrolled") try {
					await prepareCrabboxProjectFiles({
						...w,
						id: T,
						project: g,
						inspectPrepared: true,
						signal: _,
						timeoutMs: () => remainingProvisionTimeout(C, CRABBOX_SETUP_TIMEOUT_MS)
					});
				} catch (e) {
					_?.throwIfAborted();
					return await failProvisionAfterCleanup({
						...w,
						id: T,
						stopLease
					}, e);
				}
				let h = false;
				let S = false;
				const prepareRuntime = async () => {
					const e = await prepareCrabboxWorkerRuntime({
						context: d,
						prepareNodeRuntime: r?.prepareNodeRuntime,
						leaseId: T,
						preparationSignal: _,
						assertCurrent: c,
						onSetupFailure: () => {
							S = true;
						}
					});
					return {
						timeoutMs: e.timeoutMs,
						run: async (t) => {
							await e.run(t);
							h = true;
							c();
						}
					};
				};
				if (g && (await u.lookupLease(T))?.phase !== "enrolled") {
					let e;
					try {
						const t = await prepareCrabboxProjectFiles({
							...w,
							id: T,
							project: g,
							signal: _,
							timeoutMs: () => remainingProvisionTimeout(C, CRABBOX_SETUP_TIMEOUT_MS),
							recordRecipePreparation: (e) => u.noteRecipePreparation(T, e, () => {
								_?.throwIfAborted();
								c();
							}),
							setupSecrets: f.setupSecrets,
							assertCurrent: c
						});
						c();
						await u.markPrepared(T, g.baseCommit, () => {
							_?.throwIfAborted();
							c();
						}, t);
						e = !f.warmImage || t?.captureSkipped ? false : await u.capture({
							...w,
							id: T,
							profile: f,
							cliVersion: b,
							signal: _,
							assertCurrent: c,
							projectCaptureRequired: t?.captureRequired || a ? true : void 0,
							projectCaptureReplay: a ? true : void 0,
							...s.kind === "checkpoint" ? { forkedCheckpointId: s.checkpointId } : {}
						}, prepareRuntime);
					} catch (e) {
						o?.throwIfAborted();
						c();
						if (S) throw e;
						return await failProvisionAfterCleanup({
							...w,
							id: T,
							stopLease
						}, e);
					}
					if (e === true) d.inspect = await waitForProvisionReady({
						...d,
						refresh: true
					});
				}
				o?.throwIfAborted();
				const E = r?.beginNodeEnrollment;
				if (!E) return await failProvisionAfterCleanup({
					...d,
					id: T
				}, /* @__PURE__ */ new Error("Crabbox worker node enrollment is unavailable"));
				let D;
				try {
					const t = s.kind === "checkpoint" && isDeepStrictEqual(await u.checkpointRuntimeIdentity(s.checkpointId), p);
					if (r?.prepareNodeRuntime && !h && e?.phase !== "enrolled" && !t && (!g || s.kind === "checkpoint")) await (await prepareRuntime()).run();
					D = await E();
					o?.throwIfAborted();
				} catch (e) {
					o?.throwIfAborted();
					if (S) throw e;
					if (e instanceof Error && e.name === "AbortError") throw e;
					return await failProvisionAfterCleanup({
						...d,
						id: T
					}, e);
				}
				const O = createCrabboxNodeEnrollmentSetup({
					enrollment: D,
					desktop: f.desktop,
					desktopSetup: g ? void 0 : m?.setup,
					target: f.target,
					leaseId: T
				});
				const k = _ && D.signal ? AbortSignal.any([_, D.signal]) : _ ?? D.signal;
				await runProvisionSetup({
					...d,
					phase: "node enrollment setup",
					signal: k,
					setup: O.command,
					timeoutMs: resolveCrabboxNodeEnrollmentTimeoutMs(D.bootstrapTimeoutMs) + (m && !g ? CRABBOX_SETUP_TIMEOUT_MS : 0),
					forwardedEnv: O.forwardedEnv
				});
				let A;
				try {
					A = await D.waitForDeviceId();
					o?.throwIfAborted();
				} catch (e) {
					o?.throwIfAborted();
					if (D.signal?.aborted) throw e;
					const t = {
						...d,
						id: T
					};
					const n = await collectCrabboxNodeEnrollmentEvidence({
						...t,
						target: f.target,
						...k ? { signal: k } : {}
					});
					o?.throwIfAborted();
					D.signal?.throwIfAborted();
					const r = e instanceof Error ? e.message : "Worker node enrollment failed";
					return await failProvisionAfterCleanup(t, new Error(`${r}; ${n}`, { cause: e }));
				}
				if (f.warmImage) {
					await u.markEnrolled(T, () => {
						o?.throwIfAborted();
						D.signal?.throwIfAborted();
					});
					o?.throwIfAborted();
					D.signal?.throwIfAborted();
				}
				l = true;
				return {
					...v,
					node: { deviceId: A },
					...m ? { desktop: m.endpoint } : {}
				};
			} finally {
				if (!l) await i.stop(T);
			}
		};
		return async () => {
			const e = { leaseId: T };
			l.add(e);
			try {
				return await provision();
			} finally {
				l.delete(e);
			}
		};
	};
	return {
		id: CRABBOX_WORKER_PROVIDER_ID,
		resolveDisplayId: (e) => parseCrabboxProfile(e).provider,
		allowsDesktopResize: true,
		async dispose() {
			a.abort();
			await Promise.all([
				i.dispose(),
				d?.catch(() => {}),
				f.settle(),
				o.settle()
			]);
		},
		images: f.images,
		maintain(e) {
			e.assertCurrent();
			a.signal.throwIfAborted();
			return d ??= Promise.resolve().then(async () => {
				const t = AbortSignal.any([e.signal, a.signal]);
				const assertCurrent = () => {
					t.throwIfAborted();
					e.assertCurrent();
				};
				assertCurrent();
				const n = await resolveMaintenanceBinaries(e.profiles, t);
				assertCurrent();
				await u.maintain({
					binaries: n,
					signal: t,
					assertCurrent
				});
			}).finally(() => {
				d = void 0;
			});
		},
		...c,
		supportedExecutionModes: ["worker-turn", "remote-exec"],
		supportsCleanupAcceptance: true,
		provisionBeforeInstallation: true,
		requiresNodeEnrollment: true,
		supportsProjectPreparation: supportsCrabboxProjectPreparation,
		resolvePreparedIdleTimeoutMs: resolveCrabboxPreparedIdleTimeoutMs,
		resolvePreparationTarget: resolveCrabboxPreparationTarget,
		runSetupCommand: createCrabboxSetupCommandRunner({ resolveBinary: async (...e) => (await s(...e)).binary }),
		notePreparedDemand: async (e, t) => await u.notePreparedDemand(e.leaseId, t),
		resolveAllocation,
		resolveProvisionTimeoutMs(e, t) {
			return resolveCrabboxProvisionCallTimeoutMs(parseCrabboxProfile(e), t?.nodeBootstrapTimeoutMs);
		},
		resolveDestroyTimeoutMs(e) {
			return resolveCrabboxDestroyTimeoutMs(parseCrabboxCleanupProfile(e));
		},
		prepareProvision,
		async provision(...e) {
			return await (await prepareProvision(...e))();
		},
		async inspect(e) {
			const { context: t } = await resolveLeaseContext(e);
			const n = await inspectWithContext({
				...t,
				signal: e.signal
			});
			e.signal?.throwIfAborted();
			if (!n || isNonRunnableState(n.state)) {
				await i.stop(t.id);
				return { status: "unknown" };
			}
			i.start({
				...t,
				lifetime: n.lifetime
			});
			return {
				status: "active",
				sharedHost: false
			};
		},
		async destroy(e) {
			e.signal?.throwIfAborted();
			assertCrabboxLeaseId(e.leaseId);
			if (parseCrabboxCleanupProfile(e.profile).warmImage === false) await i.stop(e.leaseId);
			const { context: t, profile: r } = await resolveLeaseContext(e).catch(async (t) => {
				await i.stop(e.leaseId);
				throw t;
			});
			let o = e.onCleanupAccepted;
			try {
				const n = await u.lookupLease(t.id);
				const i = resolveCrabboxWarmImageProfile(r, n?.machineClass ?? r.class, n ? n.os ?? "linux" : r.target);
				if (i.warmImage) await u.capture({
					...t,
					signal: e.signal ? AbortSignal.any([a.signal, e.signal]) : a.signal,
					profile: i,
					teardown: true,
					onCaptureStart: () => {
						o?.();
						o = void 0;
					}
				});
			} catch (r) {
				if (e.signal?.aborted) {
					await i.stop(t.id);
					e.signal.throwIfAborted();
				}
				n(`Crabbox warm image capture failed for lease ${t.id}: ${coerceErrorMessage(r)}; next step: crabbox stop --provider ${t.provider} ${t.id}`);
			}
			await stopLease(t, o, e.signal);
		}
	};
}
//#endregion
//#region extensions/crabbox/index.ts
const workerWallpaperPath = fileURLToPath(new URL("./assets/openclaw-worker-wallpaper.png", import.meta.url));
var crabbox_default = definePluginEntry({
	id: "crabbox",
	name: "Crabbox Worker Provider",
	description: "Cloud worker provider and lease-backed sandbox backend for the Crabbox CLI",
	register(e) {
		e.registerTool((t) => createCrabboxTool({
			context: t,
			gateway: e.runtime.gateway
		}), { name: "crabbox" });
		e.registerToolMetadata({
			toolName: "crabbox",
			displayName: "Crabbox",
			description: "Run and present apps on a temporary machine attached to this conversation.",
			risk: "high",
			tags: ["cloud", "desktop"]
		});
		e.registerCli(async ({ program: t, config: n }) => {
			const { registerCrabboxWarmImageCommands: r } = await import("../../crabbox-worker-warm-image-cli-DmEUgFrN.mjs");
			r(t, e.runtime.state);
			const { registerCrabboxModelRunCommand: i } = await import("../../crabbox-model-run-cli-Cyf2Ehxt.mjs");
			i({
				program: t,
				config: n
			});
		}, { descriptors: [{
			name: "crabbox",
			description: "Run model-backed commands and manage Crabbox warm images",
			hasSubcommands: true
		}] });
		e.registerGatewayMethod("crabbox.images.list", async (t) => {
			const { listCrabboxImages: n } = await import("../../crabbox-gateway-methods-CQLMDFG2.mjs");
			await n(e, t);
		}, { scope: "operator.admin" });
		e.registerGatewayMethod("crabbox.images.recover", async (t) => {
			const { recoverCrabboxImage: n } = await import("../../crabbox-gateway-methods-CQLMDFG2.mjs");
			await n(e.runtime.state, t);
		}, { scope: "operator.admin" });
		const t = createCrabboxWorkerProvider({
			state: e.runtime.state,
			openclawRoot: resolveOpenClawRoot(e.rootDir),
			wallpaperPath: workerWallpaperPath,
			warn: (t) => e.logger.warn(t),
			info: (t) => e.logger.info(t),
			warmImagePolicy: resolveCrabboxWarmImagePolicy(e.pluginConfig)
		});
		for (const n of [
			"pin",
			"delete",
			"rollback"
		]) e.registerGatewayMethod(`crabbox.images.${n}`, async (r) => {
			const { mutateCrabboxImage: i } = await import("../../crabbox-gateway-methods-CQLMDFG2.mjs");
			await i(e, t.images, n, r);
		}, { scope: "operator.admin" });
		e.registerWorkerProvider(t);
		const n = resolveCrabboxSandboxConfig(e.pluginConfig);
		if (n && e.registrationMode === "full") {
			const t = {
				openclawRoot: resolveOpenClawRoot(e.rootDir),
				pluginConfig: n
			};
			const r = registerSandboxBackend(CRABBOX_SANDBOX_BACKEND_ID, {
				factory: createCrabboxSandboxBackendFactory(t),
				reserveRuntimeId: mintCrabboxSandboxLeaseId,
				manager: createCrabboxSandboxBackendManager(t),
				resolveWorkdir: resolveCrabboxSandboxWorkdir
			});
			e.lifecycle.registerRuntimeLifecycle({
				id: "crabbox-sandbox-cleanup",
				cleanup: ({ reason: e, sessionKey: t, runId: n }) => {
					if (t !== void 0 || n !== void 0) return;
					if (e === "disable" || e === "restart") r();
				}
			});
		}
		e.registerService({
			id: "crabbox-worker-cleanup",
			start() {},
			stop() {
				return t.dispose();
			}
		});
	}
});
//#endregion
export { crabbox_default as default };