UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

356 lines (355 loc) • 13.7 kB
import { E as parseStrictNonNegativeInteger } from "./number-coercion-D6u-4YD8.mjs"; import { i as asOptionalObjectRecord } from "./record-coerce-CVPuDqcc.mjs"; import { o as writeRuntimeJson, s as writeRuntimeStdout } from "./runtime-B-SLYP-m.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as applyProcessEnvKeys } from "./process-env-DVJdcOcM.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { n as isExecutionIdentityCollectionEnabled } from "./audit-config-DjeE3VAP.mjs"; import { n as findAgentRunTerminalOutcome } from "./agent-run-terminal-error-CbmFnPGI.mjs"; import { n as getInstallationTarget, t as LOCAL_INSTALLATION_TARGET_UNSUPPORTED } from "./installation-target-context-C_xR1SHA.mjs"; import { n as recordAgentCleanupFailure, t as createAgentCleanupScope } from "./run-cleanup-timeout-Bk3vN1Oh.mjs"; import { a as createAgentToolExecutionBudget } from "./agent-tool-source-execution-guard-CD-ezY7E.mjs"; import { i as resolveExecBaseConfig, n as buildExecRunConfig, r as resolveAgentExecPrompt, t as applyExecConfigOverrides } from "./agent-exec-input-DO0ZinZP.mjs"; import path from "node:path"; import { randomUUID } from "node:crypto"; import fs from "node:fs/promises"; import os from "node:os"; //#region src/commands/agent-exec-result.ts function projectAgentExecPayload(e) { return { ...typeof e.text === "string" ? { text: e.text } : {}, ...e.mediaUrl !== void 0 ? { mediaUrl: e.mediaUrl } : {}, ...Array.isArray(e.mediaUrls) ? { mediaUrls: [...e.mediaUrls] } : {}, ...e.isError === true ? { isError: true } : {}, ...e.isReasoning === true ? { isReasoning: true } : {}, ...e.isCommentary === true ? { isCommentary: true } : {} }; } /** Classify an embedded result into the strict `agent exec` process contract. */ function classifyAgentExecResult(e, t = false, n) { const r = e.meta; const i = e.payloads?.find((e) => e.isError === true); const a = typeof n === "string" ? n : typeof i?.text === "string" && i.text.trim() ? i.text : void 0; const o = n !== void 0 || i !== void 0; const s = (e.payloads ?? []).map(projectAgentExecPayload); if (typeof n === "string") { const e = s.findIndex((e) => e.isError !== true && e.text === n); if (e >= 0) s[e] = { ...s[e], isError: true }; } const c = r.stopReason === "timeout" || r.timeoutPhase !== void 0; const l = t || r.aborted === true || r.error !== void 0 || r.stopReason === "error" || o; const u = c ? "timeout" : l ? "error" : "ok"; const d = c ? r.error?.message ?? a ?? "Agent run timed out" : t ? r.error?.message ?? a ?? "All model fallback candidates failed" : r.error?.message ?? a ?? (l ? "Agent run failed" : void 0); const f = c ? "timeout" : t ? "fallback_exhausted" : r.error?.kind ? r.error.kind : r.aborted ? "aborted" : o ? "error_payload" : l ? "agent_error" : void 0; const p = r.agentMeta; const m = s.filter((e) => e.isError !== true && e.isReasoning !== true && e.isCommentary !== true && typeof e.text === "string" && e.text.trim().length > 0).map((e) => e.text.trimEnd()).join("\n"); return { ok: u === "ok", status: u, final: m || (!o ? e.meta.finalAssistantVisibleText?.trimEnd() : "") || "", payloads: s, ...p?.usage ? { usage: p.usage } : {}, ...p?.costUsd !== void 0 ? { costUsd: p.costUsd } : {}, ...p?.codeModeEngaged !== void 0 ? { codeModeEngaged: p.codeModeEngaged } : {}, ...p?.assistantTurns !== void 0 ? { assistantTurns: p.assistantTurns } : {}, ...p?.bridgeCalls ? { bridgeCalls: p.bridgeCalls } : {}, ...r.toolSummary ? { toolSummary: r.toolSummary } : {}, model: p?.model ?? null, provider: p?.provider ?? null, sessionId: p?.sessionId ?? "", ...d && f ? { error: { message: d, kind: f } } : {} }; } //#endregion //#region src/commands/agent-exec.ts const AGENT_EXEC_DEFAULT_TIMEOUT_SECONDS = 600; function normalizeCodeMode(e) { if (e === void 0) return; const t = { direct: false, auto: "auto", code: true }; if (typeof e === "string" && Object.hasOwn(t, e)) return t[e]; throw new Error("--code-mode must be one of direct, auto, code."); } async function requireDirectory(e, t) { const n = path.resolve(e); let r; try { r = await fs.stat(n); } catch (e) { throw new Error(`${t} does not exist: ${n}`, { cause: e }); } if (!r.isDirectory()) throw new Error(`${t} is not a directory: ${n}`); return n; } function formatActiveGatewayExecRefusal(e) { return `A Gateway is running for this state directory (pid ${e.pid}, port ${e.port}). Omit --state-dir to use isolated temporary state, or stop the Gateway first (${formatCliCommand("openclaw gateway stop")}).`; } function isStructuredTimeoutError(e) { if (findAgentRunTerminalOutcome(e)?.status === "timeout") return true; let t = e; for (let e = 0; e < 4; e += 1) { const e = asOptionalObjectRecord(t); if (!e) return false; if (e.name === "TimeoutError" || e.code === "ETIMEDOUT" || e.reason === "timeout") return true; t = e.cause; } return false; } /** Run one isolated embedded agent turn and project its stable CLI result. */ async function agentExecCommand(e, t, n) { const r = randomUUID(); const i = new AbortController(); const a = i.signal; const o = createAgentToolExecutionBudget({ signal: a, abort: (e) => i.abort(e) }); const resultForEnvelope = (e) => ({ envelope: e, exitCode: e.status === "ok" ? 0 : e.status === "timeout" ? 2 : 1, toolCalls: o.toolCalls }); let s; const c = createAgentCleanupScope(); let l; let restoreEnvironment; let restoreConfigEnvironment; let u; let restoreRuntimeConfigSnapshot; let d; let f; let p; let m; let h; let g = a; let _; try { a.throwIfAborted(); const i = normalizeCodeMode(t.codeMode); const v = await resolveAgentExecPrompt(e, t.messageFile); const y = await requireDirectory(t.cwd ?? process.cwd(), "Working directory"); const { acquireEmbeddedStateLock: b, createEmbeddedStateSignalBridge: x } = await import("./embedded-state-lock-DCwfjPhD.mjs"); _ = x(); g = AbortSignal.any([a, _.signal]); const S = t.stateDir ? await requireDirectory(t.stateDir, "State directory") : await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-agent-exec-")); l = t.stateDir ? void 0 : S; f = await import("./io-DeTUDO0h.mjs"); const C = f.getRuntimeConfigSnapshot(); const w = f; restoreRuntimeConfigSnapshot = () => { if (C) w.setRuntimeConfigSnapshot(C); else w.clearRuntimeConfigSnapshot(); }; const { restoreEnvChangesIfUnchanged: T, snapshotEnv: E } = f; const D = E(process.env); const O = await resolveExecBaseConfig(t); const ee = E(process.env); restoreConfigEnvironment = () => T({ env: process.env, before: D, after: ee }); const k = await applyExecConfigOverrides(O, t.configOverride); if (t.configOverride?.length) { const { prepareConfigRuntimeEnv: e } = await import("./config-env-vars-Deh_reRE.mjs"); u = e({ previousConfig: O, nextConfig: k }).publish(); } const A = buildExecRunConfig({ base: k, cwd: y, opts: t }); if (l || t.isolated) A.database = { engine: "sqlite" }; const j = t.isolated !== true && t.authEnvOnly !== true ? await import("./install-root-context-2ujUGLyn.mjs") : void 0; const M = j?.resolvePluginInstallRoots(); const N = t.timeout ?? String(AGENT_EXEC_DEFAULT_TIMEOUT_SECONDS); if (parseStrictNonNegativeInteger(N) === void 0) throw new Error("--timeout must be a non-negative integer in seconds."); const P = (t.fallback ?? []).map((e) => e.trim()).filter(Boolean); if (P.length > 0 && !t.model?.trim()) throw new Error("--fallback requires --model so the primary model is explicit."); const { resolveAgentDir: F, resolveAmbientOwnerAgentId: I } = await import("./agent-scope-config-B1XZecUN.mjs"); const L = I(k, void 0, { surface: "agent exec", hint: "Set agents.defaults.systemAgent.agentId." }); if (getInstallationTarget()) { const [{ resolveSandboxConfigForAgent: e }, { resolveExecToolConfig: t }] = await Promise.all([import("./config-CRxHrTpO.mjs"), import("./lazy-exec-tool-csHwlu9l.mjs")]); const n = t({ cfg: A, agentId: L }).host; if (e(A, L).mode !== "off" || n === "node" || n === "sandbox") throw new Error(LOCAL_INSTALLATION_TARGET_UNSUPPORTED); } const R = F(k, L); d = await import("./paths-C9ebzH5f.mjs"); const z = d.resolveStateDir(); const B = { OPENCLAW_STATE_DIR: process.env.OPENCLAW_STATE_DIR, OPENCLAW_CONFIG_PATH: process.env.OPENCLAW_CONFIG_PATH, OPENCLAW_WORKSPACE_DIR: process.env.OPENCLAW_WORKSPACE_DIR }; process.env.OPENCLAW_STATE_DIR = S; delete process.env.OPENCLAW_CONFIG_PATH; process.env.OPENCLAW_WORKSPACE_DIR = y; restoreEnvironment = () => applyProcessEnvKeys(Object.keys(B), B); d.pinRuntimePaths(); if (l) { const { createOpenClawDatabaseMaintenanceScope: e } = await import("./openclaw-state-db-async-lifecycle-svBk4d27.mjs"); h = e(); } const [{ resolveDatabaseEngineSelection: V }, { installDatabaseEngineSelection: H, withDatabaseEngineSelection: U }] = await Promise.all([import("./config-eNRW_vew.mjs"), import("./context-Dz_LKKUd.mjs")]); const W = await V(A); if (t.stateDir) m = await U(W, () => b({ signal: g, formatActiveGatewayRefusal: formatActiveGatewayExecRefusal })); H(W); w.setRuntimeConfigSnapshot(A); const [{ withAuthProfileStoreAgentDir: G, withEnvOnlyAuthProfileStore: K }, { withHostExecInheritedEnvOmitted: q }, { listKnownProviderAuthEnvVarNamesCore: J }, { agentCommand: Y }] = await Promise.all([ import("./auth-profiles-UUzo-h8d.mjs"), import("./host-env-security-BvlB8NAU.mjs"), import("./provider-env-vars-BkV4-5UO.mjs"), import("./agent-CRcpy-UJ.mjs") ]); let X = false; let Z; const te = { log: () => {}, error: (...e) => n.error(...e), exit: (e, t) => n.exit(e, t) }; const invoke = async () => { g.throwIfAborted(); return await Y({ message: v, sessionId: r, agentId: L, workspaceDir: y, cwd: y, model: t.model, codeModeOverride: i, thinking: t.thinking, timeout: N, modelFallbacksOverride: P.length > 0 ? P : void 0, cleanupBundleMcpOnRunEnd: true, cleanupCliLiveSessionOnRunEnd: true, oneShotCliRun: true, operatorDirectRoot: true, abortSignal: g, onModelFallbackExhausted: () => { X = true; }, onResultErrorPayload: (e) => { Z = e ?? true; } }, te); }; const runWithPluginInstallRoots = () => j && M ? j.withPluginInstallRoots(M, invoke) : invoke(); const runWithAuthScope = () => t.authEnvOnly === true ? K(runWithPluginInstallRoots) : G(R, z, runWithPluginInstallRoots); const run = async () => { if (isExecutionIdentityCollectionEnabled(A)) try { p = (await import("./agent-local-audit-BIjxTNuN.mjs")).startAgentLocalAuditWriter(A, { stateDir: S }); } catch {} return await o.run(() => q(J({ env: process.env }), runWithAuthScope)); }; const Q = await c.run(() => h ? h.run(run) : run()); a.throwIfAborted(); if (!Q) throw new Error("Agent run returned no result"); const $ = classifyAgentExecResult(Q, X, Z); if (!$.sessionId) $.sessionId = r; s = resultForEnvelope($); } catch (e) { const t = isStructuredTimeoutError(e) ? "timeout" : "error"; s = resultForEnvelope({ ok: false, status: t, final: "", payloads: [], model: null, provider: null, sessionId: r, error: { message: formatErrorMessage(e), kind: t === "timeout" ? "timeout" : "exception" } }); } let v = c.outcome === "uncertain" ? /* @__PURE__ */ new Error("Agent runtime cleanup did not settle; state ownership retained until this process exits") : void 0; const recordCleanupError = (e) => { v = e; }; const stopAudit = async () => await p?.(); await (h ? h.run(stopAudit) : stopAudit()).catch(() => void 0); if (!v && l) { const { closeOpenClawAgentDatabasesAsync: e } = await import("./openclaw-agent-db-lifecycle-W0V62HCS.mjs"); await e(l).catch(recordCleanupError); } if (!v && l) { const [{ closeOpenClawStateDatabaseByPathAsync: e }, { resolveOpenClawStateSqlitePath: t }] = await Promise.all([import("./openclaw-state-db-cache-DIGS30x4.mjs"), import("./openclaw-state-db.paths-DiM3pkKt.mjs")]); await e(t({ ...process.env, OPENCLAW_STATE_DIR: l })).catch(recordCleanupError); } if (!v) await h?.close().catch(recordCleanupError); if (!v) await m?.release().catch(recordCleanupError); const runCleanupStep = (e) => { try { e(); } catch (e) { v ??= e; } }; runCleanupStep(() => restoreEnvironment?.()); runCleanupStep(() => u?.()); runCleanupStep(() => restoreConfigEnvironment?.()); runCleanupStep(() => f?.clearConfigCache()); runCleanupStep(() => restoreRuntimeConfigSnapshot ? restoreRuntimeConfigSnapshot() : f?.clearRuntimeConfigSnapshot()); runCleanupStep(() => d?.pinRuntimePaths()); if (l && !v) try { await fs.rm(l, { recursive: true, force: true }); } catch (e) { v ??= e; } if (v) { recordAgentCleanupFailure(); const e = /* @__PURE__ */ new Error(`Agent exec cleanup failed: ${formatErrorMessage(v)}`); if (s.envelope.ok) s = resultForEnvelope({ ...s.envelope, ok: false, status: "error", error: { message: e.message, kind: "cleanup" } }); else n.error(e.message); } const y = _?.getReceivedSignal(); _?.dispose(); if (y) { n.exit(y === "SIGINT" ? 130 : 143, { resetStream: process.stderr }); return s; } const b = s.envelope; if (t.json === true) writeRuntimeJson(n, b); else if (b.final) writeRuntimeStdout(n, b.final); if (!b.ok && b.error) n.error(b.error.message); return s; } //#endregion export { agentExecCommand };