UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

683 lines (682 loc) • 22.6 kB
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs"; import { t as AsyncWorkScope } from "./async-work-scope-BXagjUap.mjs"; import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { n as runWithSpawnBroker, t as getSpawnBroker } from "./context-Btn9lVDh.mjs"; import { a as sessionChangeScopeAffectsStoredRows, o as sessionChanges } from "./session-row-changes-BA4BqVwF.mjs"; import { i as githubPublicationReceipts } from "./github-publication-receipts-DrGMcoy5.mjs"; import { t as CONTROL_UI_SESSION_PULL_REQUESTS_CHANGED_EVENT } from "./control-ui-contract-DTmt_Jww.mjs"; import { n as prepareControlUiSessionPrServiceTarget } from "./control-ui-session-pr-read-DJu6I6Wb.mjs"; import { t as recordSessionPrDiagnostic } from "./control-ui-session-pr-diagnostics-WC-f6nil.mjs"; import { t as withControlUiSessionPrSource } from "./control-ui-session-pr-source-BLvs0jy1.mjs"; import { i as yieldSessionListWork } from "./session-projection-work-B1VxG4DW.mjs"; import pLimit from "p-limit"; //#region src/gateway/control-ui-session-pr-delivery.ts /** Keyless withdrawal remains deliverable after the reader loses session visibility. */ function invalidatePrReader(e, t) { t("sessions.changed", { reason: "profile-identity" }, /* @__PURE__ */ new Set([e])); } /** Serialize snapshots so an older delivery cannot overtake its replacement. */ function enqueuePrDelivery(e, t) { const n = (e.delivery ?? Promise.resolve()).then(t).finally(() => { if (e.delivery === n) delete e.delivery; }); e.delivery = n; return n; } //#endregion //#region src/gateway/control-ui-session-pr-prepared-read.ts async function loadSessionPullRequests(e, t, n) { n.assertCurrent(); recordSessionPrDiagnostic("loader-import-started", n.target); const { loadControlUiSessionPullRequests: r } = await import("./control-ui-session-prs-BmcJuM-k.mjs"); return r(e, { cacheSignal: t, read: n }); } function pushedSnapshot(e) { return { ...e, status: e.status ?? (e.rateLimited ? "rate-limited" : "ready") }; } const UNAVAILABLE_SNAPSHOT = { pullRequests: [], rateLimited: false, status: "unavailable" }; /** Index each connection's requested keys on the cell that retains its snapshot. */ function addControlUiSessionPrMembership(e, t, n) { let r = e.sessionKeysByConnId.get(t); if (!r) { r = /* @__PURE__ */ new Set(); e.sessionKeysByConnId.set(t, r); } r.add(n); e.connIds.add(t); } /** Retire the unused cell through the same owner that retains its prepared readers. */ function retireControlUiSessionPrState(e, t) { if (!e || e.prepared || e.connIds.size > 0) return; e.cancelRefresh?.(); e.cacheLifetime.abort(null); if (t.get(e.target.identity) === e) t.delete(e.target.identity); } /** Retain only branch facts across audience/mode changes on the same physical source. */ function retainControlUiSessionPrBranchSnapshot(e, t) { if (!t?.target.branchIdentity || t.target.branchIdentity !== e.target.branchIdentity || t.target.taskReceipts?.ownerProfileId !== e.target.taskReceipts?.ownerProfileId) return; e.sourceIdentity ??= t.sourceIdentity; if (e.sourceIdentity === t.sourceIdentity && t.branchSnapshot && e.branchSnapshot !== t.branchSnapshot) { e.branchSnapshot = t.branchSnapshot; e.assertReadAuthority = t.assertReadAuthority; e.snapshot = void 0; } } /** Background readers publish into the subscription owner's existing cells and concurrency. */ function createControlUiSessionPrPreparedRead(e) { const { scope: t, limit: n, withSource: r, load: i, keyStates: a, stateForTarget: o } = e; const s = getSpawnBroker(); const c = /* @__PURE__ */ new Map(); const l = /* @__PURE__ */ new Map(); const writeSnapshot = (e, t) => { const n = JSON.stringify(e.snapshot) !== JSON.stringify(t); recordSessionPrDiagnostic("snapshot-published", e.target); e.snapshot = t; if (n && e.prepared) sessionChanges.emit({ ...e.target.params, scope: "runtime" }); }; const publishBranchSnapshot = (e, t) => { if (!e.branchIdentity || e.taskReceiptsOnly) return; const n = a.get(e.identity); if (n) n.branchSnapshot = t; const r = a.get(e.branchIdentity); if (r) writeSnapshot(r, t); }; const publishSnapshot = (e, t, n) => { e.assertReadAuthority = n; writeSnapshot(e, t); if (!t.taskPullRequests) publishBranchSnapshot(e.target, t); }; const read = (e, o, s) => { const c = a.get(e.identity); const l = c?.snapshot; let u; const assertActive = () => { if (t.isClosing) throw new Error("Session pull-request owner is closed"); o(); e.assertCurrent?.(); u?.(); }; const publish = (t) => { if (s !== "publication" && c?.prepared && a.get(e.identity) === c && c.snapshot === l && c.target.identity === e.identity) publishSnapshot(c, t, u); }; assertActive(); return t.track(() => n(async () => { assertActive(); return await r(e, async (t, n) => { const assertReadCurrent = () => { assertActive(); t(); }; assertReadCurrent(); try { const t = await i(e.params, void 0, { target: e, sourceIdentity: n, projection: s, onBranchRead: (t) => { assertReadCurrent(); publishBranchSnapshot(e, pushedSnapshot(t)); }, assertCurrent: assertReadCurrent, retainReadAuthority: (e) => { u = e; } }); assertReadCurrent(); const r = pushedSnapshot(t); publish(r); return r; } catch { assertReadCurrent(); publish(UNAVAILABLE_SNAPSHOT); return UNAVAILABLE_SNAPSHOT; } }); })); }; const readPrepared = (r, i) => { if (t.isClosing) return; const u = JSON.stringify([r.params.agentId, r.params.sessionKey]); const d = l.get(u); if (d && d !== r.identity) { const e = a.get(d); if (e) { e.prepared = false; if (e.connIds.size === 0) { e.cacheLifetime.abort(null); a.delete(d); } } } l.set(u, r.identity); const f = o(r); const p = f.target; f.prepared = true; if (!f.snapshot) { for (const e of a.values()) if (e.target.branchIdentity === r.identity && e.branchSnapshot) { f.snapshot = e.branchSnapshot; break; } } if (r.source === null && !r.githubPullRequest) f.snapshot ??= { pullRequests: [], rateLimited: false, status: "ready" }; const m = e.getSessionRowProjection; if ((!f.snapshot || f.snapshot.status !== "ready" || f.snapshot.rateLimited) && !c.has(f) && m && (!i || i())) { const e = runInDetachedAsyncContext(() => runWithSpawnBroker(s, () => t.track(async () => { const e = await n(async () => { if (t.isClosing || a.get(p.identity) !== f) return; return await prepareControlUiSessionPrServiceTarget(m, p.params); }); if (!e) return; const assertCurrent = () => { if (t.isClosing || a.get(p.identity) !== f || e.identity !== p.identity) throw new Error("Prepared session pull-request target changed"); e.assertCurrent?.(); }; assertCurrent(); await read(e, assertCurrent); }))).catch(() => {}).finally(() => c.delete(f)); c.set(f, e); } return f.snapshot; }; const u = sessionChanges.subscribeFacts((e) => { if ("sessionKey" in e && (e.facts?.kind === "unchanged" || e.scope === "runtime" && !e.facts && !e.factsInvalidated)) return; const t = "sessionKey" in e ? [...a.values()].filter((t) => t.target.params.sessionKey === e.sessionKey) : a.values(); const n = []; for (const e of t) { e.branchSnapshot = void 0; if (e.prepared) { e.prepared = false; e.snapshot = void 0; l.delete(JSON.stringify([e.target.params.agentId, e.target.params.sessionKey])); retireControlUiSessionPrState(e, a); n.push(e.target.params); } } if (!("sessionKey" in e)) sessionChanges.emitBatch(n.map(({ sessionKey: e, agentId: t }) => ({ sessionKey: e, agentId: t, scope: "runtime" }))); }); return { read, readPrepared, publishSnapshot, publishBranchSnapshot, settle: () => Promise.allSettled(c.values()), stop: () => { u(); l.clear(); } }; } //#endregion //#region src/gateway/control-ui-session-pr-subscription-params.ts function parseSessionKeys(e) { if (!Array.isArray(e) || e.length > 200) return null; const t = /* @__PURE__ */ new Set(); for (const n of e) { if (typeof n !== "string") return null; const e = n.trim(); if (!e || e.length > 512) return null; t.add(e); } return [...t]; } function parseControlUiSessionPullRequestsSubscribeParams(e) { const t = asNullableRecord(e); if (!t) return null; const n = parseSessionKeys(t.sessionKeys); const r = t.refreshSessionKeys === void 0 ? [] : parseSessionKeys(t.refreshSessionKeys); const i = t.passiveSessionKeys === void 0 ? [] : parseSessionKeys(t.passiveSessionKeys); if (!n || !r || !i) return null; const a = new Set(n); for (const e of r) if (!a.has(e)) return null; const o = i.filter((e) => !a.has(e)); if ((/* @__PURE__ */ new Set([...n, ...o])).size > 200) return null; return { sessionKeys: n, refreshSessionKeys: r, ...o.length ? { passiveSessionKeys: o } : {} }; } //#endregion //#region src/gateway/control-ui-session-pr-subscriptions.ts const CONTROL_UI_SESSION_PR_POLL_INTERVAL_MS = 6e4; const CONTROL_UI_SESSION_PR_REFRESH_INTERVAL_MS = 1e4; const CONTROL_UI_SESSION_PR_LOAD_CONCURRENCY = 4; /** * Owns the union of connection replace-sets. Only this union drives GitHub * refreshes, so hidden/disconnected clients cannot leave orphan polling work. */ function createControlUiSessionPullRequestSubscriptions(e) { const t = /* @__PURE__ */ new Map(); const n = /* @__PURE__ */ new Set(); const r = /* @__PURE__ */ new Map(); const i = /* @__PURE__ */ new Map(); const a = /* @__PURE__ */ new Map(); const o = e.scheduler.scope(); const s = pLimit(CONTROL_UI_SESSION_PR_LOAD_CONCURRENCY); const c = pLimit(CONTROL_UI_SESSION_PR_LOAD_CONCURRENCY); const withSource = (e, t) => withControlUiSessionPrSource(e.readSource, t); let l; const u = new AsyncWorkScope(); let d; const removeMembership = (e, t, n) => { const r = e?.sessionKeysByConnId.get(t); r?.delete(n); if (r?.size === 0) { e?.sessionKeysByConnId.delete(t); e?.connIds.delete(t); } retireControlUiSessionPrState(e, i); }; const removeMemberships = (e, t, n) => { for (const [r, { target: a }] of t ?? []) if (n?.get(r)?.target.identity !== a.identity) removeMembership(i.get(a.identity), e, r); }; const stateForTarget = (e, t, n) => { const { assertCurrent: r, ...a } = e; const o = i.get(e.identity); if (o?.target.identity === e.identity && (t === void 0 || o.sourceIdentity === void 0 || o.sourceIdentity === t)) { o.target = a; o.sourceIdentity ??= t; retainControlUiSessionPrBranchSnapshot(o, n); return o; } o?.cancelRefresh?.(); o?.cacheLifetime.abort(null); const s = { connIds: new Set(o?.connIds), sessionKeysByConnId: new Map(o?.sessionKeysByConnId), target: a, prepared: o?.prepared, sourceIdentity: t, cacheLifetime: new AbortController() }; retainControlUiSessionPrBranchSnapshot(s, n); i.set(e.identity, s); return s; }; const f = createControlUiSessionPrPreparedRead({ scope: u, limit: s, withSource, load: loadSessionPullRequests, keyStates: i, stateForTarget, getSessionRowProjection: e.getSessionRowProjection }); const reconcileWatcher = (r, a, o, s) => { const c = t.get(r); if (u.isClosing || c?.get(a) !== o) return; if (e.isConnectionActive?.(r) === false) { unsubscribe(r); return; } if (!o || !s) { if (o?.target.ownGitHubProfileId && e.isConnectionActive?.(r) !== false) invalidatePrReader(r, e.broadcastToConnIds); c?.delete(a); removeMembership(o && i.get(o.target.identity), r, a); if (c?.size === 0) { t.delete(r); if (t.size === 0) { l?.cancel(); l = void 0; } } return; } if (o.target.identity === s.identity) { o.target = s; return s; } const d = i.get(o.target.identity); const f = stateForTarget(s, void 0, d); if (o.target.ownGitHubIdentity && o.target.ownGitHubIdentity !== s.ownGitHubIdentity) invalidatePrReader(r, e.broadcastToConnIds); removeMembership(d, r, a); o.deliveredHash = void 0; o.target = s; addControlUiSessionPrMembership(f, r, a); const p = u.track(() => loadSnapshot(s.identity)).then(() => void 0, () => void 0); n.add(p); p.finally(() => n.delete(p)); return s; }; const currentWatcher = (n, r) => { const i = t.get(n)?.get(r); let a; if (i && e.isConnectionActive?.(n) !== false) { try { i.target.assertCurrent?.(); a = i.target.assertCurrent ? i.target : void 0; } catch {} if (!a) return c(i.readCurrent).then((e) => reconcileWatcher(n, r, i, e)); } return reconcileWatcher(n, r, i, a); }; const currentKeyState = async (e) => { const t = i.get(e); for (const [e, n] of t?.sessionKeysByConnId ?? []) for (const t of n) { const n = currentWatcher(e, t); if (n instanceof Promise) await n; } return i.get(e); }; const loadSnapshot = async (n, r = false) => { const c = await currentKeyState(n); if (u.isClosing || !c?.connIds.size) return UNAVAILABLE_SNAPSHOT; return withSource(c.target, async (l, d) => { const p = stateForTarget(c.target, d); const m = a.get(n); if (m) { if (m.state === p && (!r || m.refresh)) return m.promise; await m.promise; l(); return await currentKeyState(n) === p ? loadSnapshot(n, r) : UNAVAILABLE_SNAPSHOT; } const h = u.track(async () => { const a = r ? (p.refreshedAt ?? -Infinity) + CONTROL_UI_SESSION_PR_REFRESH_INTERVAL_MS - o.now() : 0; if (a > 0) { await new Promise((e) => { const t = o.schedule({ id: `control-ui-session-pr-refresh:${n}`, delayMs: a, run: e }); p.cancelRefresh = () => { t.cancel(); e(); }; }); p.cancelRefresh = void 0; } return await s(async () => { if (await currentKeyState(n) !== p || p.connIds.size === 0) return UNAVAILABLE_SNAPSHOT; if (r) p.refreshedAt = o.now(); const assertReadCurrent = () => { l(); if (u.isClosing || i.get(p.target.identity) !== p) throw new Error("Session pull-request watchers changed"); for (const [n, r] of p.sessionKeysByConnId) { if (e.isConnectionActive?.(n) === false) continue; for (const e of r) { const r = t.get(n)?.get(e); if (!r || r.target.identity !== p.target.identity) continue; try { r.target.assertCurrent?.(); return; } catch {} } } throw new Error("Session pull-request watchers changed"); }; let a; const s = await loadSessionPullRequests({ ...p.target.params, ...r ? { refresh: true } : {} }, p.cacheLifetime.signal, { target: p.target, sourceIdentity: d, branchSnapshot: p.branchSnapshot, onBranchRead: (e) => { assertReadCurrent(); f.publishBranchSnapshot(p.target, pushedSnapshot(e)); }, assertCurrent: assertReadCurrent, retainReadAuthority: (e) => { a = e; } }).then(pushedSnapshot).catch(() => ({ ...UNAVAILABLE_SNAPSHOT })); if (await currentKeyState(n) === p) { l(); f.publishSnapshot(p, s, a); await push(new Set(p.connIds), p, s, l, r); } return s; }); }).catch(() => UNAVAILABLE_SNAPSHOT).finally(() => { if (a.get(n)?.promise === h) a.delete(n); }); a.set(n, { promise: h, refresh: r, state: p }); return h; }).catch(() => UNAVAILABLE_SNAPSHOT); }; const push = (n, r, a, o, s = false, c) => { if (n.size === 0 || r.target.ownGitHubProfileId && r.snapshot !== a) return Promise.resolve(); const l = r.assertReadAuthority; const d = JSON.stringify(a); const isDelivered = (e) => !(s && e.refreshPending) && e.deliveredHash === d; return enqueuePrDelivery(r, async () => { for (const f of n) { const n = c ? [c] : [...r.sessionKeysByConnId.get(f) ?? []]; for (const c of n) { const n = t.get(f)?.get(c); if (!n || isDelivered(n)) continue; const p = await currentWatcher(f, c); if (!p || u.isClosing || p.identity !== r.target.identity || t.get(f)?.get(c) !== n || e.isConnectionActive?.(f) === false || i.get(r.target.identity) !== r || isDelivered(n)) continue; o(); try { p.assertCurrent?.(); l?.(); } catch { if (p.ownGitHubProfileId) { if (r.snapshot === a) r.snapshot = void 0; invalidatePrReader(f, e.broadcastToConnIds); } continue; } const m = Object.create(null); m[c] = a; recordSessionPrDiagnostic("broadcast", r.target); e.broadcastToConnIds(CONTROL_UI_SESSION_PULL_REQUESTS_CHANGED_EVENT, { sessions: m }, /* @__PURE__ */ new Set([f]), { sessionKeys: [r.target.params.sessionKey], agentId: r.target.params.agentId }); if (t.get(f)?.get(c) === n) { n.deliveredHash = d; if (s) delete n.refreshPending; } } } }); }; const pollNow = () => { if (u.isClosing) return Promise.resolve(); return u.track(async () => { const e = []; for (const [t, n] of i) if (n.connIds.size > 0) e.push(n.target.taskReceiptsOnly ? currentKeyState(t) : loadSnapshot(t)); await Promise.all([ Promise.allSettled(n), f.settle(), ...e ]); await Promise.allSettled(n); }); }; const p = sessionChanges.subscribeFacts((e) => { const t = "facts" in e ? e.facts?.kind : void 0; const n = "all" in e && (e.scope === "profiles" || e.scope === "config" || e.scope === "config-profiles"); if (i.size === 0 || !n && !sessionChangeScopeAffectsStoredRows(e) || !e.factsInvalidated && (t === "unchanged" || t === "participants" || t === "category") || e.factsInvalidated === "category") return; const r = []; for (const [t, a] of i) if (!("sessionKey" in e && e.sessionKey === a.target.params.sessionKey && e.facts?.kind === "removed") && (!n || a.target.ownGitHubProfileId) && (a.target.taskReceipts || a.target.ownGitHubProfileId) && a.connIds.size) r.push(t); if (r.length > 0) u.track(async () => { await yieldSessionListWork(); return Promise.allSettled(r.map(currentKeyState)); }).catch(() => {}); }); const m = githubPublicationReceipts.subscribeFacts((e) => { if (e.kind !== "committed" && e.kind !== "unknown") return; for (const [e, t] of i) { if (!t.target.taskReceipts) continue; t.snapshot = void 0; if (t.prepared) sessionChanges.emit({ ...t.target.params, scope: "runtime" }); if (t.connIds.size) u.track(async () => { await a.get(e)?.promise; await loadSnapshot(e); }).catch(() => {}); } }); const replace = (a, s, c = /* @__PURE__ */ new Set(), d = /* @__PURE__ */ new Set()) => { let f = c; const p = new Set(s); const m = /* @__PURE__ */ new Set([...p, ...d]); if (u.isClosing) return Promise.resolve(); const h = a.trim(); if (!h || e.isConnectionActive?.(h) === false) { unsubscribe(h); return Promise.resolve(); } const g = r.get(h)?.refreshSessionKeys; const _ = { refreshSessionKeys: g?.size ? /* @__PURE__ */ new Set([...f, ...[...g].filter((e) => p.has(e))]) : f }; r.set(h, _); for (const e of m) { const n = t.get(h)?.get(e); if (n && f.has(e)) n.refreshPending = true; } const v = u.track(async () => { const n = t.get(h); const a = /* @__PURE__ */ new Map(); for (const t of m) { const r = parseAgentSessionKey(t); const i = r?.rest === "global" ? { sessionKey: "global", agentId: r.agentId } : { sessionKey: t }; const o = n?.get(t); const s = !p.has(t); let c = o?.target.taskReceiptsOnly === true === s ? o?.readCurrent : void 0; let l = await c?.(); if (!l) { c = await e.prepareRead(h, { ...i, taskReceiptsOnly: s }); l = await c?.(); } if (!c || !l) continue; const u = o?.target.identity === l.identity && c === o.readCurrent ? o : { readCurrent: c, target: l }; if (u !== o && _.refreshSessionKeys?.has(t)) { u.refreshPending = true; if (!f.has(t)) f = /* @__PURE__ */ new Set([...f, t]); } a.set(t, u); } const s = !u.isClosing && r.get(h) === _; if (!s) { const e = t.get(h); for (const [t, n] of a) if (!f.has(t) || e?.get(t) !== n || !n.refreshPending) a.delete(t); } if (a.size === 0) { if (s) unsubscribe(h); return; } if (s) { t.set(h, a); _.refreshSessionKeys = void 0; for (const [e, t] of a) { const r = n?.get(e); const a = r && i.get(r.target.identity); addControlUiSessionPrMembership(stateForTarget(t.target, void 0, a), h, e); } removeMemberships(h, n, a); if (!l) l = o.schedule({ id: "control-ui-session-pr-poll", atMs: o.now() + CONTROL_UI_SESSION_PR_POLL_INTERVAL_MS, everyMs: CONTROL_UI_SESSION_PR_POLL_INTERVAL_MS, run: pollNow }); } await Promise.all(Array.from(a, async ([e, n]) => { const r = n.target.identity; const i = await currentKeyState(r); if (!i) return; return withSource(i.target, async (a, o) => { const s = stateForTarget(i.target, o); const isCurrent = () => t.get(h)?.get(e) === n; const c = f.has(e); const l = c ? void 0 : s.snapshot; if (l) { if (!n.deliveredHash) await push(/* @__PURE__ */ new Set([h]), s, l, a, false, e); return; } const u = await loadSnapshot(r, c); a(); if (isCurrent() && (c ? n.refreshPending : !n.deliveredHash)) await push(/* @__PURE__ */ new Set([h]), s, u, a, c, e); }).catch(() => {}); })); }); n.add(v); const releaseReplacement = () => { n.delete(v); if (r.get(h) === _) r.delete(h); }; v.then(releaseReplacement, releaseReplacement); return v; }; const unsubscribe = (e) => { const n = e.trim(); if (!n) return; r.delete(n); removeMemberships(n, t.get(n)); t.delete(n); if (t.size === 0) { l?.cancel(); l = void 0; } }; const stop = () => { if (d) return d; u.beginClose(); o.beginClose(); f.stop(); m(); p(); t.clear(); r.clear(); n.clear(); for (const e of i.values()) { e.cancelRefresh?.(); e.cacheLifetime.abort(null); } i.clear(); d = Promise.all([u.drain(), o.stop()]).then(() => a.clear()); return d; }; return { read: f.read, readPrepared: f.readPrepared, replace, unsubscribe, pollNow, stop }; } //#endregion export { parseControlUiSessionPullRequestsSubscribeParams as n, createControlUiSessionPullRequestSubscriptions as t };