openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
650 lines (649 loc) • 28.1 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { A as resolveExpiresAtMsFromDurationMs, R as resolveTimerTimeoutMs, a as addTimerTimeoutGraceMs, y as isFutureDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { i as asOptionalObjectRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as DEFAULT_ACCOUNT_ID } from "./account-id-BqKT3GuY.mjs";
import { n as awaitWithinDeadline, t as ABSOLUTE_DEADLINE_EXPIRED } from "./absolute-deadline-kK4DcdPs.mjs";
import { n as GATEWAY_CLIENT_IDS } from "./client-info-Cm1BcrMm.mjs";
import { n as availableWorkerSlots } from "./worker-capacity-CiGeSXP9.mjs";
import { d as runWithSessionSourceScope } from "./session-source-authority-TlTpfRVE.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import { A as NODE_WORKER_WORKSPACE_PREPARE_COMMAND, D as NODE_WORKER_SUPERVISOR_LAUNCH_COMMAND, F as isPrivateNodeInvokeCommand, O as NODE_WORKER_SUPERVISOR_STATUS_COMMAND, S as NODE_WORKER_ENVIRONMENT_STOP_COMMAND, k as NODE_WORKER_WORKSPACE_EXEC_COMMAND, w as NODE_WORKER_PRIVATE_COMMANDS } from "./node-commands-BfMJIlXP.mjs";
import { t as MAX_PAYLOAD_BYTES } from "./payload-limits-ChDi8AHf.mjs";
import { n as sameWorkerProtocolFeatures } from "./worker-build-identity-BrfBomn8.mjs";
import { a as NODE_WORKER_SUPERVISOR_PROTOCOL_FEATURE, l as resolveNodeWorkerExecutionIssue, n as NODE_RUNNER_UPDATE_REQUIRED_ISSUE, o as createNodeRunnerInventoryIssueError } from "./node-runner-inventory-CixlIhG-.mjs";
import { n as serializeNodeEvent, t as buildNodeInvokeRequest } from "./node-invoke-request-DwLtMARG.mjs";
import { t as NODE_INVOKE_PAIRING_CHANGED_ABORT } from "./node-registry-private-token-ChofAGxk.mjs";
import { randomUUID } from "node:crypto";
import { isDeepStrictEqual } from "node:util";
//#region src/gateway/node-registry.system-run.ts
function resolvePendingSystemRunEvent(e) {
const t = asOptionalObjectRecord(e.params);
if (e.command !== "system.run" || !t) return;
const n = normalizeOptionalString(t.runId) ?? "";
if (!n) return;
const r = normalizeSystemRunTimeoutMs(t.timeoutMs);
const i = normalizeOptionalString(t.sessionKey) ?? "";
const a = e.turnSource;
const o = normalizeMessageChannel(a?.channel);
const s = normalizeOptionalString(a?.to);
const c = o === "telegram" && s && i ? {
channel: o,
to: s,
accountId: a?.accountId ?? "default",
...a?.threadId != null ? { threadId: a.threadId } : {}
} : void 0;
return {
runId: n,
...c ? { invocationDeliveryContext: c } : {},
...i ? { sessionKey: i } : {},
...r !== void 0 ? { timeoutMs: r } : {}
};
}
function normalizeSystemRunInvokeParams(e) {
if (e.command !== "system.run" || !isRecord(e.params)) return e.params;
const t = e.params;
const n = {
...t,
runId: normalizeOptionalString(t.runId) || randomUUID()
};
const r = normalizeSystemRunTimeoutMs(t.timeoutMs);
if (r === void 0) delete n.timeoutMs;
else n.timeoutMs = r;
return n;
}
/** Normalize system.run timeout values, preserving null for no expiry. */
function normalizeSystemRunTimeoutMs(e) {
if (e === void 0) return;
if (typeof e !== "number" || !Number.isFinite(e)) return;
const t = Math.trunc(e);
return t > 0 ? resolveTimerTimeoutMs(t, 1) : null;
}
function authorizedSystemRunEventExpiresAt(e) {
if (typeof e !== "number") return null;
const t = addTimerTimeoutGraceMs(e, AUTHORIZED_SYSTEM_RUN_EVENT_GRACE_MS);
return resolveExpiresAtMsFromDurationMs(t) ?? 0;
}
function authorizedSystemRunEventKey(e) {
return `${e.nodeId}\0${e.connId}\0${e.sessionKey ?? ""}\0${e.runId}`;
}
const AUTHORIZED_SYSTEM_RUN_EVENT_GRACE_MS = 3e5;
/** Owns delayed notices independently of the inline invocation's request lifetime. */
var NodeSystemRunEvents = class {
constructor(e, t) {
this.pendingInvokes = e;
this.getNode = t;
this.authorizedSystemRunEvents = /* @__PURE__ */ new Map();
}
authorize(e) {
if (!e.connId || !e.sessionKey) return null;
const t = e.connId;
this.pruneAuthorizedSystemRunEvents();
let n = e.runId ? this.matchAuthorizedSystemRunEvent({
nodeId: e.nodeId,
connId: t,
runId: e.runId,
sessionKey: e.sessionKey
}) : null;
if (n === null && this.allowsLegacyMacRunIdFallback({
nodeId: e.nodeId,
connId: t
})) n = this.matchAuthorizedSystemRunEvent({
nodeId: e.nodeId,
connId: t,
sessionKey: e.sessionKey
});
if (n === null) return null;
const r = this.authorizedSystemRunEvents.get(n);
const i = r?.invocationDeliveryContext;
let a;
if (e.terminal) {
this.authorizedSystemRunEvents.delete(n);
clearTimeout(r?.expiryTimer);
a = [...this.pendingInvokes.values()].find((n) => n.nodeId === e.nodeId && n.connId === t && n.systemRunEvent?.runId === r?.runId);
}
return {
...i ? { invocationDeliveryContext: { ...i } } : {},
...r?.source ? {
expectedTarget: r.source.expectedTarget,
...e.terminal ? { release: r.source.release } : {}
} : {},
...a ? { holdNotice: (e) => {
const t = a.resolve;
a.resolve = (n) => {
t(n);
if (!n.ok) e();
else r?.source?.release();
};
} } : {}
};
}
remember(e) {
this.pruneAuthorizedSystemRunEvents();
const t = {
...e,
expiresAtMs: authorizedSystemRunEventExpiresAt(e.timeoutMs)
};
if (t.source && t.expiresAtMs !== null) {
t.expiryTimer = setTimeout(() => this.forget(t), Math.max(0, t.expiresAtMs - Date.now()));
t.expiryTimer.unref();
}
this.forget(t);
this.authorizedSystemRunEvents.set(authorizedSystemRunEventKey(t), t);
}
forget(e) {
const t = authorizedSystemRunEventKey(e);
const n = this.authorizedSystemRunEvents.get(t);
this.authorizedSystemRunEvents.delete(t);
clearTimeout(n?.expiryTimer);
n?.source?.release();
}
disconnect(e) {
for (const t of this.authorizedSystemRunEvents.values()) if (t.connId === e) this.forget(t);
}
matchAuthorizedSystemRunEvent(e) {
let t = null;
for (const [n, r] of this.authorizedSystemRunEvents) {
if (r.nodeId !== e.nodeId || r.connId !== e.connId || e.runId !== void 0 && r.runId !== e.runId || r.sessionKey && r.sessionKey !== e.sessionKey) continue;
if (e.runId !== void 0) return n;
if (t !== null) return null;
t = n;
}
return t;
}
allowsLegacyMacRunIdFallback(e) {
const t = this.getNode(e.nodeId);
return t?.connId === e.connId && t.clientId === "openclaw-macos" && t.platform === "darwin";
}
pruneAuthorizedSystemRunEvents(e = Date.now()) {
for (const t of this.authorizedSystemRunEvents.values()) if (t.expiresAtMs !== null && !isFutureDateTimestampMs(t.expiresAtMs, { nowMs: e })) this.forget(t);
}
};
//#endregion
//#region src/gateway/node-runner-inventory-runtime.ts
/** Both first-party hosts run the shared node runtime without changing client identity. */
function isNodeWorkerHostClientId(e) {
return e === GATEWAY_CLIENT_IDS.NODE_HOST || e === GATEWAY_CLIENT_IDS.MACOS_APP;
}
function createNodeRunnerStatePublisher(e, t) {
const n = /* @__PURE__ */ new Set();
const r = /* @__PURE__ */ new Map();
let listener = (e, t) => {};
const hasCurrent = (n) => {
const r = e(n);
return Boolean(r && r.client.invalidated !== true && resolveNodeWorkerSupervisorState(r, t));
};
return {
hasCurrent,
reconcile: (e, t) => {
const i = hasCurrent(e);
const a = n.has(e) !== i;
if (i) n.add(e);
else n.delete(e);
if (t || a) {
for (const t of r.get(e) ?? []) t();
listener(e, {
inventoryChanged: t,
availabilityChanged: a
});
}
},
setListener: (e) => {
listener = e;
},
subscribe: (e, t) => {
const n = r.get(e) ?? /* @__PURE__ */ new Set();
n.add(t);
r.set(e, n);
return () => {
n.delete(t);
if (n.size === 0) r.delete(e);
};
}
};
}
/** Availability wakes admission; only a freshly read pairing-bound proof completes the wait. */
async function waitForNodeRunnerAvailability(e, t, n, r) {
let i = createDeferredCore();
const a = e.subscribe(n, () => i.resolve());
const assertCurrent = () => {
r.signal.throwIfAborted();
r.assertCurrent();
};
try {
for (;;) {
assertCurrent();
const e = await racePromiseWithAbortSignal(t.getCurrentNode(n), r.signal);
assertCurrent();
if (e && t.isCurrent(e)) return;
const a = t.getIssue?.(n);
if (a) throw createNodeRunnerInventoryIssueError(n, a);
await racePromiseWithAbortSignal(i.promise, r.signal);
i = createDeferredCore();
}
} finally {
a();
}
}
/** Project current connection facts without pairing reads, publications, or execution admission. */
function collectNodeRunnerCatalogState(e) {
const t = /* @__PURE__ */ new Set();
const n = /* @__PURE__ */ new Set();
const r = /* @__PURE__ */ new Map();
const i = /* @__PURE__ */ new Map();
const a = /* @__PURE__ */ new Map();
const { state: o } = e;
for (const s of e.connectedNodes) {
const c = o?.getNode(s.nodeId);
if (!o || !c || c.connId !== s.connId) continue;
const l = resolveNodeWorkerSupervisorState(c, o.runnerInventoryByConn);
if (l && l.pairingGeneration === s.pairingGeneration) {
t.add(s.nodeId);
if (l.workerHost.deviceFolders === true) n.add(s.nodeId);
}
const u = resolveNodeRunnerInventoryIssue(c, o.runnerInventoryByConn) ?? (e.requireWorkerExecution && l ? resolveNodeWorkerExecutionIssue(l.workerHost) : void 0);
if (u) r.set(s.nodeId, [u]);
if (l) i.set(s.nodeId, l.workerHost.capacity);
const d = o.bundleStatusByConn.get(s.connId);
if (d) a.set(s.nodeId, d.status);
}
return {
sessionHostNodeIds: t,
deviceFolderNodeIds: n,
issuesByNodeId: r,
workerSlotsByNodeId: i,
workerBundleByNodeId: a
};
}
function resolveNodeWorkerSupervisorProof(e, t) {
const n = resolveNodeWorkerSupervisorState(e, t);
return n ? {
...n,
workerHost: structuredClone(n.workerHost),
commands: [...n.commands]
} : void 0;
}
function resolveNodeWorkerSupervisorState(e, t) {
const n = t.get(e.connId);
if (!n || !e.pairingIdentity || !e.pairingGeneration || !isNodeWorkerHostClientId(e.clientId) || e.clientMode !== "node" || n.nodeId !== e.nodeId || n.pairingIdentity !== e.pairingIdentity || n.pairingGeneration !== e.pairingGeneration || n.clientId !== e.clientId || n.clientMode !== e.clientMode || !n.protocolFeatures.includes("node-worker-supervisor-v6") || n.workerHost?.enabled !== true) return;
return {
nodeId: e.nodeId,
connId: e.connId,
pairingIdentity: e.pairingIdentity,
pairingGeneration: e.pairingGeneration,
clientId: e.clientId,
clientMode: "node",
protocolFeature: NODE_WORKER_SUPERVISOR_PROTOCOL_FEATURE,
workerHost: n.workerHost,
commands: e.commands
};
}
function resolveNodeRunnerInventoryIssue(e, t) {
const n = t.get(e.connId);
if (!n || e.client.invalidated === true || n.nodeId !== e.nodeId || n.pairingIdentity !== e.pairingIdentity || n.pairingGeneration === void 0 || n.pairingGeneration !== e.pairingGeneration || !isNodeWorkerHostClientId(e.clientId) || n.clientId !== e.clientId || e.clientMode !== "node" || n.clientMode !== "node" || n.protocolFeatures.length !== 1) return;
if (n.protocolFeatures[0] !== "node-worker-supervisor-v6") return NODE_RUNNER_UPDATE_REQUIRED_ISSUE;
return n.workerHost?.enabled === false && n.workerHost.reason ? {
code: "worker-host-unavailable",
message: n.workerHost.reason
} : void 0;
}
function isNodeWorkerSupervisorProofCurrent(e, t, n, r = {}) {
if (!e || e.client.invalidated === true || e.connId !== n.connId) return false;
const i = resolveNodeWorkerSupervisorState(e, t);
return i?.pairingIdentity === n.pairingIdentity && i.pairingGeneration === n.pairingGeneration && i.clientId === n.clientId && i.clientMode === n.clientMode && i.protocolFeature === n.protocolFeature && (!r.launchEligibility || availableWorkerSlots(i.workerHost.capacity) > 0) && (!r.environmentSession || i.workerHost.environmentSession === 1) && (!r.statusWait || i.workerHost.statusWait === 1) && (!r.preparedWorkspace || i.workerHost.preparedWorkspace === 1) && (!r.capturedExecPolicy || !resolveNodeWorkerExecutionIssue(i.workerHost)) && (!r.workspaceQuiescence || i.workerHost.workspaceQuiescence === 1) && (r.commands ?? []).every((e) => i.commands.includes(e));
}
//#endregion
//#region src/gateway/node-registry-private.ts
const NODE_REGISTRY_PRIVATE_STATES = /* @__PURE__ */ new WeakMap();
function requireNodeRegistryPrivateState(e) {
const t = NODE_REGISTRY_PRIVATE_STATES.get(e);
if (!t) throw new Error("node registry private runtime was not initialized");
return t;
}
function nodeInvokeError(e, t) {
return {
ok: false,
error: {
code: e,
message: t
}
};
}
async function invokeNodeRegistryCore(e, t, n, r) {
const i = t.turnSource ? { ...t.turnSource } : void 0;
let a = resolveTimerTimeoutMs(t.timeoutMs, 3e4, 0);
const o = t.deadlineAtMs ?? (Number.isFinite(t.timeoutMs) && a > 0 ? performance.now() + a : void 0);
if (isPrivateNodeInvokeCommand(t.command) && !n) return nodeInvokeError("INVALID_REQUEST", "private node command is not invocable");
if (t.signal?.aborted) return nodeInvokeError("ABORTED", "node invoke cancelled");
let s = e.context.getNode(t.nodeId);
if (!s) return nodeInvokeError("NOT_CONNECTED", "node not connected");
if (s.client.invalidated === true) return nodeInvokeError("PAIRING_CHANGED", "node pairing changed before dispatch");
const c = t.expectedPairingGeneration ?? s.pairingGeneration;
if (e.context.hasCurrentPairingStateResolver && !c) return nodeInvokeError("PAIRING_CHANGED", "node pairing generation unavailable");
if (c && s.pairingGeneration !== c) return nodeInvokeError("PAIRING_CHANGED", "node pairing changed before dispatch");
if (t.expectedConnId && s.connId !== t.expectedConnId) return nodeInvokeError("ROUTE_CHANGED", "node connection changed before dispatch");
if (c && e.context.hasCurrentPairingStateResolver) {
const n = s;
let r;
try {
r = await awaitWithinDeadline(() => racePromiseWithAbortSignal(e.context.resolvePairingLease(n), t.signal), o, () => performance.now());
} catch (e) {
if (t.signal?.aborted) return nodeInvokeError("ABORTED", "node invoke cancelled");
throw e;
}
if (r === ABSOLUTE_DEADLINE_EXPIRED) return nodeInvokeError("TIMEOUT", "node invoke timed out");
if (r.status === "unavailable") return nodeInvokeError("UNAVAILABLE", "node pairing state unavailable before dispatch");
if (r.status !== "current") return nodeInvokeError("PAIRING_CHANGED", "node pairing changed before dispatch");
s = r.session;
if (t.expectedConnId && s.connId !== t.expectedConnId) return nodeInvokeError("ROUTE_CHANGED", "node connection changed before dispatch");
}
const l = randomUUID();
const u = normalizeSystemRunInvokeParams({
command: t.command,
params: t.params
});
const d = buildNodeInvokeRequest({
id: l,
nodeId: t.nodeId,
command: t.command,
params: "params" in t ? u : void 0,
timeoutMs: a,
idempotencyKey: t.idempotencyKey,
sessionKey: t.sessionKey
});
if (t.command === "worker.launch.v1" && Buffer.byteLength(serializeNodeEvent("node.invoke.request", d), "utf8") > 26214400) return nodeInvokeError("INVALID_REQUEST", "worker launch exceeds the node payload limit");
const f = resolvePendingSystemRunEvent({
command: t.command,
params: u,
turnSource: i
});
const p = t.authorizeDispatch;
const closedAuthority = () => nodeInvokeError("APPROVAL_AUTHORITY_CLOSED", "runtime authority closed before node dispatch");
if (p) {
let e;
try {
e = await awaitWithinDeadline(() => racePromiseWithAbortSignal(p(), t.signal), o, () => performance.now());
} catch (e) {
if (t.signal?.aborted) return nodeInvokeError("ABORTED", "node invoke cancelled");
throw e;
}
if (e === ABSOLUTE_DEADLINE_EXPIRED) return nodeInvokeError("TIMEOUT", "node invoke timed out");
if (!e) return closedAuthority();
}
const m = s;
let h = f && t.prepareSystemRunEventSource ? await t.prepareSystemRunEventSource(f.sessionKey ?? "node") : void 0;
if (f && h) f.source = h;
try {
return await (await runWithSessionSourceScope(t.isDispatchAuthorized, async () => {
f?.source?.expectedTarget.assertCurrent?.();
if (t.isDispatchAuthorized?.() === false) return { result: closedAuthority() };
if (t.signal?.aborted) return { result: nodeInvokeError("ABORTED", "node invoke cancelled") };
if (e.context.getNode(t.nodeId) !== m) return { result: nodeInvokeError("ROUTE_CHANGED", "node connection changed before dispatch") };
if (m.client.invalidated === true || c && m.pairingGeneration !== c) return { result: nodeInvokeError("PAIRING_CHANGED", "node pairing changed before dispatch") };
if (!e.context.isCommandAllowed(t.nodeId, t.command)) return { result: nodeInvokeError("POLICY_CHANGED", "node command is no longer allowed") };
if (o !== void 0) {
a = Math.max(0, o - performance.now());
if (a === 0) return { result: nodeInvokeError("TIMEOUT", "node invoke timed out") };
d.timeoutMs = Math.ceil(a);
}
const n = new Promise((n, i) => {
const s = {
nodeId: t.nodeId,
connId: m.connId,
command: t.command,
systemRunEvent: f,
resolve: n,
reject: i,
nextProgressSeq: 0,
progressChunks: /* @__PURE__ */ new Map(),
nextInputSeq: 0,
...t.onProgress ? { onProgress: t.onProgress } : {},
...r ? { isCompletionAuthorized: r } : {}
};
const c = t.expectedPairingGeneration ? new AbortController() : void 0;
if (t.expectedPairingGeneration && c) e.generationBoundInvokes.set(s, {
expectedGeneration: t.expectedPairingGeneration,
controller: c
});
const u = c ? t.signal ? AbortSignal.any([t.signal, c.signal]) : c.signal : t.signal;
const d = resolveTimerTimeoutMs(t.idleTimeoutMs, 0, 0);
e.context.invokeStreams.armPending({
requestId: l,
pending: s,
timeoutMs: a,
deadlineAtMs: o,
idleTimeoutMs: d,
...u ? { signal: u } : {}
});
});
const i = e.context.pendingInvokes.get(l);
if (!i) return { result: n };
const s = i.deadlineAtMs;
if (!e.context.sendEventToSession(m, "node.invoke.request", d)) {
const t = e.context.pendingInvokes.get(l);
if (t) {
e.context.invokeStreams.clearTimers(t);
e.context.pendingInvokes.delete(l);
t.resolve(nodeInvokeError("UNAVAILABLE", "failed to send invoke to node"));
}
return { result: n };
}
if (f) {
e.context.rememberAuthorizedSystemRunEvent({
nodeId: t.nodeId,
connId: m.connId,
...f
});
h = void 0;
}
t.onDispatchReady?.(l, s);
return { result: n };
}, { checkAfter: false })).result;
} finally {
h?.release();
}
}
function registerNodeRegistryPrivateRuntime(e, t) {
const n = /* @__PURE__ */ new Map();
const r = createNodeRunnerStatePublisher(t.getNode, n);
const i = {
context: t,
catalogRevision: 0,
runnerInventoryByConn: n,
bundleStatusByConn: /* @__PURE__ */ new Map(),
runnerState: r,
generationBoundInvokes: /* @__PURE__ */ new WeakMap(),
workerSupervisorTransport: {
getCurrentNode: async (e) => {
const n = await t.getCurrentConnected(e);
return n ? resolveNodeWorkerSupervisorProof(n, i.runnerInventoryByConn) : void 0;
},
listCurrentNodes: async () => {
return (await t.listCurrentConnected()).flatMap((e) => {
const t = resolveNodeWorkerSupervisorProof(e, i.runnerInventoryByConn);
return t ? [t] : [];
});
},
hasCurrentRunner: r.hasCurrent,
isConnected: (e) => {
const n = t.getNode(e);
return Boolean(n && n.client.invalidated !== true);
},
getIssue: (e) => {
const n = t.getNode(e);
return n ? resolveNodeRunnerInventoryIssue(n, i.runnerInventoryByConn) : void 0;
},
getBundleStatus: (e) => {
const n = t.getNode(e);
const r = n ? i.bundleStatusByConn.get(n.connId) : void 0;
return r ? structuredClone(r) : void 0;
},
acceptBundleStatus: (e, n) => {
if (!isNodeWorkerSupervisorProofCurrent(t.getNode(e.nodeId), i.runnerInventoryByConn, e)) return false;
const r = i.context.getNode(e.nodeId);
const a = r ? resolveNodeWorkerSupervisorProof(r, i.runnerInventoryByConn) : void 0;
if (a?.workerHost.bundleRetention !== 1 || a.workerHost.bundleStatus !== 1) return false;
const o = i.bundleStatusByConn.get(e.connId);
if (n) i.bundleStatusByConn.set(e.connId, structuredClone(n));
else i.bundleStatusByConn.delete(e.connId);
if (!isDeepStrictEqual(o, n)) {
i.catalogRevision++;
i.runnerState.reconcile(e.nodeId, true);
}
return true;
},
isCurrent: (e, n = false, r = [], a = false) => isNodeWorkerSupervisorProofCurrent(t.getNode(e.nodeId), i.runnerInventoryByConn, e, {
launchEligibility: n,
commands: r,
capturedExecPolicy: a
}),
invoke: async (e) => {
if (!NODE_WORKER_PRIVATE_COMMANDS.includes(e.command)) return nodeInvokeError("INVALID_REQUEST", "private node command is not allowed");
const isNodeCurrent = () => isNodeWorkerSupervisorProofCurrent(t.getNode(e.node.nodeId), i.runnerInventoryByConn, e.node, {
environmentSession: e.command === "worker.launch.v1" || e.command === "worker.environment.stop.v1",
preparedWorkspace: e.command === NODE_WORKER_WORKSPACE_PREPARE_COMMAND,
capturedExecPolicy: e.command === NODE_WORKER_SUPERVISOR_LAUNCH_COMMAND,
workspaceQuiescence: e.command === "worker.workspace.exec.v1" && isRecord(e.params) && (e.params.quiescence !== void 0 || e.params.nativeProcessOwner === true),
statusWait: e.command === "worker.status.v1" && typeof e.params === "object" && e.params !== null && "waitMs" in e.params
});
const n = Object.assign(() => e.isDispatchAuthorized() && isNodeCurrent(), e.isDispatchAuthorized);
const r = e.isCompletionAuthorized;
const a = r ? () => r() && isNodeCurrent() : n;
if (!isNodeCurrent()) return nodeInvokeError("PRIVATE_DIALECT_UNAVAILABLE", "node worker supervisor dialect is unavailable");
return await invokeNodeRegistryCore(i, {
nodeId: e.node.nodeId,
expectedConnId: e.node.connId,
expectedPairingGeneration: e.node.pairingGeneration,
command: e.command,
...e.params !== void 0 ? { params: e.params } : {},
...e.timeoutMs !== void 0 ? { timeoutMs: e.timeoutMs } : {},
...e.signal ? { signal: e.signal } : {},
...e.idempotencyKey ? { idempotencyKey: e.idempotencyKey } : {},
...e.authorizeDispatch ? { authorizeDispatch: e.authorizeDispatch } : {},
isDispatchAuthorized: n,
...e.onDispatchReady ? { onDispatchReady: e.onDispatchReady } : {}
}, true, a);
}
}
};
NODE_REGISTRY_PRIVATE_STATES.set(e, i);
}
function createNodeRegistryRuntime(e) {
const t = e();
const n = requireNodeRegistryPrivateState(t);
return {
nodeRegistry: t,
nodeWorkerSupervisorTransport: n.workerSupervisorTransport,
closeHostStats: n.context.closeHostStats
};
}
/** Private session-host transport, retaining registry-owned pairing and connection checks. */
function getNodeWorkerSupervisorTransport(e) {
return requireNodeRegistryPrivateState(e).workerSupervisorTransport;
}
function setNodeRunnerStateChangedListener(e, t) {
requireNodeRegistryPrivateState(e).runnerState.setListener(t);
}
/** Catalog readers retain prepared rows until a registry owner changes their inputs. */
function invalidateNodeCatalog(e) {
requireNodeRegistryPrivateState(e).catalogRevision++;
}
function readNodeCatalogRevision(e) {
return requireNodeRegistryPrivateState(e).catalogRevision;
}
function waitForNodeWorkerSupervisor(e, t, n) {
const r = requireNodeRegistryPrivateState(e);
return waitForNodeRunnerAvailability(r.runnerState, r.workerSupervisorTransport, t, n);
}
function reconcileNodeRunnerAvailability(e, t) {
requireNodeRegistryPrivateState(e).runnerState.reconcile(t, false);
}
function invokePublicNodeRegistry(e, t) {
return invokeNodeRegistryCore(requireNodeRegistryPrivateState(e), t, false);
}
function invokeLifecycleNodeRegistry(e, t) {
return invokeNodeRegistryCore(requireNodeRegistryPrivateState(e), t, false, t.isDispatchAuthorized);
}
function updateNodeRunnerInventory(e) {
const t = NODE_REGISTRY_PRIVATE_STATES.get(e.registry);
if (!t) return null;
const n = t.context.getNode(e.nodeId);
const r = e.declaration.protocolFeatures.length === 1;
if (!n || n.client.invalidated === true || n.connId !== e.connId || !isNodeWorkerHostClientId(n.clientId) || n.clientMode !== "node") return null;
const i = t.runnerInventoryByConn.get(n.connId);
if (!r) {
const e = t.runnerInventoryByConn.delete(n.connId);
const r = t.bundleStatusByConn.delete(n.connId);
const i = e || r;
if (i) {
t.catalogRevision++;
t.context.publishActiveNodeContext();
t.runnerState.reconcile(n.nodeId, true);
}
return { changed: i };
}
const a = "workerHost" in e.declaration ? e.declaration.workerHost : void 0;
const o = {
nodeId: n.nodeId,
connId: n.connId,
pairingIdentity: n.pairingIdentity,
...n.pairingGeneration ? { pairingGeneration: n.pairingGeneration } : {},
clientId: n.clientId,
clientMode: "node",
protocolFeatures: [...e.declaration.protocolFeatures],
...a ? { workerHost: structuredClone(a) } : {}
};
const s = o.workerHost?.enabled !== true || o.workerHost.bundleRetention === void 0 || o.workerHost.bundleStatus === void 0 ? t.bundleStatusByConn.delete(n.connId) : false;
const c = !i || i.pairingGeneration !== o.pairingGeneration || !sameWorkerProtocolFeatures(i.protocolFeatures, o.protocolFeatures) || !isDeepStrictEqual(i.workerHost, o.workerHost) || s;
if (c) {
t.catalogRevision++;
t.runnerInventoryByConn.set(n.connId, o);
t.context.publishActiveNodeContext();
t.runnerState.reconcile(n.nodeId, true);
}
return { changed: c };
}
function forgetNodeRunnerInventory(e, t) {
const n = NODE_REGISTRY_PRIVATE_STATES.get(e);
const r = n?.runnerInventoryByConn.get(t);
if (!n || !r || !n.runnerInventoryByConn.delete(t)) return;
n.bundleStatusByConn.delete(t);
n.catalogRevision++;
n.runnerState.reconcile(r.nodeId, true);
}
/** Capture the catalog's live metadata without reloading pairing or mutating registry state. */
function collectNodeCatalogRuntimeState(e, t, n = false) {
const r = NODE_REGISTRY_PRIVATE_STATES.get(e);
return collectNodeRunnerCatalogState({
connectedNodes: t,
requireWorkerExecution: n,
state: r && {
getNode: r.context.getNode,
runnerInventoryByConn: r.runnerInventoryByConn,
bundleStatusByConn: r.bundleStatusByConn
}
});
}
function isNodeRegistryPendingInvokeConnectionActive(e) {
const t = NODE_REGISTRY_PRIVATE_STATES.get(e.registry)?.generationBoundInvokes.get(e.pending);
return e.currentNode?.connId === e.pending.connId && (!t || e.currentNode.pairingGeneration === t.expectedGeneration);
}
function settleNodeRegistryPairingGenerationChange(e) {
const t = NODE_REGISTRY_PRIVATE_STATES.get(e.registry);
if (!t) return;
const n = t.runnerInventoryByConn.delete(e.connId);
const r = t.bundleStatusByConn.delete(e.connId);
if (n || r) {
t.catalogRevision++;
t.runnerState.reconcile(e.nodeId, true);
}
for (const n of t.context.pendingInvokes.values()) {
const r = t.generationBoundInvokes.get(n);
if (n.nodeId !== e.nodeId || n.connId !== e.connId || !r || r.expectedGeneration === e.nextPairingGeneration) continue;
r.controller.abort(NODE_INVOKE_PAIRING_CHANGED_ABORT);
}
}
//#endregion
export { NodeSystemRunEvents as _, invalidateNodeCatalog as a, isNodeRegistryPendingInvokeConnectionActive as c, registerNodeRegistryPrivateRuntime as d, setNodeRunnerStateChangedListener as f, isNodeWorkerHostClientId as g, waitForNodeWorkerSupervisor as h, getNodeWorkerSupervisorTransport as i, readNodeCatalogRevision as l, updateNodeRunnerInventory as m, createNodeRegistryRuntime as n, invokeLifecycleNodeRegistry as o, settleNodeRegistryPairingGenerationChange as p, forgetNodeRunnerInventory as r, invokePublicNodeRegistry as s, collectNodeCatalogRuntimeState as t, reconcileNodeRunnerAvailability as u };