UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

485 lines (484 loc) • 20.6 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { i as asOptionalObjectRecord, p as readStringField } from "./record-coerce-CVPuDqcc.mjs"; import { t as parseBoolean } from "./boolean-coercion-B6407eeV.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs"; import { j as parseAgentSessionKey, x as isCronSessionKey, y as isAcpSessionKey } from "./session-key-CqAyZeVk.mjs"; import { n as normalizeAccountId } from "./account-id-BqKT3GuY.mjs"; import { t as freezeJsonSnapshot } from "./immutable-data-Y7xVjZoy.mjs"; import { O as tryResolveAmbientOwnerAgentId, a as resolveAgentDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { d as isUserModelAuthProfileId } from "./user-model-account-authority-CRj924IP.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs"; import { t as isDeliverableMessageChannel } from "./message-channel-normalize-CFHSufeo.mjs"; import { t as assertAdmittedRunOperatorAuthority } from "./admitted-run-context-D3Jvk_f_.mjs"; import { n as operatorScopeSatisfied, t as intersectOperatorScopes } from "./operator-scope-compat-CpFHu-FC.mjs"; import "./message-channel-DTYVLJT1.mjs"; import { n as cronJobUsesToolRuntime } from "./tools-allow-CYmLDCc7.mjs"; import { n as attributeDelegatedSessionCreator } from "./session-entry-provenance-01l9mXT0.mjs"; import { a as validateTargetProviderPrefix, t as resolveTargetPrefixedChannel } from "./channel-target-prefix-tRLuyxKs.mjs"; import { a as isAgentHarnessSessionKey, n as AGENT_HARNESS_SESSION_ID_LOCKED_MESSAGE, r as AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE } from "./agent-harness-session-key-BRYGtzM6.mjs"; import { r as resolveChannelAccountEntry } from "./account-lookup-FhQZVFfo.mjs"; import { t as loadGatewaySessionEntryReadOnlyInWorker } from "./session-utils-store-worker-BU_tdh8T.mjs"; import { c as resolveCliRuntimeExecutionProvider } from "./model-runtime-aliases-DZy9Ea2c.mjs"; import { r as resolveCronJobEffectiveAgentId } from "./agent-id-CX8HtxAT.mjs"; import { t as resolveCronAgentSessionKey } from "./session-key-BQPSZVRH.mjs"; import { n as isCronOperatorSourceParent, o as resolveCronDeliverySessionKey, s as resolveCronSessionTargetSessionKey } from "./session-target-C-4MLah6.mjs"; import { r as resolveOperatorSessionCreation } from "./session-creation-provenance-DCFhTDpD.mjs"; import { r as resolveHookExternalContentSource } from "./external-content-source-BOt3r-v5.mjs"; import { t as assertCronDeliveryInputNonBlankFields } from "./delivery-target-validation-BQd2iGZZ.mjs"; import { n as assertCanonicalCronDeliveryMode } from "./delivery-codec-BaSNePUi.mjs"; import { r as normalizeCronJobPatch, t as normalizeCronJobCreate } from "./normalize-DLzfR3Jc.mjs"; import { n as listConfiguredMessageChannels } from "./channel-selection-DBeuWpKq.mjs"; import { t as resolveSimpleCompletionSelectionForAgent } from "./simple-completion-selection-b17DajRn.mjs"; import { n as applyJobPatch } from "./jobs-DksTRJEQ.mjs"; import { t as resolveCronDeliveryPlan } from "./delivery-plan-BMeGAb9T.mjs"; import { r as resolveFailureAlert } from "./failure-alerts-DTfFZTS2.mjs"; import { t as resolveCarriedCronModelSelection } from "./session-carried-model-Dm0Bgmhs.mjs"; import { n as captureCronInferenceBinding, t as acquireCronInferenceAuthorization } from "./inference-binding.runtime-j-26n2r6.mjs"; import { n as requiresExternalCronDelivery, r as resolveDeliveryTarget } from "./delivery-target-BPDm3s8R.mjs"; import { t as preparePersonalModelAccountSelection } from "./users-model-account-access-qMuKU1sR.mjs"; //#region src/cron/delivery-channel-validation.ts function hasExplicitChannelConfigEntry(e) { const t = e.channels; if (!t || typeof t !== "object" || Array.isArray(t)) return false; return Object.entries(t).some(([e, t]) => { if (e === "defaults" || e === "modelByChannel") return false; return Boolean(t && typeof t === "object" && !Array.isArray(t) && Object.keys(t).length > 0); }); } async function assertConfiguredAnnounceChannel(e) { if (e.channel === "last") return; const t = normalizeMessageChannel(e.channel); if (!t && e.field === "delivery.channel") return; const n = (await listConfiguredMessageChannels(e.cfg)).toSorted(); if (!t) { if (n.length <= 1) return; throw new Error(`${e.field} is required when multiple channels are configured: ${n.join(", ")}`); } if (n.length === 0) { if (!hasExplicitChannelConfigEntry(e.cfg)) { if (!isDeliverableMessageChannel(t)) throw new Error(`${e.field} is not a known channel: ${t}`); return; } throw new Error(`${e.field} is not configured: ${t}`); } if (!n.includes(t)) throw new Error(`${e.field} must be one of: ${n.join(", ")}`); } /** * Rejects an announce account the operator has turned off in config, so a job is * not scheduled against a route its owner already disabled - the same late failure * this file prevents for `channel` (see `assertValidCronFailureAlert`). * * Scoped to a matching `accounts.<id>.enabled: false` entry, and nothing else. * Cron delivery ids are not always operator-typed (`delivery-context.ts` copies * the current context account into inferred jobs); channel `isEnabled` adapters * report unlisted or credential-suppressed accounts as not enabled; and a * top-level `channels.<id>.enabled: false` is not uniformly channel-wide - twitch * resolves named accounts from `accounts` alone. Only the account entry itself is * an unambiguous statement about this route. */ function assertEnabledAnnounceAccount(e) { if (!e.accountId || !e.channel || e.channel === "last") return; const t = normalizeMessageChannel(e.channel) ?? e.channel; const n = e.cfg.channels?.[t]; if (!n || typeof n !== "object" || Array.isArray(n)) return; const r = n.accounts; if (resolveChannelAccountEntry(r, e.accountId, t, normalizeAccountId)?.enabled !== false) return; throw new Error(`${e.field}: account "${e.accountId}" is disabled for channel ${t}`); } function resolveAnnounceValidationChannel(e) { return e.channel && e.channel !== "last" ? e.channel : resolveTargetPrefixedChannel(e.to) ?? e.channel; } function assertCompatibleAnnounceTarget(e) { if (!e.channel || e.channel === "last") return; const t = validateTargetProviderPrefix({ channel: e.channel, to: e.to }); if (t) throw new Error(`${e.field}: ${t.message}`); } async function assertValidCronAnnounceDelivery(e) { assertCanonicalCronDeliveryMode(e.delivery); if (e.delivery?.mode === "announce") { assertCompatibleAnnounceTarget({ channel: e.delivery.channel, to: e.delivery.to, field: "delivery.channel" }); await assertConfiguredAnnounceChannel({ cfg: e.cfg, channel: resolveAnnounceValidationChannel(e.delivery), field: "delivery.channel" }); assertEnabledAnnounceAccount({ cfg: e.cfg, channel: resolveAnnounceValidationChannel(e.delivery), accountId: e.delivery.accountId, field: "delivery.accountId" }); } const t = e.delivery?.failureDestination; if (t && (t.mode ?? "announce") === "announce") { if (t.channel === void 0 && t.to === void 0 && t.accountId === void 0 && t.mode === void 0) return; assertCompatibleAnnounceTarget({ channel: t.channel, to: t.to, field: "delivery.failureDestination.channel" }); await assertConfiguredAnnounceChannel({ cfg: e.cfg, channel: resolveAnnounceValidationChannel(t), field: "delivery.failureDestination.channel" }); } } /** * Validates the per-job `failureAlert` channel the same way announce delivery is * validated. `failureAlert` is a distinct field from `delivery.failureDestination` * (its own store columns and delivery path), so it needs its own check - otherwise * an explicit unknown channel (e.g. a Slack `C0...` id passed to * `--failure-alert-channel`) is stored and only fails later as `channel_not_found`. */ async function assertValidCronFailureAlert(e) { const t = resolveFailureAlert({ deps: { cronConfig: e.cfg.cron } }, { delivery: e.delivery, failureAlert: e.failureAlert }); if (!t || t.mode === "webhook") return; assertCompatibleAnnounceTarget({ channel: t.channel, to: t.to, field: "failureAlert.channel" }); await assertConfiguredAnnounceChannel({ cfg: e.cfg, channel: t.channel, field: "failureAlert.channel" }); } async function assertValidCronCreateDelivery(e, t) { await assertValidCronAnnounceDelivery({ cfg: e, delivery: t.delivery }); await assertValidCronFailureAlert({ cfg: e, failureAlert: t.failureAlert, delivery: t.delivery }); } //#endregion //#region src/agents/operator-run-recovery-source.ts /** Cron occurrences retain the creator turn's authenticated grant for later revalidation. */ function captureScheduledOperatorSource(e) { const { authority: t, entry: n, sessionKey: r } = e; if (!t || n.incognito || n.acp || n.pluginOwnerId || n.cronRunContinuation || isIncognitoSessionKey(r) || isCronSessionKey(r) || isAcpSessionKey(r) || isAgentHarnessSessionKey(r)) return; assertAdmittedRunOperatorAuthority(t); t.assertCurrent(); const i = t.recoverySnapshot; if (!i) return; const a = { version: 1, agentId: e.agentId, sessionKey: r, sessionId: n.sessionId, ...n.lifecycleRevision !== void 0 ? { lifecycleRevision: n.lifecycleRevision } : {}, sourceRunId: e.sourceRunId, snapshot: { ...i, scopes: intersectOperatorScopes(i.scopes, t.scopes) } }; return Buffer.byteLength(JSON.stringify(a), "utf8") <= 65536 ? freezeJsonSnapshot(a) : void 0; } //#endregion //#region src/gateway/server-methods/cron-input-validation.ts /** * The entry a job's cron session takes its runtime override from: the target row of a * `session:` job, or what a `current` job carries from its creating conversation. */ async function loadCronRuntimeSessionEntry(e) { if (e.executionEntry) return e.executionEntry; const t = e.job.sessionTarget === "current" ? e.job.sessionKey?.trim() : void 0; if (!t) return; const n = e.loaded?.key === t ? e.loaded.entry : (await loadGatewaySessionEntryReadOnlyInWorker({ cfg: e.cfg, key: t, agentId: e.agentId }))?.entry; return n ? resolveCarriedCronModelSelection(n) : void 0; } async function captureCronInferenceForCaller(e, t) { let n; let r; return { inferenceBinding: await captureCronInferenceBinding({ ...e, retainAuthorization: (e) => { r = e; }, authorizeProfile: async (e, r) => { if (isUserModelAuthProfileId(e) && !r) { n = await preparePersonalModelAccountSelection(t, e); return n.assertCurrent; } } }), assertInferenceSelectionCurrent: () => { n?.assertCurrent(); r?.assertCurrent(); }, disposeInferenceAuthorization: () => r?.dispose() }; } function requiresExplicitAgentRuntimeToolsAllow(e) { return e.callerScope !== void 0 && !e.callerScope.manageAll && cronJobUsesToolRuntime(e.job) && e.job.payload.toolsAllow === void 0; } function normalizeCronRequestDeliveryMode(e) { const t = e?.delivery; if (typeof t?.mode === "string" && t.mode.trim().toLowerCase() === "deliver") t.mode = "announce"; } /** Validate authored fields before normalization can erase blank or invalid input. */ function normalizeCronAddRequest(e) { const t = asOptionalObjectRecord(e); for (const e of ["declarationKey", "displayName"]) { const n = t?.[e]; if (typeof n === "string" && n.trim().length === 0) throw new Error(`${e} must not be blank`); } const n = Boolean(t && Object.hasOwn(t, "enabled")); const r = n ? parseBoolean(t?.enabled) : void 0; if (n && r === void 0) throw new Error("enabled must be a boolean"); assertCronDeliveryInputNonBlankFields(t?.delivery); const i = normalizeCronJobCreate(e, { sessionContext: { sessionKey: readStringField(t, "sessionKey") } }); normalizeCronRequestDeliveryMode(i); return { candidate: i ?? e, enabledExplicit: r !== void 0 }; } function normalizeCronUpdateRequest(e) { const t = asOptionalObjectRecord(e); const n = t?.patch; const r = asOptionalObjectRecord(n); const i = r?.displayName; if (typeof i === "string" && i.trim().length === 0) throw new Error("displayName must not be blank"); assertCronDeliveryInputNonBlankFields(r?.delivery); const a = normalizeCronJobPatch(n); normalizeCronRequestDeliveryMode(a); return { candidate: a && t ? { ...t, patch: a } : e, normalizedPatch: a }; } async function assertValidCronUpdatePatch(e) { const t = structuredClone(e.currentJob); applyJobPatch(t, e.patch, { defaultAgentId: e.defaultAgentId, cronConfig: e.cfg.cron }); if ("agentId" in e.patch || "sessionTarget" in e.patch || "sessionKey" in e.patch) await assertCronDoesNotTargetAgentHarness(t, e.cfg); const n = e.patch.delivery?.channel === null && t.delivery && (t.delivery.mode ?? "announce") === "announce" && t.delivery.channel === void 0 && resolveTargetPrefixedChannel(t.delivery.to) === void 0 ? { ...t.delivery, channel: "last" } : t.delivery; if ("delivery" in e.patch) await assertValidCronAnnounceDelivery({ cfg: e.cfg, delivery: n }); const r = e.patch.failureAlert; const i = r && ("channel" in r || "to" in r || "mode" in r); const a = resolveFailureAlert({ deps: { cronConfig: e.cfg.cron } }, e.currentJob); const o = resolveFailureAlert({ deps: { cronConfig: e.cfg.cron } }, { ...t, delivery: n }); const s = a === null && o !== null; const c = a?.mode !== o?.mode || a?.channel !== o?.channel || a?.to !== o?.to || a?.accountId !== o?.accountId || a?.threadId !== o?.threadId; if (i || s || c && (e.patch.delivery !== void 0 || r === null)) await assertValidCronFailureAlert({ cfg: e.cfg, failureAlert: t.failureAlert, delivery: n }); return t; } async function assertCronDoesNotTargetAgentHarness(e, t) { const n = resolveCronSessionTargetSessionKey(e.sessionTarget) ?? (e.sessionTarget === "current" ? e.sessionKey?.trim() : void 0); if (!n) return; const r = await loadGatewaySessionEntryReadOnlyInWorker({ cfg: t, key: n, agentId: e.agentId?.trim() || void 0 }); const i = isAgentHarnessSessionKey(n) || isAgentHarnessSessionKey(r.canonicalKey); if (r.entry?.modelSelectionLocked === true) throw new Error(i ? AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE : AGENT_HARNESS_SESSION_ID_LOCKED_MESSAGE); if (!i || r.entry) return; throw new Error(AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE); } async function captureCronCreatorSession(e, t, n, r, i = false) { const a = n.client?.internal?.operatorRunAuthority; const o = e.sessionTarget !== "main" && (e.payload.kind === "agentTurn" || e.payload.kind === "script" || e.payload.kind === "command"); const s = t?.sessionKey ?? (o ? e.sessionKey : void 0); const c = t?.agentId ?? e.agentId; const l = s ? await loadGatewaySessionEntryReadOnlyInWorker({ cfg: r, key: s, agentId: c }) : void 0; const u = l?.entry; const d = o && l && u?.sessionId ? { sessionKey: l.canonicalKey, sessionId: u.sessionId, lifecycleRevision: u.lifecycleRevision } : void 0; const f = t && l && u && a && operatorScopeSatisfied("operator.write", a.scopes) && e.payload.kind === "agentTurn" && isCronOperatorSourceParent({ sessionTarget: e.sessionTarget, sourceConversation: d }, l.canonicalKey) && n.client?.internal?.agentRuntimeIdentity ? captureScheduledOperatorSource({ authority: a, entry: u, agentId: l.agentId, sessionKey: l.canonicalKey, sourceRunId: n.client.internal.agentRuntimeIdentity.operationalRunInstance.runId }) : void 0; const p = t ? u?.createdActor : resolveOperatorSessionCreation(n.client).actor; const m = normalizeOptionalString(p?.id); const h = p ? { ...p, ...m ? { id: m } : {} } : void 0; const g = t ? attributeDelegatedSessionCreator(h, t.creatorProfileId, t.agentId) : h; const _ = resolveCronSessionTargetSessionKey(e.sessionTarget) ?? ""; const v = !i && e.payload.kind === "agentTurn" && _ ? await loadGatewaySessionEntryReadOnlyInWorker({ cfg: r, key: _, agentId: c }) : void 0; const y = !i && e.payload.kind === "agentTurn" ? await loadCronRuntimeSessionEntry({ cfg: r, job: e, agentId: c, executionEntry: v?.entry, loaded: s ? { key: s, entry: l?.entry } : void 0 }) : void 0; return { ...!i && e.payload.kind === "agentTurn" && e.sessionTarget !== "main" ? await captureCronInferenceForCaller({ cfg: r, agentId: resolveCronJobEffectiveAgentId({ ...e, agentId: c }, tryResolveAmbientOwnerAgentId(r)), model: e.payload.model, isGmailHook: (e.payload.externalContentSource ?? resolveHookExternalContentSource(parseAgentSessionKey(_)?.rest ?? _)) === "gmail", sessionEntry: t ? u : void 0, executionSessionEntry: v?.entry, runtimeSessionEntry: y }, n) : void 0, ...f ? { operatorSource: f } : {}, assertOperatorSourceCurrent: f ? a?.assertCurrent : void 0, ...d ? { sourceConversation: d } : {}, ...g ? { createdActor: g } : {}, ...t && u?.skillLibrarySelections ? { skillLibrarySelections: u.skillLibrarySelections } : {} }; } /** Only an explicitly selected account changes an existing job’s inference ownership. */ async function captureCronUpdatedInferenceBinding(e, t, n, r) { if (e.runtimeAuthority !== void 0 || e.payload.kind !== "agentTurn") return; const i = t.payload && "model" in t.payload ? t.payload.model : void 0; const a = resolveCronJobEffectiveAgentId(e, tryResolveAmbientOwnerAgentId(n)); const o = i ? resolveSimpleCompletionSelectionForAgent({ cfg: n, agentId: a, modelRef: i }) : null; const s = o ? resolveCliRuntimeExecutionProvider({ cfg: n, agentId: a, provider: o.provider, modelId: o.modelId, authProfileId: o.profileId }) : void 0; if (!i || !o?.profileId) { if (t.agentId !== void 0 && e.inferenceBinding) { const t = await acquireCronInferenceAuthorization({ binding: e.inferenceBinding, cfg: n, agentDir: resolveAgentDir(n, a) }); return { inferenceBinding: void 0, assertInferenceSelectionCurrent: () => t.assertCurrent(), disposeInferenceAuthorization: () => t.dispose() }; } return; } const c = e.inferenceBinding?.runtime; const l = resolveCronSessionTargetSessionKey(e.sessionTarget); const u = await captureCronInferenceForCaller({ cfg: n, agentId: a, model: i, runtimeSessionEntry: c ? { agentRuntimeOverride: c } : await loadCronRuntimeSessionEntry({ cfg: n, job: e, agentId: a, executionEntry: l ? (await loadGatewaySessionEntryReadOnlyInWorker({ cfg: n, key: l, agentId: a }))?.entry : void 0 }) }, r); if (!u.inferenceBinding) { if (s && !e.inferenceBinding) return; throw new Error("The selected automation account is unavailable."); } const d = u.inferenceBinding.runtime; if (c && d !== c && u.inferenceBinding.provider === e.inferenceBinding?.provider) { u.disposeInferenceAuthorization(); throw new Error(`The automation runs on runtime ${c}, which is unavailable for this account; the edit would move it to runtime ${d ?? "unknown"}.`); } return u; } /** Waiting cannot finish while the caller owns the execution or result conversation lane. */ async function cronRunQueuesBehindCaller(e) { const { job: t, cfg: n, caller: r } = e; if (!r?.sessionKey) return false; if (t.sessionTarget === "main") return true; const i = normalizeAgentId(t.agentId ?? e.resolveDefaultAgentId()); const isCallerSession = (e) => { if (e === void 0) return false; const t = n.session?.scope === "global" && e.trim() === "global" ? "global" : resolveCronAgentSessionKey({ sessionKey: e, agentId: i, mainKey: n.session?.mainKey, cfg: n }); return t === r.sessionKey && (t !== "global" || i === normalizeAgentId(r.agentId)); }; if (t.payload.kind === "agentTurn" && isCallerSession(resolveCronSessionTargetSessionKey(t.sessionTarget))) return true; const a = resolveCronDeliveryPlan(t); if (!a.requested) return false; const o = resolveCronDeliverySessionKey(t); try { const e = await resolveDeliveryTarget(n, i, { ...a, sessionTarget: t.sessionTarget, sourceConversation: t.sourceConversation, sessionKey: o }, { dryRun: true }); if (e.ok) return isCallerSession(e.sessionRoute?.sessionKey); return !requiresExternalCronDelivery(a, e) && isCallerSession(o); } catch { return true; } } //#endregion export { cronRunQueuesBehindCaller as a, requiresExplicitAgentRuntimeToolsAllow as c, captureCronUpdatedInferenceBinding as i, assertValidCronCreateDelivery as l, assertValidCronUpdatePatch as n, normalizeCronAddRequest as o, captureCronCreatorSession as r, normalizeCronUpdateRequest as s, assertCronDoesNotTargetAgentHarness as t };