UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

11 lines • 27.3 kB
import{d as normalizeSortedUniqueTrimmedStringList}from"./string-normalization-D_oBUpO3.mjs";import{u as normalizePluginsConfig}from"./config-state-C1eV6UWf.mjs";import{i as passesManifestOwnerBasePolicy}from"./manifest-owner-policy-DVnu9FAE.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{r as captureOpenClawStateWorkerContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{Ai as validateEnvironmentsSessionExecParams,Ci as validateEnvironmentsCreateParams,Ei as validateEnvironmentsPrepareParams,Mi as validateEnvironmentsStatusParams,Si as validateEnvironmentsAdoptSuggestedProfileParams,Ti as validateEnvironmentsListParams,Vt as validateWorkerDesktopObserveParams,_i as validateDesktopLaunchParams,bi as validateDesktopReleaseParams,vi as validateDesktopObserveParams,wi as validateEnvironmentsDestroyParams,zt as validateWorkerDesktopLaunchParams}from"./src-BDZMFmKa.mjs";import{t as shouldRejectHardlinkedPluginFiles}from"./hardlink-policy-S8MtjHnf.mjs";import{p as resolveConfigSnapshotHash}from"./io.read-helpers-B0XuPBY2.mjs";import{i as preparePluginModule}from"./plugin-module-loader-cache-Bj5H0vwC.mjs";import{n as getPluginSetupModuleLoader}from"./plugin-setup-module-DKdTsN2H.mjs";import{l as prepareSessionSourceAuthority}from"./session-source-authority-Cun3s-rH.mjs";import{r as resolvePluginRootPublicSurfaceLocation}from"./public-surface-runtime-Bi95EhPa.mjs";import{t as DEFAULT_EXEC_APPROVAL_TIMEOUT_MS}from"./exec-approvals-core-BZ6-zeZE.mjs";import{d as WRITE_SCOPE,t as ADMIN_SCOPE}from"./operator-scopes-bEvB7E5X.mjs";import{i as listAvailableManifestContractPlugins,s as loadManifestMetadataSnapshot}from"./manifest-contract-eligibility-BFn2JM5T.mjs";import{l as readConfigFileSnapshotForWrite}from"./io.runtime-BvSeVFIY.mjs";import"./io-Di_yuX3t.mjs";import{r as authorizeOperatorScopesForRequiredScope}from"./method-scopes-Dalbwzsv.mjs";import{o as resolveSessionStorePathForScope}from"./session-store-path-Co-EGagp.mjs";import{i as ErrorCodes}from"./missing-scope-error-CkgBgh6d.mjs";import{p as errorShape}from"./error-codes-CQNGhXT-.mjs";import{m as resolveOperatorRolePolicy}from"./operator-role-policy-g-dxw0h4.mjs";import{i as readSessionEntryReadOnlyInWorker}from"./session-entry-read-runtime-kAgwDw0B.mjs";import{n as captureSessionEntrySourceAssertion}from"./session-entry-source-authority-DYDyuUDE.mjs";import{o as getGatewayToolCallerIdentity}from"./gateway-caller-context-Dw9IijqV.mjs";import{i as resolveSandboxRuntimeStatus}from"./runtime-status-DDAPGR6Y.mjs";import{a as captureQueuedOperatorRecoverySource,n as captureGatewayOperatorRunAuthority}from"./operator-run-authority-DIEMEkD5.mjs";import{t as resolveWorkerPlacementCapabilities}from"./placement-capabilities-DQ5_EHl_.mjs";import{o as prepareExecApprovalsCurrentRead}from"./exec-approvals-store-CKqFK0Id.mjs";import"./exec-approvals-BLANskJu.mjs";import{t as prepareExecDefaults}from"./exec-defaults-CnnR7oU0.mjs";import{i as sanitizeExecApprovalDisplayTextWithStatus}from"./exec-approval-text-sanitize-h0o6Uj2u.mjs";import{t as formatForLog}from"./ws-log-DRCSDKLv.mjs";import{n as NODE_DESKTOP_STREAM_COMMAND}from"./node-desktop-stream-ldsAKscA.mjs";import{t as readKnownNodeCatalog}from"./node-catalog-read-BlWtUg55.mjs";import{r as respondUnavailableOnThrow,t as respondError}from"./response-BYbuAh7a.mjs";import{n as defineValidatedGatewayHandler,r as defineValidatedGatewayMethod,t as assertValidParams}from"./validation-CM41YclJ.mjs";import{t as createAgentRuntimeIdentity}from"./agent-runtime-identity-token-DO1DKFFX.mjs";import{a as readGatewayRequestMutationAuthority}from"./session-mutation-guards-Bqnc5JYL.mjs";import{t as workerInferenceMetadata}from"./inference-placement-BT7fCd4s.mjs";import{f as resolveRequiredNodeCommandAuthority,s as isNodeCommandAllowed,u as resolveNodeCommandAllowlist}from"./node-command-policy-Qm4E-4M-.mjs";import{n as readNodeSessionWithheldCommands}from"./node-registry-Bx9seCKj.mjs";import{t as lookupCronRunExecSource}from"./cron-run-exec-source-BAvIQVDR.mjs";import{t as DesktopCredentialsRequiredError}from"./host-source-errors-OIAs3Kv5.mjs";import{n as resolveDesktopObserveRequester}from"./observe-requester-BjYeu_aW.mjs";import{t as bindApprovalRequesterMetadata}from"./approval-shared-D5K52j8A.mjs";import{t as handlePendingApprovalRequestWithDelivery}from"./approval-request-delivery-D7M7U3li.mjs";import{n as getNodeDesktopService}from"./node-source-context-DcIXH7cj.mjs";import{i as summarizeWorkerEnvironment,n as resolveSessionEnvironmentCaller,r as captureSessionEnvironmentToolPolicy,t as environmentsSessionHandlers}from"./environments.session-MTCGwglc.mjs"; //!src/plugins/worker-profile-suggestions.ts const log=createSubsystemLogger(`plugins`);async function resolveSuggestedWorkerProfile(e){if(Object.keys(e.config.cloudWorkers?.profiles??{}).length>0)return;const t=normalizePluginsConfig(e.config.plugins);const n=loadManifestMetadataSnapshot({config:e.config});const r=listAvailableManifestContractPlugins({snapshot:n,config:e.config,contract:`workerProfileSuggestions`}).filter(e=>passesManifestOwnerBasePolicy({plugin:e,normalizedConfig:t}));for(const t of r)try{const n=resolvePluginRootPublicSurfaceLocation({pluginRoot:t.rootDir,pluginId:t.id,entrySource:t.source,artifactBasename:`worker-profile-api.js`});if(!n)throw new Error(`missing worker-profile-api discovery artifact`);const r=preparePluginModule({...n,boundaryLabel:`plugin root`,surfaceLabel:`worker profile discovery`,origin:t.origin,pluginId:t.id,rejectHardlinks:shouldRejectHardlinkedPluginFiles(t)}).modulePath;const i=getPluginSetupModuleLoader(t,r,n.boundaryRoot);const a=await i.initialize(()=>{const e=i(r);if(!e||typeof e!==`object`||!(`discoverWorkerProfile`in e)||typeof e.discoverWorkerProfile!==`function`)throw new Error(`worker-profile-api must export discoverWorkerProfile`);return e.discoverWorkerProfile})({refresh:e.refresh});if(a){if(!t.contracts?.workerProfileSuggestions?.includes(a.profile.provider))throw new Error(`suggested profile uses an undeclared worker provider`);return a}}catch(e){log.warn(`Worker profile discovery unavailable for ${t.id}: ${String(e)}`)}} //!src/gateway/server-methods/environments.profiles.ts function listWorkerProfiles(e){if(!e.workerEnvironmentService||!e.workerPlacementDispatchService)return[];const t=e.getRuntimeConfig().cloudWorkers?.profiles??{};return Object.entries(t).flatMap(([e,t])=>{const n=typeof t.provider===`string`?t.provider.trim():``;return e.trim()&&n?[{id:e.trim(),providerId:n,...workerInferenceMetadata({providerId:n,profileSnapshot:t})}]:[]}).toSorted((e,t)=>e.id.localeCompare(t.id))}async function listWorkerProfilesWithMachines(e){const t=listWorkerProfiles(e);return await Promise.all(t.map(async t=>{const n=[`worker-turn`,`remote-exec`].filter(n=>e.workerEnvironmentService?.supportsExecutionMode(t.id,n)===true);const r=n[0];const i=e.workerEnvironmentService?.readProviderDisplayId(t.id);const a=Object.assign(t,r?{executionMode:r,executionModes:n}:{},i?{providerDisplayId:i}:{});try{const[n,r]=await Promise.all([e.workerEnvironmentService?.listMachineOptions?.(t.id),e.workerEnvironmentService?.listOperatingSystems?.(t.id)]);const i=n??[];return Object.assign(a,i.length>0?{machines:i}:{},r&&r.length>1?{operatingSystems:r}:{})}catch(n){e.logGateway.warn(`worker machine catalog unavailable (${t.id}): ${formatForLog(n)}`);return a}}))}async function requireActiveCloudProfile(e){const t=(await listWorkerProfilesWithMachines(e)).find(e=>e.id===`cloud`);if(!t)throw new Error(`The cloud worker profile is saved but is not active on this Gateway. Wait for the Gateway to restart, then retry; if it does not restart, restart it manually.`);return t} //!src/gateway/server-methods/environments.session-exec-approval.ts async function approveSessionEnvironmentCommand(e){const{options:t,binding:n,assertCurrent:r}=e;const i=t.context.execApprovalManager;if(!i)throw new Error(`Execution approval service is unavailable`);r();const a=t.client?.internal?.syntheticClient?getGatewayToolCallerIdentity():void 0;const o=t.client?.internal?.agentRuntimeIdentity??(a?.operationalRunInstance?await createAgentRuntimeIdentity({...a,operationalRunInstance:a.operationalRunInstance}):void 0);r();if(a&&!o)throw new Error(`Environment command approval requires the current admitted run`);const s=sanitizeExecApprovalDisplayTextWithStatus(JSON.stringify({argv:e.argv,...e.input===void 0?{}:{stdin:e.input}}));if(s.truncated||s.oversized)throw new Error(`Environment command is too large to review completely; split it into smaller commands`);const c=i.create({command:s.text,host:`worker`,...n,runId:o?.operationalRunInstance.runId,allowedDecisions:[`allow-once`,`deny`],warningText:`${e.background?`Start a background process`:`Run a command`} in attached environment ${n.environmentId}.${e.input===void 0?``:` The command receives ${Buffer.byteLength(e.input)} bytes on stdin.`} Approval is limited to this environment and invocation.`,turnSourceChannel:o?.turnSourceChannel,turnSourceTo:o?.turnSourceTo,turnSourceAccountId:o?.turnSourceAccountId,turnSourceThreadId:o?.turnSourceThreadId},DEFAULT_EXEC_APPROVAL_TIMEOUT_MS);bindApprovalRequesterMetadata({record:c,client:t.client});c.approvalAuthority=r;c.approvalSignals=e.signal?[e.signal]:[];if(o)c.agentRuntimeDelegatedAuthority=o.delegatedAuthority;if(o?.executionIdentity)c.executionIdentityToken=o.executionIdentity;const{decision:l}=await i.register(c,DEFAULT_EXEC_APPROVAL_TIMEOUT_MS);l.catch(()=>void 0);let u=false;await handlePendingApprovalRequestWithDelivery({approvalKind:`exec`,manager:i,record:c,context:t.context,clientConnId:t.client?.connId,twoPhase:false,deliverToApprovalClientsOnly:lookupCronRunExecSource(o?.operationalRunInstance.runId)?.agentId===n.agentId,forwardRequest:t.context.forwardExecApprovalRequest,getIosPushDelivery:()=>t.context.execApprovalIosPushDelivery,respond:(e,t,n)=>{if(!e)throw new Error(n?.message??`Execution approval failed`)},afterDecision:async e=>{r();u=e===`allow-once`&&await i.consumeAllowOnce(c.id);r()},afterDecisionErrorLabel:`environment exec approvals: approval follow-up failed`});r();if(!u)throw new Error(`Environment command was not approved`)} //!src/gateway/server-methods/environments.session-exec.ts const environmentsSessionExecHandlers={"environments.session.exec":defineValidatedGatewayMethod(`environments.session.exec`,validateEnvironmentsSessionExecParams,async e=>{const{params:t,respond:n,context:r}=e;const i=await resolveSessionEnvironmentCaller(e,t);let a;try{const o={...i.identity,storePath:resolveSessionStorePathForScope(i.identity,r.getRuntimeConfig())};const s=await readSessionEntryReadOnlyInWorker(o,i.assertCurrent);a=await prepareSessionSourceAuthority(captureSessionEntrySourceAssertion({scope:o,expected:s,fields:[`sessionId`,`lifecycleRevision`,`execHost`,`execNode`,`permissionMode`,`sandbox`,`sandboxMode`,`createdActor`],assertCurrent:i.assertCurrent,assertHostCurrent:i.assertCurrent,refuse(){throw new Error(`The selected session changed before its operation committed.`)}}));const c=r.workerEnvironmentService;const l=c?.getSessionAttachment(i.identity.sessionId);if(!c||!l||t.environmentId!==void 0&&t.environmentId!==l.environmentId)throw new Error(`No matching environment is attached to this conversation`);const u=t.action??`run`;const d={argv:t.argv?[...t.argv]:[`openclaw-internal-workspace-process`],input:t.input,timeoutMs:t.timeoutMs,processId:t.processId};const f=captureSessionEnvironmentToolPolicy(e,i,u===`run`||u===`start`?`exec`:`process`);const p=await prepareExecApprovalsCurrentRead(captureOpenClawStateWorkerContext());let m=false;const resolvePolicy=()=>{const e=r.getRuntimeConfig();a.assertCurrent();const t=prepareExecDefaults({cfg:e,...i.identity,sessionEntry:s},resolveSandboxRuntimeStatus({cfg:e,...i.identity,preparedSessionEntry:s??null}));return t.kind===`resolved`?t.defaults:t.resolve(p())};const requiresApproval=e=>e.security!==`full`||e.ask===`always`||f.cronExecAskAlways;const assertCurrent=()=>{f.assertAllowed();c.assertSessionAttachment(l);const e=resolvePolicy();if(e.security===`deny`)throw new Error(`Conversation policy denies environment command execution`);if(u===`run`||u===`start`){if(e.security===`allowlist`&&e.ask===`off`)throw new Error(`Attached environment commands cannot inherit this host's executable allowlist`);if(e.effectiveHost!==`gateway`)throw new Error(`The conversation's exec policy binds commands to a different host`)}return e};const h=assertCurrent();if((u===`run`||u===`start`)&&requiresApproval(h)){await approveSessionEnvironmentCommand({options:e,binding:l,argv:d.argv,input:d.input,background:u===`start`,assertCurrent,signal:i.signal});m=true}const assertDispatch=()=>{const e=assertCurrent();if(u===`run`||u===`start`){if(!m&&requiresApproval(e))throw new Error(`Environment execution policy now requires approval; retry the command`)}};assertDispatch();const g=await c.execSessionAttachment(l,{argv:d.argv,...d.input===void 0?{}:{input:d.input},...d.timeoutMs===void 0?{}:{timeoutMs:d.timeoutMs},...u===`run`?{}:{process:{action:u,processId:d.processId}},transportRetry:`never`,signal:i.signal,assertCurrent:assertDispatch});assertCurrent();n(true,{environmentId:l.environmentId,...g})}finally{try{await a?.release?.()}finally{i.release()}}},e=>errorShape(ErrorCodes.INVALID_REQUEST,e instanceof Error?e.message:`Environment execution failed`))}; //!src/gateway/server-methods/environments.ts async function listSuggestedWorkerProfile(e){const t=e.getRuntimeConfig();if(Object.keys(t.cloudWorkers?.profiles??{}).length>0)return;const n=await resolveSuggestedWorkerProfile({config:t});if(!n||e.getRuntimeConfig()!==t)return;return{id:n.id,providerId:n.profile.provider,...n.providerDisplayId?{providerDisplayId:n.providerDisplayId}:{}}}const adoptSuggestedWorkerProfile=defineValidatedGatewayHandler(`environments.adoptSuggestedProfile`,validateEnvironmentsAdoptSuggestedProfileParams,async e=>{const{context:t,respond:n}=e;const r=readGatewayRequestMutationAuthority(e);await respondUnavailableOnThrow(n,async()=>{const{snapshot:i}=await readConfigFileSnapshotForWrite();r.assertCurrent();if(i.sourceConfig.cloudWorkers?.profiles?.cloud){const e=await requireActiveCloudProfile(t);r.assertCurrent();n(true,{profile:e},void 0);return}const a=await resolveSuggestedWorkerProfile({config:i.config,refresh:true});r.assertCurrent();if(!a||a.id!==`cloud`){n(false,void 0,errorShape(ErrorCodes.UNAVAILABLE,`No cloud worker profile is available to configure`));return}const o=resolveConfigSnapshotHash(i);const{configHandlers:s}=await import(`./config-BYTzOwJL.mjs`);r.assertCurrent();let c=false;await s[`config.patch`]({...e,req:{...e.req,method:`config.patch`},params:{raw:JSON.stringify({cloudWorkers:{profiles:{cloud:a.profile}}}),...o?{baseHash:t.configRevisionProjector.projectRawHash(o)}:{},response:`summary`},sessionMutationCommitGuard:r.assertCurrent,respond:(e,t,r,i)=>{if(e)c=true;else n(false,t,r,i)}});if(!c)return;const l=await requireActiveCloudProfile(t);r.assertCurrent();n(true,{profile:l},void 0)})});function respondDesktopObserveFailure(e,t,n){if(t instanceof DesktopCredentialsRequiredError){respondError(e,ErrorCodes.INVALID_REQUEST,t.message,{details:{code:t.detailCode,auth:t.auth}});return}respondError(e,ErrorCodes.UNAVAILABLE,t instanceof Error?t.message:n)}async function respondDesktopObserve(e){const{request:t,context:n,respond:r}=e;if(t.source.kind!==`environment`){const i=t.source.kind===`host`;if(i&&n.getRuntimeConfig().desktop?.host?.enabled!==true){respondError(e.respond,ErrorCodes.INVALID_REQUEST,`gateway host desktop is disabled; enable the Desktop lab (config: desktop.host.enabled=true)`);return}const a={control:t.control??false,requester:e.requester,...`credentials`in t&&t.credentials?{credentials:t.credentials}:{}};const o=i?n.hostDesktopService:void 0;const s=i?void 0:getNodeDesktopService(n);const c=t.source.kind===`host`?o?.observe.bind(o,a):s?.observe.bind(s,{...a,nodeId:t.source.nodeId});if(!c){respondError(r,ErrorCodes.INVALID_REQUEST,i?`gateway host desktop is unavailable in this Gateway runtime`:`node desktop service is unavailable; reconnect to the Gateway and retry`);return}try{r(true,await c(),void 0)}catch(e){respondDesktopObserveFailure(r,e,i?`gateway host desktop observe unavailable; verify the VNC server and retry`:`node desktop observe unavailable`)}return}const{environmentId:i}=t.source;await respondWorkerDesktop(e,`observe`,t=>t.observeDesktop({environmentId:i,control:e.request.control??false,requester:e.requester}))}async function respondDesktopLaunch(e,t,n){await respondWorkerDesktop(e,`launch`,r=>r.launchDesktopApp({environmentId:t,app:n},readGatewayRequestMutationAuthority(e).assertCurrent))}async function respondWorkerDesktop(e,t,n){const r=e.context.workerEnvironmentService;if(!r){respondError(e.respond,ErrorCodes.INVALID_REQUEST,`unknown environmentId`);return}try{e.respond(true,await n(r),void 0)}catch(n){const r=n&&typeof n===`object`&&`code`in n?n.code:void 0;const i=r===`environment_not_found`||r===`invalid_state`||t===`launch`&&(r===`desktop_app_not_found`||r===`unsupported_platform`);const a=i||t===`launch`&&r===`launcher_failure`;e.respond(false,void 0,errorShape(i?ErrorCodes.INVALID_REQUEST:ErrorCodes.UNAVAILABLE,a&&n instanceof Error?n.message:t===`launch`?`worker desktop app launch unavailable; try again`:`worker desktop observe unavailable`))}}const GATEWAY_ENVIRONMENT={id:`gateway`,type:`local`,label:`Gateway local`,status:`available`,platform:process.platform,sessionHost:true,trust:`persistent`,capabilities:[`agent.run`,`sessions`,`tools`,`workspace`]};function uniqueSortedStrings(...e){return normalizeSortedUniqueTrimmedStringList(e.flatMap(e=>e??[]))}function summarizeNodeEnvironment(e,t,n,r){const i=uniqueSortedStrings(e.caps,e.commands);const a=e.platform?.trim();const o=e.connected===true?resolveNodeCommandAllowlist(t,{platform:e.platform,deviceFamily:e.deviceFamily,commands:e.commands,approvedCommands:e.commands}):void 0;const s=o?uniqueSortedStrings(e.commands).filter(t=>t.length<=128&&isNodeCommandAllowed({command:t,declaredCommands:e.commands,allowlist:o}).ok).slice(0,128):[];const c=s.includes(NODE_DESKTOP_STREAM_COMMAND);const l=o&&r?resolveRequiredNodeCommandAuthority({nodeId:e.nodeId,requiredCommands:n,declaredCommands:r.declaredCommands,effectiveCommands:r.commands,withheldCommands:readNodeSessionWithheldCommands(r),allowlist:o}):void 0;return{id:`node:${e.nodeId}`,type:`node`,label:e.displayName??e.nodeId,status:e.connected?`available`:`unavailable`,...a?{platform:a}:{},sessionHost:e.sessionHost===true,...e.connected&&e.workerHost?.deviceFolders===true?{workerHost:{deviceFolders:true}}:{},...e.workerSlots?{workerSlots:{...e.workerSlots}}:{},...e.workerBundle?{workerBundle:structuredClone(e.workerBundle)}:{},...e.lastConnectedAtMs!==void 0?{lastConnectedAtMs:e.lastConnectedAtMs}:{},...e.lastDisconnectedAtMs!==void 0?{lastDisconnectedAtMs:e.lastDisconnectedAtMs}:{},...e.lastSeenAtMs!==void 0?{lastSeenAtMs:e.lastSeenAtMs}:{},...e.lastSeenReason?{lastSeenReason:e.lastSeenReason}:{},trust:`persistent`,...c?{desktop:true}:{},...r?.desktopAvailability?{desktopAvailability:{...r.desktopAvailability}}:{},...i.length>0?{capabilities:i}:{},...s.length>0?{invocableCommands:s}:{},...l?{requiredNodeCommand:l}:{},...e.issues?.length?{issues:[...e.issues]}:{}}}async function listGatewayEnvironments(e,t=readWorkerInventory(e,false).workers,n,r=false){const i=n?resolveWorkerPlacementCapabilities(n):void 0;const{nodes:a,connectedNodes:o}=await readKnownNodeCatalog(e.nodeRegistry,i?.executionMode===`worker-turn`?`worker-environments`:`environments`);const s=new Set(t.flatMap(e=>e.providerId!==`device`&&e.nodeDeviceId&&e.state!==`destroyed`?[e.nodeDeviceId]:[]));const c=new Map(o.map(e=>[e.nodeId,e]));const l=i?.devicePlacement?.requiredNodeCommands??[];const u=e.getRuntimeConfig();let d=u.desktop?.host?.enabled===true?{...GATEWAY_ENVIRONMENT,desktop:true}:GATEWAY_ENVIRONMENT;if(r&&u.desktop?.host?.enabled!==true){const{inspectHostDesktopSetup:e}=await import(`./host-source-BPDgoivu.mjs`);d={...d,desktopSetup:await e({config:u.desktop?.host})}}return[d,...a.filter(e=>!s.has(e.nodeId)).map(e=>summarizeNodeEnvironment(e,u,l,c.get(e.nodeId)))]}function readWorkerInventory(e,t){try{return{workers:e.workerEnvironmentService?.list()??[],preparedPool:t?e.workerEnvironmentService?.readPreparedPoolSummary():void 0}}catch{throw new Error(`environment inventory unavailable`)}}function defineEnvironmentMutation(e,t,n){return defineValidatedGatewayHandler(`environments.${e}`,t,async t=>{const{respond:r,context:i}=t;const a=i.workerEnvironmentService;if(!a){respondError(r,ErrorCodes.INVALID_REQUEST,e===`destroy`?`unknown environmentId`:`cloud worker environments are not configured`);return}try{r(true,await n(t,a),void 0)}catch(t){const n=t&&typeof t===`object`&&`code`in t?t.code:void 0;const i=e===`destroy`?n===`environment_not_found`||n===`invalid_state`:n===`profile_not_found`||n===`invalid_profile`||e===`prepare`&&n===`invalid_project`;const a=i||e===`prepare`&&n===`capacity`;const o={create:`creation`,prepare:`preparation`,destroy:`destruction`}[e];r(false,void 0,errorShape(i?ErrorCodes.INVALID_REQUEST:ErrorCodes.UNAVAILABLE,a&&t instanceof Error?t.message:`worker environment ${o} failed`,e===`prepare`&&a?{details:{code:n}}:void 0))}})}const environmentsHandlers={...environmentsSessionHandlers,"environments.adoptSuggestedProfile":adoptSuggestedWorkerProfile,...environmentsSessionExecHandlers,"environments.list":async e=>{const{params:t,respond:n,client:r,context:i}=e;if(!assertValidParams(t,validateEnvironmentsListParams,`environments.list`,n))return;const a=r?.connect.scopes??[];const o=t.includePreparedDetails===true&&authorizeOperatorScopesForRequiredScope(`operator.admin`,a).allowed;const s=readGatewayRequestMutationAuthority(e);if(t.runtimeId){const e=authorizeOperatorScopesForRequiredScope(WRITE_SCOPE,a);if(!e.allowed){respondError(n,ErrorCodes.FORBIDDEN,`missing scope: ${e.missingScope}`);return}}await respondUnavailableOnThrow(n,async()=>{let e=[];let a=[];let c;if(t.projection!==`profiles`){const n=readWorkerInventory(i,o);a=n.workers;c=n.preparedPool;e=await listGatewayEnvironments(i,a,t.runtimeId,t.includeDesktopSetup)}const l=await listWorkerProfilesWithMachines(i);const u=await listSuggestedWorkerProfile(i);s.assertCurrent();const d=resolveOperatorRolePolicy(r??null,i.getRuntimeConfig());const f=r?.connect.scopes??[];const p=f.includes(`operator.admin`)&&(!d||d.scopes.includes(`operator.admin`));const m=authorizeOperatorScopesForRequiredScope(`operator.write`,f).allowed&&(!d||authorizeOperatorScopesForRequiredScope(`operator.write`,d.scopes).allowed);const h=l.filter(e=>m&&(p||d?.workerProfiles?.includes(e.id))).map(e=>e.id);const g=o&&authorizeOperatorScopesForRequiredScope(`operator.admin`,r?.connect.scopes??[]).allowed;const _=Date.now();e.push(...a.map(e=>summarizeWorkerEnvironment(e,_,{includePreparedDetails:g})));n(true,{environments:e,...l.length>0?{dispatchableProfileIds:h}:{},...u?{suggestedProfile:u}:{},...i.getRuntimeConfig().cloudWorkers?.requiredProfile?{requiredProfile:i.getRuntimeConfig().cloudWorkers?.requiredProfile}:{},...l.length>0?{profiles:g?l.map(e=>({...e,readyWorkers:i.workerEnvironmentService?.readReadyWorkerTarget(e.id)})):l}:{},...g&&c?{preparedPool:c}:{}},void 0)})},"environments.status":async e=>{const{params:t,respond:n,client:r,context:i}=e;if(!assertValidParams(t,validateEnvironmentsStatusParams,`environments.status`,n))return;const a=readGatewayRequestMutationAuthority(e);await respondUnavailableOnThrow(n,async()=>{const e=(await listGatewayEnvironments(i)).find(e=>e.id===t.environmentId);a.assertCurrent();if(e){n(true,e,void 0);return}let o;try{o=i.workerEnvironmentService?.get(t.environmentId)}catch{respondError(n,ErrorCodes.UNAVAILABLE,`environment status unavailable`);return}n(Boolean(o),o?summarizeWorkerEnvironment(o,Date.now(),{includePreparedDetails:t.includePreparedDetails===true&&authorizeOperatorScopesForRequiredScope(`operator.admin`,r?.connect.scopes??[]).allowed}):void 0,o?void 0:errorShape(ErrorCodes.INVALID_REQUEST,`unknown environmentId`))})},"environments.create":defineEnvironmentMutation(`create`,validateEnvironmentsCreateParams,async(e,t)=>{const n=readGatewayRequestMutationAuthority(e);const r=await captureGatewayOperatorRunAuthority({client:e.client,context:e.context,hasCurrentClientAuthority:e.hasCurrentClientAuthority,invocationAuthority:{assertCurrent:n.assertCurrent}});try{return summarizeWorkerEnvironment(await t.createWithRequest({...e.params,provisionSource:captureQueuedOperatorRecoverySource(r?.authority)??{kind:`unavailable`},beforeProvision:()=>{n.assertCurrent();r?.authority.assertCurrent()}}))}finally{r?.release()}}),"environments.prepare":defineEnvironmentMutation(`prepare`,validateEnvironmentsPrepareParams,(e,t)=>t.prepare(e.params,readGatewayRequestMutationAuthority(e).assertCurrent)),"environments.destroy":defineEnvironmentMutation(`destroy`,validateEnvironmentsDestroyParams,async(e,t)=>{const{params:n,context:r}=e;const{assertCurrent:i}=readGatewayRequestMutationAuthority(e);const a=r.workerPlacementDispatchService;if(n.force&&!a?.forceDestroyEnvironment)throw new Error(`cloud worker placement control is unavailable`);const o=n.force?await a.forceDestroyEnvironment(n.environmentId,e=>r.logGateway.warn(`worker environment forced teardown cleanup failed: ${formatForLog(e)}`),i):await t.destroyUnattached(n.environmentId,i);try{await a?.reconcileActive?.(n.environmentId)}catch(e){r.logGateway.warn(`worker placement reconciliation after destroy failed: ${formatForLog(e)}`)}return summarizeWorkerEnvironment(o)}),"worker.desktop.observe":defineValidatedGatewayHandler(`worker.desktop.observe`,validateWorkerDesktopObserveParams,({params:e,respond:t,context:n,client:r,hasCurrentClientAuthority:i})=>respondDesktopObserve({request:{source:{kind:`environment`,environmentId:e.environmentId},...e.control===void 0?{}:{control:e.control}},respond:t,context:n,requester:resolveDesktopObserveRequester({client:r,hasCurrentClientAuthority:i})})),"worker.desktop.launch":defineValidatedGatewayHandler(`worker.desktop.launch`,validateWorkerDesktopLaunchParams,e=>respondDesktopLaunch(e,e.params.environmentId,e.params.app)),"desktop.observe":defineValidatedGatewayHandler(`desktop.observe`,validateDesktopObserveParams,({params:e,respond:t,context:n,client:r,hasCurrentClientAuthority:i})=>respondDesktopObserve({request:e,respond:t,context:n,requester:resolveDesktopObserveRequester({client:r,hasCurrentClientAuthority:i})})),"desktop.launch":defineValidatedGatewayHandler(`desktop.launch`,validateDesktopLaunchParams,e=>respondDesktopLaunch(e,e.params.source.environmentId,e.params.app)),"desktop.release":defineValidatedGatewayHandler(`desktop.release`,validateDesktopReleaseParams,async({params:e,respond:t,client:n,hasCurrentClientAuthority:r})=>{const{releaseDesktopObserverToken:i}=await import(`./observe-bridge-Cteupf99.mjs`);await respondUnavailableOnThrow(t,async()=>{t(true,{released:await i(e.wsPath,resolveDesktopObserveRequester({client:n,hasCurrentClientAuthority:r}))},void 0)})})};export{listGatewayEnvironments as n,listWorkerProfiles as r,environmentsHandlers as t};