openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
17 lines • 30.1 kB
JavaScript
import"./src-0ci69Prg.mjs";import{t as expectDefined}from"./expect-DkJCbmLj.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{Jn as string,Un as record,lr as uuid,or as union,qn as strictObject,sr as unknown,xn as literal}from"./schemas-DuCQi-Qb.mjs";import{n as GATEWAY_CLIENT_IDS}from"./client-info-Dr3-kuD1.mjs";import{t as GATEWAY_OWNER_PROFILE_ID}from"./user-profile-constants-abCq1jKI.mjs";import{n as enqueueKeyedTask}from"./keyed-async-queue-qBcorzrt.mjs";import{I as isPrivateNodeInvokeCommand,u as NODE_MCP_TOOLS_CALL_COMMAND}from"./node-commands-BbC002V7.mjs";import{i as MAX_BUFFERED_BYTES}from"./server-constants-BmIepgnr.mjs";import{r as parseComputerUseCapabilityDescriptor}from"./computer-use-contract-CaYMDN7U.mjs";import{t as intersectNodePermissionSurface}from"./node-pairing-surface-COC5mZ4f.mjs";import{a as removeRemoteNodeSkills,o as replaceRemoteNodeSkills,r as recordRemoteSkillNodeInfo}from"./remote-skills-B1qhcfgp.mjs";import{r as serializeNodeEvent}from"./node-invoke-request-FOuQL-5m.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-SxRDxipR.mjs";import{n as logRejectedLargePayload}from"./diagnostic-payload-CBTOiWhC.mjs";import{t as closeGatewayTransportWithGrace}from"./connection-transport-close-BBdkIVgk.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-Hba96W-E.mjs";import{o as setActiveNodeContexts}from"./active-node-context-CPBBSfF4.mjs";import{a as canInvokeNodeMcpLocally,p as retainFulfilledNodeCapabilities,u as resolveNodeCommandAllowlist}from"./node-command-policy-Qm4E-4M-.mjs";import{r as NodeInvokeStreamController}from"./node-registry.invoke-stream-DvEJa1Bm.mjs";import{i as removeConnectedNodePluginTools,r as publishNodeSessionPluginTools}from"./node-plugin-tool-snapshot-DwntiF9S.mjs";import{t as resolveEffectiveComputerUseDescriptor}from"./node-computer-use-descriptor-Dnwo0tNo.mjs";import{n as pairingBindingForSession,r as pairingStateMatchesBinding,t as isPublishedPairingCurrent}from"./node-registry-pairing-BbhKuZOH.mjs";import{AsyncLocalStorage}from"node:async_hooks";
//!src/gateway/node-event-payload.ts
const SERIALIZED_EVENT_PAYLOAD=Symbol(`openclaw.serializedEventPayload`);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}function isSerializedEventPayload(e){return typeof e===`object`&&e!==null&&Reflect.get(e,SERIALIZED_EVENT_PAYLOAD)===true&&typeof Reflect.get(e,`json`)===`string`}
//!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}}
//!src/gateway/node-mcp-elicitation.ts
const MAX_PENDING_QUESTIONS_PER_CALL=4;const identity={id:string().min(1).max(256),requestId:uuid()};const eventSchema=union([strictObject({...identity,params:record(string(),unknown())}),strictObject({...identity,cancel:literal(true)})]);var NodeMcpElicitationRegistry=class{constructor(){this.grants=/* @__PURE__ */ new Map}register(e){const{id:t,node:n,handle:r}=e;const i=new AbortController;const a=AbortSignal.any([e.signal,n.client.connectionSignal,i.signal].filter(e=>e!==void 0));a.throwIfAborted();if(this.grants.has(t))throw new Error(`MCP elicitation grant already registered`);const release=()=>i.abort();this.grants.set(t,{node:n,handle:AsyncLocalStorage.bind(r),signal:a,release,questions:/* @__PURE__ */ new Map});a.addEventListener(`abort`,()=>this.grants.delete(t),{once:true});return release}retire(e){if(!e)return;for(const t of this.grants.values())if(t.node===e)t.release()}async receive(e,t,n){const r=eventSchema.safeParse(t);if(!r.success)throw new Error(`Invalid MCP elicitation event`);const{id:i,requestId:a}=r.data;const o=this.grants.get(i);if(!o||o.node!==e)throw new Error(`MCP elicitation grant is unavailable`);if(`cancel`in r.data){o.questions.get(a)?.abort();return{action:`cancel`}}if(o.questions.has(a)||o.questions.size>=MAX_PENDING_QUESTIONS_PER_CALL)throw new Error(`MCP elicitation is already pending or at capacity`);const s=new AbortController;o.questions.set(a,s);const c=AbortSignal.any([o.signal,s.signal]);try{const assertCurrent=async()=>{if(!await n())throw new Error(`MCP elicitation authority changed`);c.throwIfAborted()};await assertCurrent();const{ElicitRequestParamsSchema:e}=await import(`/core`);const t=e.safeParse(r.data.params);if(!t.success)throw new Error(`Invalid MCP elicitation parameters`);c.throwIfAborted();const i=await o.handle({method:`elicitation/create`,params:t.data,requestId:a,signal:c});await assertCurrent();return i}finally{o.questions.delete(a)}}};
//!src/gateway/node-mcp-policy.ts
var NodeMcpPolicy=class{constructor(e,t){this.sessions=e;this.sendEvent=t;this.elicitation=new NodeMcpElicitationRegistry;this.permissions=/* @__PURE__ */ new WeakMap;this.setAvailableForConnection=(e,t)=>{const n=this.sessions.get(e.nodeId);if(n?.connId===e.connId)this.setAvailable(n,t)}}retire(e){if(e){this.elicitation.retire(e);this.setAvailable(e,false)}}send(e,t){if(!this.sendEvent(e,`node.worker.localMcpPolicy`,{allowed:t})&&e.client.socket.readyState===1)closeGatewayTransportWithGrace(e.client.socket,1011,`MCP policy delivery failed`)}setAvailable(e,t){const n=this.permissions.get(e);if(!t){this.permissions.delete(e);if(n===true)this.send(e,false);return}const r=canInvokeNodeMcpLocally(e.commands);if(r!==n){this.permissions.set(e,r);this.send(e,r)}}refresh(e,t){if(!t||!e.commands.includes(`mcp.tools.call.v1`))this.elicitation.retire(e);if(this.permissions.has(e))this.setAvailable(e,true)}};
//!src/gateway/node-registry.host-stats.ts
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={};this.checkpoints.set(e,t)}if(!t.pending&&!t.saved)this.persist(e,t)}}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=this.runInOwnerContext(async()=>{try{if(await r({nodeId:e.nodeId,hostStats:n,expectedPairingGeneration:{nodeId:e.nodeId,key:i}}))t.saved=n}catch(t){log$2.warn(`failed to persist node host stats for ${e.nodeId}: ${formatErrorMessage(t)}`)}}).then(()=>{t.pending=void 0;this.pending.delete(a)});t.pending=a;this.pending.add(a)}forget(e){this.checkpoints.delete(e)}close(){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()})()}};
//!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}
//!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`))}
//!src/gateway/node-registry.ts
const NODE_SESSION_POLICIES=/* @__PURE__ */ new WeakMap;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},onSettledResult:(e,t)=>{if(e.systemRunEvent)this.systemRunEvents.settle(t,{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.mcpPolicy=new NodeMcpPolicy(this.nodesById,this.sendEventToSession.bind(this));this.mcpElicitation=this.mcpPolicy.elicitation;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},setLocalMcpAvailable:this.mcpPolicy.setAvailableForConnection,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});publishNodeSessionPluginTools(e,n?.gateway?.nodes?.pluginTools?.enabled,this.options.listRegisteredNodePluginToolCommands?.());e.nodeSkills=n?.gateway?.nodes?.allowSkills===false?[]:t.skills;recordRemoteSkillNodeInfo(e);replaceRemoteNodeSkills({nodeId:e.nodeId,displayName:e.displayName,skills:e.nodeSkills});this.mcpPolicy.refresh(e,n?.mcp?.apps?.enabled===true)}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(e,t){return this.registerSession(e,t)}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??[]});this.mcpPolicy.retire(a);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(e){const t=this.nodesByConn.get(e);if(!t)return null;const n=this.nodesById.get(t);const r=n?.connId===e;this.mcpPolicy.retire(r?n:void 0);this.nodesByConn.delete(e);this.eventTransportsByConn.delete(e);forgetNodeRunnerInventory(this,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()}listConnectedForPairingStates(e){return this.listConnectedSessions().filter(t=>{const n=e.get(t.nodeId);return pairingStateMatchesBinding(pairingBindingForSession(t),n)})}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)}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;this.mcpPolicy.retire(e);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}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}getForPairingGeneration(e,t){return this.getRegisteredSessionForPairingGeneration(e,t)}getRegisteredSessionForPairingGeneration(e,t){const n=this.getRegisteredSession(e);return n?.pairingGeneration===t?n:void 0}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)}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}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}updatePresenceActivity(e){const t=updateNodePresenceActivity(this.getRegisteredSession(e.nodeId),e);if(t)this.publishActiveNodeContext();return t}clearPresenceActivity(e){const t=clearNodePresenceActivity(this.getRegisteredSession(e.nodeId),e.connId);if(t)this.publishActiveNodeContext();return t}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}}}))}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.mcpPolicy.retire(r)}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)}invokeLifecycle(e){return invokeLifecycleNodeRegistry(this,e)}sendInvokeInput(e,t){this.invokeStreams.sendInput(e,t)}isInvokeCurrent(e,t,n){return this.invokeStreams.isPending(e,t,n)}handleInvokeProgress(e){return this.invokeStreams.handleProgress(e)}runPendingInvokeContinuation(e){return this.invokeStreams.runPendingContinuation(e)}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))}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}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}};export{readNodeSessionWithheldCommands as n,serializeEventPayload as r,NodeRegistry as t};