openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
167 lines • 108 kB
JavaScript
import{l as normalizeOptionalString}from"../../string-coerce-CpTFcSwY.mjs";import{n as coerceErrorMessage,p as toErrorObject}from"../../error-coercion-DlKnt6w-.mjs";import{l as isRecord,u as isStringArray}from"../../record-coerce-BTbqdJ3-.mjs";import{r as truncateUtf16Safe}from"../../utf16-slice-DA3Mllbx.mjs";import{d as sleepWithAbort,o as racePromiseWithAbortSignal}from"../../src-De06gkOi.mjs";import{c as redactSensitiveText,d as redactToolPayloadText}from"../../redact-BT59pdZ_.mjs";import{r as resolvePreferredOpenClawTmpDir}from"../../tmp-openclaw-dir-DapBruir.mjs";import{t as createSubsystemLogger}from"../../subsystem-DLCDFvCH.mjs";import{t as truncateUtf8Prefix}from"../../utf8-truncate-B8GdsL7T.mjs";import{i as textResult}from"../../tool-results-BkLNMSCi.mjs";import{d as readToolStringParam,s as readPositiveIntegerParam}from"../../common-DIgvX97L.mjs";import{t as WorkerProviderError}from"../../capability-provider.types-Bir_t_Rt.mjs";import{n as resolveCrabboxBinary}from"../../crabbox-binary-Bo1EgOsf.mjs";import"../../string-coerce-runtime-BYDH9Quw.mjs";import"../../logging-core-CC7KLfEO.mjs";import"../../text-utility-runtime-CDtGqkrl.mjs";import"../../retry-runtime-IpBUqeJt.mjs";import"../../time-runtime-SSNrsaM_.mjs";import"../../error-runtime-DW-sj0iq.mjs";import{t as definePluginEntry}from"../../plugin-entry-DhKiQ4Uu.mjs";import{a as createRemoteShellSandboxBackend,p as createRemoteShellSandboxSession}from"../../ssh-backend-BLzXTMhA.mjs";import{t as SandboxRuntimeRetiredError}from"../../provisioning-error-B2l52H9p.mjs";import{a as getSandboxBackendWorkdirResolver,o as registerSandboxBackend}from"../../backend-9GepeSkQ.mjs";import"../../sandbox-BllxRuTD.mjs";import{n as withSetupSecretEgress}from"../../secret-egress-runtime-DQILxEJh.mjs";import"../../temp-path-B-Bci5oK.mjs";import"../../param-readers-BpVB3RWF.mjs";import{a as isUnrecognizedLease,c as runCrabboxCommand,d as stopCrabboxLease,f as assertCrabboxResourceReceipt,h as runCrabboxProcess,i as isFixedLeaseIdUnsupported,l as runCrabboxCommandWithCoordinatorRetry,m as readCrabboxResourceReceipt,n as crabboxCommandOutput,o as leaseRunArgs,p as crabboxResourceIdentityArgs,s as parseCrabboxJson,t as crabboxCommandError,u as sanitizeCrabboxNotice}from"../../crabbox-worker-command-DPZFykVB.mjs";import{C as resolveCrabboxWarmImageCaptureTimeoutMs,S as resolveCrabboxReadyPollIntervalMs,_ as resolveCrabboxDestroyTimeoutMs,a as CRABBOX_MACHINE_CATALOG_TIMEOUT_MS,b as resolveCrabboxProvisionBaseTimeoutMs,c as CRABBOX_RETENTION_MUTATION_TIMEOUT_MS,d as CRABBOX_WARMUP_TIMEOUT_MS,f as WARM_IMAGE_COMMAND_ROUND_TRIP_TIMEOUT_MS,g as resolveCrabboxCheckpointCaptureTimeoutMs,h as countCrabboxProvisionSetupPhases,i as CRABBOX_LIFECYCLE_TIMEOUT_MS,l as CRABBOX_SETUP_TIMEOUT_MS,m as WARM_IMAGE_NATIVE_WAIT_TIMEOUT_MS,n as CRABBOX_DESKTOP_WARMUP_TIMEOUT_MS,o as CRABBOX_NODE_ENROLLMENT_DIAGNOSTIC_TIMEOUT_MS,p as WARM_IMAGE_COMMAND_TIMEOUT_MS,r as CRABBOX_HEARTBEAT_TIMEOUT_MS,s as CRABBOX_PROJECT_PREPARATION_TIMEOUT_MS,v as resolveCrabboxLifecycleTimeoutMs,x as resolveCrabboxProvisionCallTimeoutMs,y as resolveCrabboxNodeEnrollmentTimeoutMs}from"../../crabbox-worker-timeouts-C91C79jR.mjs";import{a as isCrabboxVersionAtLeast,n as CRABBOX_NONBLOCKING_CAPTURE_VERSION,r as ensureManagedCrabboxBinary}from"../../crabbox-managed-binary-D_OJtHhk.mjs";import{S as supportsCrabboxProjectPreparation,_ as resolveCrabboxPreparedIdleTimeoutMs,a as buildCrabboxAllocationArgs,b as resolveCrabboxWarmImageProfileKey,d as operationSlug,f as parseCrabboxCleanupProfile,g as resolveCrabboxPreparationTarget,i as assertCrabboxLeaseId,m as parseCrabboxProfile,o as heartbeatIntervalMs,p as parseCrabboxDurationMs,r as CRABBOX_WORKER_PROVIDER_ID,u as operationLeaseId,v as resolveCrabboxProvisionProfile,x as resolveOpenClawRoot,y as resolveCrabboxWarmImageProfile}from"../../crabbox-worker-profile-5DxAeX_h.mjs";import{a as createCrabboxNodeResumeScript,c as wrapCrabboxNodeScript,l as createCrabboxWorkerDesktopEndpoint,n as createCrabboxNodeRuntimeSetup,o as CRABBOX_RUNTIME_NODE_PATH,s as createCrabboxWorkerStateDirScript,t as createCrabboxNodeEnrollmentSetup,u as createCrabboxWorkerDesktopSetup}from"../../crabbox-worker-node-enrollment-CMZ5ISWk.mjs";import{a as createCrabboxMachineOptionsResolver,n as assertHetznerDesktopHasManagedCoordinator,t as assertAwsWorkerHasNoInstanceProfile}from"../../crabbox-worker-preflight-DlwwukTF.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-Bkmwt6Qm.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-B8HI4d8j.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";
//!extensions/crabbox/src/crabbox-sandbox-lease.ts
const CRABBOX_SANDBOX_LEASE_ID_PATTERN=/^cbx_[a-f0-9]{12}$/u;function mintCrabboxSandboxLeaseId(){return`cbx_${randomBytes(6).toString(`hex`)}`}
//!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`}})}
//!extensions/crabbox/src/crabbox-sandbox-config.ts
const FIELDS=[`provider`,`class`,`binary`,`ttl`,`idleTimeout`];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}
//!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\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(`
`)}\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}`)}}}
//!extensions/crabbox/src/crabbox-worker-retention.ts
function prepareCrabboxRetention(e,t){if(e.provider!==`azure-sandbox`||e.target!==`linux`||e.warmImage||t.version!==1||!/^[a-f0-9]{64}$/u.test(t.ownerBinding)||!Number.isSafeInteger(t.computeWindowSeconds)||t.computeWindowSeconds<=0||t.computeWindowSeconds>9223372036)throw new WorkerProviderError(`Crabbox session disk retention requires Linux Azure Sandbox, no warm images, a SHA-256 owner binding, and a finite whole-second compute window`);return Object.freeze({version:1,ownerBinding:t.ownerBinding,computeWindowSeconds:t.computeWindowSeconds})}async function assertCrabboxRetentionSupport(e){const t=await runCrabboxProcess([e.binary,`providers`,`--json`],{maxOutputBytes:1048576,killProcessTree:true,timeoutMs:CRABBOX_MACHINE_CATALOG_TIMEOUT_MS,...e.signal?{signal:e.signal}:{}});e.signal?.throwIfAborted();const n=t.termination===`exit`&&t.code===0?parseCrabboxJson(t.stdout,`providers`):void 0;const r=Array.isArray(n)?n.find(e=>isRecord(e)&&e.provider===`azure-sandbox`):void 0;if(!isRecord(r)||!Array.isArray(r.targets)||!r.targets.includes(`linux`)||!Array.isArray(r.features)||!r.features.includes(`session-disk-retention-v1`)||!r.features.includes(`pause-resume`))throw new WorkerProviderError(`Selected Crabbox executable does not advertise Linux Azure Sandbox session-disk-retention-v1 and pause-resume; update Crabbox before retained allocation`)}function boundedText(e,t=2048){return typeof e===`string`&&e.length>0&&e.length<=t&&e.trim()===e&&!/\p{Cc}/u.test(e)}function assertCrabboxRetentionOperation(e){if(!/^[\x21-\x7e]{1,128}$/u.test(e.id)||e.action!==`pause`&&e.action!==`resume`||!boundedText(e.expectedClaimRevision))throw new Error(`Invalid Crabbox retained lifecycle operation`)}function readCrabboxRetention(e,t,n){const r=e.retention;if(!t&&r===void 0)return;if(!t)throw new Error(`Retained Crabbox allocations require the session-disk lifecycle; adoption refused`);if(e.provider!==`azure-sandbox`||!isRecord(r)||r.schema!==`crabbox.session-disk.v1`||r.mode!==`session-disk`||r.ownerBinding!==t.ownerBinding||r.computeWindowSeconds!==t.computeWindowSeconds||!boundedText(r.claimRevision)||typeof r.policyVerified!==`boolean`||typeof r.observedState!==`string`||typeof r.stopPending!==`boolean`||![`running`,`suspended`,`retired`].includes(String(r.desiredState)))throw new Error(`Crabbox retained policy observation is invalid or owner binding changed`);const i=r.identity;if(!isRecord(i)||!boundedText(i.leaseId,128)||i.leaseId!==e.id||i.attemptLeaseId!==e.id||!boundedText(i.slug)||!boundedText(i.resourceId)||boundedText(e.serverId)&&e.serverId!==i.resourceId||boundedText(e.slug)&&e.slug!==i.slug||n&&(n.version!==1||n.leaseId!==i.leaseId||n.identity.provider!==`azure-sandbox`||n.identity.resourceId!==i.resourceId||n.identity.slug!==i.slug))throw new Error(`Crabbox retained resource identity is unavailable or changed; replacement refused`);const a=r.computeWindow;if(!isRecord(a)||!boundedText(a.id)||typeof a.authorizedAt!==`string`||typeof a.expiresAt!==`string`||a.state!==`active`&&a.state!==`closed`)throw new Error(`Crabbox retained compute window is invalid`);const o=Date.parse(a.authorizedAt);const s=Date.parse(a.expiresAt);if(!Number.isSafeInteger(o)||o<=0||!Number.isSafeInteger(s)||s-o!==t.computeWindowSeconds*1e3||r.desiredState!==`running`&&a.state!==`closed`)throw new Error(`Crabbox retained compute window does not match acquisition policy`);let c;if(r.operation!==void 0){const e=r.operation;if(!isRecord(e)||!boundedText(e.id,128)||e.action!==`pause`&&e.action!==`resume`||e.phase!==`pending`&&e.phase!==`observed`||!boundedText(e.expectedClaimRevision))throw new Error(`Crabbox retained lifecycle operation is invalid`);c={id:e.id,action:e.action,phase:e.phase,expectedClaimRevision:e.expectedClaimRevision};assertCrabboxRetentionOperation(c)}const l=Date.now();let u=`unavailable`;if(r.policyVerified){if(e.state===`transitioning`||c?.phase===`pending`)u=`transitioning`;else if(e.state===`suspended`&&[`Stopped`,`Suspended`,`Idle`].includes(r.observedState))u=`suspended`;else if(e.state===`compute-expired`||e.state===`running`&&a.state===`active`&&s<=l)u=`expired`;else if(e.state===`running`&&r.observedState===`Running`&&e.ready===true&&r.desiredState===`running`&&a.state===`active`&&o<=l&&!r.stopPending)u=`running`}return{claimRevision:r.claimRevision,state:u,computeExpiresAtMs:s,...c?{operation:c}:{}}}
//!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,t,n){const r=parseCrabboxJson(e,`inspect`);if(!isRecord(r))throw new Error(`Crabbox inspect returned invalid JSON`);const i=normalizeOptionalString(r.id);const a=normalizeOptionalString(r.state)?.toLowerCase();if(!i||!/^\S{1,128}$/u.test(i)||!a)throw new Error(`Crabbox inspect returned an invalid lease identity or state`);if(r.ready!==void 0&&typeof r.ready!==`boolean`)throw new Error(`Crabbox inspect returned an invalid ready state`);if(r.sshUser!==void 0&&typeof r.sshUser!==`string`)throw new Error(`Crabbox inspect returned an invalid SSH user`);const o=normalizeOptionalString(r.sshUser);if(r.tailscale!==void 0&&!isRecord(r.tailscale))throw new Error(`Crabbox inspect returned invalid Tailscale state`);const s=r.tailscale!==void 0;let c;if(r.providerMetadata!==void 0){if(!isRecord(r.providerMetadata))throw new Error(`Crabbox inspect returned invalid provider metadata`);const e=r.providerMetadata.instanceProfileAttached;if(e!==void 0&&typeof e!==`boolean`)throw new Error(`Crabbox inspect returned invalid AWS instance profile metadata`);c=e}const l=normalizeOptionalString(r.failureError);const u=parseCrabboxLeaseLifetime(r);const d=readCrabboxResourceReceipt(r);const f=readCrabboxRetention(r,t,n);if(f?.state===`running`&&!d)throw new Error(`Crabbox retained running resource has no qualified receipt`);return{id:i,state:a,tailscaleEnabled:s,...f?{retention:f}:{},...d?{resourceReceipt:d}:{},...Object.keys(u).length?{lifetime:u}:{},...l?{failureError:truncateUtf16Safe(redactSensitiveText(l).replace(/\s+/gu,` `),512)}:{},...c!==void 0?{awsInstanceProfileAttached:c}:{},...typeof r.ready===`boolean`?{ready:r.ready}:{},...o&&o!==`<token>`?{sshUser:o}:{}}}
//!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))}}}
//!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`,`
`,"`",`$(`].some(e=>t.includes(e)))throw new WorkerProviderError(`Crabbox setup environment value cannot be represented safely: ${e}`);return`${e}="${t.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}"`}).join(`
`);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})}}
//!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})}}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(`
`)}
${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)}})}
//!extensions/crabbox/src/crabbox-worker-provision-commands.ts
const bootstrapLog=createSubsystemLogger(`gateway/worker-environments`);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,e.retention,e.resourceReceipt);const r=sanitizeCrabboxNotice(n.stderr);if(r)t.lifetime={...t.lifetime,policyNotice:r}}catch(t){const n=t instanceof Error?t.message:`Crabbox inspect returned invalid output`;if(e.resourceReceipt||e.retention)throw new Error(n,{cause:t});throw new WorkerProviderError(n)}if(e.resourceReceipt&&(!e.retention||t.resourceReceipt||t.retention?.state===`running`))assertCrabboxResourceReceipt(e.resourceReceipt,t.resourceReceipt);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)){if(e.resourceReceipt&&e.exactTeardown)return;if(e.resourceReceipt||e.retention)throw new Error(`Crabbox resource observation is unavailable; ownership preserved`);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,e.retention)],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)){if(e.retention&&(t.retention?.state===`expired`||t.retention?.state===`suspended`))throw new Error(`Crabbox retained compute needs explicit lifecycle recovery`);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(e.retention&&t.retention?.state!==`running`)throw new Error(`Crabbox retained compute is not running; explicit lifecycle recovery required`);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)}
//!extensions/crabbox/src/crabbox-worker-lease-lifecycle.ts
function createCrabboxWorkerLeaseLifecycle(e){const{resolveBinary:t,heartbeats:n}=e;const resolveLeaseContext=async e=>{const n=parseCrabboxCleanupProfile(e.profile);assertCrabboxLeaseId(e.leaseId);const r=e.retention&&prepareCrabboxRetention(n,e.retention);if(r&&(!e.resourceReceipt||e.resourceReceipt.leaseId!==e.leaseId))throw new Error(`Crabbox retained lifecycle requires the original resource receipt`);return{context:{binary:(await t(n.binary,e.signal)).binary,heartbeatIntervalMs:n.heartbeatIntervalMs,heartbeatTimeoutMs:n.heartbeatTimeoutMs,id:e.leaseId,idleTimeout:n.idleTimeout,provider:n.provider,...r?{retention:r}:{},...e.resourceReceipt?{resourceReceipt:e.resourceReceipt}:{}},profile:n}};return{resolveLeaseContext,async inspect(e){const{context:t}=await resolveLeaseContext(e);const r=await inspectWithContext({...t,signal:e.signal});e.signal?.throwIfAborted();const i=e.resourceReceipt?{resourceReceipt:e.resourceReceipt}:{};if(t.retention){await n.stop(t.id);if(!r?.retention)throw new Error(`Crabbox retained observation is unavailable; ownership preserved`);return{status:r.retention.state===`running`?`active`:`dormant`,...r.retention.state===`running`?{sharedHost:false}:{},...i,retention:r.retention}}if(!r||isNonRunnableState(r.state)){await n.stop(t.id);return{status:`unknown`,...i}}n.start({...t,lifetime:r.lifetime});return{status:`active`,sharedHost:false,...i}},async setRetainedState(t){t.assertCurrent();assertCrabboxRetentionOperation(t.operation);const r=Object.freeze({...t.operation});const{context:i}=await resolveLeaseContext(t);const a=AbortSignal.any([e.signal,...t.signal?[t.signal]:[]]);const assertCurrent=()=>{a.throwIfAborted();t.assertCurrent()};assertCurrent();await n.stop(i.id);const o=await inspectWithContext({...i,signal:a});assertCurrent();assertCrabboxResourceReceipt(t.resourceReceipt,o?.resourceReceipt);const s=i.retention;if(!s||o?.retention?.state===`unavailable`)throw new Error(`Crabbox retained ownership is unavailable; operation preserved`);const c=o?.retention;const l=c?.operation?.id===r.id;if(!c||(l?c.operation?.action!==r.action||c.operation.expectedClaimRevision!==r.expectedClaimRevision:c.claimRevision!==r.expectedClaimRevision||c.operation?.phase===`pending`))throw new Error(`Crabbox retained lifecycle revision or operation changed; inspect before retrying`);const u=await runCrabboxCommand({binary:i.binary,action:r.action,args:[r.action,`--provider`,i.provider,`--id`,i.id,`--operation-id`,r.id,`--owner-binding`,s.ownerBinding,`--expected-claim-revision`,r.expectedClaimRevision,...crabboxResourceIdentityArgs(t.resourceReceipt),`--json`],timeoutMs:CRABBOX_RETENTION_MUTATION_TIMEOUT_MS,signal:a,assertCurrent});assertCurrent();crabboxCommandOutput(r.action,{...u,stdout:``});const d=await inspectWithContext({...i,signal:a});assertCurrent();assertCrabboxResourceReceipt(t.resourceReceipt,d?.resourceReceipt);const f=d?.retention;if(!f||f.operation?.id!==r.id||f.operation.action!==r.action||f.operation.expectedClaimRevision!==r.expectedClaimRevision||f.operation.phase!==`observed`||f.state!==(r.action===`pause`?`suspended`:`running`))throw new Error(`Crabbox retained lifecycle readback remains uncertain; preserve and retry the same operation`);return f}}}
//!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)}}
//!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`)}`}
//!extensions/crabbox/src/crabbox-worker-node-resume.ts
const RESUME_WORK_TIMEOUT_MS=12e4;const RESUME_KILL_GRACE_MS=2e4;function createCrabboxNodeResumer(e){return async t=>{const n=AbortSignal.any([t.signal,e.signal]);const assertCurrent=()=>{n.throwIfAborted();t.assertCurrent()};assertCurrent();const r=parseCrabboxProfile(t.profile);if(t.platform!==`linux`||r.desktop)return;assertCrabboxLeaseId(t.leaseId);const{binary:i}=await e.resolveBinary(r.binary,n);const a=performance.now()+RESUME_WORK_TIMEOUT_MS;for(const e of[`inspect`,`launch`]){assertCurrent();const o=Math.ceil(a-performance.now());if(o<=0)throw new Error(`Crabbox node resume exceeded its ${RESUME_WORK_TIMEOUT_MS}ms deadline`);const s=await runCrabboxCommand({action:`node resume`,binary:i,args:[...leaseRunArgs({binary:i,provider:r.provider,id:t.leaseId}),`--no-hydrate`],input:createCrabboxNodeResumeScript(t,e),signal:n,timeoutMs:o,killGraceMs:RESUME_KILL_GRACE_MS});assertCurrent();if(s.termination!==`exit`||s.code!==0)throw crabboxCommandError(`node resume`,s)}}}
//!extensions/crabbox/src/crabbox-worker-project.ts
function createCrabboxPreparedProjectRefresh(e){return async(t,n)=>{const r=AbortSignal.any([e.signal,n.signal]);const assertCurrent=()=>{r.throwIfAborted();n.assertCurrent()};assertCurrent();const{context:i,profile:a}=await e.resolveLeaseContext({...t,signal:r});assertCurrent();const o=performance.now()+CRABBOX_PROJECT_PREPARATION_TIMEOUT_MS;await prepareCrabboxProjectFiles({...i,project:n,signal:r,setupSecrets:a.setupSecrets,assertCurrent,timeoutMs:()=>remainingProvisionTimeout(o,CRABBOX_SETUP_TIMEOUT_MS)});assertCurrent()}}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}}}}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,assertCurrent});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({recordRecipePreparation:e.recordRecipePreparation,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)}})}
//!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;const discoverDefault=()=>i??=resolveCrabboxBinary({openclawRoot:e.openclawRoot,pathEnv:t});return{async resolve(t,i){i?.throwIfAborted();const a=t??discoverDefault();let o=n.get(a);if(!o){e.signal.throwIfAborted();o=ensureManagedCrabboxBinary({binary:a,...t?{fallbackBinary:discoverDefault()}:{},signal:e.signal}).then(t=>{e.signal.throwIfAborted();return t}).catch(e=>{n.delete(a);throw e});n.set(a,o)}const s=await racePromiseWithAbortSignal(o,i,({reason:e})=>toErrorObject(e,`Crabbox acquisition aborted`));i?.throwIfAborted();if(t&&s.rejected&&!r.has(a)){r.add(a);e.warn(s.rejected)}return s},async settle(){await Promise.allSettled(n.values())}}}
//!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)}}}
//!extensions/crabbox/src/crabbox-worker-teardown.ts
function createCrabboxWorkerTeardown(e){const{heartbeats:t,warmImages:n,providerSignal:r,warn:i,resolveLeaseContext:a}=e;const stopLease=async(e,r,a)=>{await t.stop(e.id);e.assertCurrent?.();await stopCrabboxLease({...e,warn:i,onCleanupAccepted:r,signal:a});e.assertCurrent?.();await n.release({...e,signal:a})};return{stopLease,async destroy(e){e.signal?.throwIfAborted();assertCrabboxLeaseId(e.leaseId);if(parseCrabboxCleanupProfile(e.profile).warmImage===false)await t.stop(e.leaseId);const{context:o,profile:s}=await a(e).catch(async n=>{await t.stop(e.leaseId);throw n});if(e.resourceReceipt){if(!e.assertCurrent||s.provider!==e.resourceReceipt.identity.provider||e.leaseId!==e.resourceReceipt.leaseId)throw new Error(`Crabbox exact resource teardown authority is unavailable`);e.assertCurrent();if(o.retention){await inspectWithContext({...o,signal:e.signal,exactTeardown:true});e.assertCurrent()}await stopLease({...o,resourceReceipt:e.resourceReceipt,assertCurrent:e.assertCurrent},void 0,e.signal);return}let c=e.onCleanupAccepted;try{const t=await n.lookupLease(o.id);const i=resolveCrabboxWarmImageProfile(s,t?.machineClass??s.class,t?t.os??`linux`:s.target);if(i.warmImage)await n.capture({...o,signal:e.signal?AbortSignal.any([r,e.signal]):r,profile:i,teardown:true,onCaptureStart:()=>{c?.();c=void 0}})}catch(n){if(e.signal?.aborted){await t.stop(o.id);e.signal.throwIfAborted()}i(`Crabbox warm image capture failed for lease ${o.id}: ${coerceErrorMessage(n)}; next step: crabbox stop --provider ${o.provider} ${o.id}`)}await stopLease(o,c,e.signal)}}}
//!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`)}
//!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(`
`).some(e=>e.trim()===`checkpoint absent id=${t}`))return true}return false}
//!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)}}}
//!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
`;
//!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}}
//!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}}
//!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}}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(`, `)}`:``}`}}
//!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,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})}}
//!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 p=createCrabboxWorkerLeaseLifecycle({resolveBinary:s,heartbeats:i,signal:a.signal});const{resolveLeaseContext:m}=p;const{stopLease:h,destroy:g}=createCrabboxWorkerTeardown({heartbeats:i,warmImages:u,providerSignal:a.signal,warn:n,resolveLeaseContext:m});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?.retention&&prepareCrabboxRetention(f,r.retention);const m=f.provider===`azure-sandbox`;const g=r?.recordResourceReceipt;if(m&&!g)throw new WorkerProviderError(`Crabbox Azure Sandbox requires Gateway resource receipt persistence`);if(r?.resourceReceipt&&(!m||r.resourceReceipt.identity.provider!==f.provider))throw new Error(`Crabbox resource receipt does not match the selected provider`);let _=r?.resourceReceipt;const stopProvisionLease=e=>h({...e,resourceReceipt:_,assertCurrent:c});const v=r?.nodeRuntimeIdentity;if(f.warmImage&&!v)throw new WorkerProviderError(`Crabbox warm images require a prepared node runtime identity`);const y=f.desktop?CRABBOX_DESKTOP_WARMUP_TIMEOUT_MS:CRABBOX_WARMUP_TIMEOUT_MS;const b=Object.keys(f.setupSecrets??{}).length>0;const x=supportsCrabboxProjectPreparation(e,r?.machineClass,r?.os)?r?.project:void 0;if(r?.project?.preparation&&!x)throw new WorkerProviderError(`Crabbox prepared workers require warm images, protected setup, or a configured Linux Sandbox disk`);const S=AbortSignal.any([a.signal,...o?[o]:[],...x?.signal?[x.signal]:[]]);const C=await resolveAllocation(e,n);o?.throwIfAborted();const{binary:w,version:T}=await s(f.binary,S);S?.throwIfAborted();if(p){await assertCrabboxRetentionSupport({binary:w,signal:S});c()}if(b)await assertCrabboxSetupEgressSupport({binary:w,target:f.target,assertCurrent:c,signal:S,projectPrepared:x?Boolean(x.preparation):void 0});const E=performance.now()+resolveCrabboxProvisionBaseTimeoutMs(f);const D=resolveCrabboxNodeEnrollmentTimeoutMs(r?.nodeBootstrapTimeoutMs);const O=E+countCrabboxProvisionSetupPhases(f)*CRABBOX_SETUP_TIMEOUT_MS+2*D+(x?CRABBOX_PROJECT_PREPARATION_TIMEOUT_MS+resolveCrabboxWarmImageCaptureTimeoutMs(f.provider):0);const k={...u.startContext(w,f.provider,r,Boolean(x)),...p?{retention:p}:{}};const A=C.leaseId;if(f.desktop&&f.provider===`hetzner`)await assertHetznerDesktopHasManagedCoordinator({binary:w,signal:o});if(f.provider===`aws`)await assertAwsWorkerHasNoInstanceProfile({binary:w,signal:o});const provision=async()=>{c();if(_){const e=await inspectWithContext({...k,id:A,resourceReceipt:_,signal:S});c();assertCrabboxResourceReceipt(_,e?.resourceReceipt);if(p&&e){await waitForProvisionReady({...k,deadline:E,inspect:e,resourceReceipt:_,profile:f,stopLease:stopProvisionLease,signal:S,assertCurrent:c});c()}}const e=x?.preparation&&await u.lookupLease(A);const a=e&&e.phase!==`enrolled`;const s=await u.allocate({...k,id:A,profile:f,profileId:r?.profileId,nodeRuntimeIdentity:v,...x?{projectKey:x.key,projectLabel:x.label,projectRoot:x.root}:{},...x?.preparation?{preparation:x.preparation}:{},assertCurrent:c,signal:S,slug:operationSlug(n),timeoutMs:()=>remainingProvisionTimeout(E,y)});let l=false;try{let n;try{n=await inspectWithContext({...k,id:A,timeoutMs:remainingProvisionTimeout(E,resolveCrabboxLifecycleTimeoutMs(f.provider)),waitForReady:f.provider===`machine0`,signal:S});o?.throwIfAborted()}catch(e){o?.throwIfAborted();if(m)throw new Error(`Crabbox resource qualification failed; allocation preserved: ${coerceErrorMessage(e)}`,{cause:e});if(e instanceof WorkerProviderError)return await failProvisionAfterCleanup({...k,id:A,stopLease:stopProvisionLease},e);throw e}if(!n)throw new Error(`Crabbox warmup lease was not found during inspection`);if(m){const e=n.resourceReceipt;if(!e||!g)throw new Error(`Crabbox allocation has no qualified resource receipt`);if(_)assertCrabboxResourceReceipt(_,e);await g(e);c();_=e}if(!p)i.start({binary:w,id:A,provider:f.provider,heartbeatIntervalMs:f.heartbeatIntervalMs,heartbeatTimeoutMs:f.heartbeatTimeoutMs,idleTimeout:f.idleTimeout,lifetime:n.lifetime});const d={...k,deadline:E,inspect:n,resourceReceipt:_,profile:f,stopLease:stopProvisionLease,signal:S,assertCurrent:c};if(!p&&isNonRunnableState(n.state))return await failProvisionAfterCleanup({...d,id:A},new WorkerProviderError(`Crabbox warmup lease entered a terminal state${n.failureError?`: ${n.failureError}`:``}`));d.inspect=await waitForProvisionReady(d);d.deadline=O;if(f.setup&&s.kind!==`checkpoint`){await runProvisionSetup({...d,phase:`profile setup`,setup:f.setup});d.inspect=await waitForProvisionReady({...d,refresh:true})}const h=await prepareProvisionDesktop({...d,wallpaperBase64:t,prepareBeforeEnrollment:Boolean(x)});if(x?.preparation&&(await u.lookupLease(A))?.phase===`enrolled`)try{await prepareCrabboxProjectFiles({...k,id:A,project:x,inspectPrepared:true,signal:S,timeoutMs:()=>remainingProvisionTimeout(O,CRABBOX_SETUP_TIMEOUT_MS)})}catch(e){S?.throwIfAborted();return await failProvisionAfterCleanup({...k,id:A,stopLease:stopProvisionLease},e)}let y=false;let b=false;const prepareRuntime=async()=>{const e=await prepareCrabboxWorkerRuntime({context:d,prepareNodeRuntime:r?.prepareNodeRuntime,leaseId:A,preparationSignal:S,assertCurrent:c,onSetupFailure:()=>{b=true}});return{timeoutMs:e.timeoutMs,run:async t=>{await e.run(t);y=true;c()}}};if(x&&(await u.lookupLease(A))?.phase!==`enrolled`){let e;try{const t=await prepareCrabboxProjectFiles({...k,id:A,project:x,signal:S,timeoutMs:()=>remainingProvisionTimeout(O,CRABBOX_SETUP_TIMEOUT_MS),recordRecipePreparation:e=>u.noteRecipePreparation(A,e,()=>{S?.throwIfAborted();c()}),setupSecrets:f.setupSecrets,assertCurrent:c});c();await u.markPrepared(A,x.baseCommit,()=>{S?.throwIfAborted();c()},t);e=!f.warmImage||t?.captureSkipped?false:await u.capture({...k,id:A,profile:f,cliVersion:T,signal:S,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(b)throw e;return await failProvisionAfterCleanup({...k,id:A,stopLease:stopProvisionLease},e)}if(e===true)d.inspect=await waitForProvisionReady({...d,refresh:true})}o?.throwIfAborted();const D=r?.beginNodeEnrollment;if(!D)return await failProvisionAfterCleanup({...d,id:A},/* @__PURE__ */ new Error(`Crabbox worker node enrollment is unavailable`));let j;try{const t=s.kind===`checkpoint`&&isDeepStrictEqual(await u.checkpointRuntimeIdentity(s.checkpointId),v);if(r?.prepareNodeRuntime&&!y&&e?.phase!==`enrolled`&&!t&&(!x||s.kind===`checkpoint`))await(await prepareRuntime()).run();j=await D();o?.throwIfAborted()}catch(e){o?.throwIfAborted();if(b)throw e;if(e instanceof Error&&e.name===`AbortError`)throw e;return await failProvisionAfterCleanup({...d,id:A},e)}const M=createCrabboxNodeEnrollmentSetup({enrollment:j,desktop:f.desktop,desktopSetup:x?void 0:h?.setup,target:f.target,leaseId:A});const N=S&&j.signal?AbortSignal.any([S,j.signal]):S??j.signal;await runProvisionSetup({...d,phase:`node enrollment setup`,signal:N,setup:M.command,timeoutMs:resolveCrabboxNodeEnrollmentTimeoutMs(j.bootstrapTimeoutMs)+(h&&!x?CRABBOX_SETUP_TIMEOUT_MS:0),forwardedEnv:M.forwardedEnv});let P;try{P=await j.waitForDeviceId();o?.throwIfAborted()}catch(e){o?.throwIfAborted();if(j.signal?.aborted)throw e;const t={...d,id:A};const n=await collectCrabboxNodeEnrollmentEvidence({...t,target:f.target,...N?{signal:N}:{}});o?.throwIfAborted();j.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(A,()=>{o?.throwIfAborted();j.signal?.throwIfAborted()});o?.throwIfAborted();j.signal?.throwIfAborted()}l=true;return{...C,..._?{resourceReceipt:_}:{},node:{deviceId:P},...h?{desktop:h.endpoint}:{}}}finally{if(!l)await i.stop(A)}};return async()=>{const e={leaseId:A};l.add(e);try{return await provision()}finally{l.delete(e)}}};return{id:CRABBOX_WORKER_PROVIDER_ID,supportsResourceReceipts:true,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,resumeNode:createCrabboxNodeResumer({resolveBinary:s,signal:a.signal}),supportsProjectPreparation:supportsCrabboxProjectPreparation,resolvePreparedIdleTimeoutMs:resolveCrabboxPreparedIdleTimeoutMs,resolvePreparationTarget:resolveCrabboxPreparationTarget,runSetupCommand:createCrabboxSetupCommandRunner({resolveBinary:async(...e)=>(await s(...e)).binary}),refreshPreparedProject:createCrabboxPreparedProjectRefresh({signal:a.signal,resolveLeaseContext:m}),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))()},inspect:p.inspect,setRetainedState:p.setRetainedState,destroy:g}}
//!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-PSkJZi6J.mjs`);r(t,e.runtime.state);const{registerCrabboxModelRunCommand:i}=await import(`../../crabbox-model-run-cli-BgLQKeH5.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-CVoxx91_.mjs`);await n(e,t)},{scope:`operator.admin`});e.registerGatewayMethod(`crabbox.images.recover`,async t=>{const{recoverCrabboxImage:n}=await import(`../../crabbox-gateway-methods-CVoxx91_.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-CVoxx91_.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()}})}});export{crabbox_default as default};