UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

281 lines (280 loc) • 9.56 kB
import { t as stableStringify } from "./stable-stringify-vqde_3tT.mjs"; import { r as STATE_DIR, t as CONFIG_PATH } from "./paths-DAcAg5aV.mjs"; import { i as normalizeMainKey, r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs"; import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { h as readRuntimeConfig, i as getRuntimeConfigAppliedHash } from "./runtime-snapshot-WbwbY5b7.mjs"; import { t as GATEWAY_CLIENT_CAPS } from "./client-info-Cm1BcrMm.mjs"; import { a as resolveAgentEffectiveModelPrimary } from "./agent-scope-BwB8YH6y.mjs"; import { a as READ_SCOPE } from "./operator-scopes-CULmYfyY.mjs"; import "./io-4QsrsWTJ.mjs"; import { l as getGatewaySuspendAdmissionPhase } from "./gateway-work-admission-79pid1hQ.mjs"; import { n as operatorScopeSatisfied } from "./operator-scope-compat-CpFHu-FC.mjs"; import { r as resolveAgentMainSessionKey } from "./main-session-BNL3-mRV.mjs"; import { n as getSessionActorStorageBinding, t as captureSessionActorStorageOwner } from "./session-actor-storage-binding-DMwpDsij.mjs"; import { o as resolveSessionEventAgentScope } from "./session-request-agent-tfwWH53J.mjs"; import "./sessions-D5Vvu3AE.mjs"; import { r as listSystemPresence } from "./system-presence-Dj1W_mp4.mjs"; import { n as getUpdateSchedule, t as getUpdateAvailable } from "./update-status-state-DIJRWlvX.mjs"; import { n as resolveGatewayAgentSelectionState } from "./agent-list-eAuBkvho.mjs"; import { r as resolveGatewayAuth } from "./auth-resolve-C6_i-P4T.mjs"; import "./auth-dV1bLOjr.mjs"; import { s as projectUpdateAvailable } from "./events-BxTs-VBE.mjs"; import { a as isGatewayClientProfilePending } from "./gateway-client-identity-BkzV3v8p.mjs"; import { d as isGatewayAdmin } from "./session-sharing-policy-3TAaxC-R.mjs"; import { o as prepareProjectedSessionSharing } from "./session-sharing-read-BqjuH16A.mjs"; import "./session-sharing-BIP3raq1.mjs"; import { r as HEALTH_REFRESH_INTERVAL_MS } from "./server-constants-CYohpfLc.mjs"; //#region src/gateway/presence-projection.ts /** Roster objects are immutable for one publication; authority is checked for every recipient. */ function createPresenceRecipientProjection(e) { const t = [...new Set(e.presence.flatMap((e) => e.watchedSessions ?? []))]; const n = getSessionActorStorageBinding({}); const r = /* @__PURE__ */ new Map(); for (const i of t) { if (!isIncognitoSessionKey(i)) continue; const t = resolveSessionEventAgentScope(e.cfg, i, parseAgentSessionKey(i)?.agentId)?.[1]; if (t && !r.has(t)) r.set(t, captureSessionActorStorageOwner({ agentId: t, sessionKey: i, sessionActor: n }, { assertCurrent() {}, authorize() {} })); } const i = /* @__PURE__ */ new Map(); const a = /* @__PURE__ */ new Map(); const o = t.some(isIncognitoSessionKey); let s; let c = []; let l; const u = /* @__PURE__ */ new Map(); const resolveTarget = (t, i, a) => { if (isIncognitoSessionKey(i)) { n?.actor.assertReadable(); const e = r.get(a); const t = e?.owner?.readSession(i, e.authority)?.entry; return t ? { canonicalKey: i, entry: t } : void 0; } if (!u.has(t)) { const n = e.projection?.sharingTargetState({ key: i, agentId: a }); u.set(t, n?.status === "ready" ? n.target : null); } return u.get(t); }; return (n) => { if (!n?.connect || (n.connect.role ?? "operator") !== "operator" || !operatorScopeSatisfied("operator.read", n.connect.scopes ?? [])) return []; const r = e.projection?.getPolicyConfig() ?? e.cfg; if (s !== r) { s = r; c = t.map((e) => { const t = parseAgentSessionKey(e); const n = t?.rest === "global" || t?.rest === "unknown" ? t.rest : e; return { sessionKey: e, key: n, agentId: resolveSessionEventAgentScope(r, n, t?.agentId)?.[1] }; }); u.clear(); a.clear(); } const d = e.projection?.sharingRevision; if (l !== d || d === void 0) { l = d; u.clear(); a.clear(); } const f = isGatewayAdmin(n) || !isGatewayClientProfilePending(n); const p = prepareProjectedSessionSharing({ cfg: r, client: n, isMember: (t, n) => e.projection?.hasMembership(t.storePath, t.storeKey, n) ?? false }); const m = d && !o ? p.getCacheKey(d) : void 0; const h = m === void 0 ? void 0 : a.get(m); if (h) return h; const g = /* @__PURE__ */ new Set(); const _ = []; if (f) for (const [e, { sessionKey: t, key: n, agentId: r }] of c.entries()) { if (!r) continue; const i = resolveTarget(t, n, r); if (i && ("storePath" in i ? p.canReadTarget(i) : p.entryFilter?.(i.canonicalKey, i.entry) ?? true)) { g.add(t); _.push(e); } } const v = _.join(","); let y = i.get(v); if (!y) { y = e.presence.map((e) => { if (!e.watchedSessions) return e; const t = e.watchedSessions.filter((e) => g.has(e)); const { watchedSessions: n, ...r } = e; return t.length ? { ...r, watchedSessions: t } : r; }); i.set(v, y); } if (m !== void 0) a.set(m, y); return y; }; } //#endregion //#region src/gateway/server/health-state.ts let presenceVersion = 1; let healthVersion = 1; let healthCache = null; let healthDigest; let broadcastHealthUpdate = null; const healthRefreshStates = { public: { passive: null, probe: null }, admin: { passive: null, probe: null } }; function buildGatewaySnapshot(e) { const t = readRuntimeConfig(); const n = resolveGatewayAgentSelectionState(t); const r = n.defaultId; const i = normalizeMainKey(t.session?.mainKey); const a = t.session?.scope ?? "per-sender"; const o = a === "global" ? "global" : resolveAgentMainSessionKey({ cfg: t, agentId: r }); const s = listSystemPresence({ includeConnectionId: e.client?.connId }); const c = createPresenceRecipientProjection({ cfg: t, presence: e.client?.connect.caps?.includes(GATEWAY_CLIENT_CAPS.HELLO_PRESENCE_SELF) ? s.filter((t) => t.connectionId === e.client?.connId) : s, projection: e.sessionRowProjection })(e.client); const l = Math.round(process.uptime() * 1e3); const u = e.includeUpdateDetails === true; const d = projectUpdateAvailable(getUpdateAvailable(), u) ?? void 0; const f = u ? getUpdateSchedule() ?? void 0 : void 0; const p = getRuntimeConfigAppliedHash(); const m = { suspension: { phase: getGatewaySuspendAdmissionPhase() }, presence: c, health: {}, stateVersion: { presence: presenceVersion, health: healthVersion }, uptimeMs: l, appliedConfigHash: p ? e.revisionProjector.projectResolvedHash(p) : null, sessionDefaults: { defaultAgentId: r, modelConfigured: Boolean(resolveAgentEffectiveModelPrimary(t, r)), ownership: n.ownership, selectionRequired: n.selectionRequired, mainKey: i, mainSessionKey: o, scope: a }, updateAvailable: d, updateSchedule: f }; if (e.includeSensitive === true) { const e = resolveGatewayAuth({ authConfig: t.gateway?.auth, env: process.env }); m.configPath = CONFIG_PATH; m.stateDir = STATE_DIR; m.authMode = e.mode; } return m; } function getHealthCache() { return healthCache; } function getHealthVersion() { return healthVersion; } function incrementPresenceVersion() { presenceVersion += 1; return presenceVersion; } function getPresenceVersion() { return presenceVersion; } function setBroadcastHealthUpdate(e) { broadcastHealthUpdate = e; } function healthEventDigest(e) { const channel = ({ authAgeMs: e, lastProbeAt: t, lastInboundAt: n, lastOutboundAt: r, lastTransportActivityAt: i, lastMessageAt: a, lastEventAt: o, lastRunActivityAt: s, busy: c, activeRuns: l, activeRunStartedAt: u, accounts: d, ...f }) => ({ ...f, ...d ? { accounts: Object.fromEntries(Object.entries(d).map(([e, t]) => [e, channel(t)])) } : {} }); const t = e.eventLoop?.degraded === true && (e.eventLoop.degradedSinceMs ?? 0) >= 6e4; return stableStringify({ ...e, ts: void 0, durationMs: void 0, eventLoop: e.eventLoop ? { degraded: t, reasons: t ? e.eventLoop.reasons : [] } : void 0, channels: Object.fromEntries(Object.entries(e.channels).map(([e, t]) => [e, channel(t)])), agents: e.agents.map(({ sessions: e, ...t }) => t), sessions: void 0 }); } async function refreshGatewayHealthSnapshot(e) { const t = e?.includeSensitive === true; const n = t ? "admin" : "public"; const r = healthRefreshStates[n]; const i = e?.probe === false ? "passive" : "probe"; const a = i === "passive" ? r.probe ?? r.passive : r.probe; if (a) return a; const o = (async () => { const { collectGatewayHealthSnapshot: r } = await import("./collector-FojBcyBH.mjs"); let a; try { a = e?.getRuntimeSnapshot?.(); } catch { a = void 0; } const o = e?.getConfigReloaderHotReloadStatus?.(); const s = await r({ audience: n, probe: i === "probe", runtimeSnapshot: a, cronState: e?.getCronState?.(), ...o ? { configReloadHotReloadStatus: o } : {}, ...e?.getSessionRowProjection ? { sessionRowProjection: e.getSessionRowProjection() } : {} }); const c = e?.getEventLoopHealth?.(); if (c) s.eventLoop = c; if (!t) { const e = healthEventDigest(s); healthCache = s; if (e !== healthDigest) { healthDigest = e; healthVersion += 1; broadcastHealthUpdate?.(s); } } return s; })().finally(() => { r[i] = null; }); r[i] = o; return o; } //#endregion export { incrementPresenceVersion as a, createPresenceRecipientProjection as c, getPresenceVersion as i, getHealthCache as n, refreshGatewayHealthSnapshot as o, getHealthVersion as r, setBroadcastHealthUpdate as s, buildGatewaySnapshot as t };