openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
652 lines (651 loc) • 26.9 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { r as registerListener } from "./listeners-Cb2-CnP8.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs";
import { i as getAgentRunRegistryState, n as getAgentRunContextOwnerStatus, o as readAgentRunIndexVersion, r as getAgentRunLifecycleGeneration, t as bumpAgentRunIndexVersion } from "./agent-run-registry-state-BFfw9a4W.mjs";
import { randomUUID } from "node:crypto";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/infra/agent-event-execution-context.ts
function getAgentEventExecutionContext() {
return resolveGlobalSingleton(Symbol.for("openclaw.agentEvents.executionContext"), () => new AsyncLocalStorage());
}
/** Registration owns routing updates; cancellation may clear live authority before callbacks settle. */
function recordAgentEventRouting(e, t, n) {
const r = getAgentEventExecutionContext().getStore();
if (!r || r.lifecycleGeneration !== t.lifecycleGeneration) return;
const i = r.routingByRun ??= /* @__PURE__ */ new Map();
const a = i.get(e);
const o = a?.owner.deref();
const s = a && o === t ? a.routing : {};
s.agentId = t.agentId;
s.sessionKey = t.sessionKey;
s.sessionId = t.sessionId;
s.completionSource = t.completionSource;
s.isControlUiVisible = t.isControlUiVisible;
s.projectSessionLifecycle = t.projectSessionLifecycle;
s.projectSessionMessages = t.projectSessionMessages;
s.mainSessionRestartRecovery = t.mainSessionRestartRecovery;
s.lifecycleStartedAt = t.lifecycleStartedAt;
s.lifecycleGeneration = t.lifecycleGeneration;
s.verboseLevel = t.verboseLevel;
s.registeredAt = t.registeredAt;
s.eventState = t.eventState;
if (a && (o === t || n !== void 0 && o === n && a.routing.lifecycleGeneration !== t.lifecycleGeneration)) {
if (o !== t) a.owner = new WeakRef(t);
a.routing = s;
} else i.set(e, {
owner: new WeakRef(t),
routing: s
});
}
//#endregion
//#region src/infra/agent-run-approval-leases.ts
/** Owns subordinate claims and signal listeners; the registry validates their admitted parent. */
var AgentRunApprovalLeases = class {
constructor(e) {
this.onClose = e;
this.leases = /* @__PURE__ */ new Map();
}
claim(e, t, n) {
const r = t.claimId === e.claimId ? e : this.leases.get(t.claimId)?.authority;
if (!r) throw new Error("agent run approval authority is no longer active");
const i = [...new Set(n)];
for (const e of i) e.throwIfAborted();
for (const e of this.leases.values()) if (e.parent === r && e.signals.length === i.length && i.every((t) => e.signals.includes(t))) return e.authority;
const a = Object.freeze({
...r,
claimId: randomUUID()
});
const close = (e = "approval-scope-closed") => {
if (!this.leases.delete(a.claimId)) return;
for (const e of i) e.removeEventListener("abort", onAbort);
for (const t of this.leases.values()) if (t.parent === a) t.close(e);
this.onClose(a, e);
};
const onAbort = () => close();
this.leases.set(a.claimId, {
authority: a,
parent: r,
signals: i,
close
});
for (const e of i) e.addEventListener("abort", onAbort, { once: true });
return a;
}
isActive(e, t) {
let n = this.leases.get(t);
while (n) {
if (n.signals.some((e) => e.aborted)) return false;
if (n.parent === e) return true;
n = this.leases.get(n.parent.claimId);
}
return false;
}
getAuthority(e) {
return this.leases.get(e)?.authority;
}
release(e) {
const t = this.leases.get(e);
t?.close();
return t !== void 0;
}
close(e) {
for (const t of this.leases.values()) if (!e || t.parent === e) t.close("run-aborted");
}
};
/** The registry supplies the live root; lease ancestry can only narrow that owner. */
function isCurrentAgentRunApprovalAuthority(e, t, n, r) {
const matchesRun = (t) => t.operationalRunInstance.instanceId === e.operationalRunInstance.instanceId && t.operationalRunInstance.runId === e.operationalRunInstance.runId && t.lifecycleGeneration === e.lifecycleGeneration;
if (!matchesRun(n)) return false;
const i = e.claimId === n.claimId || t?.isActive(e, n.claimId) === true;
if (!i || !r) return i;
if (!matchesRun(r)) return false;
if (r.claimId === e.claimId) return true;
const a = t?.getAuthority(r.claimId);
return Boolean(a && t?.isActive(e, a.claimId) && (n.claimId === a.claimId || t.isActive(a, n.claimId)));
}
//#endregion
//#region src/infra/agent-run-projection.ts
function projectedRunIdentity(e, t) {
return `${normalizeAgentId(e)}\0${t}`;
}
/** Activity selected by a session key must belong to the agent encoded in that key. */
function* iterateProjectedAgentRunSessionKeys(e) {
for (const t of e.sessionKeys.keys()) {
const e = t.slice(t.indexOf("\0") + 1);
const n = parseAgentSessionKey(e)?.agentId;
if (n && t === projectedRunIdentity(n, e)) yield e;
}
}
function areAgentRunModelsEqual(e, t) {
return e?.provider === t?.provider && e?.model === t?.model;
}
/** Admission waits cannot hide an independently running or queued producer. */
function mergeProjectedAgentRunStates(e, t) {
return e === "running" || t === void 0 || e === "queued" && t !== "running" ? e : t;
}
function resolveAgentRunProjectionProgressState(e, t) {
let n = e.agentId;
if (n === void 0) {
for (const t of e.sessionKeys) {
n = parseAgentSessionKey(t)?.agentId;
if (n !== void 0) break;
}
n ??= e.defaultAgentId;
}
if (!n) return;
const r = projectedRunIdentity(n, "");
const i = e.defaultAgentId !== void 0 && r === projectedRunIdentity(e.defaultAgentId, "");
let a;
for (const n of e.sessionKeys) {
a = mergeProjectedAgentRunStates(a, t.sessionKeys.get(r + n));
if (a === "running") return a;
if (i) {
a = mergeProjectedAgentRunStates(a, t.ownerlessSessionKeys.get(n));
if (a === "running") return a;
}
}
if (e.sessionId !== void 0) {
a = mergeProjectedAgentRunStates(a, t.sessionIds.get(r + e.sessionId));
if (i) a = mergeProjectedAgentRunStates(a, t.ownerlessSessionIds.get(e.sessionId));
}
return a;
}
/** Canonicalizes every run-context field consumed by the session projection. */
function projectedAgentRunInputKey(e) {
const t = e.agentId ?? parseAgentSessionKey(e.sessionKey)?.agentId;
return JSON.stringify([
e.lifecycleGeneration ?? null,
t ? normalizeAgentId(t) : null,
e.sessionId ?? null,
e.sessionKey ?? null,
e.projectSessionActive ?? null,
e.projectSessionLifecycle ?? null,
e.isControlUiVisible ?? null,
(e.capacityWaits?.size ?? 0) > 0,
e.activeModel?.provider ?? null,
e.activeModel?.model ?? null
]);
}
function buildAgentRunProjectionIndex(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 = /* @__PURE__ */ new Map();
const add = (e, t, n) => {
const r = e.get(t);
if (r !== n && mergeProjectedAgentRunStates(r, n) === n) e.set(t, n);
};
for (const s of e.contexts) {
const c = (s.capacityWaits?.size ?? 0) > 0;
const l = s.agentId ?? parseAgentSessionKey(s.sessionKey)?.agentId;
if (s.lifecycleGeneration === e.lifecycleGeneration && l && s.sessionId && s.sessionKey && s.projectSessionActive !== false && s.projectSessionLifecycle !== false && s.isControlUiVisible !== false) {
const e = projectedRunIdentity(l, s.sessionId);
n.add(e);
if (!c && (s.activeModel !== void 0 || s.projectSessionActive === true)) {
const n = s.activeModel ?? null;
const r = t.get(e);
t.set(e, r === void 0 || areAgentRunModelsEqual(r, n) ? n : null);
}
}
if (s.lifecycleGeneration !== e.lifecycleGeneration || s.projectSessionActive !== true && (!c || s.projectSessionActive === false || s.projectSessionLifecycle === false)) continue;
const u = !c ? "running" : s.projectSessionActive === true ? "queued" : "capacity-wait";
if (s.sessionKey !== void 0 && l) add(r, projectedRunIdentity(l, s.sessionKey), u);
else if (s.sessionKey !== void 0) add(a, s.sessionKey, u);
if (s.sessionId !== void 0 && l) add(i, projectedRunIdentity(l, s.sessionId), u);
else if (s.sessionId !== void 0) add(o, s.sessionId, u);
}
for (const e of n) if (!t.has(e)) t.set(e, null);
return {
modelsBySessionId: t,
sessionKeys: r,
sessionIds: i,
ownerlessSessionKeys: a,
ownerlessSessionIds: o
};
}
//#endregion
//#region src/infra/agent-run-usage.ts
const usageByRun = /* @__PURE__ */ new Map();
/** Adds one completed model call and emits the new generation-scoped total. */
function recordAgentRunOutputTokens(e) {
const t = Math.floor(e.outputTokens);
if (!Number.isFinite(t) || t < 0 || t === 0 && !e.usageReport) return;
const n = usageByRun.get(e.runId) ?? /* @__PURE__ */ new Map();
const r = n.get(e.lifecycleGeneration);
const i = {
outputTokens: (r?.outputTokens ?? 0) + (e.usageReport?.state === "unavailable" ? 0 : t),
...r?.usageReport?.state === "unavailable" || e.usageReport?.state === "unavailable" ? { usageReport: { state: "unavailable" } } : {}
};
if (!e.emit(i)) return;
n.set(e.lifecycleGeneration, i);
usageByRun.set(e.runId, n);
return i;
}
function clearAgentRunUsage(e, t) {
if (t === void 0) {
usageByRun.delete(e);
return;
}
const n = usageByRun.get(e);
n?.delete(t);
if (n?.size === 0) usageByRun.delete(e);
}
function resetAgentRunUsageForTest() {
usageByRun.clear();
}
//#endregion
//#region src/infra/agent-run-registry.ts
const delegatedAuthorityFailures = /* @__PURE__ */ new WeakMap();
/** Diagnostic only: a retained failure never restores a released claim. */
function readAgentRunDelegatedAuthorityFailure(e) {
return delegatedAuthorityFailures.get(e);
}
function rotateAgentRunRegistryLifecycleGeneration() {
const e = getAgentRunRegistryState();
for (const t of e.contexts.values()) {
const n = t.delegatedAuthority;
if (n) {
delete t.delegatedAuthority;
delete t.assertSourceCurrent;
notifyDelegatedAuthorityClosed(e, n);
}
}
e.lifecycleGeneration = randomUUID();
bumpAgentRunIndexVersion();
return e.lifecycleGeneration;
}
function notifyDelegatedAuthorityClosed(e, t, n) {
if (!n) e.contexts.get(t.operationalRunInstance.runId)?.approvalLeases?.close(t);
for (const r of e.delegatedAuthorityClosedHandlers ?? []) try {
r(t, n);
} catch {}
}
/** Observe exact delegated-authority closure without displacing other lifecycle owners. */
function registerAgentRunDelegatedAuthorityClosedHandler(e) {
const t = getAgentRunRegistryState().delegatedAuthorityClosedHandlers ??= /* @__PURE__ */ new Set();
return registerListener(t, e);
}
/** Connects registry cleanup to the event sequencer without reversing ownership. */
function registerAgentRunSequenceResetHandler(e) {
getAgentRunRegistryState().sequenceResetHandler = e;
}
function storeRunContext(e, t, n) {
t.capacityWaits = void 0;
t.executionActivity = void 0;
t.localModelWait = void 0;
t.eventState = { seq: 0 };
t.modelCallSequence = { value: 0 };
t.acceptedUserReply = void 0;
t.registeredAt ??= Date.now();
getAgentRunRegistryState().contexts.set(e, t);
recordAgentEventRouting(e, t, n);
}
/** Registers or merges per-run context used by later agent event emissions. */
function registerAgentRunContext(e, t, n) {
if (!e) return;
const r = getAgentRunRegistryState();
const i = t.lifecycleGeneration ?? r.lifecycleGeneration;
const a = r.owners.get(e);
if (a?.lifecycleGeneration === i && a.exclusiveClaimId && (a.exclusiveClaimId !== n || a.clearRequested)) return;
const o = r.contexts.get(e);
if (!o) {
storeRunContext(e, {
...t,
lifecycleGeneration: i
});
bumpAgentRunIndexVersion(t);
return;
}
if (t.lifecycleGeneration && o.lifecycleGeneration && t.lifecycleGeneration !== o.lifecycleGeneration) return;
const s = projectedAgentRunInputKey(o);
const { sessionKey: c, sessionId: l, agentId: u } = o;
for (const e of [
"sessionKey",
"sessionId",
"agentId"
]) if (t[e] && o[e] !== t[e]) o[e] = t[e];
if (t.verboseLevel && o.verboseLevel !== t.verboseLevel) o.verboseLevel = t.verboseLevel;
o.completionSource ??= t.completionSource;
if (t.sessionEventDelivery === false) o.sessionEventDelivery = false;
for (const e of [
"isControlUiVisible",
"projectSessionActive",
"projectSessionLifecycle",
"projectSessionMessages"
]) if (t[e] !== void 0) o[e] = t[e];
if (t.mainSessionRestartRecovery === true) o.mainSessionRestartRecovery = true;
if (t.cronRunsByJobId !== void 0) {
o.cronRunsByJobId ??= /* @__PURE__ */ new Map();
for (const [e, n] of t.cronRunsByJobId) o.cronRunsByJobId.set(e, n);
}
for (const e of ["registeredAt", "lastActiveAt"]) if (t[e] !== void 0) o[e] = t[e];
recordAgentEventRouting(e, o);
if (s !== projectedAgentRunInputKey(o)) bumpAgentRunIndexVersion(o, {
sessionKey: c,
sessionId: l,
agentId: u
});
}
/** Claims a run id for a newly admitted execution, replacing stale ownership. */
function claimAgentRunContext(e, t, n = {}) {
if (!e) return;
const r = getAgentRunRegistryState();
const i = t.lifecycleGeneration ?? r.lifecycleGeneration;
const a = r.contexts.get(e);
const o = r.owners.get(e);
const s = o?.lifecycleGeneration === i ? o : void 0;
if (s?.exclusiveClaimId || n.exclusive && (a?.lifecycleGeneration === i || s !== void 0)) return;
let c;
if (n.trackOwner) {
c = randomUUID();
if (s) {
s.claimIds.add(c);
if (n.protectFromSweep) s.sweepProtectedClaimIds.add(c);
if (n.ownsContext) s.preserveAfterRelease = false;
if (n.onClearRequested) (s.clearListeners ??= /* @__PURE__ */ new Map()).set(c, n.onClearRequested);
} else r.owners.set(e, {
lifecycleGeneration: i,
claimIds: /* @__PURE__ */ new Set([c]),
sweepProtectedClaimIds: new Set(n.protectFromSweep ? [c] : []),
preserveAfterRelease: n.ownsContext !== true && a?.lifecycleGeneration === i,
clearRequested: false,
...n.exclusive ? { exclusiveClaimId: c } : {},
...n.onClearRequested ? { clearListeners: /* @__PURE__ */ new Map([[c, n.onClearRequested]]) } : {}
});
} else if (o?.lifecycleGeneration !== i) r.owners.delete(e);
if (a?.lifecycleGeneration === i) {
const n = readAgentRunIndexVersion();
registerAgentRunContext(e, {
...t,
lifecycleGeneration: i
}, c);
if (readAgentRunIndexVersion() === n) bumpAgentRunIndexVersion(a);
return c;
}
storeRunContext(e, {
...t,
lifecycleGeneration: i
}, a);
r.sequenceResetHandler?.(e);
clearAgentRunUsage(e);
bumpAgentRunIndexVersion(t, a);
return c;
}
/** Returns the currently registered context for a run, if it has not been cleared or swept. */
function getAgentRunContext(e) {
return getAgentRunRegistryState().contexts.get(e);
}
/** Holds an existing run context only while its current execution awaits lane admission. */
function retainQueuedAgentRunContext(e, t) {
const n = getAgentRunRegistryState();
const r = n.contexts.get(e);
if (!r || r.lifecycleGeneration !== t || n.lifecycleGeneration !== t) return;
const i = hasAgentRunContextExecutionOwner(e);
const a = n.queuedRunContextLeases ??= /* @__PURE__ */ new WeakMap();
a.set(r, (a.get(r) ?? 0) + 1);
if (!i) bumpAgentRunIndexVersion(r);
let o = false;
return (i) => {
if (o) return;
o = true;
const s = (a.get(r) ?? 0) - 1;
if (s > 0) a.set(r, s);
else a.delete(r);
if (n.contexts.get(e) === r && r.lifecycleGeneration === t && n.lifecycleGeneration === t) {
if (i === "admitted") r.lastActiveAt = Date.now();
if (!hasAgentRunContextExecutionOwner(e)) bumpAgentRunIndexVersion(r);
}
};
}
function getAgentRunContextOwnership(e) {
return getAgentRunRegistryState().owners.get(e);
}
/** Claims approval authority for the exact admitted operational execution. */
function claimAgentRunDelegatedAuthority(e, t) {
const n = e.instanceId.trim();
const r = e.runId.trim();
if (!n || !r) throw new Error("agent run delegated authority requires an operational run instance");
const i = getAgentRunRegistryState();
const a = e.instanceId === n && e.runId === r ? e : Object.freeze({
instanceId: n,
runId: r
});
const o = i.contexts.get(r);
if (o?.delegatedAuthority?.operationalRunInstance.instanceId === n && o.assertSourceCurrent !== t) throw new Error("agent run source authority is already bound");
t?.();
const s = i.lifecycleGeneration;
const c = getActiveAgentRunDelegatedAuthority(a);
if (c) return c;
const l = i.contexts.get(r)?.delegatedAuthority;
if (l) releaseAgentRunContext(r, l.claimId);
const u = claimAgentRunContext(r, {
lifecycleGeneration: s,
lastActiveAt: Date.now()
}, {
trackOwner: true,
protectFromSweep: true,
onClearRequested: (e) => {
releaseAgentRunContext(r, e);
}
});
if (!u) throw new Error("agent run delegated authority could not claim the operational execution");
const d = Object.freeze({
operationalRunInstance: a,
lifecycleGeneration: s,
claimId: u
});
const f = i.contexts.get(r);
if (!f || f.lifecycleGeneration !== s) {
releaseAgentRunContext(r, u);
throw new Error("agent run delegated authority lost its lifecycle during admission");
}
f.acceptedUserReply = void 0;
f.delegatedAuthority = d;
f.assertSourceCurrent = t;
return d;
}
/** Returns authority only while the exact lifecycle owner still holds its claim. */
function getActiveAgentRunDelegatedAuthority(e) {
return readActiveAgentRunDelegatedAuthority(e, (e) => e.assertSourceCurrent?.());
}
function readActiveAgentRunDelegatedAuthority(e, t) {
const n = getAgentRunRegistryState().contexts.get(e.runId);
const r = n?.delegatedAuthority;
if (!n || !r || r.operationalRunInstance.instanceId !== e.instanceId || r.operationalRunInstance.runId !== e.runId || getAgentRunContextOwnerStatus(e.runId, r.claimId, r.lifecycleGeneration) === void 0) return;
try {
t(n);
return getAgentRunContext(e.runId) === n && n.delegatedAuthority === r && getAgentRunContextOwnerStatus(e.runId, r.claimId, r.lifecycleGeneration) !== void 0 ? r : void 0;
} catch (t) {
if (!delegatedAuthorityFailures.has(r)) delegatedAuthorityFailures.set(r, { cause: t });
releaseAgentRunContext(e.runId, r.claimId);
return;
}
}
/** Retain the exact source binding while its storage checks prepare outside writer grants. */
function captureAgentRunDelegatedSourceAssertion(e, t) {
const n = e.operationalRunInstance;
const r = getAgentRunContext(n.runId);
const i = r?.assertSourceCurrent;
const assertActive = (a) => {
const o = readActiveAgentRunDelegatedAuthority(n, (e) => {
if (e !== r || e.assertSourceCurrent !== i) t();
a();
});
if (!o || !isCurrentAgentRunApprovalAuthority(o, r?.approvalLeases, e)) t();
};
const a = readActiveAgentRunDelegatedAuthority(n, () => {});
if (!a || !isCurrentAgentRunApprovalAuthority(a, r?.approvalLeases, e)) return;
return {
assertBinding: () => assertActive(() => {}),
assertCurrent: composeSessionSourceAssertion([i], assertActive)
};
}
function validateAgentRunDelegatedAuthority(e, t) {
const n = getActiveAgentRunDelegatedAuthority(e.operationalRunInstance);
return Boolean(n && isCurrentAgentRunApprovalAuthority(n, getAgentRunContext(e.operationalRunInstance.runId)?.approvalLeases, e, t));
}
/** Narrows an admitted run to one live tool generation without replacing its outer claim. */
function claimAgentRunApprovalAuthority(e, t) {
const n = getAgentRunRegistryState();
const r = n.contexts.get(e.operationalRunInstance.runId);
if (!r?.delegatedAuthority || !validateAgentRunDelegatedAuthority(e)) throw new Error("agent run approval authority is no longer active");
return (r.approvalLeases ??= new AgentRunApprovalLeases((e, t) => notifyDelegatedAuthorityClosed(n, e, t))).claim(r.delegatedAuthority, e, t);
}
/** Compare-releases only the exact authority owned by one admitted execution. */
function releaseAgentRunDelegatedAuthority(e) {
const { runId: t, instanceId: n } = e.operationalRunInstance;
const r = getAgentRunContext(t);
const i = r?.delegatedAuthority;
if (!r || !i || i.operationalRunInstance.instanceId !== n || i.lifecycleGeneration !== e.lifecycleGeneration || getAgentRunContextOwnerStatus(t, i.claimId, i.lifecycleGeneration) === void 0) return false;
if (i.claimId !== e.claimId) return r.approvalLeases?.release(e.claimId) === true;
releaseAgentRunContext(t, e.claimId);
return true;
}
/** Exact execution claims and scheduler queue leases, excluding UI projection metadata. */
function hasAgentRunContextExecutionOwner(e) {
const t = getAgentRunRegistryState();
const n = t.contexts.get(e);
if (!n || n.lifecycleGeneration !== t.lifecycleGeneration) return false;
const r = t.owners.get(e);
return r?.lifecycleGeneration === t.lifecycleGeneration && r.claimIds.size > 0 || (t.queuedRunContextLeases?.get(n) ?? 0) > 0;
}
/** Counts admitted executions, excluding retained display-only context. */
function getActiveAgentRunContextCount() {
let e = 0;
for (const t of getAgentRunRegistryState().contexts.keys()) if (hasAgentRunContextExecutionOwner(t)) e += 1;
return e;
}
/** Live display projection also includes a producer's active-session marker. */
function hasLiveAgentRunContext(e) {
const t = getAgentRunRegistryState();
const n = t.contexts.get(e);
return n?.lifecycleGeneration === t.lifecycleGeneration && (hasAgentRunContextExecutionOwner(e) || n.projectSessionActive === true);
}
function listLiveAgentRunIds() {
return [...getAgentRunRegistryState().contexts.keys()].filter(hasLiveAgentRunContext);
}
function recordAgentRunModel(e, t) {
const n = getAgentRunContext(e);
if (!n || n.lifecycleGeneration !== getAgentRunLifecycleGeneration()) return;
if (areAgentRunModelsEqual(n.activeModel, t)) return;
if (t) n.activeModel = t;
else delete n.activeModel;
bumpAgentRunIndexVersion(n);
}
function resolveProjectedAgentRunModel(e) {
return e.sessionId === void 0 ? void 0 : (e.index ?? buildProjectedAgentRunIndex()).modelsBySessionId.get(projectedRunIdentity(e.agentId, e.sessionId));
}
function buildProjectedAgentRunIndex() {
const { contexts: e, lifecycleGeneration: t } = getAgentRunRegistryState();
return buildAgentRunProjectionIndex({
contexts: e.values(),
lifecycleGeneration: t
});
}
function resolveProjectedAgentRunProgressState(e) {
return resolveAgentRunProjectionProgressState(e, e.index ?? buildProjectedAgentRunIndex());
}
const preparedProgressStates = /* @__PURE__ */ new WeakMap();
/** Bind an immutable query once; each owner-published run index supplies its progress fact. */
function prepareProjectedAgentRunProgressState(e) {
return (t) => {
let n = preparedProgressStates.get(t);
if (!n) {
n = /* @__PURE__ */ new WeakMap();
preparedProgressStates.set(t, n);
}
let r = n.get(e);
if (r === void 0) {
r = resolveAgentRunProjectionProgressState(e, t) ?? null;
n.set(e, r);
}
return r ?? void 0;
};
}
/** Clears context state for a run that has ended or been discarded. */
function clearAgentRunContext(e, t, n) {
const r = getAgentRunRegistryState();
const i = r.contexts.get(e);
if (t && i && i.lifecycleGeneration !== t) return;
const a = r.owners.get(e);
if (n && (!a || t && a.lifecycleGeneration !== t || !a.claimIds.has(n))) return;
if (a?.exclusiveClaimId && a.exclusiveClaimId !== n) return;
if (a?.claimIds.size) {
if (!t || a.lifecycleGeneration === t) {
const e = a.clearRequested;
a.clearRequested = true;
for (const [e, t] of a.clearListeners ?? []) {
if (e === i?.delegatedAuthority?.claimId) continue;
t(e);
}
if (!e) bumpAgentRunIndexVersion(i);
}
return;
}
const o = r.contexts.delete(e);
r.sequenceResetHandler?.(e);
clearAgentRunUsage(e, t ?? i?.lifecycleGeneration);
if (o) bumpAgentRunIndexVersion(i);
}
/** Releases one tracked owner and clears its context after the final owner exits. */
function releaseAgentRunContext(e, t) {
if (!e || !t) return;
const n = getAgentRunRegistryState();
const r = n.owners.get(e);
if (!r?.claimIds.delete(t)) return;
const i = n.contexts.get(e);
const a = i?.delegatedAuthority;
if (i && a?.claimId === t) {
delete i.delegatedAuthority;
delete i.assertSourceCurrent;
notifyDelegatedAuthorityClosed(n, a);
}
r.sweepProtectedClaimIds.delete(t);
const o = readAgentRunIndexVersion();
r.clearListeners?.delete(t);
if (r.exclusiveClaimId === t) r.exclusiveClaimId = void 0;
if (r.claimIds.size > 0) {
bumpAgentRunIndexVersion(i);
return;
}
n.owners.delete(e);
if (r.clearRequested || !r.preserveAfterRelease) clearAgentRunContext(e, r.lifecycleGeneration);
if (readAgentRunIndexVersion() === o) bumpAgentRunIndexVersion(i);
}
/** Sweeps orphaned run contexts that exceeded the given TTL. */
function sweepStaleRunContexts(e = 18e5) {
const t = getAgentRunRegistryState();
const n = Date.now();
let r = 0;
for (const [i, a] of t.contexts) {
if (a.lifecycleGeneration === t.lifecycleGeneration && (t.queuedRunContextLeases?.get(a) ?? 0) > 0) continue;
const o = t.owners.get(i);
if (o?.lifecycleGeneration === t.lifecycleGeneration && o.sweepProtectedClaimIds.size > 0) continue;
const s = a.lastActiveAt ?? a.registeredAt;
if ((s ? n - s : Infinity) > e) {
t.contexts.delete(i);
t.sequenceResetHandler?.(i);
clearAgentRunUsage(i, a.lifecycleGeneration);
t.owners.delete(i);
r += 1;
}
}
if (r > 0) bumpAgentRunIndexVersion();
return r;
}
function resetAgentRunRegistryForTest() {
const e = getAgentRunRegistryState();
const t = e.contexts.size > 0;
for (const t of e.contexts.values()) t.approvalLeases?.close();
resetAgentRunUsageForTest();
e.contexts.clear();
e.owners.clear();
e.queuedRunContextLeases = void 0;
if (t) bumpAgentRunIndexVersion();
}
//#endregion
export { iterateProjectedAgentRunSessionKeys as A, resolveProjectedAgentRunModel as C, sweepStaleRunContexts as D, rotateAgentRunRegistryLifecycleGeneration as E, getAgentEventExecutionContext as M, recordAgentEventRouting as N, validateAgentRunDelegatedAuthority as O, resetAgentRunRegistryForTest as S, retainQueuedAgentRunContext as T, registerAgentRunContext as _, claimAgentRunDelegatedAuthority as a, releaseAgentRunContext as b, getActiveAgentRunDelegatedAuthority as c, hasAgentRunContextExecutionOwner as d, hasLiveAgentRunContext as f, recordAgentRunModel as g, readAgentRunDelegatedAuthorityFailure as h, claimAgentRunContext as i, projectedAgentRunInputKey as j, recordAgentRunOutputTokens as k, getAgentRunContext as l, prepareProjectedAgentRunProgressState as m, captureAgentRunDelegatedSourceAssertion as n, clearAgentRunContext as o, listLiveAgentRunIds as p, claimAgentRunApprovalAuthority as r, getActiveAgentRunContextCount as s, buildProjectedAgentRunIndex as t, getAgentRunContextOwnership as u, registerAgentRunDelegatedAuthorityClosedHandler as v, resolveProjectedAgentRunProgressState as w, releaseAgentRunDelegatedAuthority as x, registerAgentRunSequenceResetHandler as y };