openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 20.9 kB
JavaScript
import{l as normalizeOptionalString,m as readNonBlankString}from"./string-coerce-CpTFcSwY.mjs";import{E as parseStrictNonNegativeInteger}from"./number-coercion-B3CfI447.mjs";import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{o as writeRuntimeJson}from"./runtime-DIcLIHcp.mjs";import{a as captureAsyncWorkTracker,t as AsyncWorkScope}from"./async-work-scope-DBcxYU4O.mjs";import{t as sleep}from"./sleep-B4CgCyZu.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import{n as buildAgentMainSessionKey}from"./session-key-DYtwLLn1.mjs";import{l as resolveAgentIdFromSessionKey,m as scopeLegacySessionKeyToAgent,o as classifySessionKeyShape,s as isUnscopedSessionKeySentinel}from"./session-key-BPgKfU2m.mjs";import{r as getBoundLegacyPluginSdkResourceHost}from"./legacy-sdk-resource-host-9HMZFK01.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{i as listAgentIds,p as tryResolveSoleAgentId}from"./agent-roster-4XrgUgPK.mjs";import{D as tryResolveAgentOperationAgentId,t as AgentSelectionRequiredError,z as resolvePersistedSessionStoreOwnerForKey}from"./agent-scope-config-CG9CFpGX.mjs";import{i as routeLogsToStderr}from"./console-BHJbJ-IX.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{i as GATEWAY_CLIENT_NAMES,r as GATEWAY_CLIENT_MODES}from"./client-info-Dr3-kuD1.mjs";import{o as READ_SCOPE,t as ADMIN_SCOPE}from"./operator-scopes-bEvB7E5X.mjs";import{n as normalizeMessageChannel}from"./message-channel-core-D_hPOadj.mjs";import"./message-channel-normalize-hDAO6_JQ.mjs";import{n as isExecutionIdentityCollectionEnabled}from"./audit-config-Dqz9Raz7.mjs";import{t as GATEWAY_SERVER_CAPS}from"./server-capabilities-HdXShIdT.mjs";import{n as isGatewaySecretRefUnavailableError}from"./credentials-BL-kavyD.mjs";import{n as GatewayProtocolRequestError}from"./protocol-request-BJ6X44Q9.mjs";import{s as isGatewayTransportError}from"./transport-error-COMVGbZH.mjs";import{n as throwExpectedCliError}from"./expected-cli-error-oDVmXYil.mjs";import{l as readCliGatewayRunFailure,u as recordCliGatewayRunFailure}from"./failure-output-Gn9zHEk3.mjs";import{n as readGatewayDispatchConfigWithShellEnvFallback,t as readGatewayDispatchConfig}from"./gateway-dispatch-config-Dls5-KRg.mjs";import{d as isGatewayExplicitAuthRequiredError,m as assertGatewayCliMessageContext,p as randomIdempotencyKey,r as callGateway,u as isGatewayCredentialsRequiredError}from"./call-CVqWsTxX.mjs";import{n as readAgentRunTerminalOutcome}from"./agent-run-terminal-outcome-BEd4_P7Y.mjs";import{r as withProgress}from"./progress-BcNIavn6.mjs";import{t as measureAgentStartup}from"./startup-timing-CsYAzFF_.mjs";import{r as prepareCliGatewayStateAccess}from"./gateway-rpc.runtime-BsBTgIGC.mjs";import{t as createProcessSignalBridge}from"./process-signal-bridge-RBNLV1ll.mjs";import{t as readAgentMessageFile}from"./agent-message-input-CSKqkvmS.mjs";
//!src/plugins/one-shot-diagnostics.ts
const log=createSubsystemLogger(`plugins`);const ONE_SHOT_DIAGNOSTICS_SERVICE_IDS=/* @__PURE__ */ new Set([`diagnostics-otel`]);const ONE_SHOT_DIAGNOSTICS_DRAIN_TIMEOUT_MS=5e3;const ONE_SHOT_DIAGNOSTICS_FLUSH_TIMEOUT_MS=1e4;function suppressOtelStdoutLogSink(e){const t=e.diagnostics;const n=t?.otel;if(n?.logs!==true||n.logsExporter!==`stdout`&&n.logsExporter!==`both`)return e;return{...e,diagnostics:{...t,otel:{...n,logs:n.logsExporter===`both`,logsExporter:`otlp`}}}}function isOtelExportConfigured(e){const t=e.diagnostics;return Boolean(t&&t.enabled!==false&&t.otel?.enabled)}async function startOneShotDiagnosticsExporters(e){const t=e.suppressStdoutDiagnosticLogs===true?suppressOtelStdoutLogSink(e.config):e.config;if(!isOtelExportConfigured(t))return null;const n=getBoundLegacyPluginSdkResourceHost();if(!n)throw new Error(`One-shot diagnostics requires a bound SDK host scheduler`);const r=n.scheduler;const[{acquirePluginRegistryForInspection:i},{startPluginServices:a}]=await Promise.all([import(`./plugins/loader.js`),import(`./services-Cwwp0ijv.mjs`)]);const o=await i({config:t,onlyPluginIds:[...ONE_SHOT_DIAGNOSTICS_SERVICE_IDS],preferBuiltPluginArtifacts:true});const s=new AsyncWorkScope;let c;let l;const reportShutdownFailure=e=>{for(const t of e instanceof AggregateError?e.errors:[e])log.warn(`one-shot diagnostics shutdown failed: ${String(t)}`)};const release=async()=>{await s.drain();await o.release()};const stop=()=>{const e=captureAsyncWorkTracker();if(!l){const e=s.track(async()=>{try{const e=await c?.stop();for(const t of e?.errors??[])reportShutdownFailure(t)}catch(e){reportShutdownFailure(e)}});l={stopping:e,released:e.then(release,release).catch(reportShutdownFailure)}}const{stopping:t,released:n}=l;e(()=>n).catch(reportShutdownFailure);return t};try{const e=o.registry.services.filter(e=>ONE_SHOT_DIAGNOSTICS_SERVICE_IDS.has(e.id));if(e.length===0){log.warn(`diagnostics.otel is enabled but the diagnostics-otel plugin is not installed or not enabled; this run exports no telemetry.`);await release().catch(reportShutdownFailure);return null}c=await s.track(()=>a({scheduler:r,registry:{...o.registry,services:e},config:t,oneShotStopTimeouts:{eventDrainMs:ONE_SHOT_DIAGNOSTICS_DRAIN_TIMEOUT_MS,serviceStopMs:ONE_SHOT_DIAGNOSTICS_FLUSH_TIMEOUT_MS},onHandle:e=>{c=e}}));return{stop}}catch(e){await stop();throw e}}
//!src/commands/agent-gateway-identity.ts
function resolveAgentGatewayIdentity(e,t){return{clientName:e?GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT:GATEWAY_CLIENT_NAMES.CLI,mode:e?GATEWAY_CLIENT_MODES.BACKEND:GATEWAY_CLIENT_MODES.CLI,...e||!t?{scopes:[ADMIN_SCOPE]}:{}}}
//!src/commands/agent-via-gateway.ts
const GATEWAY_TRANSIENT_CONNECT_RETRY_DELAYS_MS=[1e3,2e3,5e3,1e4,15e3];function usesImplicitRemoteCompatibilityDefault(e){return!e.selectionRequired&&(e.ownership===`legacy`||!e.ownership&&e.agentIds.length>1)}function resolveImplicitCliAgentId(e,t){const n=t?t.selectionRequired?void 0:t.defaultId:tryResolveAgentOperationAgentId(e);if(n)return n;const r=t?.agentIds??listAgentIds(e);throw new AgentSelectionRequiredError(r,{surface:`agent turn`,hint:`Pass --agent <id> to select one of: ${r.join(`, `)}.`})}const GATEWAY_ABORT_RETRY_DELAYS_MS=[50,150,300,600];const GATEWAY_ABORT_REQUEST_TIMEOUT_MS=2e3;const AGENT_CLI_SIGNAL_EXIT_CODES={SIGINT:130,SIGTERM:143};async function runEmbeddedAgentCommand(e,t){const{agentCommand:n}=await measureAgentStartup(`command-import`,()=>import(`./agent-DKoYAw2O.mjs`));const r=await loadRuntimeConfig();let i=null;try{i=await startOneShotDiagnosticsExporters({config:r,suppressStdoutDiagnosticLogs:e.json===true})}catch(e){t.error?.(`diagnostics exporter startup failed for embedded run: ${String(e)}`)}let a;if(isExecutionIdentityCollectionEnabled(r))try{const{startAgentLocalAuditWriter:e}=await import(`./agent-local-audit-Co5n4OM0.mjs`);a=e(r)}catch{}try{return await n(e,t)}finally{await Promise.all([i?.stop(),a?.().catch(()=>void 0)])}}async function loadRuntimeConfig(){const{captureRuntimeConfigAsyncReader:e}=await import(`./io-Daz-kTPd.mjs`);return await e()()}function usesRemoteGateway(e){return Boolean(e.gateway?.mode===`remote`||normalizeOptionalString(process.env.OPENCLAW_GATEWAY_URL))}async function loadRemoteGatewayRoster(e){const t=await callGateway({method:`agents.list`,beforeDeviceIdentityLoad:prepareCliGatewayStateAccess,params:{},config:e,clientName:GATEWAY_CLIENT_NAMES.CLI,mode:GATEWAY_CLIENT_MODES.CLI,scopes:[READ_SCOPE]});return{agentIds:t.agents.filter(e=>e.kind!==`system`).map(e=>normalizeAgentId(e.id)),defaultId:normalizeAgentId(t.defaultId),ownership:t.ownership,selectionRequired:t.selectionRequired??t.ownership===`explicit`,mainKey:t.mainKey,scope:t.scope}}async function loadRemoteGatewayRosterWithShellEnvFallback(e){try{return{config:e,roster:await loadRemoteGatewayRoster(e)}}catch(e){if(!shouldRetryGatewayDispatchWithShellEnvFallback(e))throw e;const t=await readGatewayDispatchConfigWithShellEnvFallback();return{config:t,roster:await loadRemoteGatewayRoster(t)}}}function parseTimeoutSeconds(e){if(e===void 0)return;const t=parseStrictNonNegativeInteger(e);if(t===void 0)throwExpectedCliError(`Invalid --timeout. Use seconds as a non-negative integer, for example --timeout 600. Use --timeout 0 to disable the timeout.`);return t}function isCompactControlCommand(e){return/^\/compact(?:\s|:|$)/iu.test(e.trim())}function isSessionResetCommand(e){return/^\/(?:new|reset)(?:\s|$)/i.test(e.trim())}function shouldRetryGatewayDispatchWithShellEnvFallback(e){return isGatewayCredentialsRequiredError(e)||isGatewayExplicitAuthRequiredError(e)||isGatewaySecretRefUnavailableError(e)}function isTransientGatewayAgentConnectClose(e){if(!isGatewayTransportError(e)||e.kind!==`closed`)return false;const t=normalizeOptionalString(e.reason);return e.code===1e3&&(!t||t===`no close reason`)}function validateExplicitSessionKeyForDispatch(e){const t=e.sessionKey?.trim();if(!t)return;if(classifySessionKeyShape(t)===`malformed_agent`)throwExpectedCliError(`Invalid --session-key "${t}". Agent-prefixed session keys must use agent:<agent-id>:<session-key>.`);const n=e.agent?.trim()||void 0;if(!n||classifySessionKeyShape(t)!==`agent`)return;const r=normalizeAgentId(n);const i=resolveAgentIdFromSessionKey(t);if(i!==r)throwExpectedCliError(`Agent id "${n}" does not match session key agent "${i}".`)}async function normalizeSessionKeyOptsForDispatch(e){let t=e;const n=e.sessionKey?.trim();const r=e.to?.trim();if(!n&&!e.sessionId?.trim()&&classifySessionKeyShape(r)===`agent`)return normalizeSessionKeyOptsForDispatch({...e,to:void 0,sessionKey:r});const i=n&&classifySessionKeyShape(n)===`legacy_or_alias`;const a=e.agent?.trim();let o=a;const s=Boolean(e.sessionId?.trim())||[n,r].some(e=>classifySessionKeyShape(e)===`agent`);let c;let l;if(e.local!==true){const e=readGatewayDispatchConfig();t={...t,gatewayDispatchConfig:e};c=e;if(n&&usesRemoteGateway(e)&&classifySessionKeyShape(n)!==`agent`)return t}if(!o&&!s&&!(e.local===true&&r)){let i=e.local===true?await loadRuntimeConfig():c??readGatewayDispatchConfig();if(e.local!==true&&usesRemoteGateway(i)){const e=await loadRemoteGatewayRosterWithShellEnvFallback(i);i=e.config;l=e.roster;t={...t,gatewayDispatchConfig:i,remoteGatewayRoster:l}}c=i;const s=n??(i.session?.scope===`global`?`global`:void 0);const u=l?{kind:`none`}:resolvePersistedSessionStoreOwnerForKey(i,s);if(u.kind===`retired`)throw new AgentSelectionRequiredError(listAgentIds(i),{surface:`session key "${n}"`,hint:`The shared fixed-store row belongs to retired agent "${u.agentId}".`});if(u.kind===`configured`&&n===void 0&&s===`global`)t={...t,sessionKey:`global`};const d=u.kind===`configured`?u.agentId:resolveImplicitCliAgentId(i,l);const f=l?l.ownership===`sole`||!l.ownership&&l.agentIds.length===1:tryResolveSoleAgentId(i)===d;const p=l?usesImplicitRemoteCompatibilityDefault(l):!f;const m=!a&&n===void 0&&(l?l.scope===`global`:(e.local===true||!usesRemoteGateway(i))&&i.session?.scope===`global`);const h=isUnscopedSessionKeySentinel(n)||m;o=(f||p)&&h?void 0:d;if(!l&&p)t={...t,localGatewayCompatibilityAgentId:d};if(o&&p&&!n&&!r)t={...t,sessionKey:buildAgentMainSessionKey({agentId:d,mainKey:l?.mainKey??i.session?.mainKey})};else if(o&&!p)t={...t,agent:d}}const u=i&&(o||!isUnscopedSessionKeySentinel(n))?t.local===true?await loadRuntimeConfig():c??readGatewayDispatchConfig():void 0;if((u&&n&&i&&!isUnscopedSessionKeySentinel(n)?resolvePersistedSessionStoreOwnerForKey(u,n):void 0)?.kind===`configured`||isUnscopedSessionKeySentinel(n))return t;const d=scopeLegacySessionKeyToAgent({agentId:o,sessionKey:t.sessionKey,mainKey:l?.mainKey??u?.session?.mainKey});if(d===t.sessionKey)return t;return{...t,sessionKey:d}}function isAbortError(e){return e instanceof Error&&e.name===`AbortError`}function readAcceptedRunContext(e){const t=asOptionalRecord(e);if(t?.status!==`accepted`)return;return{runId:normalizeOptionalString(t.runId),sessionKey:normalizeOptionalString(t.sessionKey),agentId:normalizeOptionalString(t.agentId)}}function isConfirmedChatAbortResponseForRun(e,t){const n=asOptionalRecord(e);if(n?.aborted!==true)return false;if(n.runIds===void 0)return true;return Array.isArray(n.runIds)&&n.runIds.includes(t)}function exitForReceivedSignal(e,t){if(!e)return false;t.exit(AGENT_CLI_SIGNAL_EXIT_CODES[e]);return true}function returnAfterSignalExit(e,t,n){return exitForReceivedSignal(t,n)?void 0:e}function markAgentRunExitCode(e){if(e===void 0||e===null||e===``)return;process.exitCode=e===`ok`||e===`completed`?0:1}function formatInFlightGatewayAgentMessage(e){return e.runId?`Agent run ${e.runId} is already in flight; not starting a duplicate run.`:`Agent run is already in flight; not starting a duplicate run.`}async function agentViaGatewayCommand(e,t,n,r){const i=e.message;const a=e.sessionKey?.trim();let o=e.gatewayDispatchConfig??readGatewayDispatchConfig();const s=usesRemoteGateway(o);const c=e.remoteGatewayRoster?.ownership===`sole`||!e.remoteGatewayRoster?.ownership&&e.remoteGatewayRoster?.agentIds.length===1;const l=Boolean(e.remoteGatewayRoster&&usesImplicitRemoteCompatibilityDefault(e.remoteGatewayRoster));const u=(e.remoteGatewayRoster?.scope??o.session?.scope)===`global`&&(e.remoteGatewayRoster?!e.remoteGatewayRoster.selectionRequired&&(c||l):!s&&(tryResolveSoleAgentId(o)!==void 0||e.localGatewayCompatibilityAgentId!==void 0));if(!e.to&&!e.sessionId&&!e.agent&&!a&&!u)throwExpectedCliError(`No target session selected. Use --agent <id>, --session-key <key>, --session-id <id>, or --to <E.164>. Run ${formatCliCommand(`openclaw agents list`)} to see agents.`);const d=e.agent?.trim();const f=d?normalizeAgentId(d):void 0;if(f){const t=e.remoteGatewayRoster?.agentIds??(s?void 0:listAgentIds(o));if(t&&!t.includes(f))throwExpectedCliError(`Unknown agent id "${d}". Use "${formatCliCommand(`openclaw agents list`)}" to see configured agents.`)}const p=parseTimeoutSeconds(e.timeout);const m=normalizeMessageChannel(e.channel);const h=Boolean(!a&&!e.sessionId?.trim()&&f&&m&&m!==`last`&&e.to?.trim()&&classifySessionKeyShape(e.to)!==`agent`);const g=Boolean(e.sessionId?.trim()&&!a);const _=Boolean(s&&a&&classifySessionKeyShape(a)!==`agent`);const v=Boolean(f&&!a&&!e.sessionId?.trim()&&!e.to?.trim());const y=(c||l)&&!f&&(isUnscopedSessionKeySentinel(a)||u)||_?a:v||h||g?void 0:classifySessionKeyShape(a)===`agent`?a:(await(await import(`./session.runtime-DGqGHFsV.mjs`)).resolveSessionKeyForRequest({cfg:o,agentId:f,to:e.to,sessionId:e.sessionId,sessionKey:a})).sessionKey;const b=g?void 0:h?(await(await import(`./session.runtime-DGqGHFsV.mjs`)).resolveSessionKeyForRequest({cfg:o,agentId:f})).sessionKey:y;const x=normalizeOptionalString(e.runId)||randomIdempotencyKey();const S=normalizeOptionalString(e.model);const C=Boolean(S)||isSessionResetCommand(i);const w=resolveAgentGatewayIdentity(C,s);let T=false;let E=false;let D;const abortGatewayRun=async(e,i=true)=>{const a=r.accepted?.runId??x;const o=r.accepted?.sessionKey??b;const s=r.accepted?.agentId;const c=n.getReceivedSignal();for(const[n,r]of[...GATEWAY_ABORT_RETRY_DELAYS_MS,0].entries()){const l=n===GATEWAY_ABORT_RETRY_DELAYS_MS.length;const u=i&&l;if(c&&a&&o)try{if(isConfirmedChatAbortResponseForRun(await e(`chat.abort`,{sessionKey:o,runId:a,...s?{agentId:s}:{}},{timeoutMs:GATEWAY_ABORT_REQUEST_TIMEOUT_MS}),a))return true;if(u)t.error?.(`Interrupted by ${c}; Gateway run ${a} was not confirmed aborted.`)}catch(e){if(u)t.error?.(`Interrupted by ${c}; failed to abort Gateway run ${a}: ${String(e)}`)}if(l)return false;await sleep(r)}return false};const dispatchGatewayAgentCall=async t=>await withProgress({label:`Waiting for agent reply…`,indeterminate:true,enabled:e.json!==true},async()=>await callGateway({method:`agent`,beforeDeviceIdentityLoad:prepareCliGatewayStateAccess,requiredCapabilities:g?[GATEWAY_SERVER_CAPS.AGENT_SESSION_ID_CREATE]:void 0,params:{message:i,agentId:f,model:S,to:e.to,replyTo:e.replyTo,sessionId:e.sessionId,sessionKey:y,createSessionIfMissing:g||void 0,thinking:e.thinking,deliver:Boolean(e.deliver),channel:m,replyChannel:e.replyChannel,replyAccountId:e.replyAccount,bestEffortDeliver:e.bestEffortDeliver,timeout:p,lane:e.lane,extraSystemPrompt:e.extraSystemPrompt,idempotencyKey:x},expectFinal:true,timeoutMs:null,config:t,signal:n.signal,onAccepted:e=>{r.accepted=readAcceptedRunContext(e)},onSignalAbort:async e=>{T=true;E=await abortGatewayRun(e,false)},...w}));let O=1;const consumeShellEnvFallbackRetry=()=>O-->0;for(;;)try{D=await dispatchGatewayAgentCall(o);break}catch(e){if(!r.accepted&&shouldRetryGatewayDispatchWithShellEnvFallback(e)&&consumeShellEnvFallbackRetry()){o=await readGatewayDispatchConfigWithShellEnvFallback();continue}if(isAbortError(e)&&!E&&(r.accepted||T))await abortGatewayRun((e,t,n)=>callGateway({method:e,beforeDeviceIdentityLoad:prepareCliGatewayStateAccess,params:t,timeoutMs:n?.timeoutMs,expectFinal:n?.expectFinal,config:o,...w}));const t=e instanceof GatewayProtocolRequestError?asOptionalRecord(e.responsePayload):void 0;if(t?.reason===`input_withdrawn_before_turn`&&typeof t.pendingInputId===`string`){D={...t,status:`cancelled`};break}recordCliGatewayRunFailure(e,normalizeOptionalString(t?.runId)??r.accepted?.runId);throw e}if(!D)throw new Error(`gateway agent call did not return a response`);markAgentRunExitCode(D.status);if(e.json){const e=D.result?.deliveryStatus;writeRuntimeJson(t,e===void 0?D:{...D,deliveryStatus:e});return D}const k=D.result?.payloads??[];if(D.result?.meta?.requestShaping?.thinkingClamp)t.log(D.result.meta.requestShaping.thinkingClamp);if(D.reason===`input_withdrawn_before_turn`){t.error?.(D.summary);return D}if(D.status===`in_flight`){t.error?.(formatInFlightGatewayAgentMessage(D));return D}if(k.length===0){if(D?.status!==`ok`)t.log(D?.summary?D.summary:`No reply from agent.`);else{const e=normalizeOptionalString(D.result?.meta?.yieldAcknowledgment);if(e)t.log(e)}return D}const{logAgentGatewayPayloads:A}=await import(`./agent-gateway-output-DQialAyQ.mjs`);await A(t,k);return D}async function agentViaGatewayCommandWithTransientRetries(e,t,n){const r={};for(const[i,a]of[...GATEWAY_TRANSIENT_CONNECT_RETRY_DELAYS_MS,0].entries())try{return await agentViaGatewayCommand(e,t,n,r)}catch(e){if(isAbortError(e))throw e;if(i===GATEWAY_TRANSIENT_CONNECT_RETRY_DELAYS_MS.length||!isTransientGatewayAgentConnectClose(e))throw e;t.error?.(`Gateway agent connection closed during handshake; retrying in ${a}ms before failing.`);await sleep(a,n.signal)}throw new Error(`Gateway agent retry loop exhausted unexpectedly.`)}async function agentCliCommand(e,t){if(e.local!==true)assertGatewayCliMessageContext(`agent`);for(const[t,n]of[[`--agent`,e.agent],[`--session-id`,e.sessionId],[`--session-key`,e.sessionKey],[`--to`,e.to]])if(n!==void 0&&!n.trim())throwExpectedCliError(`${t} must not be blank`);if(e.json===true)routeLogsToStderr();const{messageFile:n,...r}=e;const i=readNonBlankString(n);if(e.message!==void 0&&i)throwExpectedCliError(`Use either --message or --message-file, not both.`);if(n!==void 0&&!i)throwExpectedCliError(`--message-file must not be empty.`);const a=i?await readAgentMessageFile(i):e.message??``;if(!i&&!a.trim())throwExpectedCliError(`Missing message. Use ${formatCliCommand(`openclaw agent --message "..." --agent <id>`)} or ${formatCliCommand(`openclaw agent --message-file <path> --agent <id>`)}.`);if(isCompactControlCommand(a))throwExpectedCliError(`Slash commands cannot be executed via --message from the CLI. Use: openclaw sessions compact <key>`);const o=await normalizeSessionKeyOptsForDispatch({...r,message:a});validateExplicitSessionKeyForDispatch(o);const s=o.runId?o:{...o,runId:randomIdempotencyKey()};const c=createProcessSignalBridge();try{if(o.local===true){const{runWithLocalStateOwner:e}=await import(`./local-state-owner-D6lzsNxM.mjs`);const n=await e({method:`agent --local`,params:{},target:`agent state`,onForeignOwner:`refuse`,onlineAlternative:`Omit --local to run it through the Gateway.`,signal:c.signal,runLocal:()=>runEmbeddedAgentCommand({...s,agentId:s.agent??s.localGatewayCompatibilityAgentId,replyAccountId:s.replyAccount,cleanupBundleMcpOnRunEnd:true,cleanupCliLiveSessionOnRunEnd:true,oneShotCliRun:true,abortSignal:c.signal},t)});markAgentRunExitCode(readAgentRunTerminalOutcome(n));return returnAfterSignalExit(n,c.getReceivedSignal(),t)}try{return returnAfterSignalExit(await agentViaGatewayCommandWithTransientRetries(s,t,c),c.getReceivedSignal(),t)}catch(e){if(!isAbortError(e)&&isGatewayTransportError(e)){const n=e.kind===`timeout`?`timed out`:`connection closed`;const r=readCliGatewayRunFailure(e);const i=`Gateway agent call ${n}; the Gateway may still be running this turn${r?` (accepted run ${r.runId})`:``}. Check \`openclaw gateway status\` and the session transcript before retrying or rerunning with --local, so the turn does not execute twice.`;t.error?.(i)}throw e}}catch(e){if(isAbortError(e)&&exitForReceivedSignal(c.getReceivedSignal(),t))return;throw e}finally{c.dispose()}}export{agentCliCommand};