UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

347 lines (346 loc) • 15.4 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { d as isUserModelAuthProfileId } from "./user-model-account-authority-CRj924IP.mjs"; import { i as resolveProviderIdForAuth } from "./provider-auth-aliases-CgGlzANu.mjs"; import { o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs"; import { c as createOperatorModelSelectionAssertion, r as assertOperatorModelAllowed } from "./admitted-run-context-D3Jvk_f_.mjs"; import { a as isInternalMessageChannel } from "./message-channel-DTYVLJT1.mjs"; import { d as sessionSnapshotChangesApplied, o as SESSION_MODEL_OVERRIDE_TRANSACTION_FIELDS, s as adoptPersistedSessionSnapshot, u as sessionModelOverrideChangesApplied } from "./session-entry-patch-operation--iew--8y.mjs"; import { i as resolveOperatorModelDefault } from "./operator-model-policy-BoEHyFtN.mjs"; import { n as createModelVisibilityPolicy } from "./model-visibility-policy-CH4gPfvH.mjs"; import { i as ensureAuthProfileStoreAsync, l as findPersistedAuthProfileCredentialAsync } from "./store-runtime-dW0pXLJI.mjs"; import { a as prepareUserModelAccountAuthority } from "./user-model-account-operations-DmkXXwRf.mjs"; import { n as resolveModelDirectiveSelection } from "./model-selection-directive-FdMmemOH.mjs"; import "./model-selection-B0_L0UXS.mjs"; import { t as persistReplySessionEntry } from "./session-entry-persistence-DCzsfK4-.mjs"; //#region src/auto-reply/reply/directive-handling.arguments.ts function resolveInvalidExecDirectiveMessage(e) { return e.invalidExecHost ? `Unrecognized exec host "${e.rawExecHost ?? ""}". Valid hosts: auto, sandbox, gateway, node.` : e.invalidExecSecurity ? `Unrecognized exec security "${e.rawExecSecurity ?? ""}". Valid: deny, allowlist, full.` : e.invalidExecAsk ? `Unrecognized exec ask "${e.rawExecAsk ?? ""}". Valid: off, on-miss, always.` : e.invalidExecNode ? "Exec node requires a value." : void 0; } /** Rejects prose left over after canonical command-specific validation succeeds. */ function maybeHandleUnexpectedDirectiveArguments(e) { const t = e.command; const n = t?.unconsumedArguments; if (!t || !n) return; return { text: `Unexpected argument "${n.trimStart().split(/\s+/, 1)[0] ?? n}" for /${t.name}.` }; } //#endregion //#region src/auto-reply/reply/directive-handling.model-selection.ts function validateOperatorSelection(e, t) { try { assertOperatorModelAllowed(e, t); return; } catch (e) { return formatErrorMessage(e); } } async function resolveStoredNumericProfileModelDirective(e, t) { const n = e.lastIndexOf("/"); const r = e.indexOf("@", n + 1); if (r <= 0) return null; const i = e.slice(r + 1).trim(); if (!/^\d{8}$/.test(i)) return null; const a = e.slice(0, r).trim(); const o = (await ensureAuthProfileStoreAsync(t, { allowKeychainPrompt: false })).profiles[i]; return o ? { modelRaw: a, profileId: i, profileProvider: o.provider } : null; } /** Resolves the requested model/profile override from parsed inline directives. */ async function resolveModelSelectionFromDirective(e) { if (!e.directives.hasModelDirective || !e.directives.rawModelDirective) { if (e.directives.rawModelProfile) return { errorText: "Auth profile override requires a model selection." }; return {}; } const t = e.directives.rawModelDirective.trim(); if (/^default$/i.test(t)) { const t = e.modelPolicy ?? createModelVisibilityPolicy({ cfg: e.cfg, agentId: e.agentId, catalog: [], defaultProvider: e.defaultProvider, defaultModel: e.defaultModel }); const n = resolveOperatorModelDefault({ cfg: e.cfg, agentId: e.agentId, policy: e.operatorAuthority?.modelPolicy, model: { provider: e.defaultProvider, model: e.defaultModel }, allows: t.allows }); const r = validateOperatorSelection(e.operatorAuthority, n); if (r) return { errorText: r }; if (!n) return { errorText: "No model is available for this operator role and agent." }; return { modelSelection: { ...n, isDefault: true, resetToDefault: true }, validateModelSelection: () => validateOperatorSelection(e.operatorAuthority, n), modelSelectionSource: createOperatorModelSelectionAssertion(e.operatorAuthority, n) }; } const n = e.directives.rawModelProfile === void 0 ? await resolveStoredNumericProfileModelDirective(t, e.agentDir) : null; const resolveSelection = (t) => resolveModelDirectiveSelection({ raw: t, defaultProvider: e.defaultProvider, defaultModel: e.defaultModel, aliasIndex: e.aliasIndex, allowedModelKeys: e.allowedModelKeys, modelPolicy: e.modelPolicy, operatorModelPolicy: e.operatorAuthority?.modelPolicy, cfg: e.cfg, agentId: e.agentId, rawRuntime: e.directives.rawModelRuntime }); const r = n ? resolveSelection(n.modelRaw) : null; const i = Boolean(r?.selection) && resolveProviderIdForAuth(r?.selection?.provider ?? "", { config: e.cfg }) === resolveProviderIdForAuth(n?.profileProvider ?? "", { config: e.cfg, storedCredential: true }); if (/^[0-9]+$/.test(t)) return { errorText: [ "Numeric model selection is not supported in chat.", "", "Browse: /models or /models <provider>", "Switch: /model <provider/model>" ].join("\n") }; const a = i && r ? r : resolveSelection(t); if (a.error) return { errorText: a.error }; const o = a.selection; if (o) { const t = validateOperatorSelection(e.operatorAuthority, o); if (t) return { errorText: t }; } let s; let c; const l = e.directives.rawModelProfile ?? (i ? n?.profileId : void 0); if (o && l) { const t = o.provider; const n = e.agentDir; const r = e.requesterProfileId; const i = normalizeOptionalString(l); if (i) { let e; if (isUserModelAuthProfileId(i)) { const t = r ? await prepareUserModelAccountAuthority({ profileId: r, authProfileId: i }) : void 0; const n = "Select a personal model account connected to your signed-in profile."; if (!t) return { errorText: n }; const validateSelection = () => t.isCurrent() ? void 0 : n; const a = validateSelection(); if (a) return { errorText: a }; e = t.provider; c = validateSelection; } else { const t = await findPersistedAuthProfileCredentialAsync({ agentDir: n, profileId: i }) ?? (await ensureAuthProfileStoreAsync(n, { allowKeychainPrompt: false })).profiles[i]; if (!t) return { errorText: `Auth profile "${i}" not found.` }; e = t.provider; } if (e !== t) return { errorText: `Auth profile "${i}" is for ${e}, not ${t}.` }; s = i; } } return { modelSelection: o, profileOverride: s, ...c ? { validateAuthProfileSelection: c } : {}, ...o ? { validateModelSelection: () => validateOperatorSelection(e.operatorAuthority, o) ?? c?.(), modelSelectionSource: composeSessionSourceAssertion([createOperatorModelSelectionAssertion(e.operatorAuthority, o)], (e) => { e(); const t = c?.(); if (t) throw new Error(t); }) } : {} }; } //#endregion //#region src/auto-reply/reply/directive-handling.shared.ts const DIRECTIVE_ACK_MESSAGES = { verbose: { off: "Verbose logging disabled.", on: "Verbose logging enabled.", full: "Verbose logging set to full." }, trace: { off: "Trace disabled.", on: "Trace enabled. Warning: trace output may contain sensitive information.", raw: "Trace set to raw. Warning: trace output may contain sensitive information." }, reasoning: { off: "Reasoning visibility disabled.", on: "Reasoning visibility enabled.", stream: "Reasoning stream enabled." }, elevated: { off: "Elevated mode disabled.", on: "Elevated mode set to ask (approvals may still apply).", ask: "Elevated mode set to ask (approvals may still apply).", full: "Elevated mode set to full (auto-approve)." } }; const withOptions = (e, t) => `${e}\nOptions: ${t}.`; function formatModelSelectionScopeAck(e) { const { provider: t, model: n, alias: r, isDefault: i } = e.selection; const a = `${t}/${n}`; const o = r ? `${r} (${a})` : a; if (i && !e.stickyModelSelectionTarget) return `Session model reset to configured default (${o}).`; const s = e.stickyModelSelectionTarget === "agent" ? "Agent default" : e.stickyModelSelectionTarget === "defaults" ? "Global default" : "Configured default"; if (e.configuredDefaultUpdate === "requested") return `Model set to ${o} for this session. ${s} update requested.`; if (e.configuredDefaultUpdate === "skipped-immutable") return `Model set to ${o} for this session. ${s} unchanged because configuration is immutable.`; return `Model set to ${o} for this session only; configured default unchanged.`; } function canPersistSessionDirectiveDefaults(e) { const t = normalizeOptionalString(e.messageProvider) ?? normalizeOptionalString(e.surface); if (!t) return true; if (isInternalMessageChannel(t)) return e.gatewayClientScopes?.includes("operator.admin") === true; return e.commandAuthorized === true || e.senderIsOwner === true; } const SESSION_LEVEL_DIRECTIVE_FIELDS = [ ["hasThinkDirective", "thinkingLevel"], ["hasFastDirective", "fastMode"], ["hasVerboseDirective", "verboseLevel"], ["hasTraceDirective", "traceLevel"], ["hasReasoningDirective", "reasoningLevel"], ["hasElevatedDirective", "elevatedLevel"] ]; const SESSION_EXEC_DIRECTIVE_FIELDS = ["execHost", "execNode"]; const SESSION_QUEUE_DIRECTIVE_FIELDS = [ ["queueMode", "queueMode"], ["debounceMs", "queueDebounceMs"], ["cap", "queueCap"], ["dropPolicy", "queueDrop"] ]; /** Names explicit directive writes that snapshot equality cannot infer. */ function resolveDirectiveTouchedSessionFields(e) { const { directives: t } = e; const n = new Set(t.hasModelDirective ? SESSION_MODEL_OVERRIDE_TRANSACTION_FIELDS : []); if (!e.directiveOnly) return [...n]; for (const [r, i] of SESSION_LEVEL_DIRECTIVE_FIELDS) if (t[r] && (i !== "verboseLevel" || e.allowPrivilegedPersistence)) n.add(i); if (t.hasExecDirective && e.allowPrivilegedPersistence) { for (const e of SESSION_EXEC_DIRECTIVE_FIELDS) if (t[e]) n.add(e); } if (t.hasQueueDirective) for (const [e, r] of SESSION_QUEUE_DIRECTIVE_FIELDS) { const i = t[e]; if (t.queueReset || typeof i === "number" || Boolean(i)) n.add(r); } return [...n]; } /** Keeps the first informational/denied acknowledgement while validating the remaining hints. */ async function acknowledgeIgnoredSessionDirective(e) { if (!e.persistenceState) return e.reply; const { directives: t, ignoredDirective: n } = e; const r = n === "hasExecDirective" && t.hasExecOptions ? { ...t, invalidExecHost: false, invalidExecSecurity: false, invalidExecAsk: false, invalidExecNode: false } : { ...t, [n]: false, ...n === "hasThinkDirective" ? { clearThinkLevel: false } : {}, ...n === "hasFastDirective" ? { clearFastMode: false } : {}, ...n === "hasModelDirective" ? { rawModelProfile: void 0 } : {} }; const i = await e.applyRemainingDirectives(r); if (e.persistenceState.outcome.kind === "rejected") return i ?? e.reply; return e.reply; } /** Applies canonical session settings while each caller retains its authorization boundaries. */ function applySessionDirectiveFields(e) { const { directives: t, sessionEntry: n } = e; let r = false; const updateField = (e, t) => { n[e] = t; r = true; }; if (t.clearThinkLevel) { if (n.thinkingLevel) { delete n.thinkingLevel; r = true; } } else if (t.hasThinkDirective && t.thinkLevel) updateField("thinkingLevel", t.thinkLevel); if (t.clearFastMode) { if (n.fastMode !== void 0) { delete n.fastMode; r = true; } } else if (t.hasFastDirective && t.fastMode !== void 0) updateField("fastMode", t.fastMode); if (t.hasVerboseDirective && t.verboseLevel && e.allowPrivilegedPersistence) updateField("verboseLevel", t.verboseLevel); if (t.hasTraceDirective && t.traceLevel) updateField("traceLevel", t.traceLevel); if (t.hasReasoningDirective && t.reasoningLevel) updateField("reasoningLevel", t.reasoningLevel); if (t.hasElevatedDirective && t.elevatedLevel && e.allowElevatedPersistence) updateField("elevatedLevel", t.elevatedLevel); if (t.hasExecDirective && t.hasExecOptions && e.allowPrivilegedPersistence) for (const e of SESSION_EXEC_DIRECTIVE_FIELDS) { const n = t[e]; if (n) updateField(e, n); } if (t.hasQueueDirective && t.queueReset) { for (const [, e] of SESSION_QUEUE_DIRECTIVE_FIELDS) delete n[e]; r = true; } else if (t.hasQueueDirective) for (const [e, n] of SESSION_QUEUE_DIRECTIVE_FIELDS) { const r = t[e]; if (typeof r === "number" || r) updateField(n, r); } return r; } /** Commits a directive snapshot only when its touched fields still win the session transaction. */ async function persistSessionDirectiveSnapshot(e) { const { sessionEntry: t, sessionKey: n, sessionStore: r } = e; const i = await persistReplySessionEntry({ storePath: e.storePath, sessionKey: n, initialEntry: e.initialEntry, entry: t, reassertLiveModelSwitchPending: e.reassertLiveModelSwitchPending, requireModelSelectionUnlocked: e.hasModelSelection, touchedFields: e.touchedFields, validateCommit: e.validateCommit, commitGuard: e.commitGuard }); if (i.status !== "current") { if (i.entry) { r[n] = i.entry; adoptPersistedSessionSnapshot(t, i.entry); } if (i.status === "commit-rejected") return i; return { status: i.status === "model-selection-locked" ? i.status : "conflict" }; } const a = i.entry; r[n] = a; const o = sessionSnapshotChangesApplied({ initial: e.initialEntry, next: t, current: a, touchedFields: e.touchedFields }) && (!e.hasModelSelection || sessionModelOverrideChangesApplied({ initial: e.initialEntry, next: t, current: a, reassertLiveModelSwitchPending: e.reassertLiveModelSwitchPending })); adoptPersistedSessionSnapshot(t, a); return { status: o ? "applied" : "conflict" }; } const formatElevatedEvent = (e) => e === "full" ? "Elevated FULL - exec runs on host with auto-approval." : e === "ask" || e === "on" ? "Elevated ASK - exec runs on host; approvals may still apply." : "Elevated OFF - exec stays in sandbox."; const formatReasoningEvent = (e) => e === "stream" ? "Reasoning STREAM - emit live <think>." : e === "on" ? "Reasoning ON - include <think>." : "Reasoning OFF - hide <think>."; function formatElevatedUnavailableText(e) { const t = e.failures ?? []; const n = [`elevated is not available right now (runtime=${e.runtimeSandboxed ? "sandboxed" : "direct"}).`, t.length > 0 ? `Failing gates: ${t.map((e) => `${e.gate} (${e.key})`).join(", ")}` : "Fix-it keys: tools.elevated.enabled, tools.elevated.allowFrom.<provider>, agents.entries.*.tools.elevated.*"]; if (e.sessionKey) n.push(`See: ${formatCliCommand(`openclaw sandbox explain --session ${e.sessionKey}`)}`); return n.join("\n"); } //#endregion export { formatElevatedEvent as a, formatReasoningEvent as c, withOptions as d, resolveModelSelectionFromDirective as f, canPersistSessionDirectiveDefaults as i, persistSessionDirectiveSnapshot as l, resolveInvalidExecDirectiveMessage as m, acknowledgeIgnoredSessionDirective as n, formatElevatedUnavailableText as o, maybeHandleUnexpectedDirectiveArguments as p, applySessionDirectiveFields as r, formatModelSelectionScopeAck as s, DIRECTIVE_ACK_MESSAGES as t, resolveDirectiveTouchedSessionFields as u };