UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

397 lines (396 loc) • 15.9 kB
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { o as writeRuntimeJson, r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import { a as displayPath } from "./utils-C8YECn2Q.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { n as listAgentEntries } from "./agent-roster-t1ooUdXp.mjs"; import { A as tryResolveLegacyCompatibilityAgentId, a as resolveAgentDir, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { b as resolveAuthProfileDatabasePath } from "./sqlite-B2CoJ4Om.mjs"; import { t as resolveSharedMainAuthAgentDir } from "./shared-main-dir-C2ynhf4g.mjs"; import { t as applyAgentConfig } from "./agents.config-T4w0h7rr.mjs"; import { x as buildPortableAuthProfileStoreForAgentCopy } from "./store-Bh2lUvOT.mjs"; import { n as prepareAgentAuthProfileRowsRead, t as loadPersistedAuthProfileStoreFromRows } from "./sqlite-read-CREbuXqx.mjs"; import { o as withPluginLifecycleLease } from "./plugin-lifecycle-lease-CXjHGDEI.mjs"; import { g as loadAuthProfileStoreWithoutExternalProfilesAsync } from "./store-runtime-dW0pXLJI.mjs"; import { n as WizardCancelledError } from "./prompts-CCXo2K24.mjs"; import { d as throwExpectedCliError } from "./failure-output-DVVDqwuu.mjs"; import { n as loadAgentRole } from "./agent-roles-BJUCg-FF.mjs"; import { o as transformConfigWithPendingPluginInstalls, t as commitConfigWithPendingPluginInstalls } from "./install-record-commit-BBhtfevs.mjs"; import { t as runWithLocalStateOwner } from "./local-state-owner-DTl7OHpC.mjs"; import "./auth-profiles-VRLhewIH.mjs"; import { a as ensureOnboardingAgentWorkspace, c as resolveOnboardingAgentTarget, r as applyOnboardingUtilityModel } from "./onboard-agent-target-D7VNwjZB.mjs"; import { n as buildChannelBindings, t as applyAgentBindings } from "./agents.bindings-Cz76H01e.mjs"; import { n as createAgent, r as validateAgentIdInput, t as checkAgentCreationGate } from "./agent-create-l2Gq2JQH.mjs"; import { r as isTerminalInteractive } from "./terminal-interactivity-B_L_vZTP.mjs"; import { r as stageProviderAuthProfileBatch } from "./provider-auth-persistence-qfBTNlSU.mjs"; import { t as createClackPrompter } from "./clack-prompter-oqVcatgQ.mjs"; import { r as logConfigUpdated } from "./logging-D0RirHBi.mjs"; import { r as requireValidConfigForWrite } from "./config-validation-Cy6dkTWs.mjs"; import { i as setupChannels, n as createChannelSetupHooks } from "./channel-setup-CreFIC7D.mjs"; import { n as describeBindingConflict, t as describeBinding } from "./agents.binding-format-DRkepwQw.mjs"; import { n as promptAuthChoiceGrouped } from "./auth-choice-prompt-CxeMwsLJ.mjs"; import { n as prepareAuthChoice } from "./auth-choice.apply-DYJ_v1UI.mjs"; import { r as warnIfModelConfigLooksOff } from "./auth-choice.model-check-CkhG2JaT.mjs"; import path from "node:path"; //#region src/commands/agents.commands.add.ts async function loadReadablePersistedAuthProfileStore(e, t) { const n = resolveAuthProfileDatabasePath(e); const r = await prepareAgentAuthProfileRowsRead({ databasePath: n, agentId: t, env: process.env, source: "canonical" }); try { return loadPersistedAuthProfileStoreFromRows(await r.read(), n); } finally { await r.dispose(); } } function formatSkippedOAuthProfilesMessage(e, t) { return t ? terminalText`OAuth profiles stay shared from "${e}" unless this agent signs in separately.` : terminalText`OAuth profiles were not copied from "${e}"; sign in separately for this agent.`; } async function agentsAddCommand(e, t) { if (e.role !== void 0) try { await loadAgentRole(e.role); } catch (e) { throwExpectedCliError(e instanceof Error ? e.message : String(e)); } const n = t?.hasAutomationFlags === true; const r = e.nonInteractive === true || n; const i = e.json ? process.stderr : process.stdout; if (!r && !isTerminalInteractive(i)) throwExpectedCliError(`Agent creation needs an interactive TTY. Use \`${formatCliCommand("openclaw agents add <id> --non-interactive --workspace <dir>")}\` for automation.`); const a = e.workspace?.trim(); const o = e.name?.trim(); if (r) { if (!a && !e.role) throwExpectedCliError(`Non-interactive agent creation requires --workspace. Re-run ${formatCliCommand("openclaw agents add <id> --workspace <path>")} or omit flags to use the wizard.`); if (!o) throwExpectedCliError(`Agent name is required in non-interactive mode. Run ${formatCliCommand("openclaw agents add <id> --workspace <path>")}.`); const t = validateAgentIdInput(o); if (!t.ok) throwExpectedCliError(t.reason === "reserved-id" ? `"${t.agentId}" is reserved. Choose another name, or run ${formatCliCommand("openclaw agents list")} to inspect configured agents.` : t.message); const n = t.agentId; if (!e.json && n !== o) defaultRuntime.log(terminalText`Normalized agent id to "${n}".`); const r = await runWithLocalStateOwner({ method: "agents.create", params: { name: o, workspace: a, ...e.model ? { model: e.model } : {} }, target: n, recoveryCommand: "openclaw agents list", ...e.role || e.agentDir || e.bind?.length ? { onForeignOwner: "refuse" } : {}, runLocal: ({ assertCurrent: t }) => withPluginLifecycleLease({}, async () => { const n = await createAgent({ name: o, workspace: a, ...e.role ? { role: e.role } : {}, ...e.agentDir ? { agentDir: e.agentDir } : {}, ...e.model ? { model: e.model } : {}, ...e.bind?.length ? { bindingSpecs: e.bind } : {}, transformConfig: transformConfigWithPendingPluginInstalls, beforePersistentApply: t }); if (n.status === "error") throwExpectedCliError(n.reason === "reserved-id" ? `"${n.agentId}" is reserved. Choose another name, or run ${formatCliCommand("openclaw agents list")} to inspect configured agents.` : n.message); return n; }) }); const { added: i = [], updated: s = [], skipped: c = [], conflicts: l = [] } = r.bindingResult ?? {}; if (!e.json) logConfigUpdated(defaultRuntime); const u = { agentId: r.agentId, name: r.name, workspace: r.workspace, agentDir: r.agentDir, model: r.model, bindings: { added: i.map(describeBinding), updated: s.map(describeBinding), skipped: c.map(describeBinding), conflicts: l.map(describeBindingConflict) } }; if (e.json) writeRuntimeJson(defaultRuntime, u); else { defaultRuntime.log(terminalText`Agent: ${n}`); defaultRuntime.log(`Workspace: ${displayPath(r.workspace)}`); defaultRuntime.log(`Agent dir: ${displayPath(r.agentDir)}`); if (r.model) defaultRuntime.log(terminalText`Model: ${r.model}`); if (l.length > 0) defaultRuntime.error(["Skipped bindings already claimed by another agent:", ...u.bindings.conflicts.map((e) => terminalText`- ${e}`)].join("\n")); } if (l.length > 0) defaultRuntime.exit(1); return; } await runWithLocalStateOwner({ method: "agents.setup", params: {}, target: o ?? "interactive agent setup", onForeignOwner: "refuse", runLocal: () => runInteractiveAgentsAdd(e, i) }); } async function runInteractiveAgentsAdd(e, t) { const n = await requireValidConfigForWrite(defaultRuntime); if (!n) return; const r = n.snapshot.sourceConfig; const i = e.name?.trim(); const a = createClackPrompter(t); const o = e.json ? { ...defaultRuntime, log: (...e) => defaultRuntime.error(...e) } : defaultRuntime; try { await a.intro("Add OpenClaw agent"); const t = i ?? await a.text({ message: "Agent name", validate: (e) => { if (!e?.trim()) return "Required"; const t = validateAgentIdInput(e); if (!t.ok) return t.reason === "reserved-id" ? terminalText`"${t.agentId}" is reserved. Choose another name.` : terminalText`${t.message}`; } }); const s = normalizeOptionalString(t) ?? ""; const c = validateAgentIdInput(s); if (!c.ok) { if (c.reason === "reserved-id") { await a.outro(terminalText`"${c.agentId}" is reserved. Choose another name.`); return; } await a.outro(terminalText`${c.message}`); return; } const l = c.agentId; if (s !== l) await a.note(terminalText`Normalized id to "${l}".`, "Agent id"); const u = listAgentEntries(r).find((e) => normalizeAgentId(e.id) === l); if (u) { if (e.role) throwExpectedCliError(`Agent "${l}" already exists. Choose a new id to create an agent from a role.`); if (!await a.confirm({ message: terminalText`Agent "${l}" already exists. Update it?`, initialValue: false })) { await a.outro("No changes made."); return; } } else { const e = await checkAgentCreationGate(l); if (e) { await a.outro(terminalText`${e.message}`); return; } } const d = resolveAgentWorkspaceDir(r, l); const f = await a.text({ message: "Workspace directory", initialValue: d, validate: (e) => e?.trim() ? void 0 : "Required" }); const p = resolveUserPath(normalizeOptionalString(f) || d); const m = resolveAgentDir(r, l); let h = applyAgentConfig(r, { agentId: l, name: s, workspace: p, agentDir: m }); const g = []; let _; let reportPortableAuthCopy; const v = tryResolveLegacyCompatibilityAgentId(r) ?? await a.select({ message: "Copy auth profiles from another agent?", initialValue: "__skip__", options: [{ value: "__skip__", label: "Skip copying auth profiles" }, ...listAgentEntries(r).map((e) => normalizeAgentId(e.id)).filter((e) => e !== l).map((e) => ({ value: e, label: terminalText`${e}` }))] }); if (v !== "__skip__" && v !== l) { const e = resolveAgentDir(r, v); const t = resolveAuthProfileDatabasePath(e); const n = resolveAuthProfileDatabasePath(m); const i = resolveAuthProfileDatabasePath(resolveSharedMainAuthAgentDir()); const o = normalizeLowercaseStringOrEmpty(path.resolve(t)) === normalizeLowercaseStringOrEmpty(path.resolve(n)); const s = normalizeLowercaseStringOrEmpty(path.resolve(t)) === normalizeLowercaseStringOrEmpty(path.resolve(i)); if (!o) { const t = s ? await loadAuthProfileStoreWithoutExternalProfilesAsync(e) : await loadReadablePersistedAuthProfileStore(e, v); const n = await loadReadablePersistedAuthProfileStore(m, l); const r = t ? buildPortableAuthProfileStoreForAgentCopy(t) : void 0; const i = t && r ? r.skippedProfileIds.some((e) => t.profiles[e]?.type === "oauth") : false; if (t && r && r.copiedProfileIds.length > 0 && Object.keys(n?.profiles ?? {}).length === 0) { if (await a.confirm({ message: terminalText`Copy portable auth profiles from "${v}"?`, initialValue: false })) { const e = r.copiedProfileIds; const n = e.filter((e) => t.profiles[e]?.type === "oauth"); for (const [e, t] of Object.entries(r.store.profiles)) g.push({ profileId: e, credential: t, replaceExisting: false }); _ = r.store.order; reportPortableAuthCopy = async () => { const t = await loadReadablePersistedAuthProfileStore(m, l); const r = new Set(Object.keys(t?.profiles ?? {})); const o = e.filter((e) => r.has(e)).length; const c = i || n.some((e) => !r.has(e)); const u = o ? terminalText`Copied ${o} portable auth profile${o === 1 ? "" : "s"} from "${v}".` : ""; const d = c ? ` ${formatSkippedOAuthProfilesMessage(v, s)}` : ""; await a.note(`${u}${d}`.trim(), "Auth profiles"); }; } } else if (i) reportPortableAuthCopy = async () => { await a.note(formatSkippedOAuthProfilesMessage(v, s), "Auth profiles"); }; } } if (await a.confirm({ message: "Configure model/auth for this agent now?", initialValue: false })) while (true) { const e = await promptAuthChoiceGrouped({ prompter: a, includeSkip: true, config: h }); const t = await prepareAuthChoice({ authChoice: e, config: h, prompter: a, runtime: o, agentDir: m, setDefaultModel: false, agentId: l }); h = t.config; if (t.retrySelection) continue; g.push(...t.authProfiles); if (t.utilityModelOverride) h = applyOnboardingUtilityModel(h, resolveOnboardingAgentTarget(h, l), t.utilityModelOverride); if (t.agentModelOverride) h = applyAgentConfig(h, { agentId: l, model: t.agentModelOverride }); break; } await warnIfModelConfigLooksOff(h, a, { agentId: l, agentDir: m, pendingAuthProfiles: g.map(({ profileId: e, credential: t }) => ({ profileId: e, credential: t })) }); const y = createChannelSetupHooks({ runtime: o }); let b = []; const x = {}; h = await setupChannels(h, o, a, { workspaceDir: p, deferStatusUntilSelection: true, allowIMessageInstall: true, allowSignalInstall: true, onSelection: (e) => { b = e; }, promptAccountIds: true, onAccountId: (e, t) => { x[e] = t; }, onPostWriteHook: y.onPostWriteHook }); if (b.length > 0) { if (await a.confirm({ message: "Route selected channels to this agent now? (bindings)", initialValue: false })) { const e = buildChannelBindings({ agentId: l, selection: b, config: h, accountIds: x }); const t = applyAgentBindings(h, e); h = t.config; if (t.conflicts.length > 0) await a.note(["Skipped bindings already claimed by another agent:", ...t.conflicts.map((e) => terminalText`- ${describeBindingConflict(e)}`)].join("\n"), "Routing bindings"); } else await a.note(["Routing unchanged. Add bindings when you're ready.", "Docs: https://docs.openclaw.ai/concepts/multi-agent"].join("\n"), "Routing"); } const S = u ? void 0 : listAgentEntries(h).find((e) => normalizeAgentId(e.id) === l); const C = g.length > 0 ? { profiles: g, ..._ ? { order: _ } : {}, agentDir: m, config: h } : void 0; let w; if (u) { const e = resolveOnboardingAgentTarget(h, l); await ensureOnboardingAgentWorkspace(e, o, { skipBootstrap: Boolean(h.agents?.defaults?.skipBootstrap), skipOptionalBootstrapFiles: h.agents?.defaults?.skipOptionalBootstrapFiles }); const t = C ? await stageProviderAuthProfileBatch(C) : void 0; try { const e = await commitConfigWithPendingPluginInstalls({ sourceConfig: h, writeOptions: n.writeOptions, baseHash: n.snapshot.hash }); await y.runPostWriteHooks(e.path); } catch (e) { await t?.rollback(); throw e; } await t?.commit(); w = { agentId: e.agentId, name: s, workspace: e.workspaceDir, agentDir: e.agentDir }; } else { if (!S) throw new Error(`staged agent "${l}" is missing from config`); const t = await withPluginLifecycleLease({}, async () => { return await createAgent({ entry: { ...S, id: l }, ...e.role ? { role: e.role } : {}, stagedConfig: { config: h, writeSnapshot: n }, transformConfig: transformConfigWithPendingPluginInstalls, ...C ? { prepareConfigCommit: async () => await stageProviderAuthProfileBatch(C) } : {} }); }); if (t.status === "error") { await a.outro(terminalText`${t.message}`); return; } w = { agentId: t.agentId, name: t.name, workspace: t.workspace, agentDir: t.agentDir }; await y.runPostWriteHooks(t.configPath); } await reportPortableAuthCopy?.(); if (!e.json) logConfigUpdated(defaultRuntime); if (e.json) writeRuntimeJson(defaultRuntime, w); await a.outro(terminalText`Agent "${l}" ready.`); } catch (e) { if (e instanceof WizardCancelledError) { defaultRuntime.exit(1); return; } throw e; } } //#endregion export { agentsAddCommand };