UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,331 lines (1,330 loc) • 48.8 kB
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { c as isSecretRef } from "./ref-contract-b8L-9DrQ.mjs"; import { p as normalizeSecretInputString } from "./types.secrets-BmNLLnHp.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs"; import "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as buildAgentMainSessionKey } from "./session-key-DW1jcHbM.mjs"; import { g as toAgentStoreSessionKey } from "./session-key-CqAyZeVk.mjs"; import { h as SYSTEM_AGENT_ID } from "./agent-roster-t1ooUdXp.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { a as resolveAgentEffectiveModelPrimary } from "./agent-scope-BwB8YH6y.mjs"; import { o as resolveCliBackendConfig } from "./cli-backends-B8PrIwPC.mjs"; import { f as prepareSystemAgentRunAdmission } from "./admitted-run-context-D3Jvk_f_.mjs"; import { n as resolveAgentTimeoutMs } from "./timeout-BEnEcjB4.mjs"; import { r as runOutsidePreparedModelRuntimePluginGenerationScope } from "./prepared-model-runtime-generation-scope-Dpvf6WHJ.mjs"; import { n as sanitizeWizardStepForClient, r as wizardStepAwaitsInput, t as WizardSession } from "./session-beMMG7GW.mjs"; import { t as isSystemAgentNavigationOperation } from "./operation-types-3IrpSF7Y.mjs"; import { n as resolveWizardLocale, t as createSetupTranslator } from "./i18n-AiHKCZaZ.mjs"; import { a as isPersistentSystemAgentOperation, n as SYSTEM_AGENT_OPERATOR_NAVIGATION_HANDOFF, o as parseSystemAgentOperation, r as describeSystemAgentPersistentOperation, s as redactSensitiveCommandText, u as isInvalidConfigSetOperation } from "./operations-parse-DoFrSk0v.mjs"; import { g as resolveTuiAgentId, n as SystemAgentOperationExitError, u as getRegularAgentSetupNotice } from "./operations-execution-helpers-cXxYzJCh.mjs"; import { t as executeSystemAgentOperation } from "./operations-CBf52_6Y.mjs"; import { a as resolveOperatorApprovalDecision, i as hashSystemAgentOperation, n as SYSTEM_AGENT_APPROVAL_TERMINAL_MESSAGES, o as resolvePendingOperatorProposal, r as classifySystemAgentApprovalText, t as SYSTEM_AGENT_APPROVAL_APPLICATION_UNCONFIRMED_TEXT } from "./operator-approval-DrWu-F-I.mjs"; import { i as isSystemAgentInferenceUnavailableError, n as requireSystemAgentPersistentApplyInference, r as SystemAgentInferenceUnavailableError, t as requireSystemAgentInferenceRoute } from "./inference-guard-D92Jot8f.mjs"; import { i as loadSystemAgentOverview } from "./overview-DAa4f9mq.mjs"; import { a as resolveSystemAgentVerifiedInferenceRoute, i as resolveSystemAgentExpectedAgentHarnessRuntimeArtifact } from "./verified-inference-B9tngoud.mjs"; import { n as formatSystemAgentTurnInput, t as approvalQuestion } from "./dialogue-CGAI4JoY.mjs"; import { n as extractAgentRunTerminalError, r as extractAgentRunText } from "./agent-run-result-Bi1gRTvj.mjs"; import { t as SessionManager } from "./session-manager-DuaaMI5O.mjs"; import "./sessions-G45sHB31.mjs"; import { t as createSystemAgentUserTurnRecorder } from "./user-turn-transcript-Bot7_IyX.mjs"; import { a as normalizeCliModel } from "./helpers-aqu9cn2k.mjs"; import { l as buildSystemAgentSystemPrompt, n as systemAgentTerminalFailureGuidance, t as systemAgentRuntimeFailureGuidance } from "./inference-run-errors-BNCBVqvM.mjs"; import path from "node:path"; import { randomUUID } from "node:crypto"; import fs from "node:fs/promises"; //#region src/system-agent/agent-turn.ts /** * OpenClaw is a real agent: same loop, session transcript, and tool pipeline * as regular agents — restricted to the single ring-zero `openclaw` tool. * Embedded runtimes enforce that restriction with toolsAllow. CLI harnesses * must explicitly support per-run native-tool selection, then receive the tool * over a dedicated stdio MCP server that replaces the normal bundle surface. * Turns share one persistent session so the conversation has genuine * multi-turn memory. Inference setup must succeed before this runner is entered. */ const SYSTEM_AGENT_TOOL_NAME = "openclaw"; function createSystemAgentSession(e) { if (!e) throw new SystemAgentInferenceUnavailableError("agent-turn", [], "setup"); return { sessionId: `openclaw-${randomUUID()}`, verifiedInference: e, proposalRef: {} }; } async function cleanupSystemAgentSession(e) { delete e.cliSession; delete e.sessionManager; } function clearFailedSystemAgentSessionState(e) { e.proposalRef.current = void 0; e.proposalRef.operation = void 0; delete e.cliSession; } function throwSystemAgentInferenceUnavailable(e) { clearFailedSystemAgentSessionState(e.session); throw new SystemAgentInferenceUnavailableError("agent-turn", e.failures, e.guidance); } function cliRouteKey(e, t) { return JSON.stringify({ provider: e.provider, backendId: t?.id ?? e.provider, modelLabel: e.modelLabel, configuredModel: e.model, model: t ? normalizeCliModel(e.model, t.config) : e.model, authProfileId: e.authProfileId ?? "", agentDir: path.resolve(e.agentDir), backend: t ? { pluginId: t.pluginId, modelProvider: t.modelProvider, config: t.config, bundleMcp: t.bundleMcp, bundleMcpMode: t.bundleMcpMode, authEpochMode: t.authEpochMode, nativeToolMode: t.nativeToolMode, toolAvailabilityEnforcement: t.toolAvailabilityEnforcement, sideQuestionToolMode: t.sideQuestionToolMode } : null }); } function resolveSystemAgentCliBackend(e) { const t = resolveCliBackendConfig(e.provider, e.runConfig, { agentId: SYSTEM_AGENT_ID }); if (!t) return null; const { liveSession: n, ...r } = t.config; return { ...t, config: r }; } function resolveSystemAgentCliToolAvailability(e) { if (e?.nativeToolMode === "none") return; if (e?.nativeToolMode === "selectable" && (e.toolAvailabilityEnforcement === "execution-args" && e.resolveExecutionArgs || e.toolAvailabilityEnforcement === "prepare-execution" && e.prepareExecution)) return { native: [], openClaw: [SYSTEM_AGENT_TOOL_NAME] }; const t = e?.id ?? "unknown"; throw new Error(`CLI backend ${t} cannot enforce OpenClaw's exact tool availability`); } /** * CLI harnesses run the openclaw tool in a stdio MCP subprocess, so the * in-process proposalRef/directiveRef cannot be shared with the host. Mirror * the tool's transitions from the harness tool events instead: a denial * registers the exact-operation hash, a mismatch voids it, an executed * mutation consumes it, and directive actions replay the interactive handoff — * same lifecycle as system-agent-tool.ts enforces. */ async function mirrorSystemAgentToolStateFromEvents(e) { const [{ onAgentEventForRun: t }, { extractToolResultText: n }, { resolveSystemAgentProposalTransition: r, resolveSystemAgentDirectiveTransition: i }] = await Promise.all([ import("./agent-events-BEXuCIv5.mjs"), import("./embedded-agent-tool-results-C-a2Oquf.mjs"), import("./system-agent-tool-ClexxBGr.mjs") ]); return t(e.runId, (t) => { if (t.runId !== e.runId || t.stream !== "tool" || t.data.phase !== "result") return; const a = typeof t.data.name === "string" ? t.data.name : ""; if (a !== "openclaw" && !a.endsWith("__openclaw")) return; const o = typeof t.data.args === "object" && t.data.args !== null ? t.data.args : {}; const s = n(t.data.result) ?? ""; const c = r({ args: o, resultText: s }); if (c) { e.proposalRef.current = c.proposal; e.proposalRef.operation = c.operation; } const l = i({ args: o, resultText: s }); if (l && e.directiveRef.current?.kind !== "approved-operation") e.directiveRef.current = l; }); } /** * Run one OpenClaw turn through the embedded agent loop. Route, runner, and * output failures are typed so callers may try another inference path without * mistaking the failure for deterministic setup authority. */ async function runSystemAgentTurn(e) { const t = e.session.verifiedInference; const n = await requireSystemAgentInferenceRoute(t, "agent-turn", () => clearFailedSystemAgentSessionState(e.session)); let r; let i; try { r = resolveSystemAgentExpectedAgentHarnessRuntimeArtifact(t); i = path.join(resolveStateDir(), "openclaw", "workspace"); await fs.mkdir(i, { recursive: true }); } catch (t) { return throwSystemAgentInferenceUnavailable({ session: e.session, failures: [t], guidance: "retry" }); } const a = `openclaw-turn-${randomUUID()}`; const o = e.session.sessionManager ?? SessionManager.inMemory(i); e.session.sessionManager = o; const s = prepareSystemAgentRunAdmission(n.runConfig, a, SYSTEM_AGENT_ID, "system-agent.turn"); const c = buildAgentMainSessionKey({ agentId: SYSTEM_AGENT_ID }); const l = buildSystemAgentSystemPrompt(n.modelTarget === "utility" && !resolveAgentEffectiveModelPrimary(n.sourceConfig, n.agentId) ? n.modelLabel : void 0); const u = { preparedRunAdmission: s, sessionId: e.session.sessionId, sessionKey: toAgentStoreSessionKey({ agentId: SYSTEM_AGENT_ID, requestKey: e.session.sessionId }), agentId: SYSTEM_AGENT_ID, trigger: "manual", sessionFile: `in-memory:${e.session.sessionId}`, sessionManager: o, workspaceDir: i, config: n.runConfig, provider: n.provider, model: n.model, agentDir: n.agentDir, extraSystemPrompt: l, ...n.authProfileId ? { authProfileId: n.authProfileId } : {}, prompt: e.input, userTurnTranscriptRecorder: createSystemAgentUserTurnRecorder(e.input), timeoutMs: resolveAgentTimeoutMs({ cfg: n.runConfig }), thinkLevel: "off", runId: a, messageChannel: "openclaw", messageProvider: "openclaw", terminalReplyExpectation: "result-required", disableTrajectory: true }; const d = {}; const f = { agentId: n.agentId, surface: e.surface, approvalArmed: e.approvalArmed, ...e.operatorApprovalOnly ? { operatorApprovalOnly: true } : {}, proposalRef: e.session.proposalRef, directiveRef: d }; let p = "retry"; try { let i; if (n.runner === "cli") { const t = resolveSystemAgentCliBackend(n); p = "compatible-route"; const r = resolveSystemAgentCliToolAvailability(t); p = "retry"; const o = cliRouteKey(n, t); const s = e.session.cliSession?.routeKey === o ? e.session.cliSession.binding : void 0; if (!s) delete e.session.cliSession; const { runCliAgent: m } = await import("./cli-runner-D5gydz-B.mjs"); const h = await mirrorSystemAgentToolStateFromEvents({ runId: a, proposalRef: e.session.proposalRef, directiveRef: d }); try { i = await m({ ...u, extraSystemPromptStatic: l, systemAgentTool: f, ...r ? { cliToolAvailability: r } : {}, ...s ? { cliSessionBinding: s } : {}, runtimePolicySessionKey: c, disableCliLiveSession: true, cleanupCliLiveSessionOnRunEnd: true }); } finally { h(); } const g = i.meta?.agentMeta; if (g?.clearCliSessionBinding || !g?.cliSessionBinding?.sessionId) delete e.session.cliSession; else e.session.cliSession = { routeKey: o, binding: g.cliSessionBinding }; } else { delete e.session.cliSession; const { runEmbeddedAgent: t } = await import("./embedded-agent-CncWgJKu.mjs"); i = await t({ ...u, lane: "system-agent-inference", toolsAllow: ["openclaw"], toolExecutionAllow: ["openclaw"], systemAgentTool: f, disableMessageTool: true, agentHarnessRuntimeOverride: n.agentHarnessRuntimeOverride, sandboxSessionKey: c, ...r ? { expectedAgentHarnessRuntimeArtifact: r } : {}, ...n.authProfileId ? { authProfileIdSource: "user" } : {} }); } const o = extractAgentRunTerminalError(i); if (o) { p = systemAgentTerminalFailureGuidance(i); throw new Error(o); } p = "route-changed"; if (e.session.verifiedInference !== t) throw new SystemAgentInferenceUnavailableError("agent-turn"); if (!await resolveSystemAgentVerifiedInferenceRoute(t)) throw new SystemAgentInferenceUnavailableError("agent-turn"); p = "retry"; const s = extractAgentRunText(i); if (!s) throw new SystemAgentInferenceUnavailableError("agent-turn"); return { text: s, ...d.current ? { directive: d.current } : {} }; } catch (t) { const n = t instanceof SystemAgentInferenceUnavailableError ? [...t.failures] : [t]; const r = systemAgentRuntimeFailureGuidance(t) ?? p; return throwSystemAgentInferenceUnavailable({ session: e.session, failures: n, guidance: r }); } finally { s.close(); } } //#endregion //#region src/system-agent/chat-wizard-host.ts const log = createSubsystemLogger("system-agent/chat-wizard-host"); const WIZARD_CANCEL_HINT = "Say `cancel` to stop this setup."; const HOSTED_SETUP = { skills: { label: "skills", runtime: "runHostedSkillsSetup", success: ["Done — skills dependency setup is complete."], operation: "skills.setup", summary: "Completed skills dependency setup via chat", capability: "skills" }, search: { label: "web search", runtime: "runHostedSearchSetup", success: ["Done — web search setup is complete.", "Restart the Gateway if the selected provider or plugin changed."], operation: "search.setup", summary: "Configured web search via chat setup", capability: "web-search" }, gateway: { label: "gateway", runtime: "runHostedGatewaySetup", success: ["Done — gateway settings saved.", "Restart the Gateway to apply them (`restart gateway`)."], operation: "gateway.setup", summary: "Configured Gateway via chat setup", capability: "gateway" } }; function formatWizardOptions(e) { return (e.options ?? []).map((e, t) => { const n = e.hint ? ` — ${e.hint}` : ""; return `${t + 1}. ${e.label}${n}`; }); } function wizardStepChatQuestion(e) { if (!e) return; if (e.type === "confirm") { const t = e.initialValue !== false; return { id: e.id, header: e.title ?? "Confirm", question: e.message ?? "Continue?", options: [{ label: "Yes", reply: "yes", ...t ? { recommended: true } : {} }, { label: "No", reply: "no", ...!t ? { recommended: true } : {} }] }; } if (e.type !== "select") return; const t = e.options ?? []; if (t.length < 2 || t.length > 4) return; return { id: e.id, header: e.title ?? "Choose one", question: e.message ?? "Choose one.", options: t.map((t) => { const n = { label: t.label }; if (t.hint) n.description = t.hint; if (e.initialValue !== void 0 && t.value === e.initialValue) n.recommended = true; return n; }) }; } function renderWizardStep(e) { const t = []; if (e.title) t.push(`**${e.title}**`); if (e.message) t.push(e.message); switch (e.type) { case "select": t.push(...formatWizardOptions(e), "Reply with a number."); break; case "multiselect": t.push(...formatWizardOptions(e), "Reply with numbers (e.g. 1,3) or `none`."); break; case "confirm": t.push("Reply yes or no."); break; case "text": if (e.placeholder) t.push(`(e.g. ${e.placeholder})`); t.push("Type your answer."); } return t.filter(Boolean).join("\n"); } function parseWizardAnswer(e, t) { const n = t.trim(); if (e.type === "confirm") { const e = classifySystemAgentApprovalText(n); return e === "approve" ? { value: true } : e === "decline" ? { value: false } : null; } if (e.type === "text") return { value: n }; const r = e.options ?? []; const matchOption = (e) => { if (/^\d+$/.test(e)) { const t = Number(e); if (Number.isSafeInteger(t) && t >= 1 && t <= r.length) return r[t - 1]; } const t = e.toLowerCase(); return r.find((e) => e.label.toLowerCase() === t || typeof e.value === "string" && e.value.toLowerCase() === t); }; if (e.type === "select") { const e = matchOption(n); return e ? { value: e.value } : null; } if (e.type === "multiselect") { if (/^none$/i.test(n)) return { value: [] }; const e = []; for (const t of n.split(/[\s,]+/).filter(Boolean)) { const n = matchOption(t); if (!n) return null; e.push(n.value); } return { value: e }; } return { value: e.type === "action" ? true : void 0 }; } function formatStructuredWizardAnswerForHistory(e, t) { if (e.sensitive === true) return "<redacted secret>"; if (e.type === "text") return [ "string", "number", "boolean", "bigint" ].includes(typeof t) ? String(t) : "<wizard answer>"; if (e.type === "confirm") return typeof t === "boolean" ? t ? "Yes" : "No" : "<wizard answer>"; if (e.type === "select") return e.options?.find((e) => Object.is(e.value, t))?.label ?? "<wizard answer>"; if (e.type === "multiselect") { if (!Array.isArray(t)) return "<wizard answer>"; if (t.length === 0) return "None"; const n = t.map((t) => e.options?.find((e) => Object.is(e.value, t))?.label); return n.every((e) => e !== void 0) ? n.join(", ") : "<wizard answer>"; } return "Continue"; } var SystemAgentWizardAnswerError = class extends Error {}; var ChatWizardHost = class { constructor(e) { this.options = e; this.bridge = null; this.awaitingSetupChannel = false; } get active() { return this.bridge !== null; } get sensitiveInputPending() { return this.bridge?.step?.sensitive === true; } dispose() { this.bridge?.session.cancel(); this.bridge = null; } clearHandoff() { this.awaitingSetupChannel = false; this.lastSensitiveChannel = void 0; } resolveChannelHandoffInput(e) { if (!this.awaitingSetupChannel) return null; if (/^(cancel|abort|stop)$/i.test(e)) { this.awaitingSetupChannel = false; return { text: "Channel wizard handoff cancelled.", action: "none" }; } if (!/^[a-z0-9_-]+$/i.test(e)) return { text: "Reply with one channel id, such as `slack` or `telegram`, or say `cancel`.", action: "none" }; this.awaitingSetupChannel = false; return { kind: "open-setup", target: "channels", channel: e.toLowerCase() }; } openSetup(e) { if (this.options.surface === "gateway") return { text: "Open Settings to change your model or connect a channel. To change providers from a shell, run `openclaw onboard` on the machine running OpenClaw.", action: "none" }; if (![ "channels", "search", "gateway" ].includes(e.target)) return { text: "Setup can replace the inference route powering this session. Exit OpenClaw and run `openclaw onboard`; it saves only a route that passes a live test. Then start OpenClaw again.", action: "none" }; let t = e; if (t.target === "channels" && !t.channel) { if (!this.lastSensitiveChannel) { this.awaitingSetupChannel = true; return { text: "Which channel should I open in the masked terminal wizard?", action: "none" }; } t = { ...t, channel: this.lastSensitiveChannel }; this.lastSensitiveChannel = void 0; } this.awaitingSetupChannel = false; return { text: `Opening the ${t.target === "channels" ? `${t.channel ?? "channel"} setup` : t.target === "search" ? "web search setup" : "Gateway setup"} wizard.`, action: "open-setup", handoff: t }; } decorateReply(e) { const t = this.bridge?.step ?? null; const n = e.text && t && wizardStepAwaitsInput(t) ? { ...e, text: `${e.text}\n${WIZARD_CANCEL_HINT}` } : e; const r = wizardStepChatQuestion(t); const i = t ? sanitizeWizardStepForClient(t) : null; return { ...n, ...t?.sensitive === true ? { sensitive: true } : {}, ...this.bridge ? { wizardInputPending: true } : {}, ...r ? { question: r } : {}, ...i ? { step: i } : {} }; } async answer(e) { const t = this.bridge; const n = t?.step; if (!t || !n) throw new SystemAgentWizardAnswerError("No hosted wizard is awaiting an answer."); if (e.stepId !== n.id) throw new SystemAgentWizardAnswerError("The hosted wizard answer targets a stale step."); const r = await t.session.answer(n.id, e.value); return { ...r ? { text: [r, renderWizardStep(n)].join("\n\n"), configWritten: false } : await this.pump(), userHistoryText: formatStructuredWizardAnswerForHistory(n, e.value) }; } async cancel(e) { const t = this.bridge; const n = t?.step; if (!t || !n) throw new SystemAgentWizardAnswerError("No hosted wizard is awaiting cancellation."); if (e.stepId !== n.id) throw new SystemAgentWizardAnswerError("The hosted wizard cancel targets a stale step."); if (!t.session.cancel()) throw new SystemAgentWizardAnswerError("The hosted wizard cannot be cancelled right now."); return { ...await this.pump(), userHistoryText: "Cancel" }; } async resolveReply(e) { const t = this.bridge; if (!t) return { text: "", configWritten: false }; if (/^(cancel|abort|stop|quit|exit)$/i.test(e.trim())) { t.session.cancel(); return await this.pump(); } const n = t.step; if (!n) return await this.pump(); const r = parseWizardAnswer(n, e); if (!r) return { text: ["I could not match that answer.", renderWizardStep(n)].join("\n"), configWritten: false }; const i = await t.session.answer(n.id, r.value); return i ? { text: [i, renderWizardStep(n)].join("\n\n"), configWritten: false } : await this.pump(); } async startChannel(e) { return await this.start({ kind: "channel", label: e, autoSelectChannel: e, run: async (t, n) => { const beforePersistentApply = async (e) => { n(); await this.options.beforePersistentApply(e); n(); }; return await (await import("./hosted-setup.runtime.js")).runHostedChannelSetup(e, t, beforePersistentApply, void 0, n); } }); } async startSetup(e) { const t = HOSTED_SETUP[e]; const n = await this.start({ kind: e, label: t.label, run: async (e) => await (await import("./hosted-setup.runtime.js"))[t.runtime](e, this.options.beforePersistentApply) }); if (e !== "gateway" || this.options.surface !== "gateway" || !this.bridge) return n; const r = ["Before we start: changing the Gateway port, bind address, or auth credential requires a Gateway restart to apply.", "That restart may disconnect this chat, and you may need to sign in to the Control UI again with the new address or credential."].join(" "); return { ...n, text: [r, n.text].filter(Boolean).join("\n\n") }; } async startMemoryImport() { const e = []; return await this.start({ kind: "memory-import", label: "memory import", memoryImportProviders: e, run: async (t) => await (await import("./hosted-setup.runtime.js")).runHostedMemoryImport(t, this.options.beforePersistentApply, (t) => e.push(t)) }); } async start(e) { this.lastSensitiveChannel = void 0; const t = { status: "applied", ...e.memoryImportProviders ? { memoryImportProviders: e.memoryImportProviders } : {} }; const n = new WizardSession(async (n, r, i) => { await Promise.resolve(); const assertPersistentEffectCurrent = () => { i.assertPersistentEffectCurrent(); if (this.bridge?.session !== i) throw new Error("Setup session is no longer active"); }; const a = await e.run(n, assertPersistentEffectCurrent); if (typeof a === "string") t.status = a; else if (a) t.memoryImport = a; }); this.bridge = { session: n, step: null, kind: e.kind, label: e.label, completion: t, ...e.autoSelectChannel ? { autoSelectChannel: e.autoSelectChannel } : {} }; const r = await this.pump(); if (r.sensitiveChannel) this.lastSensitiveChannel = r.sensitiveChannel; return r; } tryAutoSelect(e) { const t = this.bridge; const n = t?.autoSelectChannel; if (!t || !n || e.type !== "select" && e.type !== "multiselect") return null; const r = (e.options ?? []).find((e) => typeof e.value === "string" && e.value.toLowerCase() === n); if (!r) return null; t.autoSelectChannel = void 0; return { value: e.type === "multiselect" ? [r.value] : r.value }; } async pump() { const e = this.bridge; if (!e) return { text: "", configWritten: false }; const t = await e.session.next(); if (t.done) { this.bridge = null; const n = e.label; if (t.status === "done") { if (e.kind === "memory-import") return { text: await (await import("./hosted-setup.runtime.js")).renderMemoryImport(e.completion.memoryImport), configWritten: false }; if (e.completion.status === "kept-current") return { text: `${n[0]?.toUpperCase() ?? "S"}${n.slice(1)} setup kept the current configuration. Nothing was changed.`, configWritten: false }; await this.auditSetup(e.kind, e.label); return { text: (e.kind === "channel" ? [`Done — ${n} is configured.`, "Say `restart gateway` to apply channel changes, or `channels` to review."] : HOSTED_SETUP[e.kind].success).join("\n"), configWritten: true }; } if (e.kind === "memory-import") await (await import("./hosted-setup.runtime.js")).auditMemoryImport(e.completion.memoryImportProviders ?? []); if (t.status === "cancelled") return { text: `${n[0]?.toUpperCase() ?? "S"}${n.slice(1)} setup cancelled. Nothing was changed beyond completed steps.`, configWritten: false }; return { text: `${n[0]?.toUpperCase() ?? "S"}${n.slice(1)} setup stopped: ${t.error ?? "unknown error"}`, configWritten: false }; } e.step = t.step ?? null; if (e.step) { const t = e.step; const n = this.tryAutoSelect(t); if (!n && this.options.surface === "cli" && t.sensitive === true) { e.session.cancel(); this.bridge = null; return { text: ["Sensitive input is not accepted in the OpenClaw chat because terminal input is visible.", e.kind === "channel" ? `Say \`open channel wizard\` and I'll hand you to the masked terminal wizard for ${e.label}, or run \`openclaw channels add --channel ${e.label}\` yourself later.` : e.kind === "gateway" ? "Say `open gateway wizard` and I'll hand you to the masked terminal wizard, or run `openclaw configure --section gateway` yourself later." : "Say `open search wizard` and I'll hand you to the masked terminal wizard, or run `openclaw configure --section web` yourself later."].join("\n"), configWritten: false, ...e.kind === "channel" ? { sensitiveChannel: e.label } : {} }; } const r = t.type === "note" || t.type === "progress"; if (n || r || t.type === "action" && t.executor !== "client") { e.step = null; await e.session.answer(t.id, n ? n.value : r ? void 0 : true); const i = await this.pump(); return r ? { ...i, text: [renderWizardStep(t), i.text].filter(Boolean).join("\n\n") } : i; } } return { text: e.step ? renderWizardStep(e.step) : "", configWritten: false }; } async auditSetup(e, t) { const n = e === "channel" ? void 0 : HOSTED_SETUP[e]; const r = !n ? { operation: "channels.setup", summary: `Configured channel ${t} via chat setup`, details: { channel: t } } : { operation: n.operation, summary: n.summary, details: { capability: n.capability } }; try { const e = (await import("./system-agent/audit.js")).appendSystemAgentAuditEntry; await e(r); } catch (t) { log.warn(`${e} setup completed without audit entry: ${formatErrorMessage(t)}`); } } }; //#endregion //#region src/system-agent/chat-engine.ts function unavailable(e) { return [`⚠ The write was applied, but post-write verification is unavailable: ${e}.`, "Run `openclaw doctor --fix` on the machine running OpenClaw, then verify the configuration before continuing."].join("\n"); } function createCaptureRuntime() { const e = []; return { log: (...t) => e.push(t.join(" ")), error: (...t) => e.push(t.join(" ")), exit: (e) => { throw new Error(`OpenClaw operation exited with code ${String(e)}`); }, read: () => e.join("\n").trim() }; } var SystemAgentChatEngine = class { constructor(e) { this.options = e; this.history = []; this.pending = null; this.turnQueue = Promise.resolve(); const t = e?.verifiedInference; if (!t) throw new SystemAgentInferenceUnavailableError("conversation"); this.verifiedInference = t; this.agentSession = createSystemAgentSession(t); this.wizard = new ChatWizardHost({ surface: e.surface, beforePersistentApply: async (e) => { await this.requirePersistentApplyInference(e); } }); } propose(e) { this.clearPendingProposals(); this.pending = this.recordCreateAgentRequester(e); return describeSystemAgentPersistentOperation(this.pending); } getPendingOperatorProposal() { const e = resolvePendingOperatorProposal(this.pending, this.agentSession.proposalRef); if (!e) return null; const t = this.recordCreateAgentRequester(e.operation); return t === e.operation ? e : { operation: t, hash: hashSystemAgentOperation(t) }; } async resolveOperatorApproval(e, t, n, r) { return await this.enqueueTurn(async () => { const i = await resolveOperatorApprovalDecision({ decision: e, proposalHash: t, getProposal: () => this.getPendingOperatorProposal(), clear: () => this.clearPendingProposals(), apply: async (e) => { this.proposalResolution = "approved"; return await this.applyApprovedPersistentOperation(e, n); }, denied: () => { this.proposalResolution = "declined"; return { text: "Denied. No change.", action: "none", applied: false }; } }); if (i && r && !i.applied) i.text = SYSTEM_AGENT_APPROVAL_TERMINAL_MESSAGES[r]; if (i && e === "allow-once" && !i.applied) i.text += ` ${SYSTEM_AGENT_APPROVAL_APPLICATION_UNCONFIRMED_TEXT}`; if (i?.text) this.history.push({ role: "assistant", text: i.text }); return i; }); } noteAssistantMessage(e) { this.history.push({ role: "assistant", text: e }); } seedHistory(e) { this.history.push(...e.map((e) => ({ ...e, text: e.role === "user" ? redactSensitiveCommandText(e.text) : e.text }))); } historyLength() { return this.history.length; } historySince(e) { return this.history.slice(e).map((e) => ({ role: e.role, text: e.text })); } async dispose() { this.wizard.dispose(); await cleanupSystemAgentSession(this.agentSession); } /** * Project the live hosted-wizard interaction onto a rejoin reply so a * reconnecting client re-renders the answer controls this session still * awaits; a no-op when no wizard is active. */ decorateRejoinReply(e) { return this.wizard.decorateReply(e); } async handle(e, t) { return await this.enqueueTurn(async () => { await this.requireVerifiedInference(); const n = this.wizard.sensitiveInputPending; const r = await this.resolveTurn(e, t); return this.completeTurn(r, n ? "<redacted secret>" : redactSensitiveCommandText(e)); }); } async answerWizard(e) { return await this.enqueueTurn(async () => { await this.requireVerifiedInference(); const t = await this.wizard.answer(e); return this.completeTurn({ text: await this.finishWizardText(t), action: "none" }, t.userHistoryText); }); } async cancelWizard(e) { return await this.enqueueTurn(async () => { const t = await this.wizard.cancel(e); return this.completeTurn({ text: await this.finishWizardText(t), action: "none" }, t.userHistoryText); }); } enqueueTurn(e) { const t = this.turnQueue.then(e); this.turnQueue = t.catch(() => void 0); return t; } completeTurn(e, t) { const n = this.wizard.decorateReply(e); this.history.push({ role: "user", text: t }); if (n.text) this.history.push({ role: "assistant", text: n.text }); return n; } async loadOverview() { const e = await this.requireVerifiedInference(); const t = await (this.options.deps?.loadOverview ?? loadSystemAgentOverview)({ agentId: e.agentId }); return e.modelTarget === "utility" ? { ...t, setupModel: e.modelLabel } : { ...t, defaultModel: e.modelLabel }; } async planGreeting(e) { const runPlanner = async () => await import("./assistant-ByN5PBz-.mjs").then(({ planSystemAgentGreetingWithConfiguredModel: t }) => t({ ...e, verifiedInference: this.verifiedInference })); const t = this.options.requesterAgentId?.trim(); const n = t && t !== this.verifiedInference.execution.agentId ? await runOutsidePreparedModelRuntimePluginGenerationScope(runPlanner) : await runPlanner(); if (n) await this.requireVerifiedInference(); return n; } async requireVerifiedInference() { const e = this.verifiedInference; if (this.agentSession.verifiedInference !== e) return this.throwInferenceUnavailable(); return await requireSystemAgentInferenceRoute(e, "conversation", (e) => this.throwInferenceUnavailable(e)); } async requirePersistentApplyInference(e) { const t = this.verifiedInference; if (this.agentSession.verifiedInference !== t) return this.throwInferenceUnavailable(); return await requireSystemAgentPersistentApplyInference({ binding: t, runtime: e }, (e) => this.throwInferenceUnavailable(isSystemAgentInferenceUnavailableError(e[0]) ? e[0].failures : e, false)); } rebindVerifiedInference(e) { if (e.execution.agentId !== this.verifiedInference.execution.agentId) return; delete this.agentSession.cliSession; this.verifiedInference = e; this.agentSession.verifiedInference = e; } throwInferenceUnavailable(e = [], t = true) { this.clearPendingProposals(); this.proposalResolution = void 0; this.wizard.clearHandoff(); delete this.agentSession.cliSession; if (t) this.wizard.dispose(); this.history.splice(0); throw new SystemAgentInferenceUnavailableError("conversation", e, "route-changed"); } async verifyConfigAfterWrite() { let e; try { const { readConfigFileSnapshot: t } = await import("./config/config.js"); const n = await t(); if (!n.exists) return unavailable("openclaw.json was not found"); if (n.valid) return null; const r = (n.issues ?? []).map((e) => `${e.path ? `${e.path}: ` : ""}${e.message}`); e = r.length > 0 ? r.join("\n") : "unknown validation failure"; } catch { return unavailable("openclaw.json could not be read"); } return await this.resolveConfigWriteRepair(e, true); } async resolveConfigWriteRepair(e, t = false) { const n = t ? `⚠ openclaw.json failed validation after that write:\n${e}` : `The config write failed; proposing a fix.\n${e}`; let r; try { r = await this.resolveAssistantTurn(`[config-verify] ${t ? "The config file is now invalid" : "The config write failed"}:\n${e}\n${t ? "" : "If the report says the config was written, inspect the current value before correcting it. "}Propose one corrective command from the allowed list.`, false); } catch (e) { if (!isSystemAgentInferenceUnavailableError(e)) throw e; return `${n}\n${t ? "The write was applied, but inference" : "Inference"} could not propose a repair. Run \`openclaw doctor --fix\` on the machine running OpenClaw, then try again.`; } return r.text ? `${n}\n\n${r.text}` : `${n}\nUse \`config schema <path>\` here to check the expected shape. Or, with OpenClaw stopped, run \`openclaw doctor --fix\` on the machine running it.`; } async resolveTurn(e, t) { if (this.wizard.active) { const t = await this.wizard.resolveReply(e); return { text: await this.finishWizardText(t), action: "none" }; } const n = e.trim(); if (!n) return { text: "Tiny claw tap: tell me what you want — setup, repair, channels, anything config.", action: "none" }; if (/^(quit|exit)$/i.test(n)) return { text: "OpenClaw retracts into shell. Bye.", action: "exit" }; const r = this.wizard.resolveChannelHandoffInput(n); if (r) return "kind" in r ? await this.runOperation(r) : r; if (this.options.operatorApprovalOnly && this.getPendingOperatorProposal()) return { text: "Approval pending. Human must decide in OpenClaw UI.", action: "none" }; const i = parseSystemAgentOperation(e); if (isInvalidConfigSetOperation(i)) return { text: i.message, action: "none" }; if (i.kind === "config-set" || i.kind === "config-unset" || i.kind === "config-set-ref" || i.kind === "config-get" || i.kind === "config-schema") return await this.runOperation(i); if (isSystemAgentNavigationOperation(i)) return await this.runOperation(i); const a = this.options.operatorApprovalOnly ? "other" : await this.classifyApprovalIntent(e); if (this.pending) { if (a === "approve") { await this.requireVerifiedInference(); return await this.applyPendingProposal(this.pending); } if (a === "decline") { this.clearPendingProposals(); this.proposalResolution = "declined"; return { text: "Skipped. No barnacles on config today.", action: "none" }; } } if (a === "decline") { this.agentSession.proposalRef.current = void 0; this.agentSession.proposalRef.operation = void 0; } return await this.resolveAssistantTurn(e, this.options.operatorApprovalOnly ? false : a === "approve", t?.uiContext); } async classifyApprovalIntent(e) { if (!(this.pending !== null || this.agentSession.proposalRef.current !== void 0)) return "other"; return await (this.options.classifyApproval ?? (await import("./approval-intent-yTJqgxC2.mjs")).classifySystemAgentApprovalIntent)({ message: e, ...this.pending ? { proposal: describeSystemAgentPersistentOperation(this.pending) } : {}, verifiedInference: this.verifiedInference }); } async applyPendingProposal(e) { this.clearPendingProposals(); this.proposalResolution = "approved"; return await this.applyApprovedPersistentOperation(e); } async applyApprovedPersistentOperation(e, t) { if (!isPersistentSystemAgentOperation(e)) throw new Error("OpenClaw host received a non-persistent approved operation."); const n = createCaptureRuntime(); const r = await this.executeOperation(e, n, t); if ((e.kind === "config-set" || e.kind === "config-unset" || e.kind === "config-set-ref") && r === void 0) return { text: await this.resolveConfigWriteRepair(n.read()), action: "none", applied: false }; const i = r?.applied ? await this.verifyConfigAfterWrite() : null; const a = [n.read() || "Applied. Audit entry written.", i].filter(Boolean).join("\n\n"); if ((e.kind === "setup" || e.kind === "create-agent") && r?.applied && r.bootstrapPending === true && i === null) { const t = getRegularAgentSetupNotice(await this.loadOverview(), r.agentId); if (t) return { text: `${a}\n\n${t}`, action: "none", applied: true }; return { text: [a, `Your agent is hatching — handing you over now. ${this.agentHandoffReturnHint()}`].join("\n\n"), action: "open-tui", applied: true, agentDraft: "hatch", handoff: { kind: "open-tui", agentDraft: "hatch", ...e.workspace ? { workspace: e.workspace } : {}, ...r.agentId ? { agentId: r.agentId } : {} } }; } return { text: a, action: "none", applied: r?.applied === true }; } async resolveAssistantTurn(e, t, n) { await this.requireVerifiedInference(); const r = this.options.runAgentTurn ?? runSystemAgentTurn; const i = formatSystemAgentTurnInput(e, this.pending, this.proposalResolution, n); const runTurn = () => r({ input: i, surface: this.options.surface ?? "cli", approvalArmed: t, ...this.options.operatorApprovalOnly ? { operatorApprovalOnly: true } : {}, session: this.agentSession }); const a = this.options.requesterAgentId?.trim(); const o = a && a !== this.agentSession.verifiedInference.execution.agentId ? await runOutsidePreparedModelRuntimePluginGenerationScope(runTurn) : await runTurn(); if (!o?.text) throw new SystemAgentInferenceUnavailableError("agent-turn"); this.proposalResolution = void 0; if (o.directive) this.clearPendingProposals(); else if (this.agentSession.proposalRef.current !== void 0) this.pending = null; return await this.applyAgentTurnReply(o); } async applyAgentTurnReply(e) { await this.requireVerifiedInference(); const t = e.directive; if (!t) return { text: e.text, action: "none" }; const n = t.kind === "approved-operation" ? await this.applyApprovedPersistentOperation(t.operation) : await this.runOperation(t); return { ...n, text: t.kind === "open-tui" && n.action === "open-tui" ? e.text : [e.text, n.text].filter(Boolean).join("\n\n") }; } async runOperation(e) { const t = this.recordCreateAgentRequester(e); await this.requireVerifiedInference(); if (this.options.operatorApprovalOnly && isSystemAgentNavigationOperation(t)) return { text: SYSTEM_AGENT_OPERATOR_NAVIGATION_HANDOFF, action: "none" }; if (t.kind === "open-tui") { this.clearPendingProposals(); const e = await this.loadOverview(); const n = getRegularAgentSetupNotice(e, resolveTuiAgentId({ requestedAgentId: t.agentId, requestedWorkspace: t.workspace, overview: e })); if (n) return { text: n, action: "none" }; return { text: `Opening a chat with your agent. ${this.agentHandoffReturnHint()}`, action: "open-tui", handoff: t }; } if (t.kind === "model-accounts") { this.clearPendingProposals(); return { text: this.options.surface === "gateway" ? "Opening Settings → Profile → Connected accounts. Check the Gateway, person, and Personal scope, then sign in or select a saved account. Nothing has changed yet." : "Run `openclaw models accounts list` to see your personal accounts, or `openclaw models accounts login <provider>` for protected sign-in. Check the Gateway and person shown before signing in. You can also use Settings → Profile → Connected accounts in the Control UI. Nothing has changed.", action: "none", ...this.options.surface === "gateway" ? { handoff: t } : {} }; } if (t.kind === "open-setup") { this.clearPendingProposals(); return this.wizard.openSetup(t); } if (t.kind === "channel-setup") return await this.startWizard(this.wizard.startChannel(t.channel)); if (t.kind === "skills-setup") return await this.startWizard(this.wizard.startSetup("skills")); if (t.kind === "search-setup") return await this.startWizard(this.wizard.startSetup("search")); if (t.kind === "gateway-config-setup") return await this.startWizard(this.wizard.startSetup("gateway")); if (t.kind === "memory-import") return await this.startWizard(this.wizard.startMemoryImport()); if (t.kind === "model-setup") return this.startModelSetup(); const n = createCaptureRuntime(); if (isPersistentSystemAgentOperation(t) && !this.options.yes) { this.clearPendingProposals(); await executeSystemAgentOperation(t, n, { approved: false, operatorApprovalOnly: this.options.operatorApprovalOnly, deps: this.commandDeps() }); this.pending = t; return { text: [n.read(), this.options.operatorApprovalOnly ? void 0 : approvalQuestion(t)].filter(Boolean).join("\n\n"), action: "none" }; } if (isPersistentSystemAgentOperation(t)) return await this.applyApprovedPersistentOperation(t); const r = await this.executeOperation(t, n); const i = n.read(); if (r?.exitsInteractive === true) return { text: i, action: "exit" }; return { text: i, action: "none" }; } async executeOperation(e, t, n) { try { await this.requirePersistentApplyInference(t); return await executeSystemAgentOperation(e, t, { approved: true, ...this.options.requesterAgentId ? { requesterAgentId: this.options.requesterAgentId } : {}, deps: this.commandDeps(), beforePersistentApply: n, onVerifiedInferenceChanged: (e) => this.rebindVerifiedInference(e) }); } catch (e) { if (isSystemAgentInferenceUnavailableError(e)) throw e; if (!(e instanceof SystemAgentOperationExitError)) { const n = e instanceof Error ? e.message : String(e); t.error(`That did not go through: ${n}`); } return; } } async startWizard(e) { this.clearPendingProposals(); const t = await e; return { text: await this.finishWizardText(t), action: "none" }; } async finishWizardText(e) { const t = e.configWritten ? await this.verifyConfigAfterWrite() : null; return [e.text, t].filter(Boolean).join("\n"); } async startModelSetup() { this.clearPendingProposals(); const e = createCaptureRuntime(); await executeSystemAgentOperation({ kind: "model-setup" }, e); return { text: e.read(), action: "none" }; } commandDeps() { return { ...this.options.deps, loadOverview: async () => await this.loadOverview(), ...this.options.surface ? { setupSurface: this.options.surface } : {} }; } agentHandoffReturnHint() { return this.options.surface === "gateway" ? "You can return through Settings → Ask OpenClaw." : "Use /openclaw to come back."; } clearPendingProposals() { this.pending = null; this.agentSession.proposalRef.current = void 0; this.agentSession.proposalRef.operation = void 0; } recordCreateAgentRequester(e) { const t = this.options.requesterAgentId?.trim(); if (e.kind !== "create-agent" || !t || e.requesterAgentId === t) return e; return { ...e, requesterAgentId: t }; } }; //#endregion //#region src/system-agent/onboarding-welcome.ts /** * The basic bootstrap is conversational: the welcome message carries the plan * and the engine holds it as the pending proposal, so a bare "yes" applies it. * This path starts only after a live inference turn. Already-configured * installs get the channels/handoff guide instead. */ async function buildOnboardingWelcome(e) { const t = createSetupTranslator({ keyPrefix: "wizard.onboardingWelcome", locale: e.locale === void 0 ? void 0 : resolveWizardLocale(e.locale) }); const n = await e.engine.loadOverview(); /** * "Configured" must match the app onboarding gate (wizard metadata or gateway * auth), not just a model: a model-only config would otherwise get the * ready-guide welcome while the gate stays locked, stranding the page. */ let r; if (n.config.exists && n.config.valid) try { const { readConfigFileSnapshot: e } = await import("./config/config.js"); const t = await e(); r = t.sourceConfig ?? t.config ?? {}; } catch {} const i = r?.gateway?.auth; const a = normalizeSecretInputString(i?.mode) !== void 0; const o = isSecretRef(i?.token) || normalizeSecretInputString(i?.token) !== void 0 || isSecretRef(i?.password) || normalizeSecretInputString(i?.password) !== void 0; const s = r?.wizard !== void 0 && Object.keys(r.wizard).length > 0 || a || o; const c = e.localRecovery === true && n.config.exists && n.config.valid && r !== void 0 && r?.gateway?.mode !== "remote" ? await (await import("./state/local-onboarding-state.js")).readLocalOnboardingStateForConfigAsync(n.config.path, r) : void 0; const l = c?.status === "pending" ? c : void 0; const u = (n.defaultModel ?? n.setupModel)?.trim(); const d = e.workspace?.trim() ? resolveUserPath(e.workspace.trim()) : void 0; const f = r?.agents?.defaults?.workspace?.trim() ? resolveUserPath(r.agents.defaults.workspace.trim()) : void 0; if (s && !l && u && (!d || d === f)) { const { formatSystemAgentOnboardingWelcome: r } = await import("./overview-DQm7SK5E.mjs"); const i = r(n, t); e.engine.noteAssistantMessage(i); return { text: i, question: { id: "onboarding-next-step", header: t("nextStep"), question: t("firstAction"), options: [ { label: t("talkToAgent"), reply: "talk to agent", recommended: true, description: t("meetAgent") }, { label: t("connectWhatsApp"), reply: "connect whatsapp" }, { label: t("connectTelegram"), reply: "connect telegram" }, { label: t("allChannels"), reply: "channels" } ], isOther: true, skipAction: "exit" } }; } if (!u) throw new Error("OpenClaw onboarding requires working inference first. Run `openclaw onboard` on the machine running OpenClaw to configure and verify a default model."); const p = resolveUserPath(l?.workspace || d || f || (await import("./onboard-helpers-Cy-Vj-Pl.mjs")).DEFAULT_WORKSPACE); e.engine.propose({ kind: "setup", workspace: p, ...e.agentName ? { agentName: e.agentName } : {} }); const m = [ `## ${t(n.defaultModel ? "hatchIntro" : "setupIntro")}`, "", t("machineIntro"), "", `- ${t(n.defaultModel ? "verifiedAi" : "verifiedSetupAi", { model: u })}`, `- ${t("workspace", { workspace: shortenHomePath(p) })}`, `- ${t("localGateway")}`, "", t("applyPrompt"), "", t("security"), t(n.defaultModel ? "afterSetup" : "setupModelNext") ].join("\n"); e.engine.noteAssistantMessage(m); return { text: m, question: { id: "onboarding-apply-setup", header: t("readyWhenYouAre"), question: t("applyQuestion"), options: [{ label: t("applyYes"), reply: "yes", recommended: true }, { label: t("inspectChanges"), reply: "what exactly will you set up?", description: t("askBeforeWriting") }], isOther: true } }; } //#endregion export { SystemAgentChatEngine as n, SystemAgentWizardAnswerError as r, buildOnboardingWelcome as t };