UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

974 lines (973 loc) • 36.1 kB
import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { n as GATEWAY_CLIENT_IDS } from "./client-info-Cm1BcrMm.mjs"; import { t as GATEWAY_OWNER_PROFILE_ID } from "./user-profile-constants-Bj3FwpfE.mjs"; import { n as enqueueKeyedTask } from "./keyed-async-queue-DewLnYvW.mjs"; import { F as isPrivateNodeInvokeCommand, l as NODE_MCP_TOOLS_CALL_COMMAND } from "./node-commands-BfMJIlXP.mjs"; import { n as monotonicNow } from "./monotonic-time-Cc4T2fkU.mjs"; import { i as MAX_BUFFERED_BYTES } from "./server-constants-CYohpfLc.mjs"; import { r as parseComputerUseCapabilityDescriptor } from "./computer-use-contract-DrB9JL-Y.mjs"; import { t as intersectNodePermissionSurface } from "./node-pairing-surface-0CH0V-VR.mjs"; import { a as removeRemoteNodeSkills, o as replaceRemoteNodeSkills, r as recordRemoteSkillNodeInfo } from "./remote-skills-DesALNDd.mjs"; import { n as serializeNodeEvent } from "./node-invoke-request-DwLtMARG.mjs"; import { _ as NodeSystemRunEvents, a as invalidateNodeCatalog, c as isNodeRegistryPendingInvokeConnectionActive, d as registerNodeRegistryPrivateRuntime, g as isNodeWorkerHostClientId, o as invokeLifecycleNodeRegistry, p as settleNodeRegistryPairingGenerationChange, r as forgetNodeRunnerInventory, s as invokePublicNodeRegistry, u as reconcileNodeRunnerAvailability } from "./node-registry-private-Bz6rjvDD.mjs"; import { n as logRejectedLargePayload } from "./diagnostic-payload-KWldAlR0.mjs"; import { t as closeGatewayTransportWithGrace } from "./connection-transport-close-C7HyHuZq.mjs"; import { i as NODE_SKILL_NAME_RE, n as NODE_SKILL_MAX_DESCRIPTION_LENGTH, r as NODE_SKILL_MAX_TOTAL_BYTES, t as NODE_SKILL_MAX_CONTENT_BYTES } from "./node-skill-constraints-BWWr2p01.mjs"; import { o as setActiveNodeContexts } from "./active-node-context-Cw5OntFe.mjs"; import { f as retainFulfilledNodeCapabilities, l as resolveNodeCommandAllowlist } from "./node-command-policy-DkH-pkTr.mjs"; import { r as NodeInvokeStreamController } from "./node-registry.invoke-stream-pPc5-Kl3.mjs"; import { a as removeConnectedNodePluginTools, i as normalizeNodePluginToolDescriptors, o as replaceConnectedNodePluginTools, t as createRegisteredNodePluginToolDescriptorMap } from "./node-plugin-tool-snapshot-CrPIkFh2.mjs"; import { t as resolveEffectiveComputerUseDescriptor } from "./node-computer-use-descriptor-D0U4PsFz.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/gateway/node-event-payload.ts const SERIALIZED_EVENT_PAYLOAD = Symbol("openclaw.serializedEventPayload"); /** Serialize an event payload once so fanout can reuse the same JSON string. */ function serializeEventPayload(e) { if (e === void 0) return null; const t = JSON.stringify(e); return typeof t === "string" ? { json: t, [SERIALIZED_EVENT_PAYLOAD]: true } : null; } /** Narrow values created by serializeEventPayload. */ function isSerializedEventPayload(e) { return typeof e === "object" && e !== null && Reflect.get(e, SERIALIZED_EVENT_PAYLOAD) === true && typeof Reflect.get(e, "json") === "string"; } //#endregion //#region src/gateway/node-event-send.ts function sendNodeWebSocketEvent(e, t, n) { if (e.readyState !== 1) return false; if (e.bufferedAmount > 52428800) { logRejectedLargePayload({ surface: "gateway.ws.outbound_buffer", bytes: e.bufferedAmount, limitBytes: MAX_BUFFERED_BYTES, reason: "ws_send_buffer_close" }); closeGatewayTransportWithGrace(e, 1008, "slow consumer"); return false; } try { const r = Buffer.from(n()); const i = e.send(r, { binary: false }); e.recordEventSent?.(t, r, void 0, void 0, i); return true; } catch { return false; } } //#endregion //#region src/gateway/node-registry-pairing.ts function pairingBindingForSession(e) { return { identity: e.pairingIdentity, ...e.pairingGeneration ? { generation: e.pairingGeneration } : {} }; } function pairingStateMatchesBinding(e, t) { if (!t) return false; if (e.identity !== t.identity) return false; return !e.generation || e.generation === t.generation; } function isPublishedPairingCurrent(e, t) { if (!t) return true; try { return Boolean(e.pairingIdentity && t(e.nodeId, { identity: e.pairingIdentity, ...e.pairingGeneration ? { generation: e.pairingGeneration } : {} })); } catch { return false; } } //#endregion //#region src/gateway/node-registry.host-stats.ts const HOST_STATS_CHECKPOINT_MS = 3e5; const log$2 = createSubsystemLogger("gateway/nodes"); var NodeHostStatsCheckpoints = class { constructor(e) { this.options = e; this.checkpoints = /* @__PURE__ */ new Map(); this.pending = /* @__PURE__ */ new Set(); this.runInOwnerContext = AsyncLocalStorage.snapshot(); } record(e) { if (this.options.persistHostStats && e.pairingGeneration && !this.closing) { let t = this.checkpoints.get(e); if (!t) { t = { failed: false }; this.checkpoints.set(e, t); } t.failed = false; this.captureSampleDeadline(e, t); if (!t.pending && !t.saved) this.persist(e, t); this.schedule(); } } /** * Pairs a received sample's persisted receipt with the monotonic clock while the two * are still in sync. Persisting later (the timer writes a buffered sample) would * otherwise fold any clock step since the receipt into the following budget. */ captureSampleDeadline(e, t) { const n = e.hostStats; if (!n || n === t.saved) return; t.sample = { stats: n, nextCheckpointAtMs: monotonicNow() + Math.max(0, n.updatedAtMs + HOST_STATS_CHECKPOINT_MS - Date.now()) }; } persist(e, t) { const n = e.hostStats; const r = this.options.persistHostStats; const i = e.pairingGeneration; if (!n || !r || !i || t.pending) return; const a = t.sample?.stats === n ? t.sample.nextCheckpointAtMs : void 0; const o = this.runInOwnerContext(async () => { try { if (await r({ nodeId: e.nodeId, hostStats: n, expectedPairingGeneration: { nodeId: e.nodeId, key: i } })) { t.saved = n; t.savedAtMonotonicMs = a; } else t.failed = true; } catch (n) { t.failed = true; log$2.warn(`failed to persist node host stats for ${e.nodeId}: ${formatErrorMessage(n)}`); } }).then(() => { t.pending = void 0; this.pending.delete(o); this.schedule(); }); t.pending = o; this.pending.add(o); } schedule() { clearTimeout(this.timer); this.timer = void 0; if (this.closing) return; let e = Infinity; for (const [t, n] of this.checkpoints) if (!n.pending && !n.failed && t.hostStats !== n.saved) e = Math.min(e, n.savedAtMonotonicMs ?? 0); if (e === Infinity) return; this.runInOwnerContext(() => { this.timer = setTimeout(() => { for (const [e, t] of this.checkpoints) if (!t.pending && !t.failed && e.hostStats !== t.saved && (t.savedAtMonotonicMs ?? 0) <= monotonicNow()) this.persist(e, t); this.schedule(); }, Math.max(0, e - monotonicNow())); this.timer.unref(); }); } forget(e) { this.checkpoints.delete(e); this.schedule(); } close() { clearTimeout(this.timer); return this.closing ??= (async () => { await Promise.all(this.pending); for (const [e, t] of this.checkpoints) if (e.hostStats !== t.saved) this.persist(e, t); await Promise.all(this.pending); this.checkpoints.clear(); })(); } }; //#endregion //#region src/gateway/node-registry.presence.ts function preferActiveNode(e, t) { return t.lastActiveAtMs !== void 0 && (!e || t.lastActiveAtMs > (e.lastActiveAtMs ?? 0) || t.lastActiveAtMs === e.lastActiveAtMs && (t.presenceUpdatedAtMs ?? 0) > (e.presenceUpdatedAtMs ?? 0)) ? t : e; } function selectActiveNode(e) { return e.reduce(preferActiveNode, void 0); } function selectActiveNodesByProfile(e) { const t = /* @__PURE__ */ new Map(); for (const n of e) { const e = n.client.authenticatedUserProfile?.profileId; const r = e === "gateway-owner" ? void 0 : e; t.set(r, preferActiveNode(t.get(r), n)); } return new Map([...t].flatMap(([e, t]) => t ? [[e, t]] : [])); } function updateNodePresenceActivity(e, t) { const n = t.source ?? "system"; if (!e || !t.connId || e.connId !== t.connId || e.client.socket.readyState !== 1) return null; if (n === "app") { if (e.clientId !== GATEWAY_CLIENT_IDS.MACOS_APP || e.clientMode !== "node" || !/^(?:darwin|macos(?: \d+(?:\.\d+){0,2})?)$/i.test(e.platform ?? "")) return null; } else if (e.permissions?.accessibility !== true) return null; const r = t.observedAtMs ?? Date.now(); const i = Math.max(0, r - t.idleSeconds * 1e3); if (e.presenceActivitySource !== n) e.lastActiveAtMs = i; else if (t.saturated !== true || e.lastActiveAtMs === void 0) e.lastActiveAtMs = Math.max(e.lastActiveAtMs ?? 0, i); e.presenceActivitySource = n; e.presenceUpdatedAtMs = r; return e; } function clearNodePresenceActivity(e, t, n) { if (!e || !t || e.connId !== t) return null; if (n === "system" && e.presenceActivitySource === "app" || e.lastActiveAtMs === void 0 && e.presenceUpdatedAtMs === void 0) return false; e.lastActiveAtMs = void 0; e.presenceUpdatedAtMs = void 0; e.presenceActivitySource = void 0; return true; } //#endregion //#region src/gateway/node-skill-descriptors.ts const log$1 = createSubsystemLogger("gateway/node-skills"); function normalizeNodeSkillDescriptors(e) { const t = []; const n = /* @__PURE__ */ new Set(); let r = 0; let i = 0; for (const a of e.skills ?? []) { const e = a.name.trim(); const o = a.description.trim(); const s = Buffer.byteLength(a.content, "utf8"); if (!NODE_SKILL_NAME_RE.test(e) || !o || o.length > 1024 || !a.content || s > 65536 || n.has(e) || t.length >= 64 || r + s > 524288) { i += 1; continue; } n.add(e); r += s; t.push({ name: e, description: o, content: a.content }); } if (i > 0) log$1.warn(`node ${e.nodeId} published ${e.skills?.length ?? 0} skill descriptors; dropped ${i} invalid or over-limit descriptors`); return t.toSorted((e, t) => e.name.localeCompare(t.name, "en")); } //#endregion //#region src/gateway/node-registry.ts const NODE_SESSION_POLICIES = /* @__PURE__ */ new WeakMap(); /** Reads commands withheld by current policy from the live session's declaration. */ function readNodeSessionWithheldCommands(e) { return NODE_SESSION_POLICIES.get(e)?.withheldCommands ?? []; } const FAILED_EVENT_LOG_INTERVAL_MS = 3e4; const log = createSubsystemLogger("gateway/nodes"); const failedEventLogAtByNode = /* @__PURE__ */ new WeakMap(); var NodeRegistry = class { constructor(e = {}) { this.options = e; this.nodesById = /* @__PURE__ */ new Map(); this.nodesByConn = /* @__PURE__ */ new Map(); this.eventTransportsByConn = /* @__PURE__ */ new Map(); this.pendingInvokes = /* @__PURE__ */ new Map(); this.invokeStreams = new NodeInvokeStreamController({ pendingInvokes: this.pendingInvokes, sendCancel: (e, t) => { const n = this.nodesById.get(t.nodeId); if (!n || n.connId !== t.connId || !t.onProgress && (!isNodeWorkerHostClientId(n.clientId) || n.clientMode !== "node")) return; this.sendEventToSession(n, "node.invoke.cancel", { invokeId: e, nodeId: t.nodeId }); }, isConnectionActive: (e) => { const t = this.nodesById.get(e.nodeId); return isNodeRegistryPendingInvokeConnectionActive({ registry: this, pending: e, currentNode: t }); }, isCommandAllowed: (e, t) => this.isCommandAllowed(e, t), sendInput: (e, t, n, r) => { const i = this.nodesById.get(t.nodeId); return i ? this.sendEventToSession(i, "node.invoke.input", { id: e, nodeId: t.nodeId, seq: n, payloadJSON: r }) : false; }, onFailedResult: (e) => { if (e.systemRunEvent) this.systemRunEvents.forget({ nodeId: e.nodeId, connId: e.connId, ...e.systemRunEvent }); }, disconnectPending: (e) => { e.resolve({ ok: false, error: e.command === "mcp.tools.call.v1" ? { code: "MCP_SERVER_UNAVAILABLE", message: "node host disconnected during MCP tool call" } : { code: "DISCONNECTED", message: `node disconnected (${e.command})` } }); } }); this.systemRunEvents = new NodeSystemRunEvents(this.pendingInvokes, (e) => this.nodesById.get(e)); this.pairingGenerationEventChains = /* @__PURE__ */ new Map(); this.hostStatsCheckpoints = new NodeHostStatsCheckpoints(e); this.committedConfig = e.getConfig?.(); registerNodeRegistryPrivateRuntime(this, { getNode: (e) => this.nodesById.get(e), isCommandAllowed: (e, t) => this.isCommandAllowed(e, t, this.options.getConfig?.()), listCurrentConnected: () => this.listCurrentConnected(), getCurrentConnected: (e) => this.getCurrentConnected(e), hasCurrentPairingStateResolver: Boolean(this.options.resolveCurrentPairingState), resolvePairingLease: async (e) => { const t = this.nodesById.get(e.nodeId); if (!t || t.connId !== e.connId || t.pairingIdentity !== e.pairingIdentity || t.pairingGeneration !== e.pairingGeneration) return { status: "stale", presenceInvalidated: false }; return await this.resolvePairingLease(this.capturePairingLease(t), { invalidateStale: false }); }, pendingInvokes: this.pendingInvokes, invokeStreams: this.invokeStreams, sendEventToSession: (e, t, n) => { const r = this.nodesById.get(e.nodeId); return r?.connId === e.connId ? this.sendEventToSession(r, t, n) : false; }, rememberAuthorizedSystemRunEvent: (e) => this.systemRunEvents.remember(e), publishActiveNodeContext: () => this.publishActiveNodeContext(), closeHostStats: () => this.hostStatsCheckpoints.close() }); } listConnectedSessions() { return [...this.nodesById.values()].filter((e) => e.client.invalidated !== true); } capturePairingLease(e) { return { session: e, nodeId: e.nodeId, connId: e.connId, binding: pairingBindingForSession(e) }; } currentSessionForLease(e) { const t = this.nodesById.get(e.nodeId); return t === e.session && t.connId === e.connId && t.pairingIdentity === e.binding.identity && t.pairingGeneration === e.binding.generation && t.client.invalidated !== true ? t : void 0; } settlePairingLease(e) { const t = this.currentSessionForLease(e.lease); if (!t) return { status: "stale", presenceInvalidated: false }; if (e.isCurrent) return { status: "current", session: t }; return { status: "stale", presenceInvalidated: e.invalidateStale ? this.invalidateSessionForPairingChange(t) : false }; } async resolvePairingLease(e, t) { const n = this.options.resolveCurrentPairingState; if (!n) { const t = this.currentSessionForLease(e); return t ? { status: "current", session: t } : { status: "stale", presenceInvalidated: false }; } let r; try { r = await n(e.nodeId); } catch { return { status: "unavailable" }; } let i = pairingStateMatchesBinding(e.binding, r); try { if (i && this.options.isPairingStateCurrent) i = this.options.isPairingStateCurrent(e.nodeId, e.binding); } catch { return { status: "unavailable" }; } return this.settlePairingLease({ lease: e, isCurrent: i, invalidateStale: t.invalidateStale }); } refreshSessionPolicy(e) { invalidateNodeCatalog(this); const t = expectDefined(NODE_SESSION_POLICIES.get(e), "registered node policy missing"); const n = this.committedConfig; const r = e.sessionCommandsCeiling ?? e.declaredCommands; const i = n ? resolveNodeCommandAllowlist(n, { ...e, caps: e.sessionCapsCeiling ?? e.declaredCaps, commands: r, approvedCommands: r }) : void 0; e.commands = t.approvedCommands.filter((e) => r.includes(e) && (!i || i.has(e))); if (i) t.withheldCommands = r.filter((e) => !i.has(e)); e.caps = retainFulfilledNodeCapabilities({ caps: t.approvedCaps, admittedCommands: e.commands, withheldCommands: r.filter((t) => !e.commands.includes(t)) }); e.computerUse = resolveEffectiveComputerUseDescriptor({ commands: e.commands, declared: e.declaredComputerUse }); Object.assign(e.client.connect, { commands: e.commands, caps: e.caps, computerUse: e.computerUse }); const a = normalizeNodePluginToolDescriptors({ nodeId: e.nodeId, tools: e.declaredNodePluginTools, allowedCommands: e.commands, enabled: n?.gateway?.nodes?.pluginTools?.enabled, registeredDescriptors: createRegisteredNodePluginToolDescriptorMap(this.options.listRegisteredNodePluginToolCommands?.()) }); e.nodePluginTools = a.map((e) => e.descriptor); replaceConnectedNodePluginTools({ nodeId: e.nodeId, displayName: e.displayName, tools: a }); e.nodeSkills = n?.gateway?.nodes?.allowSkills === false ? [] : t.skills; recordRemoteSkillNodeInfo(e); replaceRemoteNodeSkills({ nodeId: e.nodeId, displayName: e.displayName, skills: e.nodeSkills }); } isCommandAllowed(e, t, n) { if (!this.committedConfig || isPrivateNodeInvokeCommand(t)) return true; const r = this.nodesById.get(e); return Boolean(r?.commands.includes(t) && (!n || resolveNodeCommandAllowlist(n, r).has(t))); } refreshRuntimePolicy(e = this.committedConfig) { this.committedConfig = e; const t = this.listConnected(); for (const e of t) this.refreshSessionPolicy(e); this.invokeStreams.reconcileRuntimePolicy(); return t; } /** Register a websocket client as the current connection for its node id. */ register(e, t) { return this.registerSession(e, t); } /** Register a node whose events are delivered by an HTTP polling transport. */ registerTransport(e, t, n) { return this.registerSession(e, t, n); } registerSession(e, t, n) { if (!t.pairingIdentity) throw new Error("node session registration requires pairing identity"); const r = e.connect; const i = r.device?.id ?? r.client.id; const a = this.nodesById.get(i); const o = a?.pairingGeneration; const s = r.caps ?? []; const c = r.commands ?? []; const l = r.declaredCaps ?? s; const u = r.declaredCommands ?? c; const d = r.computerUse === void 0 ? void 0 : parseComputerUseCapabilityDescriptor(r.computerUse); const f = r.declaredComputerUse; const p = f === void 0 ? d : parseComputerUseCapabilityDescriptor(f); const m = r.sessionCapsCeiling ?? l; const h = r.sessionCommandsCeiling ?? u; const g = r.declaredPermissions ?? r.permissions; const _ = t.approvedSurface ? intersectNodePermissionSurface({ approved: t.approvedSurface.permissions, declared: g }) : r.permissions; r.permissions = _; const v = { nodeId: i, connId: e.connId, pairingIdentity: t.pairingIdentity, ...t.pairingGeneration ? { pairingGeneration: t.pairingGeneration } : {}, client: e, clientId: r.client.id, clientMode: r.client.mode, displayName: r.client.displayName, platform: r.client.platform, version: r.client.version, coreVersion: r.coreVersion, uiVersion: r.uiVersion, deviceFamily: r.client.deviceFamily, modelIdentifier: r.client.modelIdentifier, remoteIp: t.remoteIp, declaredCaps: l, sessionCapsCeiling: m, caps: s, declaredCommands: u, sessionCommandsCeiling: h, commands: c, ...p ? { declaredComputerUse: p } : {}, ...d ? { computerUse: d } : {}, declaredNodePluginTools: [], nodePluginTools: [], nodeSkills: [], declaredPermissions: g, permissions: _, pathEnv: r.pathEnv, connectedAtMs: Date.now() }; NODE_SESSION_POLICIES.set(v, { approvedCaps: (t.approvedSurface?.caps ?? s).filter((e) => m.includes(e)), approvedCommands: (t.approvedSurface?.commands ?? c).filter((e) => h.includes(e)), skills: [], withheldCommands: r.withheldCommands ?? [] }); const y = a?.lastActiveAtMs !== void 0; forgetNodeRunnerInventory(this, e.connId); this.nodesById.set(i, v); this.nodesByConn.set(e.connId, i); if (a && a.connId !== e.connId) this.unregister(a.connId); if (o && v.pairingGeneration && o !== v.pairingGeneration) this.options.onPairingGenerationChanged?.({ nodeId: i, previousPairingGeneration: o, nextPairingGeneration: v.pairingGeneration, preserveSessionState: false }); if (n) this.eventTransportsByConn.set(e.connId, n); else this.eventTransportsByConn.delete(e.connId); this.refreshSessionPolicy(v); if (a) { this.hostStatsCheckpoints.forget(a); this.clearDesktopAvailability(a); } if (y) this.publishActiveNodeContext(); reconcileNodeRunnerAvailability(this, i); return v; } /** Unregister one connection and reject invokes tied to that connection. */ unregister(e) { const t = this.nodesByConn.get(e); if (!t) return null; this.nodesByConn.delete(e); this.eventTransportsByConn.delete(e); forgetNodeRunnerInventory(this, e); const n = this.nodesById.get(t); const r = n?.connId === e; if (r) { this.hostStatsCheckpoints.forget(n); invalidateNodeCatalog(this); const e = n.lastActiveAtMs !== void 0; this.nodesById.delete(t); this.clearDesktopAvailability(n); removeConnectedNodePluginTools(t); removeRemoteNodeSkills(t); if (e) this.publishActiveNodeContext(); } this.disconnectSessionInvokes(e); reconcileNodeRunnerAvailability(this, t); return r ? t : null; } listConnected() { return this.listConnectedSessions(); } /** Filter connected sessions against an already-loaded pairing-state snapshot. */ listConnectedForPairingStates(e) { return this.listConnectedSessions().filter((t) => { const n = e.get(t.nodeId); return pairingStateMatchesBinding(pairingBindingForSession(t), n); }); } /** Reconcile connected sessions against the pairing owner's committed publication. */ listCurrentConnectedSync() { const e = this.options.isPairingStateCurrent; if (!e) return this.listConnected(); const t = []; for (const n of this.listConnectedSessions()) { const r = this.capturePairingLease(n); let i; try { i = e(n.nodeId, r.binding); } catch { continue; } t.push(this.settlePairingLease({ lease: r, isCurrent: i, invalidateStale: true })); } return this.projectNodePairingLeaseResolutions(t); } /** Resolve persistent pairing state before projecting connected sessions. */ async listCurrentConnected() { return await this.resolveCurrentConnectedSessions(this.listConnectedSessions()); } async getCurrentConnected(e) { const t = this.nodesById.get(e); return t && t.client.invalidated !== true ? (await this.resolveCurrentConnectedSessions([t]))[0] : void 0; } async resolveCurrentConnectedSessions(e) { const t = await Promise.all(e.map((e) => this.resolvePairingLease(this.capturePairingLease(e), { invalidateStale: true }))); return this.projectNodePairingLeaseResolutions(t); } projectNodePairingLeaseResolutions(e) { const t = []; let n = false; for (const r of e) if (r.status === "current") t.push(r.session); else if (r.status === "stale") n ||= r.presenceInvalidated; if (n) this.publishActiveNodeContext(); return t; } invalidateSessionForPairingChange(e, t = "device-pairing-changed") { if (this.nodesById.get(e.nodeId) !== e || e.client.invalidated === true) return false; e.client.invalidated = true; this.hostStatsCheckpoints.forget(e); invalidateNodeCatalog(this); e.client.invalidatedReason ??= t; this.clearDesktopAvailability(e); forgetNodeRunnerInventory(this, e.connId); removeConnectedNodePluginTools(e.nodeId); removeRemoteNodeSkills(e.nodeId); this.disconnectSessionInvokes(e.connId); reconcileNodeRunnerAvailability(this, e.nodeId); this.options.onPairingInvalidated?.({ nodeId: e.nodeId, connId: e.connId }); return e.lastActiveAtMs !== void 0; } /** Immediately retires one exact transport after its persisted pairing authority changes. */ invalidateConnectionForPairingChange(e, t = "device-pairing-changed") { const n = this.nodesByConn.get(e); const r = n ? this.nodesById.get(n) : void 0; if (!r || r.connId !== e) return false; if (this.invalidateSessionForPairingChange(r, t)) this.publishActiveNodeContext(); return r.client.invalidated === true; } get(e) { return this.getRegisteredSession(e); } getRegisteredSession(e) { const t = this.nodesById.get(e); return t?.client.invalidated === true ? void 0 : t; } /** Return only the session authenticated for the requested persistent pairing generation. */ getForPairingGeneration(e, t) { return this.getRegisteredSessionForPairingGeneration(e, t); } getRegisteredSessionForPairingGeneration(e, t) { const n = this.getRegisteredSession(e); return n?.pairingGeneration === t ? n : void 0; } /** Revalidates that one inbound node connection still owns its persisted pairing state. */ async isConnectionCurrentPairingState(e) { const t = this.nodesByConn.get(e); const n = t ? this.nodesById.get(t) : void 0; if (!t || !n || n.connId !== e || n.client.invalidated === true || !this.options.resolveCurrentPairingState) return false; const r = await this.resolvePairingLease(this.capturePairingLease(n), { invalidateStale: true }); return this.projectNodePairingLeaseResolutions([r]).length > 0; } clearDesktopAvailability(e) { if (!e.desktopAvailability) return; delete e.desktopAvailability; this.options.onDesktopAvailabilityChanged?.(e.nodeId); } /** Records operational state without publishing activity or retaining it across connections. */ updateDesktopAvailability(e) { const t = this.getRegisteredSession(e.nodeId); if (!t || t.connId !== e.connId || t.client.socket.readyState !== 1) return null; if (t.desktopAvailability?.state === e.availability.state) return false; t.desktopAvailability = { state: e.availability.state }; this.options.onDesktopAvailabilityChanged?.(t.nodeId); return true; } /** Stores the latest resource snapshot for the exact authenticated node connection. */ updateHostStats(e) { const t = this.getRegisteredSession(e.nodeId); if (!t || t.connId !== e.connId) return null; t.hostStats = { ...e.stats, updatedAtMs: e.observedAtMs ?? Date.now() }; invalidateNodeCatalog(this); this.hostStatsCheckpoints.record(t); return t.hostStats; } /** Updates recent input activity for the exact authenticated node connection. */ updatePresenceActivity(e) { const t = updateNodePresenceActivity(this.getRegisteredSession(e.nodeId), e); if (t) this.publishActiveNodeContext(); return t; } /** Clears recent input activity for the exact authenticated node connection. */ clearPresenceActivity(e) { const t = clearNodePresenceActivity(this.getRegisteredSession(e.nodeId), e.connId); if (t) this.publishActiveNodeContext(); return t; } /** Returns the connected node with the freshest reported local input. */ getActiveNode(e = this.listConnected()) { return selectActiveNode(e); } publishActiveNodeContext() { invalidateNodeCatalog(this); const e = selectActiveNodesByProfile(this.listConnectedSessions()); setActiveNodeContexts([...e].map(([e, t]) => { const n = this.capturePairingLease(t); const r = t.client.authenticatedUserProfile?.profileId; return { nodeId: t.nodeId, profileId: e, pairingGeneration: t.pairingGeneration, prepare: () => this.getCurrentConnected(n.nodeId), isCurrent: () => { if (!this.currentSessionForLease(n) || t.client.authenticatedUserProfile?.profileId !== r) return false; return this.options.isPairingStateCurrent ? this.options.isPairingStateCurrent(n.nodeId, n.binding) : true; } }; })); } /** Probe websocket liveness with ping/pong when the socket supports it. */ async checkConnectivity(e, t = 2e3) { const n = this.getRegisteredSession(e); if (!n) return { ok: false, error: { code: "NOT_CONNECTED", message: "node not connected" } }; const currentConnectionResult = (t) => this.nodesById.get(e) === n && n.client.invalidated !== true ? t : { ok: false, error: { code: "NOT_CONNECTED", message: "node connection changed during connectivity check" } }; const r = this.eventTransportsByConn.get(n.connId); if (r) return currentConnectionResult(r.checkConnectivity ? await r.checkConnectivity(t) : { ok: true }); const i = n.client.webSocket; if (n.client.socket.readyState !== 1) return { ok: false, error: { code: "NOT_CONNECTED", message: "node socket not open" } }; if (!i) return { ok: true }; const a = Math.max(1, Math.trunc(t)); return await new Promise((e) => { let t = false; const cleanup = () => { i.off("pong", onPong); i.off("close", onClose); i.off("error", onError); }; const finish = (r) => { if (t) return; t = true; clearTimeout(n); cleanup(); e(currentConnectionResult(r)); }; const onPong = () => finish({ ok: true }); const fail = (e, t) => finish({ ok: false, error: { code: e, message: t } }); const onClose = () => fail("NOT_CONNECTED", "node socket closed during connectivity check"); const onError = (e) => fail("UNAVAILABLE", e instanceof Error ? e.message : "node socket error during connectivity check"); const n = setTimeout(() => fail("TIMEOUT", "node connectivity check timed out"), a); i.once("pong", onPong); i.once("close", onClose); i.once("error", onError); try { i.ping(void 0, false, (e) => { if (e) fail("UNAVAILABLE", e.message); }); } catch (e) { fail("UNAVAILABLE", e instanceof Error ? e.message : "node ping failed"); } }); } updateNodePluginTools(e, t, n) { const r = this.getRegisteredSession(e); if (!r || r.connId !== t) return null; r.declaredNodePluginTools = [...n]; this.refreshSessionPolicy(r); return r; } updateNodeSkills(e, t, n) { const r = this.getRegisteredSession(e); if (!r || r.connId !== t) return null; expectDefined(NODE_SESSION_POLICIES.get(r), "registered node policy missing").skills = normalizeNodeSkillDescriptors({ nodeId: e, skills: n }); this.refreshSessionPolicy(r); return r; } updateSurface(e, t, n) { const r = this.getRegisteredSession(e); if (!r || n !== void 0 && (r.connId !== n.expectedConnId || r.pairingIdentity !== n.expectedPairingIdentity || r.pairingGeneration !== n.expectedPairingGeneration)) return null; const i = expectDefined(NODE_SESSION_POLICIES.get(r), "registered node policy missing"); const a = new Set(r.sessionCommandsCeiling ?? r.declaredCommands); i.approvedCommands = t.commands.filter((e) => a.has(e)); if ("caps" in t) { const e = new Set(r.sessionCapsCeiling ?? r.declaredCaps); i.approvedCaps = (t.caps ?? []).filter((t) => e.has(t)); } if ("permissions" in t) { r.permissions = t.permissions === void 0 ? void 0 : intersectNodePermissionSurface({ approved: t.permissions, declared: r.declaredPermissions }); r.client.connect.permissions = r.permissions; if (r.permissions?.accessibility !== true && clearNodePresenceActivity(r, r.connId, "system")) this.publishActiveNodeContext(); } const o = r.pairingGeneration; if (n) { this.hostStatsCheckpoints.forget(r); r.hostStats = void 0; r.pairingGeneration = n.nextPairingGeneration; } this.refreshSessionPolicy(r); if (n) { settleNodeRegistryPairingGenerationChange({ registry: this, nodeId: e, connId: r.connId, nextPairingGeneration: n.nextPairingGeneration }); reconcileNodeRunnerAvailability(this, e); if (o) this.options.onPairingGenerationChanged?.({ nodeId: e, previousPairingGeneration: o, nextPairingGeneration: n.nextPairingGeneration, preserveSessionState: true }); this.publishActiveNodeContext(); } return r; } async invoke(e) { return await invokePublicNodeRegistry(this, e); } /** Internal cleanup retains its owner through replies without admitting new root work. */ invokeLifecycle(e) { return invokeLifecycleNodeRegistry(this, e); } /** Send one ordered input frame to a pending streaming invoke. */ sendInvokeInput(e, t) { this.invokeStreams.sendInput(e, t); } /** Synchronous effect fence for callbacks retained across awaited host work. */ isInvokeCurrent(e, t, n) { return this.invokeStreams.isPending(e, t, n); } handleInvokeProgress(e) { return this.invokeStreams.handleProgress(e); } /** Continues only the exact live owner of a pending node invocation. */ runPendingInvokeContinuation(e) { return this.invokeStreams.runPendingContinuation(e); } /** Authorize an inbound system.run event against a recently issued node invoke. */ authorizeSystemRunEvent(e) { const t = this.authorizeSystemRunEventWithState(e); t?.release?.(); return t !== null; } authorizeSystemRunEventWithState(e) { return this.systemRunEvents.authorize(e); } disconnectSessionInvokes(e) { this.invokeStreams.handleDisconnect(e); this.systemRunEvents.disconnect(e); } handleInvokeResult(e) { return this.invokeStreams.handleResult(e); } sendEvent(e, t, n) { const r = this.nodesById.get(e); if (!r) return false; return this.sendEventToSession(r, t, n); } sendEventRaw(e, t, n) { const r = this.nodesById.get(e); if (!r) return false; return this.observeEventSend(r, t, this.sendEventRawInternal(r, t, n)); } /** Sends command-free events only to the exact authenticated pairing connection. */ async sendEventForPairingIdentity(e) { const t = this.nodesById.get(e.nodeId); if (!t || t.connId !== e.connId || t.pairingIdentity !== e.pairingIdentity || t.client.invalidated === true || !this.options.resolveCurrentPairingState) return false; const n = await this.resolvePairingLease(this.capturePairingLease(t), { invalidateStale: true }); const [r] = this.projectNodePairingLeaseResolutions([n]); return r ? this.sendEventToSession(r, e.event, e.payload) : false; } /** Sends only to a session that still owns the requested persistent pairing generation. */ async sendEventRawForPairingGeneration(e, t, n, r, i) { return await enqueueKeyedTask({ tails: this.pairingGenerationEventChains, key: e, task: async () => { let a = this.getRegisteredSessionForPairingGeneration(e, t); if (!a) return false; if (this.options.resolveCurrentPairingState) { const e = await this.resolvePairingLease(this.capturePairingLease(a), { invalidateStale: true }); a = this.projectNodePairingLeaseResolutions([e])[0]; if (!a) return false; } const o = i?.(a.connId); if (i && !o) return false; const s = this.observeEventSend(a, n, this.sendEventRawInternal(a, n, o ? o.payloadJSON : r)); if (s && this.nodesById.get(e) === a) o?.onSent?.(); return s; } }); } sendEventInternal(e, t, n) { if (e.client.invalidated === true || !isPublishedPairingCurrent(e, this.options.isPairingStateCurrent)) return false; const r = this.eventTransportsByConn.get(e.connId); if (r) return r.send(t, n); return sendNodeWebSocketEvent(e.client.socket, t, () => serializeNodeEvent(t, n)); } sendEventRawInternal(e, t, n) { if (e.client.invalidated === true || !isPublishedPairingCurrent(e, this.options.isPairingStateCurrent)) return false; if (n !== null && n !== void 0 && !isSerializedEventPayload(n)) return false; const r = this.eventTransportsByConn.get(e.connId); if (r) return r.sendRaw(t, n); return sendNodeWebSocketEvent(e.client.socket, t, () => { const e = n ? `,"payload":${n.json}` : ""; return `{"type":"event","event":${JSON.stringify(t)}${e}}`; }); } sendEventToSession(e, t, n) { return this.observeEventSend(e, t, this.sendEventInternal(e, t, n)); } observeEventSend(e, t, n) { if (n || this.nodesById.get(e.nodeId) !== e || e.client.invalidated === true) return n; const r = Date.now(); const i = failedEventLogAtByNode.get(e); if (i === void 0 || r - i >= FAILED_EVENT_LOG_INTERVAL_MS) { failedEventLogAtByNode.set(e, r); log.warn("node event delivery failed", { nodeId: e.nodeId, event: t }); } return n; } }; //#endregion export { readNodeSessionWithheldCommands as n, serializeEventPayload as r, NodeRegistry as t };