openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,114 lines (1,113 loc) • 40.7 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { n as safeParseJsonRecord } from "./json-coercion-CaJLaav-.mjs";
import { s as raceWithTimeout } from "./src-BPmQBLJp.mjs";
import { n as groupPluginRecords } from "./record-groups-DII71OvH.mjs";
import { r as getBoundLegacyPluginSdkResourceHost } from "./legacy-sdk-resource-host-BiedXayN.mjs";
import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs";
import { d as hasAgentRunContextExecutionOwner, l as getAgentRunContext, p as listLiveAgentRunIds } from "./agent-run-registry-D7vkrqFT.mjs";
import { a as emitAgentEvent } from "./agent-events-BdfWYmot.mjs";
import { a as listAgentRunsForSession } from "./agent-run-registry-state-BFfw9a4W.mjs";
import { n as enqueueKeyedTask } from "./keyed-async-queue-DewLnYvW.mjs";
import { i as mcpCatalogToolsSignature, r as compareMcpCatalogTools } from "./agent-bundle-mcp-names-856aMFJA.mjs";
import { i as logWarn } from "./logger-CIwfuhOU.mjs";
import { n as createCombinedSessionMcpRuntime, t as sessionMcpRuntimeOwners } from "./agent-bundle-mcp-runtime-owner-COu6tF9k.mjs";
import { n as recordAgentCleanupFailure } from "./run-cleanup-timeout-Bk3vN1Oh.mjs";
import { c as buildMcpRequesterRuntimeCacheKey, f as resolveRequesterScopedMcpConnections, l as hashMcpResolvedConnections, o as MCP_CONNECTION_REVALIDATE_MS, u as partitionMcpServersByConnectionScope } from "./bundle-mcp-config-Ca9TXxki.mjs";
import { t as loadSessionMcpConfig } from "./agent-bundle-mcp-runtime-config-CBo1pSHY.mjs";
import { i as resetMcpStartupBackoff } from "./mcp-startup-backoff-cb5C4N0P.mjs";
import { i as resolveSessionMcpRuntimeIdleTtlMs, n as SESSION_MCP_RUNTIME_SWEEP_INTERVAL_MS, r as SessionMcpRuntimeCapacityError, t as SESSION_MCP_RUNTIME_MANAGER_KEY } from "./agent-bundle-mcp-runtime-shared-CHct-FOd.mjs";
import { f as peekSessionMcpRuntimeManager, p as releaseSessionMcpRuntime, s as revokeMcpAppModelContext, t as allowMcpAppModelContext } from "./mcp-app-model-context-Nt0AWggG.mjs";
import { t as createRequesterMcpConnect } from "./agent-bundle-mcp-requester-connect-DWToqIx_.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/agents/agent-bundle-mcp-manager-install.ts
const matchesRuntime = (e, t, n) => sessionMcpRuntimeOwners.get(e)?.isCurrent() !== false && e.workspaceDir === t.workspaceDir && e.agentDir === t.agentDir && e.configFingerprint === n;
function requesterRuntimeFingerprint(e, t) {
return t ? `${e}:${t.configFingerprint}` : e;
}
function createSessionMcpRuntimeManagerInstall(e) {
const { store: t } = e;
const reconcileReusableRetirement = (n, r) => {
const { sessionId: i } = n;
const a = sessionMcpRuntimeOwners.get(r);
if (a && n.agentId) a.agentId = n.agentId;
const o = t.runtimeSlots.get(r);
if (o) o.idleTtlMs = resolveSessionMcpRuntimeIdleTtlMs(t.configReload?.cfg ?? n.cfg);
e.ensureIdleSweepTimer();
if (o && t.liveRuntimeSlots.has(o)) e.catalogs.observeCatalog(r, n.runtimeKey, {
sessionId: i,
sessionKey: n.sessionKey,
agentId: n.agentId ?? parseAgentSessionKey(n.sessionKey ?? "")?.agentId,
workspaceDir: n.workspaceDir,
agentDir: n.agentDir,
configFingerprint: r.configFingerprint
});
if (t.requiredRetirementSessionIds.has(i)) {
t.deferredRetirementSessionIds.add(i);
revokeMcpAppModelContext(r);
return;
}
t.deferredRetirementSessionIds.delete(i);
allowMcpAppModelContext(r);
};
/** Install under the runtime-key queue shared by acquisition and disposal. */
const getOrCreateRuntimeEntry = async (n, r) => {
const i = loadSessionMcpConfig({
...n,
loaded: r,
logDiagnostics: false
});
const a = requesterRuntimeFingerprint(i.fingerprint, n.requesterConnect);
const o = Object.keys(i.loaded.mcpServers).length > 0;
const { runtimeKey: s, configReloadAtAdmission: c, ...l } = n;
const u = {
sessionId: n.sessionId,
sessionKey: n.sessionKey,
agentId: n.agentId ?? parseAgentSessionKey(n.sessionKey ?? "")?.agentId,
workspaceDir: n.workspaceDir,
agentDir: n.agentDir,
configFingerprint: a
};
e.catalogs.reconcileCatalog(s, u);
const d = t.runtimesBySessionId.get(s);
const f = !n.connectionOverrides || t.connectionMetaByRuntimeKey.get(s)?.connectionHash === hashMcpResolvedConnections(n.connectionOverrides);
if (d && f && matchesRuntime(d, n, a)) {
reconcileReusableRetirement(n, d);
d.markUsed();
return d;
}
const p = await e.reserveRuntimeSlot(s, d, o);
t.connectionMetaByRuntimeKey.delete(s);
let m;
let h;
try {
m = d && sessionMcpRuntimeOwners.get(d)?.replace({
...l,
configFingerprint: a
});
t.runtimesBySessionId.delete(s);
if (m) t.runtimesBySessionId.set(s, m);
if (d) {
h = e.disposeRuntime(s, d, false);
await h;
}
m ??= await t.createRuntime({
...l,
configFingerprint: a
});
t.runtimeSlots.set(m, p);
t.runtimesBySessionId.set(s, m);
const r = t.configReload;
if (r && r !== c) await sessionMcpRuntimeOwners.get(m)?.reload({
...r,
reloadPlugins: r.pluginGeneration !== (c?.pluginGeneration ?? 0)
});
if (!(sessionMcpRuntimeOwners.get(m)?.hasServers() ?? o)) await e.releaseEmptyRuntimeSlot(s, m);
reconcileReusableRetirement(n, m);
m.markUsed();
return m;
} catch (n) {
t.runtimesBySessionId.delete(s);
const r = (await Promise.allSettled([h ?? (d && e.disposeRuntime(s, d, false)), m && e.disposeRuntime(s, m, false)])).find((e) => e.status === "rejected");
if (r) throw r.reason;
t.liveRuntimeSlots.delete(p);
e.ensureIdleSweepTimer();
throw n;
}
};
/** Install or reuse one requester runtime. Must run under its runtime-key lock. */
const installRequesterRuntime = async (e) => {
const n = hashMcpResolvedConnections(e.connectionOverrides);
const r = await getOrCreateRuntimeEntry(e);
if (t.runtimesBySessionId.get(e.runtimeKey) === r) t.connectionMetaByRuntimeKey.set(e.runtimeKey, {
connectionHash: n,
resolvedAt: t.scheduler.now()
});
return r;
};
/**
* Full requester section for one runtimeKey: reuse / resolve / install / revoke.
* Always invoked under runExclusiveOnRuntimeKey.
*/
const resolveAndInstallRequesterRuntime = async (n) => {
const r = await createRequesterMcpConnect({
serverNames: n.oauthRequesterNameSet,
mcpServers: n.mcpServers,
safeServerNamesByServer: n.safeServerNamesByServer,
requesterScope: n.requesterScope,
cfg: n.cfg,
configFingerprint: n.fullScopedFingerprint
});
const i = /* @__PURE__ */ new Set([...r?.authorizedServerNames ?? [], ...n.resolverRequesterServerNames]);
const { fingerprint: a } = loadSessionMcpConfig({
...n,
logDiagnostics: false,
includeServerNames: i,
redactConnectionServerNames: new Set(n.resolverRequesterServerNames)
});
const o = requesterRuntimeFingerprint(a, r);
const s = t.runtimesBySessionId.get(n.runtimeKey);
const c = t.connectionMetaByRuntimeKey.get(n.runtimeKey);
if (c !== void 0 && t.scheduler.now() - c.resolvedAt < 3e5 && s && matchesRuntime(s, n, o)) {
reconcileReusableRetirement(n, s);
s.markUsed();
return s;
}
const l = await resolveRequesterScopedMcpConnections({
serverNames: n.resolverRequesterServerNames,
requesterSenderId: n.requesterSenderId,
agentAccountId: n.agentAccountId,
messageChannel: n.messageChannel
});
const u = /* @__PURE__ */ new Set([...r?.authorizedServerNames ?? [], ...l.keys()]);
if (u.size === 0 && !r) {
if (t.runtimesBySessionId.has(n.runtimeKey)) await e.disposeRuntimeKeyNow(n.runtimeKey);
return;
}
try {
return await installRequesterRuntime({
runtimeKey: n.runtimeKey,
configReloadAtAdmission: n.configReloadAtAdmission,
sessionId: n.sessionId,
sessionKey: n.sessionKey,
agentId: n.agentId,
workspaceDir: n.workspaceDir,
agentDir: n.agentDir,
cfg: n.cfg,
manifestRegistry: n.manifestRegistry,
safeServerNamesByServer: n.safeServerNamesByServer,
includeServerNames: u,
requesterConnect: r,
connectionOverrides: l,
redactConnectionServerNames: new Set(n.resolverRequesterServerNames),
requesterScope: n.requesterScope,
toolOverrides: n.toolOverrides,
toolDenylist: n.toolDenylist
});
} catch (e) {
if (e instanceof SessionMcpRuntimeCapacityError) return n.onCapacityRefusal(e, r);
throw e;
}
};
return {
getOrCreateRuntimeEntry,
resolveAndInstallRequesterRuntime
};
}
//#endregion
//#region src/agents/agent-bundle-mcp-manager-catalog.ts
function matchesBinding(e, t) {
return e.configFingerprint === t.configFingerprint && e.workspaceDir === t.workspaceDir && e.agentDir === t.agentDir && e.agentId === t.agentId && e.sessionKey === t.sessionKey;
}
/** Catalog lifetime follows sessions, independently of transport eviction. */
function createSessionMcpCatalogStore(e, t) {
const n = {
catalogByRuntimeKey: /* @__PURE__ */ new Map(),
advertisedScopedCatalogBySessionId: /* @__PURE__ */ new Map()
};
const { catalogByRuntimeKey: r, advertisedScopedCatalogBySessionId: i } = n;
const sessionEntries = (e) => [...[...r.values()].filter((t) => t.sessionId === e), ...[i.get(e)].filter((e) => e !== void 0)];
const hasSession = (e) => sessionEntries(e).length > 0;
const deleteSession = (e) => {
for (const [t, n] of r) if (n.sessionId === e) r.delete(t);
i.delete(e);
};
const reconcileCatalog = (e, t) => {
const n = r.get(e);
r.delete(e);
if (n && matchesBinding(n, t)) r.set(e, n);
};
const rememberAdvertisedScopedCatalog = (t, n) => {
const a = i.get(t.runtime.sessionId);
const o = [...e].find(([, e]) => e === t.runtime)?.[0];
if (a?.configFingerprint !== t.advertisedCatalogConfigFingerprint || o === void 0 || r.get(o)?.catalog !== n) return;
const s = groupPluginRecords(n.tools, (e) => e.serverName);
for (const [e, t] of Object.entries(n.servers)) {
const n = (s.get(e) ?? []).toSorted((e, t) => e.toolName.localeCompare(t.toolName));
const r = mcpCatalogToolsSignature(n);
if (a.signaturesByServer.get(e) !== r) {
a.servers.set(e, t);
a.toolsByServer.set(e, n);
a.signaturesByServer.set(e, r);
}
}
};
const a = /* @__PURE__ */ new WeakSet();
const observeCatalog = (t, n, i) => {
reconcileCatalog(n, i);
if (!r.has(n)) r.set(n, {
...i,
catalog: null
});
if (a.has(t)) return;
a.add(t);
const o = t.getCatalog.bind(t);
t.getCatalog = async () => {
const i = r.get(n);
const a = await o();
if (i && e.get(n) === t && sessionMcpRuntimeOwners.get(t)?.isCurrent() !== false) i.catalog = a;
return a;
};
};
const getAdvertisedScopedCatalog = (e) => {
const n = i.get(e);
if (!n || n.servers.size === 0) return null;
const r = {};
const a = [];
for (const e of [...n.servers.keys()].toSorted((e, t) => e.localeCompare(t))) {
r[e] = n.servers.get(e);
a.push(...n.toolsByServer.get(e) ?? []);
}
a.sort(compareMcpCatalogTools);
return {
version: 1,
generatedAt: t(),
servers: r,
tools: a
};
};
const reconcileAdvertisedScopedCatalogConfig = (e, t) => {
const n = i.get(e.sessionId);
i.delete(e.sessionId);
if (n && matchesBinding(n, e)) {
i.set(e.sessionId, n);
return;
}
for (const [t, n] of r) if (t !== e.sessionId && n.sessionId === e.sessionId) r.delete(t);
if (t) i.set(e.sessionId, {
...e,
servers: /* @__PURE__ */ new Map(),
toolsByServer: /* @__PURE__ */ new Map(),
signaturesByServer: /* @__PURE__ */ new Map()
});
};
const prune = (e, t, n) => {
const pruneMap = (e, t, n) => {
const r = [];
for (const [i, a] of e) if (!t(i, a)) {
if (n(a)) r.push(i);
else e.delete(i);
}
for (const t of r.slice(0, -256)) e.delete(t);
};
pruneMap(r, (e, r) => t.has(e) || n.has(r.sessionId), (e) => e.catalog !== null);
const a = new Set([...r.values()].map((e) => e.sessionId));
pruneMap(i, (t) => e.has(t), (e) => e.servers.size > 0 || a.has(e.sessionId));
};
return {
store: n,
sessionEntries,
hasSession,
deleteSession,
reconcileCatalog,
observeCatalog,
rememberAdvertisedScopedCatalog,
getAdvertisedScopedCatalog,
reconcileAdvertisedScopedCatalogConfig,
prune,
clear: () => {
r.clear();
i.clear();
},
captureSession(e) {
const t = sessionEntries(e);
return t.length ? () => {
const n = sessionEntries(e);
return n.length === t.length && t.every((e) => n.includes(e));
} : void 0;
}
};
}
//#endregion
//#region src/agents/agent-bundle-mcp-manager-lifecycle.ts
const runInMcpManagerContext = AsyncLocalStorage.snapshot();
const CAPACITY_CLEANUP_WAIT_MS = 5e3;
function parseRuntimeCacheSessionId(e) {
const t = e.startsWith("{") ? safeParseJsonRecord(e)?.sessionId : void 0;
return typeof t === "string" ? t : e;
}
function runtimeAgentId(e) {
return sessionMcpRuntimeOwners.get(e)?.agentId ?? parseAgentSessionKey(e.sessionKey ?? "")?.agentId;
}
function createSessionMcpRuntimeManagerLifecycle(e, t) {
const n = /* @__PURE__ */ new Map();
const r = createSessionMcpCatalogStore(n, () => i.scheduler.now());
const i = {
...r.store,
runtimesBySessionId: n,
sessionIdBySessionKey: /* @__PURE__ */ new Map(),
deferredRetirementSessionIds: /* @__PURE__ */ new Set(),
requiredRetirementSessionIds: /* @__PURE__ */ new Set(),
connectionMetaByRuntimeKey: /* @__PURE__ */ new Map(),
/**
* Per-runtimeKey serialization for acquisition and dispose.
* Sections never overlap for one key, so a slow resolve cannot clobber a newer install.
* Entries are removed when their chain drains.
*/
runtimeWorkChains: /* @__PURE__ */ new Map(),
pendingDisposals: /* @__PURE__ */ new Map(),
createRuntime: t,
runtimeSlots: /* @__PURE__ */ new WeakMap(),
liveRuntimeSlots: /* @__PURE__ */ new Set(),
scheduler: e.scheduler,
idleSweepJob: void 0
};
let a = i.scheduler.scope();
let o = false;
const capacityRefusal = (e) => {
const t = new SessionMcpRuntimeCapacityError(!o, e);
if (t.notify) logWarn(`bundle-mcp: ${t.message}`);
o = true;
return t;
};
const reserveRuntimeSlot = async (e, t, n) => {
if (n && i.pendingDisposals.get(e)?.failure) throw capacityRefusal("MCP tools are temporarily unavailable: the previous runtime has not confirmed shutdown. This turn will continue without MCP tools; restart the Gateway before retrying.");
const r = (t && i.runtimeSlots.get(t)) ?? { idleTtlMs: 0 };
if (!n || i.liveRuntimeSlots.has(r)) return r;
const a = performance.now() + CAPACITY_CLEANUP_WAIT_MS;
while (i.liveRuntimeSlots.size >= 256) {
const e = [...i.runtimesBySessionId].filter(([e, t]) => {
const n = i.runtimeSlots.get(t);
return n !== void 0 && i.liveRuntimeSlots.has(n) && isRuntimeIdle(e, t);
}).toSorted(([, e], [, t]) => e.lastUsedAt - t.lastUsedAt)[0];
const t = Math.ceil(a - performance.now());
if (!e || t <= 0) throw capacityRefusal();
if (!await raceWithTimeout(retireIdleRuntimes([{
runtimeKey: e[0],
runtime: e[1]
}]).then(() => true), t, () => false, { ref: false })) throw capacityRefusal();
}
o = false;
i.liveRuntimeSlots.add(r);
return r;
};
const releaseEmptyRuntimeSlot = async (e, t) => {
const n = i.runtimeSlots.get(t);
if (!n) return;
if (!t.joinCleanup) throw new Error("MCP runtime does not expose cleanup ownership");
await t.joinCleanup();
const r = sessionMcpRuntimeOwners.get(t);
if (i.runtimesBySessionId.get(e) === t && r?.hasServers() !== true) {
i.liveRuntimeSlots.delete(n);
if (r?.hasServers() === false && (t.activeLeases ?? 0) === 0 && Object.keys(t.requesterConnect?.catalog.servers ?? {}).length === 0) {
i.runtimesBySessionId.delete(e);
i.connectionMetaByRuntimeKey.delete(e);
i.runtimeSlots.delete(t);
pruneSessionBookkeeping();
}
}
};
const disposeRuntime = async (e, t, n = true) => {
const r = i.pendingDisposals.get(e) ?? {
sessionId: t.sessionId,
pending: /* @__PURE__ */ new Set()
};
r.agentId ??= runtimeAgentId(t);
i.pendingDisposals.set(e, r);
try {
await t.dispose();
if (!t.joinCleanup) throw new Error("MCP runtime does not expose cleanup ownership");
await t.joinCleanup();
const e = i.runtimeSlots.get(t);
if (n && e) {
i.liveRuntimeSlots.delete(e);
i.runtimeSlots.delete(t);
}
} catch (e) {
r.failure ??= {
status: "rejected",
reason: e
};
recordAgentCleanupFailure();
throw e;
} finally {
if (r.pending.size === 0 && !r.failure) i.pendingDisposals.delete(e);
}
};
const trackDisposal = (e, t) => {
const n = Promise.resolve().then(t).catch((e) => {
recordAgentCleanupFailure();
throw e;
}).finally(() => {
for (const t of e) {
const e = i.pendingDisposals.get(t);
e?.pending.delete(n);
if (e?.pending.size === 0 && !e.failure) i.pendingDisposals.delete(t);
}
pruneSessionBookkeeping();
});
for (const t of e) {
const e = i.pendingDisposals.get(t) ?? {
sessionId: parseRuntimeCacheSessionId(t),
pending: /* @__PURE__ */ new Set()
};
i.pendingDisposals.set(t, e);
e.pending.add(n);
}
return n;
};
const pruneSessionBookkeeping = () => {
const e = /* @__PURE__ */ new Set([...[...i.runtimesBySessionId.values()].map((e) => e.sessionId), ...[...i.runtimeWorkChains.keys(), ...i.pendingDisposals.keys()].map(parseRuntimeCacheSessionId)]);
const t = /* @__PURE__ */ new Set();
for (const n of listLiveAgentRunIds()) if (hasAgentRunContextExecutionOwner(n)) {
const r = getAgentRunContext(n);
const a = r?.sessionId ?? i.sessionIdBySessionKey.get(r?.sessionKey ?? "");
if (a) {
e.add(a);
t.add(a);
}
}
r.prune(e, /* @__PURE__ */ new Set([
...i.runtimesBySessionId.keys(),
...i.runtimeWorkChains.keys(),
...i.pendingDisposals.keys()
]), t);
const n = /* @__PURE__ */ new Set([...[...i.catalogByRuntimeKey.values()].map((e) => e.sessionId), ...i.advertisedScopedCatalogBySessionId.keys()]);
for (const [t, r] of i.sessionIdBySessionKey) if (!e.has(r) && !n.has(r)) i.sessionIdBySessionKey.delete(t);
};
const runtimeKeysForSessionId = (e) => {
const t = /* @__PURE__ */ new Set();
for (const [n, r] of i.runtimesBySessionId.entries()) if (r.sessionId === e) t.add(n);
for (const n of [...i.runtimeWorkChains.keys(), ...i.pendingDisposals.keys()]) if (parseRuntimeCacheSessionId(n) === e) t.add(n);
return [...t];
};
const totalActiveLeasesForSessionId = (e) => {
let t = 0;
for (const n of runtimeKeysForSessionId(e)) t += i.runtimesBySessionId.get(n)?.activeLeases ?? 0;
return t;
};
const runExclusiveOnRuntimeKeys = (e, t) => {
const n = enqueueKeyedTask({
tails: i.runtimeWorkChains,
keys: e,
task: t
});
n.then(() => void 0, () => void 0).finally(() => {
pruneSessionBookkeeping();
});
return n;
};
const isRuntimeIdle = (e, t) => (t.activeLeases ?? 0) === 0 && !i.runtimeWorkChains.has(e) && (e !== t.sessionId || !listLiveAgentRunIds().some((e) => {
const n = getAgentRunContext(e);
return hasAgentRunContextExecutionOwner(e) && (n?.sessionId === t.sessionId || !n?.sessionId && t.sessionKey !== void 0 && n?.sessionKey === t.sessionKey);
}));
const retireIdleRuntimes = async (e) => {
for (const { runtimeKey: t } of e) {
i.runtimesBySessionId.delete(t);
i.connectionMetaByRuntimeKey.delete(t);
}
const t = new Set(e.map(({ runtime: e }) => e.sessionId));
for (const e of t) if (runtimeKeysForSessionId(e).length === 0) i.deferredRetirementSessionIds.delete(e);
await Promise.allSettled(e.map(({ runtimeKey: e, runtime: t }) => {
const n = runExclusiveOnRuntimeKeys([e], () => disposeRuntime(e, t));
return trackDisposal([e], () => n);
}));
ensureIdleSweepTimer();
};
const sweepIdleRuntimes = async () => {
const e = i.scheduler.now();
const t = [...i.runtimesBySessionId].flatMap(([t, n]) => {
const r = i.runtimeSlots.get(n)?.idleTtlMs ?? 0;
return r > 0 && e - n.lastUsedAt >= r && isRuntimeIdle(t, n) ? [{
runtimeKey: t,
runtime: n
}] : [];
});
await retireIdleRuntimes(t);
};
const ensureIdleSweepTimer = () => {
if (![...i.runtimesBySessionId.values()].some((e) => (i.runtimeSlots.get(e)?.idleTtlMs ?? 0) > 0)) {
clearIdleSweepTimer();
return;
}
if (i.idleSweepJob || a.signal.aborted) return;
i.idleSweepJob = runInMcpManagerContext(() => a.schedule({
id: "mcp:idle-runtimes",
atMs: i.scheduler.now() + SESSION_MCP_RUNTIME_SWEEP_INTERVAL_MS,
everyMs: SESSION_MCP_RUNTIME_SWEEP_INTERVAL_MS,
run: () => sweepIdleRuntimes().catch((e) => {
logWarn(`bundle-mcp: idle runtime sweep failed: ${String(e)}`);
})
}));
};
const clearIdleSweepTimer = () => {
i.idleSweepJob?.cancel();
i.idleSweepJob = void 0;
};
const setScheduler = async (e) => {
e.signal.throwIfAborted();
if (e === i.scheduler) return;
const t = a;
t.beginClose();
i.scheduler = e;
await t.stop();
i.idleSweepJob = void 0;
a = e.scope();
ensureIdleSweepTimer();
};
const disposeRuntimeKeyNow = async (e) => {
const t = i.runtimesBySessionId.get(e);
i.runtimesBySessionId.delete(e);
i.connectionMetaByRuntimeKey.delete(e);
if (t) await disposeRuntime(e, t);
};
const disposeManagedRuntimes = (e, t) => {
const n = [...new Set(e === void 0 ? [
...i.runtimesBySessionId.keys(),
...i.runtimeWorkChains.keys(),
...i.pendingDisposals.keys()
] : [e, ...runtimeKeysForSessionId(e)])];
const a = new Set(n.flatMap((e) => [...i.pendingDisposals.get(e)?.pending ?? []]));
const o = i.disposalInFlight;
const s = runExclusiveOnRuntimeKeys(n, async () => {
await o;
t?.assertCurrent?.();
const s = t?.expectedRuntimes;
if (t?.catalogsAreCurrent && !t.catalogsAreCurrent()) return;
if (s && ([...s].some(([e, t]) => i.runtimesBySessionId.get(e) !== t) || e !== void 0 && runtimeKeysForSessionId(e).some((e) => {
const t = i.runtimesBySessionId.get(e);
return t && s.get(e) !== t;
}))) return;
if (t?.preserveActiveLeases && e !== void 0 && totalActiveLeasesForSessionId(e) > 0) {
i.deferredRetirementSessionIds.add(e);
return;
}
const c = t?.agentDeletion;
if (c) {
c.assertCurrent();
if (r.sessionEntries(e ?? "").some((e) => e.agentId !== c.agentId)) return;
const t = n.map((e) => i.pendingDisposals.get(e)).find((e) => e?.failure && e.agentId === c.agentId);
if (t?.failure) throw t.failure.reason;
if (n.some((e) => {
const t = i.runtimesBySessionId.get(e);
return t && runtimeAgentId(t) !== c.agentId;
})) return;
if (e !== void 0 && totalActiveLeasesForSessionId(e) > 0) {
c.deferRetirement();
throw new Error(`Session ${e} still has active MCP leases; close its views and retry deletion`);
}
}
if (t?.requireStoppedScheduler && (!i.scheduler.signal.aborted || e !== void 0 && totalActiveLeasesForSessionId(e) > 0)) return;
if (e === void 0) {
clearIdleSweepTimer();
i.configReload = void 0;
i.sessionIdBySessionKey.clear();
i.deferredRetirementSessionIds.clear();
i.requiredRetirementSessionIds.clear();
r.clear();
} else {
i.deferredRetirementSessionIds.delete(e);
if (t?.preserveRequiredRetirement !== true) i.requiredRetirementSessionIds.delete(e);
r.deleteSession(e);
}
const l = (await Promise.allSettled([...a, ...n.map(async (e) => {
c?.assertCurrent();
t?.assertCurrent?.();
const n = i.runtimesBySessionId.get(e);
if (c && n && runtimeAgentId(n) !== c.agentId) return;
await disposeRuntimeKeyNow(e);
})])).find((e) => e.status === "rejected") ?? n.map((e) => i.pendingDisposals.get(e)).find((e) => e?.failure && (!c || !e.agentId || e.agentId === c.agentId))?.failure;
ensureIdleSweepTimer();
if (l) throw l.reason;
});
const c = trackDisposal(n, () => s).catch((e) => {
if (t?.agentDeletion || t?.assertCurrent) throw e;
});
if (e === void 0) i.disposalInFlight = c;
return c.finally(() => {
if (i.disposalInFlight === c) i.disposalInFlight = void 0;
});
};
return {
store: i,
runtimeKeysForSessionId,
pruneSessionBookkeeping,
totalActiveLeasesForSessionId,
runExclusiveOnRuntimeKeys,
sweepIdleRuntimes,
setScheduler,
reserveRuntimeSlot,
releaseEmptyRuntimeSlot,
disposeRuntime,
ensureIdleSweepTimer,
disposeRuntimeKeyNow,
disposeManagedRuntimes,
catalogs: r
};
}
//#endregion
//#region src/agents/agent-bundle-mcp-manager.ts
const sessionMcpRuntimeLoader = createLazyImportLoader(() => import("./agents/agent-bundle-mcp-runtime.js"));
const createSessionMcpRuntimeLazy = async (e) => {
return (await sessionMcpRuntimeLoader.load()).createSessionMcpRuntime(e);
};
function createSessionMcpRuntimeManager(e) {
const t = createSessionMcpRuntimeManagerLifecycle(e, createSessionMcpRuntimeLazy);
const { store: n, catalogs: r } = t;
const i = createSessionMcpRuntimeManagerInstall(t);
const leaseRuntime = (e, r) => ({
runtime: e,
releaseLease: e.acquireLease?.() ?? (() => {}),
async retireUnusedServers(i) {
const a = sessionMcpRuntimeOwners.get(e);
if (n.runtimesBySessionId.get(r) !== e || !a?.isCurrent()) return;
await a.retireUnusedServers(i);
if (!a.hasServers()) await t.releaseEmptyRuntimeSlot(r, e);
}
});
const acquireCurrent = (e, r) => async function current(i) {
const o = normalizeOptionalString(i.requesterSenderId);
const s = o ? {
senderId: o,
runtimeKey: buildMcpRequesterRuntimeCacheKey({
...i,
requesterSenderId: o
})
} : void 0;
const c = s ? [s.runtimeKey] : [];
if (e === "full" || !s) c.push(i.sessionId);
const l = n.disposalInFlight;
const u = n.runtimeWorkChains.get(i.sessionId);
const d = n.configReload;
let f;
try {
return await t.runExclusiveOnRuntimeKeys(c, async () => {
await Promise.all([l, u].filter((e) => e !== void 0));
n.scheduler.signal.throwIfAborted();
const e = n.configReload;
f = await r({
...i,
requester: s,
...e && e !== d ? {
cfg: e.cfg,
manifestRegistry: e.manifestRegistry
} : {}
});
n.scheduler.signal.throwIfAborted();
return f;
});
} catch (e) {
f?.releaseLease();
f = void 0;
throw e;
} finally {
if (!f) await a.completeDeferredRetirement(i.sessionId);
}
};
const createUnavailableRuntime = (e, t, r = e.sessionId) => {
const i = n.catalogByRuntimeKey.get(r)?.catalog;
if (t.notify && e.sessionKey) for (const n of listAgentRunsForSession({
sessionKey: e.sessionKey,
sessionId: e.sessionId
})) {
if (!hasAgentRunContextExecutionOwner(n.runId)) continue;
emitAgentEvent({
...n,
sessionKey: e.sessionKey,
stream: "notice",
data: {
phase: "warning",
message: t.message
}
});
}
const a = createCombinedSessionMcpRuntime({
...e,
parts: []
});
const o = {
version: 1,
generatedAt: 0,
servers: {},
tools: [],
...i,
diagnostics: [...i?.diagnostics ?? [], {
serverName: "Gateway",
safeServerName: "gateway",
launchSummary: "MCP runtime capacity",
message: t.message
}]
};
a.getCatalog = async () => o;
a.peekCatalog = () => o;
a.callTool = async () => ({
isError: true,
content: [{
type: "text",
text: t.message
}]
});
const unavailable = async () => {
throw new Error(t.message);
};
a.listTools = unavailable;
a.listResources = unavailable;
a.readResource = unavailable;
a.listResourceTemplates = unavailable;
a.listPrompts = unavailable;
a.getPrompt = unavailable;
return a;
};
const withoutMcp = (e, t) => leaseRuntime(createUnavailableRuntime(e, t), e.sessionId);
const prepareAcquisition = (e, t, n) => {
const i = loadSessionMcpConfig({
...e,
logDiagnostics: false
});
const a = partitionMcpServersByConnectionScope(i.loaded.mcpServers);
const { safeServerNamesByServer: o } = i;
const s = e.requester;
const c = JSON.stringify([
e.sessionKey,
e.agentId ?? parseAgentSessionKey(e.sessionKey ?? "")?.agentId,
e.workspaceDir,
e.agentDir,
loadSessionMcpConfig({
...e,
loaded: i.loaded,
logDiagnostics: false,
redactConnectionServerNames: new Set(a.requesterScopedServerNames),
safeServerNamesByServer: o
}).fingerprint
]);
if (n === "requester" || s && a.requesterScopedServerNames.length > 0) r.reconcileAdvertisedScopedCatalogConfig({
sessionId: e.sessionId,
sessionKey: e.sessionKey,
agentId: e.agentId ?? parseAgentSessionKey(e.sessionKey ?? "")?.agentId,
workspaceDir: e.workspaceDir,
agentDir: e.agentDir,
configFingerprint: c
}, s !== void 0 && a.requesterScopedServerNames.length > 0);
return {
advertisedCatalogConfigFingerprint: c,
fullConfig: i,
...a,
safeServerNamesByServer: o,
requester: s,
acquireRequester: () => s ? materializeRequesterScopedRuntime({
...e,
configReloadAtAdmission: t,
mcpServers: i.loaded.mcpServers,
oauthRequesterServerNames: a.oauthRequesterServerNames,
resolverRequesterServerNames: a.resolverRequesterServerNames,
scopedNameSet: new Set(a.requesterScopedServerNames),
safeServerNamesByServer: o,
requesterSenderId: s.senderId,
runtimeKey: s.runtimeKey
}) : void 0
};
};
const materializeRequesterScopedRuntime = async (e) => {
const t = new Set(e.oauthRequesterServerNames);
const n = new Set(e.resolverRequesterServerNames);
const r = normalizeOptionalString(e.agentAccountId);
const a = normalizeOptionalString(e.messageChannel);
const o = loadSessionMcpConfig({
...e,
logDiagnostics: false,
includeServerNames: e.scopedNameSet,
redactConnectionServerNames: n
}).fingerprint;
const s = {
requesterSenderId: e.requesterSenderId,
...r ? { agentAccountId: r } : {},
...a ? { messageChannel: a } : {}
};
const c = await i.resolveAndInstallRequesterRuntime({
...e,
fullScopedFingerprint: o,
oauthRequesterNameSet: t,
agentAccountId: r,
messageChannel: a,
requesterScope: s,
onCapacityRefusal(t, n) {
return Object.assign(createUnavailableRuntime(e, t, e.runtimeKey), {
requesterScope: s,
requesterConnect: n && {
...n,
createExecute: () => void 0
}
});
}
});
return c ? leaseRuntime(c, e.runtimeKey) : void 0;
};
const a = {
acquire: acquireCurrent("full", async (e) => {
const t = n.configReload;
if (e.sessionKey) n.sessionIdBySessionKey.set(e.sessionKey, e.sessionId);
const { fullConfig: r, staticServers: a, requesterScopedServerNames: o, safeServerNamesByServer: s, requester: c, acquireRequester: l } = prepareAcquisition(e, t, "full");
const u = [];
try {
let n;
try {
n = leaseRuntime(await i.getOrCreateRuntimeEntry({
...e,
runtimeKey: e.sessionId,
configReloadAtAdmission: t,
excludeServerNames: new Set(o),
safeServerNamesByServer: s
}, r.loaded), e.sessionId);
} catch (t) {
if (!(t instanceof SessionMcpRuntimeCapacityError)) throw t;
n = withoutMcp(e, t);
}
u.push(n);
if (o.length === 0) return n;
const d = Object.keys(a).length > 0 ? [n.runtime] : [];
const f = c ? await l() : void 0;
if (f) {
u.push(f);
d.push(f.runtime);
}
return {
runtime: d.length === 0 ? n.runtime : createCombinedSessionMcpRuntime({
sessionId: e.sessionId,
sessionKey: e.sessionKey,
workspaceDir: e.workspaceDir,
agentDir: e.agentDir,
parts: d
}),
releaseLease: () => u.forEach((e) => e.releaseLease()),
async retireUnusedServers(e) {
const t = (await Promise.allSettled(u.map(async (t) => await t.retireUnusedServers?.(e)))).find((e) => e.status === "rejected");
if (t) throw t.reason;
}
};
} catch (e) {
u.forEach((e) => e.releaseLease());
throw e;
}
}),
acquireRequesterScoped: acquireCurrent("requester", async (e) => {
const t = n.configReload;
const { advertisedCatalogConfigFingerprint: r, requesterScopedServerNames: i, requester: a, acquireRequester: o } = prepareAcquisition(e, t, "requester");
if (!a) return;
if (e.sessionKey) n.sessionIdBySessionKey.set(e.sessionKey, e.sessionId);
if (i.length === 0) return;
const s = await o();
if (!s) return;
return {
...s,
advertisedCatalogConfigFingerprint: r
};
}),
rememberAdvertisedScopedCatalog: r.rememberAdvertisedScopedCatalog,
getAdvertisedScopedCatalog: r.getAdvertisedScopedCatalog,
resolveSessionId(e) {
return n.sessionIdBySessionKey.get(e);
},
peekSession(e) {
const t = e.sessionId ?? (e.sessionKey ? n.sessionIdBySessionKey.get(e.sessionKey) : void 0);
return t ? n.runtimesBySessionId.get(t) : void 0;
},
captureSessionRetirement(e) {
const i = e.sessionId ?? (e.sessionKey ? n.sessionIdBySessionKey.get(e.sessionKey) : void 0);
if (!i) return;
const a = /* @__PURE__ */ new Map();
const o = r.captureSession(i);
for (const e of t.runtimeKeysForSessionId(i)) {
const t = n.runtimesBySessionId.get(e);
if (t) a.set(e, t);
}
if (a.size === 0 && !o) return;
return {
sessionId: i,
retire: (e) => t.disposeManagedRuntimes(i, {
expectedRuntimes: a,
catalogsAreCurrent: o,
assertCurrent: e,
preserveActiveLeases: true,
preserveRequiredRetirement: n.requiredRetirementSessionIds.has(i)
})
};
},
disposeSession: t.disposeManagedRuntimes,
deferRetirement(e, i) {
if (i?.retainAcrossReuse === true) {
for (const r of t.runtimeKeysForSessionId(e)) {
const e = n.runtimesBySessionId.get(r);
if (e) revokeMcpAppModelContext(e);
}
n.requiredRetirementSessionIds.add(e);
}
if (t.runtimeKeysForSessionId(e).length === 0 && !r.hasSession(e) && !n.requiredRetirementSessionIds.has(e)) return false;
n.deferredRetirementSessionIds.add(e);
return true;
},
async completeDeferredRetirement(e, i) {
if (i !== void 0 && i.sessionId !== e) return false;
const o = n.deferredRetirementSessionIds.has(e);
const s = !o && n.scheduler.signal.aborted;
if (!o && !s) {
for (const r of t.runtimeKeysForSessionId(e)) {
const e = n.runtimesBySessionId.get(r);
if (e && sessionMcpRuntimeOwners.get(e)?.hasServers() === false) await t.releaseEmptyRuntimeSlot(r, e);
}
return false;
}
if (t.totalActiveLeasesForSessionId(e) > 0 || (i?.activeLeases ?? 0) > 0) return false;
const c = t.runtimeKeysForSessionId(e);
if (c.length === 0 && !r.hasSession(e)) return false;
const l = c.map((e) => n.runtimeWorkChains.get(e)).filter((e) => e !== void 0);
if (l.length > 0) {
await Promise.allSettled(l);
return await a.completeDeferredRetirement(e, i);
}
await t.disposeManagedRuntimes(e, {
preserveRequiredRetirement: n.requiredRetirementSessionIds.has(e),
requireStoppedScheduler: s
});
return !s || t.runtimeKeysForSessionId(e).length === 0;
},
async reloadConfig(e) {
resetMcpStartupBackoff();
n.configReload = {
...e,
pluginGeneration: (n.configReload?.pluginGeneration ?? 0) + (e.reloadPlugins ? 1 : 0)
};
r.clear();
t.pruneSessionBookkeeping();
for (const t of n.runtimesBySessionId.values()) {
const r = n.runtimeSlots.get(t);
if (r) r.idleTtlMs = resolveSessionMcpRuntimeIdleTtlMs(e.cfg);
}
t.ensureIdleSweepTimer();
await Promise.all([...n.runtimesBySessionId].map(async ([n, r]) => {
const i = sessionMcpRuntimeOwners.get(r);
await i?.reload(e);
if (i?.hasServers() === false) await t.releaseEmptyRuntimeSlot(n, r);
}));
},
disposeAll: () => {
resetMcpStartupBackoff();
return t.disposeManagedRuntimes();
},
sweepIdleRuntimes: t.sweepIdleRuntimes,
listSessionIds() {
return [...new Set(Array.from(n.runtimesBySessionId.values(), (e) => e.sessionId))].toSorted((e, t) => e.localeCompare(t));
},
listRuntimeKeys() {
return Array.from(n.runtimesBySessionId.keys()).toSorted((e, t) => e.localeCompare(t));
},
totalActiveLeasesForSession: t.totalActiveLeasesForSessionId
};
return Object.assign(a, {
setScheduler: t.setScheduler,
listSessionIdsForAgent(e) {
return [.../* @__PURE__ */ new Set([
...[...n.sessionIdBySessionKey].flatMap(([r, i]) => parseAgentSessionKey(r)?.agentId === e && !t.runtimeKeysForSessionId(i).some((t) => {
const r = n.runtimesBySessionId.get(t);
const i = r && sessionMcpRuntimeOwners.get(r)?.agentId;
return i !== void 0 && i !== e;
}) ? [i] : []),
...[...n.runtimesBySessionId.values()].flatMap((t) => sessionMcpRuntimeOwners.get(t)?.agentId === e ? [t.sessionId] : []),
...[...n.pendingDisposals.values()].flatMap((t) => t.agentId === e ? [t.sessionId] : []),
...[...n.catalogByRuntimeKey.values(), ...n.advertisedScopedCatalogBySessionId.values()].flatMap((t) => t.agentId === e ? [t.sessionId] : [])
])];
},
retireSessionForAgentDeletion(e, n, r) {
return t.disposeManagedRuntimes(e, { agentDeletion: {
agentId: n,
assertCurrent: r,
deferRetirement: () => a.deferRetirement(e, { retainAcrossReuse: true })
} });
}
});
}
//#endregion
//#region src/agents/agent-bundle-mcp-manager-api.ts
/** Module-level session MCP runtime manager entry APIs. */
function getSessionMcpRuntimeManager() {
const e = peekSessionMcpRuntimeManager();
if (!e) throw new Error("Session MCP runtime scheduler has not been bound by its lifecycle owner");
return e;
}
function setSessionMcpRuntimeScheduler(e) {
return resolveGlobalSingleton(SESSION_MCP_RUNTIME_MANAGER_KEY, () => createSessionMcpRuntimeManager({ scheduler: e })).setScheduler(e);
}
async function acquireManagedRuntime(e) {
const t = getBoundLegacyPluginSdkResourceHost();
const n = t?.scheduler;
if (n) {
await setSessionMcpRuntimeScheduler(n);
t?.assertOpen();
n.signal.throwIfAborted();
}
const r = await e(getSessionMcpRuntimeManager());
try {
t?.assertOpen();
n?.signal.throwIfAborted();
return r;
} catch (e) {
if (r) await releaseSessionMcpRuntime(r);
throw e;
}
}
function acquireSessionMcpRuntime(e) {
return acquireManagedRuntime((t) => t.acquire(e));
}
/**
* Requester-scoped MCP runtime only (no static partition).
* Shared-thread harnesses use this so static MCP stays harness-native.
*/
function acquireRequesterScopedMcpRuntime(e) {
return acquireManagedRuntime((t) => t.acquireRequesterScoped(e));
}
function rememberAdvertisedScopedMcpCatalog(e, t) {
getSessionMcpRuntimeManager().rememberAdvertisedScopedCatalog(e, t);
}
function getAdvertisedScopedMcpCatalog(e) {
return peekSessionMcpRuntimeManager()?.getAdvertisedScopedCatalog(e) ?? null;
}
/** Looks up an existing session MCP runtime without creating it or connecting transports. */
function peekSessionMcpRuntime(e) {
const t = normalizeOptionalString(e.sessionId);
const n = normalizeOptionalString(e.sessionKey);
return peekSessionMcpRuntimeManager()?.peekSession({
...t ? { sessionId: t } : {},
...n ? { sessionKey: n } : {}
});
}
/** Captures only currently registered MCP runtimes; invoking it never selects a successor. */
function captureSessionMcpRuntimeRetirement(e) {
return peekSessionMcpRuntimeManager()?.captureSessionRetirement(e);
}
async function retireSessionMcpRuntime(e) {
const t = normalizeOptionalString(e.sessionId);
if (!t) return false;
const n = peekSessionMcpRuntimeManager();
if (!n) return true;
try {
if (e.preserveActiveLeases === true && n.deferRetirement(t, { retainAcrossReuse: e.retainAcrossReuse })) await n.completeDeferredRetirement(t);
else await n.disposeSession(t);
return true;
} catch (n) {
e.onError?.(n, t, e.reason);
return false;
}
}
async function retireSessionMcpRuntimeForSessionKey(e) {
const t = normalizeOptionalString(e.sessionKey);
if (!t) return false;
const n = peekSessionMcpRuntimeManager()?.resolveSessionId(t);
return await retireSessionMcpRuntime({
sessionId: n,
reason: e.reason,
preserveActiveLeases: e.preserveActiveLeases,
onError: e.onError
});
}
async function reloadSessionMcpRuntimes(e) {
const t = peekSessionMcpRuntimeManager();
if (t) await t.reloadConfig(e);
else resetMcpStartupBackoff();
}
async function disposeAllSessionMcpRuntimes() {
const e = peekSessionMcpRuntimeManager();
if (e) await e.disposeAll();
else resetMcpStartupBackoff();
}
//#endregion
export { getAdvertisedScopedMcpCatalog as a, rememberAdvertisedScopedMcpCatalog as c, setSessionMcpRuntimeScheduler as d, disposeAllSessionMcpRuntimes as i, retireSessionMcpRuntime as l, acquireSessionMcpRuntime as n, peekSessionMcpRuntime as o, captureSessionMcpRuntimeRetirement as r, reloadSessionMcpRuntimes as s, acquireRequesterScopedMcpRuntime as t, retireSessionMcpRuntimeForSessionKey as u };