openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
11 lines • 17.6 kB
JavaScript
import{l as normalizeOptionalString,o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{P as resolveIntegerOption}from"./number-coercion-B3CfI447.mjs";import{s as formatErrorMessage}from"./error-coercion-DlKnt6w-.mjs";import{r as asNullableRecord}from"./record-coerce-BTbqdJ3-.mjs";import{b as resolveGatewayPort}from"./paths-D_FOvGon.mjs";import{h as readRuntimeConfig}from"./runtime-snapshot-Bg5K4JNu.mjs";import{i as GATEWAY_CLIENT_NAMES,r as GATEWAY_CLIENT_MODES}from"./client-info-Dr3-kuD1.mjs";import{c as getActiveAgentRunDelegatedAuthority,r as claimAgentRunApprovalAuthority}from"./agent-run-registry-ONwZSqWq.mjs";import{s as resolveMessageActionTurnCapability}from"./message-action-turn-capability-Ck1vCMVz.mjs";import{l as resolveLeastPrivilegeOperatorScopesForMethod}from"./method-scopes-Dalbwzsv.mjs";import{i as ErrorCodes}from"./missing-scope-error-CkgBgh6d.mjs";import{o as getGatewayToolCallerIdentity}from"./gateway-caller-context-Dw9IijqV.mjs";import{d as readToolStringParam,s as readPositiveIntegerParam}from"./common-DIgvX97L.mjs";import"./config-DkZ8y8Gv.mjs";import{m as prepareQuestionGatewayDispatch}from"./host-private-capabilities-B_SEzbNU.mjs";import{c as trimToUndefined,i as resolveGatewayCredentialsFromConfig}from"./credentials-BL-kavyD.mjs";import{n as loadDeviceIdentityIfPresentAsync,r as loadOrCreateDeviceIdentityAsync}from"./device-identity-async-BkJXqwph.mjs";import{t as SYSTEM_RUN_EXECUTION_CONTEXT_CAPABILITY}from"./system-run-execution-context-DU2hf81q.mjs";import{i as verifyAgentRuntimeIdentityToken,o as createAgentRuntimeExecutionLineageHandoff,r as mintAgentRuntimeIdentityToken,s as readAgentRuntimeExecutionLineage,t as createAgentRuntimeIdentity}from"./agent-runtime-identity-token-DO1DKFFX.mjs";import{r as callGateway}from"./call-CVqWsTxX.mjs";import{t as getOperatorApprovalRuntimeToken}from"./operator-approval-runtime-token-BqZXRbM-.mjs";import{AsyncLocalStorage}from"node:async_hooks";
//!src/agents/tools/gateway-caller-availability.ts
function hasInProcessGatewayToolCaller(){const e=getGatewayToolCallerIdentity()?.gatewayContextResolver;return Boolean(e)&&e?.()?.localEmbedded!==true}
//!src/agents/tools/gateway-session-spawn-context.ts
const sessionSpawnContext=new AsyncLocalStorage;function runWithGatewaySessionSpawnContext(e,t){return sessionSpawnContext.run(e,t)}function getGatewaySessionSpawnContext(){return sessionSpawnContext.getStore()}
//!src/agents/tools/gateway-session-spawn-execution-identity.ts
const parentExecutionIdentityToken=new AsyncLocalStorage;function runWithGatewaySessionSpawnParentExecutionIdentity(e,t){return e?parentExecutionIdentityToken.run(e,t):t()}function getGatewaySessionSpawnParentExecutionIdentityToken(){return parentExecutionIdentityToken.getStore()}
//!src/agents/tools/gateway-transport-errors.ts
function isStaleGatewayAgentRuntimeIdentityRejection(e){const t=formatErrorMessage(e);return t.includes(`gateway rejected required agent runtime identity auth field; refusing to retry without it`)||t.includes(`invalid connect params`)&&t.includes(`/auth`)&&t.includes(`unexpected property 'agentRuntimeIdentityToken'`)}function isStaleGatewayNodeInvokeTurnSourceRejection(e){if(!(e instanceof Error)||e.name!==`GatewayClientRequestError`)return false;const t=asNullableRecord(e);if(t?.gatewayCode!==ErrorCodes.INVALID_REQUEST)return false;if(asNullableRecord(t.details)?.nodeCommandDispatched!==false)return false;const n=formatErrorMessage(e);if(!n.includes(`invalid node.invoke params:`))return false;return[`turnSourceChannel`,`turnSourceTo`,`turnSourceAccountId`,`turnSourceThreadId`].some(e=>n.includes(`unexpected property '${e}'`))}function staleGatewayAgentRuntimeIdentityError(e){return new Error([`The running Gateway is from an older OpenClaw build and rejected current agent runtime connection metadata.`,"Restart the Gateway with `openclaw gateway restart`, then retry."].join(` `),{cause:e})}
//!src/agents/tools/gateway.ts
function readGatewayToolOperatorScopes(){const e=getGatewayToolCallerIdentity()?.operatorAuthority;if(!e)return;e.assertCurrent();return[...e.scopes]}function readGatewayCallOptions(e){return{gatewayUrl:readToolStringParam(e,`gatewayUrl`,{trim:false}),gatewayToken:readToolStringParam(e,`gatewayToken`,{trim:false}),timeoutMs:readPositiveIntegerParam(e,`timeoutMs`)}}function canonicalizeToolGatewayWsUrl(e){const t=e.trim();let n;try{n=new URL(t)}catch(e){const n=formatErrorMessage(e);throw new Error(`invalid gatewayUrl: ${t} (${n})`,{cause:e})}if(n.protocol!==`ws:`&&n.protocol!==`wss:`)throw new Error(`invalid gatewayUrl protocol: ${n.protocol} (expected ws:// or wss://)`);if(n.username||n.password)throw new Error(`invalid gatewayUrl: credentials are not allowed`);if(n.search||n.hash)throw new Error(`invalid gatewayUrl: query/hash not allowed`);if(n.pathname&&n.pathname!==`/`)throw new Error(`invalid gatewayUrl: path not allowed`);return{origin:n.origin,key:`${n.protocol}//${normalizeLowercaseStringOrEmpty(n.host)}`}}function resolveLocalGatewayUrlKeys(e){const t=resolveGatewayPort(e);return/* @__PURE__ */ new Set([`ws://127.0.0.1:${t}`,`wss://127.0.0.1:${t}`,`ws://localhost:${t}`,`wss://localhost:${t}`,`ws://[::1]:${t}`,`wss://[::1]:${t}`])}function resolveConfiguredRemoteGatewayKey(e){const t=normalizeOptionalString(e.gateway?.remote?.url)??``;if(t)try{return canonicalizeToolGatewayWsUrl(t).key}catch{}}function resolveDefaultGatewayTarget(e){if(e.envGatewayUrl)return`remote`;if(e.cfg.gateway?.mode===`remote`&&normalizeOptionalString(e.cfg.gateway.remote?.url))return`remote`;return`local`}function validateGatewayUrlOverrideForAgentTools(e){const{cfg:t}=e;const n=resolveLocalGatewayUrlKeys(t);const r=resolveConfiguredRemoteGatewayKey(t);const i=canonicalizeToolGatewayWsUrl(e.urlOverride);if(n.has(i.key))return{url:i.origin,target:`local`};if(r&&i.key===r)return{url:i.origin,target:`remote`};const a=resolveGatewayPort(t);throw new Error([`gatewayUrl override rejected.`,`Allowed: ws(s) loopback on port ${a} (127.0.0.1/localhost/[::1])`,`Or: configure gateway.remote.url and omit gatewayUrl to use the configured remote gateway.`].join(` `))}function resolveGatewayOverrideToken(e){if(e.explicitToken)return e.explicitToken;return resolveGatewayCredentialsFromConfig({cfg:e.cfg,env:process.env,modeOverride:e.target,remoteTokenFallback:e.target===`remote`?`remote-only`:`remote-env-local`,remotePasswordFallback:e.target===`remote`?`remote-only`:`remote-env-local`}).token}function resolveGatewayOptions(e){const t=readRuntimeConfig();const n=trimToUndefined(e?.gatewayUrl)!==void 0?validateGatewayUrlOverrideForAgentTools({cfg:t,urlOverride:String(e?.gatewayUrl)}):void 0;const r=trimToUndefined(e?.gatewayToken);const i=getGatewayToolCallerIdentity()?.gatewayContextResolver;const a=t.gateway?.mode===`remote`&&!n&&!r&&i?i():void 0;const o=a&&a.localEmbedded!==true?a.getRuntimeConfig():void 0;const s=n?resolveGatewayOverrideToken({cfg:t,target:n.target,explicitToken:r}):r;const c=resolveIntegerOption(e?.timeoutMs,3e4,{min:1});const l=trimToUndefined(process.env.OPENCLAW_GATEWAY_URL);const u=o?`local`:n?.target??resolveDefaultGatewayTarget({cfg:t,envGatewayUrl:l});return{url:n?.url,token:s,timeoutMs:c,target:u,...o?{config:o,localPortOverride:resolveGatewayPort(o),ignoreEnvUrlOverride:true,tlsFingerprint:a?.gatewayTlsFingerprint}:{}}}const APPROVAL_RUNTIME_METHODS=/* @__PURE__ */ new Set([`exec.approval.request`,`exec.approval.resolve`,`exec.approval.waitDecision`,`plugin.approval.request`,`plugin.approval.waitDecision`]);const AGENT_RUNTIME_IDENTITY_METHODS=/* @__PURE__ */ new Set([`exec.approval.request`,`plugin.approval.request`,`wake`,`cron.list`,`cron.get`,`cron.scratch.get`,`cron.scratch.set`,`cron.add`,`cron.update`,`cron.remove`,`cron.bind`,`cron.run`,`cron.runs`,`secrets.store.delete`]);const OPTIONAL_LOCAL_AGENT_RUNTIME_IDENTITY_METHODS=/* @__PURE__ */ new Set([`ui.command`,`node.invoke`,`computer.invoke`,`question.request`]);async function resolveApprovalRuntimeTokenForGatewayTool(e){if(!APPROVAL_RUNTIME_METHODS.has(e.method))return;if(trimToUndefined(e.opts.gatewayUrl)!==void 0)return;if(e.target!==`local`)return;return getOperatorApprovalRuntimeToken()}function isApprovalReplayNodeSystemRun(e,t){const n=e===`node.invoke`?asNullableRecord(t):null;const r=n?.command===`system.run`?asNullableRecord(n.params):null;const i=normalizeOptionalString(r?.approvalDecision);return r?.approved===true||i===`allow-once`||i===`allow-always`}function attachNodeInvokeTurnSource(e,t){if(e!==`node.invoke`)return t;const n=asNullableRecord(t);const r=getGatewayToolCallerIdentity();if(!n||!r)return t;return{...omitNodeInvokeTurnSource(n),...r.turnSourceChannel?{turnSourceChannel:r.turnSourceChannel}:{},...r.turnSourceTo?{turnSourceTo:r.turnSourceTo}:{},...r.turnSourceAccountId?{turnSourceAccountId:r.turnSourceAccountId}:{},...r.turnSourceThreadId!==void 0?{turnSourceThreadId:r.turnSourceThreadId}:{}}}function omitNodeInvokeTurnSource(e){const t={...e};delete t.turnSourceChannel;delete t.turnSourceTo;delete t.turnSourceAccountId;delete t.turnSourceThreadId;return t}function stripNodeInvokeTurnSource(e){const t=asNullableRecord(e);return t?omitNodeInvokeTurnSource(t):e}async function resolveApprovalRequesterDeviceIdentityForGatewayTool(e){const t=APPROVAL_RUNTIME_METHODS.has(e.method);const n=isApprovalReplayNodeSystemRun(e.method,e.callParams);if(!t&&!n)return;if(t&&trimToUndefined(e.opts.gatewayUrl)!==void 0)return;if(e.approvalRuntimeToken!==void 0)return;try{if(n){const e=await loadDeviceIdentityIfPresentAsync();if(!e)throw new Error(`device identity is not persisted`);return e}return await loadOrCreateDeviceIdentityAsync()}catch(e){if(n)throw new Error([`approved node gateway calls require a stable device identity.`,`Fix the OpenClaw state directory permissions and retry the approval.`].join(` `),{cause:e});throw new Error([`remote approval gateway calls require a stable device identity.`,`Fix the OpenClaw state directory permissions or use the local approval-runtime gateway.`].join(` `),{cause:e})}}async function resolveAgentRuntimeIdentityForGatewayTool(e){const t=OPTIONAL_LOCAL_AGENT_RUNTIME_IDENTITY_METHODS.has(e.method);if(!e.required&&!AGENT_RUNTIME_IDENTITY_METHODS.has(e.method)&&!t)return;const n=getGatewayToolCallerIdentity();if(!n){if(e.required)throw new Error(`trusted agent runtime identity required for this gateway call`);return}const r=trimToUndefined(e.opts.gatewayUrl)!==void 0;const i=trimToUndefined(e.opts.gatewayToken)!==void 0;if(r||i||e.target!==`local`){if(t&&!e.required)return;throw new Error(`agent gateway calls require the trusted local gateway context`)}if(n.signedAgentRuntimeIdentityToken){if(!e.inProcess)return n.signedAgentRuntimeIdentityToken;const t=await verifyAgentRuntimeIdentityToken(n.signedAgentRuntimeIdentityToken);if(!t)throw new Error(`invalid agent runtime identity token`);return t}if(t&&!e.required&&!n.gatewayContextResolver)return;if(!n.operationalRunInstance){if(t&&!e.required)return;throw new Error(`trusted operational run instance required for this gateway call`)}let a;try{const t=getGatewaySessionSpawnContext();const r=getGatewaySessionSpawnParentExecutionIdentityToken();const i=n.approvalAuthority??getActiveAgentRunDelegatedAuthority(n.operationalRunInstance);const o=readAgentRuntimeExecutionLineage(t);if(o&&!i)throw new Error(`execution lineage handoff requires active parent authority`);a=t&&o&&i?createAgentRuntimeExecutionLineageHandoff({agentId:n.agentId,sessionKey:n.sessionKey,operationalRunInstance:n.operationalRunInstance,delegatedAuthority:i,...r?{executionIdentity:r}:{},sessionSpawnContext:t}):void 0;if(o&&!a)throw new Error(`execution lineage handoff could not bind the parent admission`);const s=e.method===`exec.approval.request`||e.method===`plugin.approval.request`?[...n.approvalSignals??[],...e.signal?[e.signal]:[]]:void 0;const c=i&&s?.length?claimAgentRunApprovalAuthority(i,s):i;const l={...n,operationalRunInstance:n.operationalRunInstance,approvalAuthority:c,...a?{executionIdentityToken:void 0}:{},...a?{executionLineageHandoffId:a.id}:t?{executionIdentityToken:r,sessionSpawnContext:t}:{}};if(!e.inProcess)return await mintAgentRuntimeIdentityToken(l);const u=await createAgentRuntimeIdentity(l);if(!u)throw new Error(`invalid agent runtime identity`);return u}catch(n){a?.revoke();if(t&&!e.required)return;throw n}}async function resolveMessageActionIdentity(e,t){const n=e.sourceReplyFinal===true;const r=normalizeOptionalString(e.sourceReplyToolCallId);if(n&&!r)throw new Error(`terminal source reply requires tool-call correlation`);const i=getGatewayToolCallerIdentity();if(!i){if(n)throw new Error(`terminal source reply requires trusted agent runtime identity`);return}const a=trimToUndefined(e.opts.gatewayUrl)!==void 0;const o=trimToUndefined(e.opts.gatewayToken)!==void 0;const s=a||o||e.target!==`local`;if(s&&!n)return;const c=normalizeOptionalString(e.turnCapabilitySessionKey)??i.sessionKey;const l=resolveMessageActionTurnCapability({token:e.turnCapability,agentId:i.agentId,runId:e.runId,sessionKey:c,sessionId:e.sessionId});if(!l){if(n)throw new Error(`terminal source reply requires an active turn capability. This run has no live source turn to finish (it ended, or this is a heartbeat or background run), so changing channel or target will not help. To deliver the message anyway, send it again with final=false.`);return}if(n&&!normalizeOptionalString(l.toolContext?.currentSourceTurnId))throw new Error(`terminal source reply requires source-turn correlation`);if(s)return;if(!i.operationalRunInstance){if(n)throw new Error(`terminal source reply requires a trusted operational run instance`);return}const u={...l,turnCapability:e.turnCapability,...n?{sourceReplyFinal:true,sourceReplyToolCallId:r}:{...e.sourceReplyFinal===false?{sourceReplyFinal:false}:{},...r?{sourceReplyToolCallId:r}:{}}};return await t({...i,sessionKey:c,operationalRunInstance:i.operationalRunInstance,messageActionContext:u})}async function resolveMessageActionAgentRuntimeIdentityToken(e){return await resolveMessageActionIdentity(e,mintAgentRuntimeIdentityToken)}async function resolveMessageActionAgentRuntimeIdentity(e){return await resolveMessageActionIdentity(e,async e=>{const t=await createAgentRuntimeIdentity(e);if(!t)throw new Error(`invalid agent runtime identity`);return t})}function shouldUseInProcessGatewayTool(e){return!trimToUndefined(e.gatewayUrl)&&!trimToUndefined(e.gatewayToken)&&hasInProcessGatewayToolCaller()}async function callGatewayTool(e,t,n,r){const i=r?.dispatchAuthority;if(i&&(i.version!==2||typeof i.assertCurrent!==`function`))throw new Error(`Gateway dispatch authority requires version 2 and a synchronous assertion`);const a=shouldUseInProcessGatewayTool(t);const o=resolveGatewayOptions(t);const s=getGatewayToolCallerIdentity()?.gatewayContextResolver;const c=attachNodeInvokeTurnSource(e,n);const l=e===`node.invoke`?asNullableRecord(c):null;const u=Array.isArray(r?.scopes)?r.scopes:resolveLeastPrivilegeOperatorScopesForMethod(e,c);const d=await resolveAgentRuntimeIdentityForGatewayTool({method:e,opts:t,target:a?`local`:o.target,required:r?.requireAgentRuntimeIdentity,signal:r?.signal,inProcess:a});if(a){if(typeof d===`string`)throw new Error(`in-process Gateway requests require an internal runtime identity`);const{callAgentToolGatewayRequest:t,withAgentToolGatewayRuntimeIdentity:n}=await import(`./in-process-gateway-DxSLSn2a.mjs`);return await t(n({method:e,params:c,timeoutMs:o.timeoutMs,signal:r?.signal,expectFinal:r?.expectFinal,...prepareQuestionGatewayDispatch(i,true),...Array.isArray(r?.scopes)?{scopes:u}:{}},d))}const f=typeof d===`string`?d:void 0;const p=await resolveApprovalRuntimeTokenForGatewayTool({method:e,opts:t,target:o.target});const m=await resolveApprovalRequesterDeviceIdentityForGatewayTool({method:e,callParams:c,opts:t,approvalRuntimeToken:p});const h={...o.localPortOverride!==void 0?{config:o.config,localPortOverride:o.localPortOverride,ignoreEnvUrlOverride:o.ignoreEnvUrlOverride,tlsFingerprint:o.tlsFingerprint}:{},url:o.url,token:o.token,method:e,params:c,timeoutMs:o.timeoutMs,signal:r?.signal,expectFinal:r?.expectFinal,onHelloOk:r?.onHelloOk,requiredCapabilities:(l?.command===`system.run`||l?.command===`system.run.prepare`)&&asNullableRecord(l.params)?.executionContext!==void 0?[SYSTEM_RUN_EXECUTION_CONTEXT_CAPABILITY]:void 0,...prepareQuestionGatewayDispatch(i),clientName:GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,clientDisplayName:`agent`,mode:GATEWAY_CLIENT_MODES.BACKEND,...p?{approvalRuntimeToken:p}:{},...f?{agentRuntimeIdentityToken:f}:{},...m?{deviceIdentity:m}:{},scopes:u};const dispatch=e=>{if(s&&!s())throw new Error(`The admitting Gateway is no longer available. Retry from a new agent run.`);return callGateway(e)};try{return await dispatch(h)}catch(t){if(e===`node.invoke`&&isStaleGatewayNodeInvokeTurnSourceRejection(t))return await dispatch({...h,params:stripNodeInvokeTurnSource(h.params)});if(f&&isStaleGatewayAgentRuntimeIdentityRejection(t)){if(e===`node.invoke`&&r?.requireAgentRuntimeIdentity!==true)return await dispatch({...h,params:stripNodeInvokeTurnSource(h.params),agentRuntimeIdentityToken:void 0});throw staleGatewayAgentRuntimeIdentityError(t)}throw t}}export{resolveMessageActionAgentRuntimeIdentity as a,runWithGatewaySessionSpawnParentExecutionIdentity as c,resolveGatewayOptions as i,runWithGatewaySessionSpawnContext as l,readGatewayCallOptions as n,resolveMessageActionAgentRuntimeIdentityToken as o,readGatewayToolOperatorScopes as r,shouldUseInProcessGatewayTool as s,callGatewayTool as t,hasInProcessGatewayToolCaller as u};