UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2 lines • 12.8 kB
import{N as e,at as t,xt as n}from"./openclaw-state-read-subsystem-Dwoo5bcz.mjs";import{o as r}from"./openclaw-state-read-schemas-YhOPoIHM.mjs";import{a as i,r as a}from"./openclaw-state-read-kysely-sync-Bcu0Qb7F.mjs";import"./openclaw-state-read.worker.js";import{t as o}from"./openclaw-state-read-openclaw-state-feature-schema-BaBHFVL8.mjs";import{c as s,s as c}from"./openclaw-state-read-placement-row-codec-DQrOmCiV.mjs";import l from"node:path";import{AsyncLocalStorage as u}from"node:async_hooks";import"node:util";import"node:buffer";function isWorkerDesktopString(e){return typeof e==`string`&&!e.includes(`\0`)&&Buffer.byteLength(e)<=4096}function isWorkerDesktopArgs(e){return Array.isArray(e)&&e.length<=32&&e.every(isWorkerDesktopString)&&e.reduce((e,t)=>e+Buffer.byteLength(t),0)<=8192}function isWorkerDesktopUsername(e){return typeof e==`string`&&e.length>0&&e.trim()===e&&!/[\0\r\n]/u.test(e)&&Buffer.byteLength(e)<=63}((e,t=256)=>r(e=>typeof e==`string`&&e.length>0&&e.length<=t&&e.trim()===e&&!e.includes(`\0`),{error:`INVALID_REQUEST: ${e} must be a bounded non-empty identifier`}))(`gatewayNamespace`).refine(e=>/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(e),{error:`INVALID_REQUEST: gatewayNamespace must be a safe bounded path component`});function hasExactOwnKeys(e,t,n=[]){return t.every(t=>Object.hasOwn(e,t))&&n.every(t=>Object.hasOwn(e,t)||!Reflect.has(e,t))&&Object.keys(e).every(e=>t.includes(e)||n.includes(e))}function isAbsoluteDesktopPath(e){return isWorkerDesktopString(e)&&(l.posix.isAbsolute(e)||l.win32.isAbsolute(e))}function normalizeWorkerDesktopEndpoint(e){if(!n(e)||e.protocol!==`rfb`)throw Error(`Worker environment desktop protocol must be "rfb"`);if(!hasExactOwnKeys(e,[`protocol`,`port`],[`passwordFilePath`,`username`,`apps`,`allowsResize`]))throw Error(`Worker environment desktop endpoint contains unknown fields`);if(typeof e.port!=`number`||!Number.isSafeInteger(e.port)||e.port<1||e.port>65535)throw Error(`Worker environment desktop port must be an integer from 1 through 65535`);let t=e.passwordFilePath;if(t!==void 0&&!isAbsoluteDesktopPath(t))throw Error(`Worker environment desktop password file path must be absolute`);if(e.allowsResize!==void 0&&typeof e.allowsResize!=`boolean`)throw Error(`Worker environment desktop allowsResize must be a boolean`);if(e.username!==void 0&&(!isWorkerDesktopUsername(e.username)||!t))throw Error(`Worker environment desktop username requires a bounded ARD account and password file`);if(e.apps!==void 0&&!Array.isArray(e.apps))throw Error(`Worker environment desktop apps must be an array`);if((e.apps?.length??0)>8)throw Error(`Worker environment desktop apps cannot exceed 8`);let r=/* @__PURE__ */ new Set,i=(e.apps??[]).map(e=>{if(!n(e)||e.id!==`browser`&&e.id!==`terminal`)throw Error(`Worker environment desktop app id must be "browser" or "terminal"`);if(r.has(e.id))throw Error(`Worker environment desktop app id ${e.id} must be unique`);if(r.add(e.id),!isAbsoluteDesktopPath(e.executablePath))throw Error(`Worker environment desktop app executable path must be absolute`);if(e.args!==void 0&&!isWorkerDesktopArgs(e.args))throw Error(`Worker environment desktop app args must be bounded strings`);if(!hasExactOwnKeys(e,e.id===`terminal`?[`id`,`executablePath`]:[`id`,`executablePath`,`cdpPort`],[`args`]))throw Error(`Worker environment ${e.id} desktop app contains unknown fields`);let t;if(e.id===`terminal`)t={id:`terminal`,executablePath:e.executablePath};else{if(typeof e.cdpPort!=`number`||!Number.isSafeInteger(e.cdpPort)||e.cdpPort<1||e.cdpPort>65535)throw Error(`Worker environment browser CDP port must be an integer from 1 through 65535`);t={id:`browser`,executablePath:e.executablePath,cdpPort:e.cdpPort}}return e.args!==void 0&&(t.args=[...e.args]),t});return{protocol:`rfb`,port:e.port,...t===void 0?{}:{passwordFilePath:t},...e.username===void 0?{}:{username:e.username},...e.allowsResize===void 0?{}:{allowsResize:e.allowsResize},...e.apps===void 0?{}:{apps:i}}}new u;function readWorkerEnvironmentPreparation(e){let{preparation_key:t,preparation_purpose:n,preparation_demand_at_ms:r,preparation_expires_at_ms:i,preparation_consumed_at_ms:a}=e;if(t===null&&n===null&&r===null&&i===null&&a===null)return null;if(n!==null&&n!==`reserve`&&n!==`build`||typeof t!=`string`||!/^[a-f0-9]{64}$/u.test(t)||r===null||!Number.isSafeInteger(r)||r<0||i===null||!Number.isSafeInteger(i)||i<=r||a!==null&&(!Number.isSafeInteger(a)||a<r||a>=i))throw Error(`Worker environment preparation metadata is invalid`);return{purpose:n??`reserve`,key:t,demandAtMs:r,expiresAtMs:i,consumedAtMs:a}}const query=e=>i(e);o(`worker_environment_session_attachments`);function fromRow(e){return{sessionId:e.session_id,sessionKey:e.session_key,agentId:e.agent_id,...e.session_lifecycle_revision?{sessionLifecycleRevision:e.session_lifecycle_revision}:{},environmentId:e.environment_id,generation:e.generation,createdAtMs:e.created_at_ms,lastUsedAtMs:e.last_used_at_ms,closedAtMs:e.closed_at_ms}}function readWorkerEnvironmentSessionAttachments(e,t){if(t?.length===0)return[];let n=query(e).selectFrom(`worker_environment_session_attachments`).selectAll();return a(e,t?n.where(`environment_id`,`in`,t):n).rows.map(fromRow)}const d=/^[a-f0-9]{64}$/u,f=/^[A-Za-z0-9_-]{43}$/u,p=/^(?:ssh|ecdsa-sha2|sk-(?:ssh|ecdsa-sha2))-[A-Za-z0-9@._+-]+$/u,m=/^[A-Za-z0-9+/]+={0,2}$/u;function requireWorkerEnvironmentString(e,t){if(typeof e!=`string`||!e.trim())throw Error(`Worker environment ${t} must be a non-empty string`);return e.trim()}function normalizeOpenSshHostKey(e){if(typeof e!=`string`||e.length>16384||e.includes(` `)||e.includes(`\r`))throw Error(`Worker environment SSH host key must be one OpenSSH public-key line`);let t=e.trim().split(/\s+/u),[n,r]=t;if(t.length!==2||!n||!r||!p.test(n)||!m.test(r)||r.length%4!=0)throw Error(`Worker environment SSH host key must use OpenSSH public-key format`);return`${n} ${r}`}function normalizeBootstrapReceipt(e){let n=requireWorkerEnvironmentString(e.bundleHash,`bootstrap bundle hash`);if(!d.test(n))throw Error(`Worker environment bootstrap bundle hash must be lowercase SHA-256 hex`);if(!Array.isArray(e.protocolFeatures))throw Error(`Worker environment bootstrap protocol features must be an array`);if(e.protocolFeatures.length>64||e.protocolFeatures.some(e=>typeof e!=`string`||e.trim().length>128))throw Error(`Worker environment bootstrap protocol features exceed admission limits`);if(e.installKind!==void 0&&e.installKind!==`bundle`&&e.installKind!==`local`)throw Error(`Worker environment bootstrap install kind is invalid`);return{bundleHash:n,openclawVersion:requireWorkerEnvironmentString(e.openclawVersion,`bootstrap OpenClaw version`),protocolFeatures:t(e.protocolFeatures),...e.installKind?{installKind:e.installKind}:{}}}function normalizeCredentialHash(e){let t=requireWorkerEnvironmentString(e,`credential hash`);if(!f.test(t))throw Error(`Worker credential hash must be a SHA-256 base64url digest`);return t}function normalizeAttachedSessionIds(e){let n=t(e);for(let e of n)if(e.length>256)throw Error(`Worker environment attached session id exceeds the admission limit`);return n}function normalizeWorkerSshEndpoint(t){let n=requireWorkerEnvironmentString(t.host,`SSH host`),r=requireWorkerEnvironmentString(t.user,`SSH user`),i=normalizeOpenSshHostKey(t.hostKey);if(!Number.isSafeInteger(t.port)||t.port<1||t.port>65535)throw Error(`Worker environment SSH port must be an integer from 1 through 65535`);if(!e(t.keyRef))throw Error(`Worker environment SSH key must be a valid SecretRef`);if(t.fallbackPorts!==void 0&&!Array.isArray(t.fallbackPorts))throw Error(`Worker environment SSH fallback ports must be an array`);let a=/* @__PURE__ */ new Set([t.port]),o=[];for(let e of t.fallbackPorts??[]){if(!Number.isSafeInteger(e)||e<1||e>65535)throw Error(`Worker environment SSH fallback ports must be integers from 1 through 65535`);a.has(e)||(a.add(e),o.push(e))}if(o.length>10)throw Error(`Worker environment SSH fallback ports cannot exceed 10`);return{host:n,port:t.port,...o.length>0?{fallbackPorts:o}:{},user:r,hostKey:i,keyRef:{...t.keyRef}}}function assertShape(e){if(e.sshEndpoint&&e.nodeDeviceId)throw Error(`Worker environment cannot retain both SSH and node transports`);if(s(e.state)){if(!e.leaseId)throw Error(`Worker environment state ${e.state} requires a provider lease`);if(e.state===`bootstrapping`&&!e.sshEndpoint)throw Error(`Worker environment bootstrap requires an SSH endpoint reference`);if(e.state===`ready`&&!e.sshEndpoint&&!e.nodeDeviceId)throw Error(`Ready worker environment requires a transport binding`)}else if(e.leaseId||e.sshEndpoint||e.desktop)throw Error(`Worker environment state ${e.state} cannot retain a provider lease`);if(e.state===`bootstrapping`&&e.bootstrapReceipt)throw Error(`Bootstrapping worker environment cannot retain a stale bootstrap receipt`);if(e.state===`attached`&&e.attachedSessionIds.length!==1)throw Error(`Attached worker environment requires exactly one session id`);if(e.state!==`attached`&&e.attachedSessionIds.length!==0)throw Error(`Only an attached worker environment may retain a session id`)}function teardownTerminalStateFrom(e){if(e===null||e===`destroyed`||e===`failed`)return e;throw Error(`Worker environment teardown terminal state is invalid`)}function endpointFrom(e,t){let{ssh_host:n,ssh_port:r,ssh_user:i,ssh_host_key:a,ssh_key_ref_json:o}=e;return n===null||r===null||i===null||a===null||o===null?null:normalizeWorkerSshEndpoint({host:n,port:r,...t.length>0?{fallbackPorts:t}:{},user:i,hostKey:a,keyRef:JSON.parse(o)})}function bootstrapReceiptFrom(e){let{bootstrap_bundle_hash:t,bootstrap_openclaw_version:n,bootstrap_protocol_features_json:r,bootstrap_install_kind:i}=e;if(t===null&&n===null&&r===null)return null;if(t===null||n===null||r===null)throw Error(`Worker environment bootstrap receipt is incomplete`);return normalizeBootstrapReceipt({bundleHash:t,openclawVersion:n,protocolFeatures:JSON.parse(r),...i===null?{}:{installKind:i}})}function decodeWorkerEnvironmentRow(e,t){let n={environmentId:e.environment_id,providerId:e.provider_id,profileId:e.profile_id,profileSnapshot:JSON.parse(e.profile_snapshot_json),preparation:readWorkerEnvironmentPreparation(e),provisionOperationId:e.provision_operation_id,nodeSetupId:e.node_setup_id,nodeDeviceId:e.node_device_id,sharedHost:e.shared_host===null?null:e.shared_host===1,leaseId:e.lease_id,sshEndpoint:endpointFrom(e,t),desktop:e.desktop_json===null?null:normalizeWorkerDesktopEndpoint(JSON.parse(e.desktop_json)),bootstrapReceipt:bootstrapReceiptFrom(e),ownerEpoch:e.owner_epoch,teardownTerminalState:teardownTerminalStateFrom(e.teardown_terminal_state),state:c(e.state),attachedSessionIds:normalizeAttachedSessionIds(JSON.parse(e.attached_session_ids_json)),createdAtMs:e.created_at_ms,updatedAtMs:e.updated_at_ms,stateChangedAtMs:e.state_changed_at_ms,lastActivatedAtMs:e.last_activated_at_ms,idleSinceAtMs:e.idle_since_at_ms,destroyRequestedAtMs:e.destroy_requested_at_ms,lastError:e.last_error};return assertShape(n),n}function credentialFromRow(e){return{environmentId:e.environment_id,credentialHash:normalizeCredentialHash(e.credential_hash),bundleHash:e.bundle_hash,sessionId:e.session_id,rpcSetVersion:e.rpc_set_version,ownerEpoch:e.owner_epoch,expiresAtMs:e.expires_at_ms,deliveredAtMs:e.delivered_at_ms}}const queryWorkerEnvironmentStore=e=>i(e);function environmentRows(e){return queryWorkerEnvironmentStore(e).selectFrom(`worker_environments`).leftJoin(`worker_environment_ssh_fallback_ports as ports`,`ports.environment_id`,`worker_environments.environment_id`).selectAll(`worker_environments`).select(e=>e.cast(`ports.port`,`double precision`).as(`ssh_fallback_port`)).orderBy(`worker_environments.created_at_ms`).orderBy(`worker_environments.environment_id`).orderBy(`ports.position`)}function recordsFromRows(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=t.get(n.environment_id)??{row:n,ports:[]};n.ssh_fallback_port!==null&&e.ports.push(n.ssh_fallback_port),t.set(n.environment_id,e)}return Array.from(t.values(),({row:e,ports:t})=>decodeWorkerEnvironmentRow(e,t))}function findWorkerEnvironment(e,t){let n=a(e,environmentRows(e).where(`worker_environments.environment_id`,`=`,t)).rows;return recordsFromRows(n)[0]}function listRows(e){return recordsFromRows(a(e,environmentRows(e)).rows)}function readWorkerEnvironmentFacts(e,t){let n=t?t.flatMap(t=>{let n=findWorkerEnvironment(e,t);return n?[n]:[]}):listRows(e),r=queryWorkerEnvironmentStore(e).selectFrom(`worker_environment_credentials`).selectAll(),i=t?.length===0?[]:a(e,t?r.where(`environment_id`,`in`,t):r).rows.map(credentialFromRow),o=readWorkerEnvironmentSessionAttachments(e,t);return{ids:t?[...t]:n.map(e=>e.environmentId),environments:n,credentials:i,attachments:o}}export{decodeWorkerEnvironmentRow,readWorkerEnvironmentFacts};