openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
686 lines (685 loc) • 26.9 kB
JavaScript
import { l as normalizeOptionalString, m as readNonBlankString } from "./string-coerce-CCIiB4H7.mjs";
import { E as parseStrictNonNegativeInteger } from "./number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { o as writeRuntimeJson } from "./runtime-B-SLYP-m.mjs";
import { s as readFileDescriptorBounded } from "./boundary-file-read-BfaFLDqt.mjs";
import { t as sleep } from "./sleep-CkI3nkiJ.mjs";
import { a as captureAsyncWorkTracker, t as AsyncWorkScope } from "./async-work-scope-BXagjUap.mjs";
import { r as getBoundLegacyPluginSdkResourceHost } from "./legacy-sdk-resource-host-BiedXayN.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { n as buildAgentMainSessionKey } from "./session-key-DW1jcHbM.mjs";
import { l as resolveAgentIdFromSessionKey, m as scopeLegacySessionKeyToAgent, o as classifySessionKeyShape, s as isUnscopedSessionKeySentinel } from "./session-key-CqAyZeVk.mjs";
import { i as listAgentIds, p as tryResolveSoleAgentId } from "./agent-roster-t1ooUdXp.mjs";
import { D as tryResolveAgentOperationAgentId, t as AgentSelectionRequiredError, z as resolvePersistedSessionStoreOwnerForKey } from "./agent-scope-config-DmXgFGKP.mjs";
import { i as routeLogsToStderr } from "./console-BkI11Tqj.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs";
import { a as READ_SCOPE, t as ADMIN_SCOPE } from "./operator-scopes-CULmYfyY.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import "./message-channel-normalize-CFHSufeo.mjs";
import { n as isExecutionIdentityCollectionEnabled } from "./audit-config-DjeE3VAP.mjs";
import { t as GATEWAY_SERVER_CAPS } from "./server-capabilities-BDosLJeN.mjs";
import { n as isGatewaySecretRefUnavailableError } from "./credentials-UDpmcQCV.mjs";
import { t as GatewayProtocolRequestError } from "./protocol-request-CsClAJsG.mjs";
import { s as isGatewayTransportError } from "./transport-error-BL_kuysc.mjs";
import { c as readCliGatewayRunFailure, l as recordCliGatewayRunFailure } from "./failure-output-DVVDqwuu.mjs";
import { n as readGatewayDispatchConfigWithShellEnvFallback, t as readGatewayDispatchConfig } from "./gateway-dispatch-config-NmsdoFuC.mjs";
import { d as isGatewayExplicitAuthRequiredError, m as assertGatewayCliMessageContext, p as randomIdempotencyKey, r as callGateway, u as isGatewayCredentialsRequiredError } from "./call-DVCK1deJ.mjs";
import { t as readByteStreamWithLimit } from "./read-byte-stream-with-limit-BjmaH2Xs.mjs";
import { n as readAgentRunTerminalOutcome } from "./agent-run-terminal-outcome-BQoZ_25h.mjs";
import { r as withProgress } from "./progress-DZHhZ1Fk.mjs";
import { t as measureAgentStartup } from "./startup-timing-KnC51YT7.mjs";
import { r as prepareCliGatewayStateAccess } from "./gateway-rpc.runtime-DGuEWCMQ.mjs";
import { n as createEmbeddedStateSignalBridge, t as acquireEmbeddedStateLock } from "./embedded-state-lock-B6qVAmNT.mjs";
import fs from "node:fs/promises";
import { TextDecoder } from "node:util";
//#region 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);
}
/** CLI agent runs own exporter services outside the Gateway; stop drains and flushes them. */
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-EBMoKece.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;
}
}
//#endregion
//#region 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] } : {}
};
}
//#endregion
//#region src/commands/agent-message-input.ts
const MESSAGE_FILE_DECODER = new TextDecoder("utf-8", { fatal: true });
function formatMessageFileReadFailure(e, t) {
const n = asOptionalRecord(t)?.code;
if (n === "ENOENT") return `Message file not found: ${e}`;
if (n === "EISDIR") return `Message file is a directory: ${e}`;
return `Unable to read message file ${e}: ${t instanceof Error ? t.message : String(t)}`;
}
const AGENT_MESSAGE_FILE_MAX_BYTES = 4194304;
async function readAgentMessageFile(e) {
let t;
if (e === "-") t = await readByteStreamWithLimit(process.stdin, {
maxBytes: AGENT_MESSAGE_FILE_MAX_BYTES,
onOverflow: () => /* @__PURE__ */ new Error(`Message stdin exceeds ${AGENT_MESSAGE_FILE_MAX_BYTES} bytes`)
});
else {
let n;
try {
n = await fs.open(e, "r");
const r = await n.stat();
if (r.isDirectory()) throw Object.assign(/* @__PURE__ */ new Error("Message file is a directory"), { code: "EISDIR" });
if (r.isFile() && r.size > AGENT_MESSAGE_FILE_MAX_BYTES) throw new Error(`File exceeds ${AGENT_MESSAGE_FILE_MAX_BYTES} bytes: ${e}`);
t = await readFileDescriptorBounded(n.fd, AGENT_MESSAGE_FILE_MAX_BYTES);
} catch (t) {
throw new Error(formatMessageFileReadFailure(e, t), { cause: t });
} finally {
await n?.close().catch(() => void 0);
}
}
let n;
try {
n = MESSAGE_FILE_DECODER.decode(t).replace(/^\uFEFF/, "");
} catch {
throw new Error(e === "-" ? "Message stdin must be valid UTF-8" : `Message file must be valid UTF-8: ${e}`);
}
if (!n.trim()) throw new Error(e === "-" ? "Message stdin is empty" : `Message file is empty: ${e}`);
return n;
}
//#endregion
//#region 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
};
/**
* Run the embedded agent command with OTel diagnostics export for this
* one-shot process: the Gateway only starts diagnostics exporters in its own
* process, so embedded runs start one here and flush it before the CLI exits
* (including signal exits, which happen after this returns).
*/
async function runEmbeddedAgentCommand(e, t) {
const { agentCommand: n } = await measureAgentStartup("command-import", () => import("./agent-CRcpy-UJ.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-BIjxTNuN.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-DeTUDO0h.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 formatActiveGatewayLocalRefusal(e) {
return `A Gateway is running for this state directory (pid ${e.pid}, port ${e.port}). Run without --local to use it, or stop the Gateway first (${formatCliCommand("openclaw gateway stop")}).`;
}
function missingAgentMessageError() {
return /* @__PURE__ */ new Error(`Missing message. Use ${formatCliCommand("openclaw agent --message \"...\" --agent <id>")} or ${formatCliCommand("openclaw agent --message-file <path> --agent <id>")}.`);
}
function parseTimeoutSeconds(e) {
const t = e.timeout !== void 0 ? parseStrictNonNegativeInteger(e.timeout) : e.cfg.agents?.defaults?.timeoutSeconds ?? 600;
if (t === void 0) throw new Error(`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") throw new Error(`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) throw new Error(`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) throw new Error(`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)) throw new Error(`Unknown agent id "${d}". Use "${formatCliCommand("openclaw agents list")}" to see configured agents.`);
}
const p = parseTimeoutSeconds({
cfg: o,
timeout: 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.js")).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.js")).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.");
return D;
}
for (const e of k) {
const { resolveSendableOutboundReplyParts: n } = await import("./plugin-sdk/reply-payload.js");
const { formatOutboundPayloadLog: r } = await import("./payloads-CnJuG_O9.mjs");
const i = r(n({
text: e.text,
mediaUrls: e.mediaUrls,
mediaUrl: typeof e.mediaUrl === "string" ? e.mediaUrl : void 0
})).trimEnd();
if (i) t.log(i);
}
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()) throw new Error(`${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) throw new Error("Use either --message or --message-file, not both.");
if (n !== void 0 && !i) throw new Error("--message-file must not be empty.");
const a = i ? await readAgentMessageFile(i) : e.message ?? "";
if (!i && !a.trim()) throw missingAgentMessageError();
if (isCompactControlCommand(a)) throw new Error("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 = createEmbeddedStateSignalBridge();
try {
if (o.local === true) {
const e = await acquireEmbeddedStateLock({
signal: c.signal,
formatActiveGatewayRefusal: formatActiveGatewayLocalRefusal
});
let n;
try {
n = await runEmbeddedAgentCommand({
...s,
agentId: s.agent ?? s.localGatewayCompatibilityAgentId,
replyAccountId: s.replyAccount,
cleanupBundleMcpOnRunEnd: true,
cleanupCliLiveSessionOnRunEnd: true,
oneShotCliRun: true,
abortSignal: c.signal
}, t);
} finally {
await e?.release();
}
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}` + (n === "timed out" ? "; use --timeout <seconds> to extend the CLI wait" : "") + ")" : ""}. 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();
}
}
//#endregion
export { agentCliCommand };