UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 11 kB
import{d as normalizeSortedUniqueTrimmedStringList}from"./string-normalization-D_oBUpO3.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import{Oi as validateEnvironmentsSessionCreateParams,ji as validateEnvironmentsSessionStatusParams,ki as validateEnvironmentsSessionDestroyParams}from"./src-BDZMFmKa.mjs";import{a as isRuntimeToolAllowed,s as isToolAllowedByPolicyName}from"./tool-policy-match-D9XrfLbh.mjs";import{i as ErrorCodes}from"./missing-scope-error-CkgBgh6d.mjs";import{p as errorShape}from"./error-codes-CQNGhXT-.mjs";import{c as resolveGatewayPersonalToolParticipant,o as getGatewayToolCallerIdentity,t as captureGatewayToolCallerAssertion}from"./gateway-caller-context-Dw9IijqV.mjs";import{r as resolveRequestedSessionAgentId}from"./session-request-agent-DmeXmT1P.mjs";import{a as resolveSessionStoreIdentity}from"./session-store-key-DZXBwthg.mjs";import{r as requireSessionRowProjection}from"./session-row-projection-access-w2LnU_PB.mjs";import{t as prepareSessionMutationFacts}from"./session-sharing-preparation-Bx3oY7gx.mjs";import{i as resolveConversationCapabilityProfile}from"./conversation-capability-profile-DiRRWN6T.mjs";import{n as isConversationToolAllowed}from"./conversation-tool-policy-pipeline-DYGf_lAW.mjs";import{c as prepareSessionSharingProfiles,o as prepareProjectedSessionSharing}from"./session-sharing-read-Cm-EAfc6.mjs";import{r as defineValidatedGatewayMethod}from"./validation-CM41YclJ.mjs";import{t as dispatchUiCommandToRequester}from"./ui-command-iqzqt9Hb.mjs"; //!src/gateway/worker-environments/environment-summary.ts const WORKER_STATUS={requested:`starting`,provisioning:`starting`,bootstrapping:`starting`,ready:`available`,attached:`available`,idle:`available`,draining:`stopping`,destroying:`stopping`,destroyed:`unavailable`,failed:`error`,orphaned:`error`};function summarizeWorkerEnvironment(e,t=Date.now(),n={}){const r=e.destroyRequestedAtMs!==null&&e.state!==`destroyed`&&!(e.state===`failed`&&e.leaseId===null);const i=e.state===`failed`||e.state===`orphaned`||r?e.error:void 0;return{id:e.environmentId,type:`worker`,status:i?`error`:r?`stopping`:WORKER_STATUS[e.state],...e.sharedHost===null?{}:{trust:e.sharedHost?`persistent`:`disposable`},...e.desktopAvailable?{desktop:true}:{},...e.preparation?{preparation:{purpose:e.preparation.purpose,key:e.preparation.key,...n.includePreparedDetails?{details:{demandAtMs:e.preparation.demandAtMs,expiresAtMs:e.preparation.expiresAtMs,consumedAtMs:e.preparation.consumedAtMs,...e.preparation.project?{project:{...e.preparation.project.label?{label:e.preparation.project.label}:{},baseCommit:e.preparation.project.baseCommit}}:{}}}:{}}}:{},worker:{profileId:e.profileId,providerId:e.providerId,...e.leaseId?{leaseId:e.leaseId}:{},state:e.state,...e.startStatus?{startStatus:e.startStatus}:{},...n.includePreparedDetails&&e.destroyRequestedAtMs!==null?{destroyRequestedAtMs:e.destroyRequestedAtMs}:{},ageMs:Math.max(0,Math.trunc(t-e.createdAtMs)),...e.state===`idle`&&e.idleSinceAtMs!==null?{idleMs:Math.max(0,Math.trunc(t-e.idleSinceAtMs))}:{},attachedSessionIds:normalizeSortedUniqueTrimmedStringList(e.attachedSessionIds),tunnelStatus:e.tunnelStatus,...i?{error:i}:{},...e.desktopAvailable?{desktop:true}:{},...e.desktopApps.length>0?{desktopApps:[...e.desktopApps]}:{}}}} //!src/gateway/server-methods/environments.session-tool-policy.ts function captureSessionEnvironmentToolPolicy(e,t,n){const r=getGatewayToolCallerIdentity();const i=e.client?.internal?.agentRuntimeIdentity;const a=r?.operationalRunInstance;const o=r?.assertToolAllowed;const s=i?.sessionSpawnContext?.inheritedToolPolicy;const c=s?{allow:[...s.allow],deny:[...s.deny]}:void 0;return{cronExecAskAlways:r?.cronExecToolTarget?.ask===`always`||i?.cronExecToolTarget?.ask===`always`,assertAllowed:()=>{t.assertCurrent();if(r){if(!a||!o||r.agentId!==t.identity.agentId||r.sessionKey!==t.identity.sessionKey||i&&(i.operationalRunInstance.instanceId!==a.instanceId||i.operationalRunInstance.runId!==a.runId))throw new Error(`Environment ${n} has no matching captured tool authority`);o(n)}else if((i||e.client?.internal?.agentToolCaller)&&!c)throw new Error(`Environment ${n} has no captured tool authority`);const s=e.context.getRuntimeConfig();const readCapabilityEntry=(t,n)=>{const r=requireSessionRowProjection(e.context).readCapabilityEntry({...n,agentId:t,storePath:resolveSessionStorePathCore(s.session?.store,{agentId:t})});if(!r)throw new Error(`Conversation capability projection is unavailable`);return r.entry};const l=resolveConversationCapabilityProfile({config:s,...t.identity,preparedSessionCapabilityStore:{authoritative:true,get:e=>{const n=parseAgentSessionKey(e)?.agentId??t.identity.agentId;return readCapabilityEntry(n,{key:e})},getById:e=>readCapabilityEntry(t.identity.agentId,{sessionId:e})},modelProvider:i?.sessionSpawnContext?.resolvedModel?.provider,modelId:i?.sessionSpawnContext?.resolvedModel?.model});if(!isConversationToolAllowed(l,n)||c&&(!isRuntimeToolAllowed(n,c.allow)||!isToolAllowedByPolicyName(n,{deny:c.deny})))throw new Error(`Conversation policy denies ${n}`)}}} //!src/gateway/server-methods/environments.session.ts async function resolveSessionEnvironmentCaller(e,t={}){const{context:n,client:r}=e;const i=r?.internal?.agentToolCaller;const a=r?.internal?.agentRuntimeIdentity;const o=r?.internal?.syntheticClient?getGatewayToolCallerIdentity():void 0;const s=o?captureGatewayToolCallerAssertion():void 0;const c=i??a??(s?o:void 0);if(!r||r.internal?.syntheticClient&&!c)throw new Error(`Conversation environments require an authenticated operator or admitted agent run`);if(i&&!i.assertCurrent)throw new Error(`Conversation environment tool has no live run authority`);if(c&&(t.sessionKey&&t.sessionKey!==c.sessionKey||t.agentId&&t.agentId!==c.agentId))throw new Error(`An agent can only manage its own conversation environment`);const l=c?.sessionKey??t.sessionKey;if(!l)throw new Error(`sessionKey is required for operator environment requests`);const u=resolveRequestedSessionAgentId(n.getRuntimeConfig(),l,c?.agentId??t.agentId);if(!u.ok)throw new Error(u.error.message);if(isIncognitoSessionKey(resolveSessionStoreIdentity({cfg:n.getRuntimeConfig(),sessionKey:l,agentId:u.agentId}).canonicalKey))throw new Error(`A persistent conversation is required for an attached environment`);const d=await prepareSessionSharingProfiles(r);const f=await prepareSessionMutationFacts({cfg:n.getRuntimeConfig(),sessionKey:l,agentId:u.agentId});try{const t=f.readCurrent(n.getRuntimeConfig()).target;if(!t||t.entry.incognito===true)throw new Error(`A persistent conversation is required for an attached environment`);const l={sessionId:t.entry.sessionId,sessionKey:t.canonicalKey,agentId:u.agentId,...t.entry.lifecycleRevision?{sessionLifecycleRevision:t.entry.lifecycleRevision}:{}};const p=[e.signal,r.connectionSignal,...o?.approvalSignals??[]].filter(e=>e!==void 0);const m=p.length?AbortSignal.any(p):void 0;const assertCurrent=()=>{m?.throwIfAborted();e.sessionMutationCommitGuard?.();e.sessionMutationAuthorization?.assertCurrent();if(r.invalidated||e.hasCurrentClientAuthority?.()===false)throw new Error(`Conversation environment requester is no longer active`);i?.assertCurrent?.();if(o){if(!s||o.gatewayContextResolver&&o.gatewayContextResolver()!==n)throw new Error(`Conversation environment tool belongs to a different or retired Gateway`);s()}if(a&&n.validateAgentRuntimeApprovalAuthority?.(a)!==true)throw new Error(`Conversation environment agent run is no longer active`);const t=n.getRuntimeConfig();const u=f.readCurrent(t);if(u.target?.entry.sessionId!==l.sessionId||u.target.entry.lifecycleRevision!==l.sessionLifecycleRevision)throw new Error(`Conversation identity changed before the environment operation`);if(!c){const e=prepareProjectedSessionSharing({cfg:t,client:r,profiles:d,isMember:(e,t)=>u.membership.has(t)});const n=u.target&&e.authorizeTarget(u.target);if(n)throw new Error(n.message)}};assertCurrent();return{identity:l,assertCurrent,signal:m,release:f.release}}catch(e){f.release();throw e}}function failure(e){return errorShape(ErrorCodes.INVALID_REQUEST,e instanceof Error?e.message:`Conversation environment request failed`)}const environmentsSessionHandlers={"environments.session.create":defineValidatedGatewayMethod(`environments.session.create`,validateEnvironmentsSessionCreateParams,async e=>{const{params:t,respond:n,context:r}=e;const i=await resolveSessionEnvironmentCaller(e,t);try{const{presentation:a,...o}=t;if(a)try{resolveGatewayPersonalToolParticipant(e.client?.internal?.agentRuntimeIdentity)}catch(e){throw new Error(`${e instanceof Error?e.message:String(e)} Create the environment without presentation, then show it with screen (desktop_show or portal_show with environmentId) and user set to the requester's requester_profile.id.`,{cause:e})}const s=a?captureSessionEnvironmentToolPolicy(e,i,`screen`).assertAllowed:i.assertCurrent;s();const c=r.workerEnvironmentService;if(!c)throw new Error(`Cloud worker environments are not configured`);const l=await c.createSessionAttachment({...o,...i.identity},s,i.signal,a?async({environmentId:t})=>{s();const n=dispatchUiCommandToRequester({client:e.client,context:r,params:{sessionKey:i.identity.sessionKey,agentId:i.identity.agentId,command:{kind:`panel`,panel:a===`desktop`?`desktop`:`portal`,environmentId:t,open:true,dock:`right`}}});if(!n.ok)throw new Error(n.error.message);s()}:void 0);s();n(true,{...l,environment:summarizeWorkerEnvironment(l.environment)})}finally{i.release()}},failure),"environments.session.status":defineValidatedGatewayMethod(`environments.session.status`,validateEnvironmentsSessionStatusParams,async e=>{const{params:t,respond:n,context:r}=e;const i=await resolveSessionEnvironmentCaller(e,t);try{const e=r.workerEnvironmentService?.getSessionAttachmentStatus(i.identity.sessionId);if(t.environmentId&&e?.attachment.environmentId!==t.environmentId)throw new Error(`Conversation environment target changed`);i.assertCurrent();n(true,e?{attachment:e.attachment,closed:e.attachment.closedAtMs!==null,environment:summarizeWorkerEnvironment(e.environment)}:{attachment:null})}finally{i.release()}},failure),"environments.session.destroy":defineValidatedGatewayMethod(`environments.session.destroy`,validateEnvironmentsSessionDestroyParams,async e=>{const{params:t,respond:n,context:r}=e;const i=await resolveSessionEnvironmentCaller(e,t);try{const e=r.workerEnvironmentService;if(!e)throw new Error(`Cloud worker environments are not configured`);const a=await e.destroySessionAttachment({sessionId:i.identity.sessionId,environmentId:t.environmentId},i.assertCurrent);i.assertCurrent();n(true,{stopped:true,...a?{environment:summarizeWorkerEnvironment(a)}:{}})}finally{i.release()}},failure)};export{summarizeWorkerEnvironment as i,resolveSessionEnvironmentCaller as n,captureSessionEnvironmentToolPolicy as r,environmentsSessionHandlers as t};