openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
473 lines (472 loc) • 16.4 kB
JavaScript
import { _ as resolveGlobalSingleton } from "./runtime-doctor-migrations-JGL9tD-z.js";
import { b as collectNestedErrorCandidates, g as runWithAsyncStore, h as getPluginExecutionFrame } from "./subsystem-DLheYoE0.js";
import { n as raceWithTimeout } from "./src-CSCqKRHJ.js";
import "./runtime-process-manifest-B0mzdXd2.js";
import path from "node:path";
import openClawRootFsSync from "node:fs";
import { fileURLToPath } from "node:url";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/shared/deferred.ts
const promiseWithResolvers = Promise;
function createDeferredCore() {
return promiseWithResolvers.withResolvers();
}
//#endregion
//#region src/infra/error-graph-internal.ts
/** Keep an aggregate envelope even when only one joined operation failed. */
function throwSettledAggregate(e, t) {
const n = e.flatMap((e) => e.status === "rejected" ? [e.reason] : []);
if (n.length) throw new AggregateError(n, t);
}
/** Retained errors must not keep callers alive through V8's lazy stack frames. */
function materializeErrorStack(e) {
try {
for (const t of collectNestedErrorCandidates(e)) try {
if (!(t instanceof Error)) continue;
try {
t.stack = String(t.stack);
} catch {
t.stack = "Stack trace unavailable: custom formatter failed";
}
} catch {}
} catch {}
}
/** Run every operation in iteration order; callers retain their own settlement and error envelope. */
function collectSynchronousErrors(e, t) {
const n = [];
for (const r of e) try {
t(r);
} catch (e) {
n.push(e);
}
return n;
}
//#endregion
//#region src/shared/settle-within.ts
/** A deadline bounds waiting; fulfillment alone does not certify resource cleanup. */
async function settlesWithin(e, t) {
return await raceWithTimeout(e.then(() => true), t, () => false, { ref: false });
}
//#endregion
//#region src/shared/async-work-scope.ts
const currentWorkScope = resolveGlobalSingleton(Symbol.for("openclaw.asyncWorkScope"), () => new AsyncLocalStorage());
const currentWorkScopeAncestry = resolveGlobalSingleton(Symbol.for("openclaw.asyncWorkScopeAncestry"), () => new AsyncLocalStorage());
const AsyncWorkScopeClosedError = resolveGlobalSingleton(Symbol.for("openclaw.asyncWorkScopeClosedError"), () => class ClosedError extends Error {
constructor() {
super("Async work scope is closed");
this.name = "AsyncWorkScopeClosedError";
}
});
/** Joins cooperating descendants even when their caller returns a cached value first. */
var AsyncWorkScope = class AsyncWorkScope {
constructor(e) {
this.failures = e;
this.pending = /* @__PURE__ */ new Set();
this.controller = new AbortController();
this.phase = "open";
}
get signal() {
return this.controller.signal;
}
get hasPendingWork() {
return this.pending.size > 0;
}
get isClosing() {
return this.phase !== "open";
}
enter(e) {
const t = currentWorkScope.getStore();
if (t === this) return e();
const n = currentWorkScopeAncestry.getStore();
const r = t ? n?.scope === t ? n : { scope: t } : void 0;
return runWithAsyncStore(currentWorkScope, this, () => {
currentWorkScopeAncestry.enterWith({
scope: this,
parent: r
});
return e();
});
}
/** Enters synchronous work without inspecting or assimilating its return value. */
run(e) {
if (this.phase === "closed") throw new AsyncWorkScopeClosedError();
if (this.pending.size > 0) return this.enter(e);
const t = createDeferredCore();
this.pending.add(t.promise);
try {
return this.enter(e);
} finally {
t.resolve();
this.pending.delete(t.promise);
}
}
track(e) {
if (this.phase === "closed") return Promise.reject(new AsyncWorkScopeClosedError());
const t = createDeferredCore();
this.pending.add(t.promise);
t.promise.then(() => this.pending.delete(t.promise), (e) => {
this.pending.delete(t.promise);
if (this.failures) {
materializeErrorStack(e);
this.failures.add(e);
}
});
try {
t.resolve(this.enter(e));
} catch (e) {
t.reject(e);
}
return t.promise;
}
beginClose(e) {
if (this.phase !== "open") return;
this.phase = "closing";
this.controller.abort(e);
materializeErrorStack(this.controller.signal.reason);
}
/** Starts the next phase in the same continuation that observes settled pending work. */
runWhenIdle(e) {
return AsyncWorkScope.runWhenAllIdle(() => [this], () => this.track(e));
}
/** Reselects owners so work admitted into a later phase is not mistaken for earlier work. */
static async runWhenAllIdle(e, t) {
let n = e();
while (n.some((e) => e.pending.size > 0)) {
await Promise.allSettled(n.flatMap((e) => Array.from(e.pending)));
n = e();
}
return t();
}
async drain() {
this.beginClose();
while (this.pending.size > 0) await Promise.allSettled(this.pending);
this.phase = "closed";
}
};
const GatewayRetainedWorkTimeoutError = resolveGlobalSingleton(Symbol.for("openclaw.gatewayRetainedWorkTimeoutError"), () => class RetainedWorkTimeoutError extends Error {
constructor() {
super("Retained Gateway work did not settle after abort; resources remain retained");
}
});
/** Starts work its caller does not own, so the caller's scope neither waits for it nor closes under it. */
function runOutsideAsyncWorkScope(e) {
if (currentWorkScope.getStore() === void 0) return currentWorkScopeAncestry.getStore() === void 0 ? e() : currentWorkScopeAncestry.exit(e);
return runWithAsyncStore(currentWorkScope, void 0, () => {
currentWorkScopeAncestry.enterWith(void 0);
return e();
});
}
//#endregion
//#region src/plugins/host-hook-cleanup-result.ts
/** Merge raw instance outcomes without duplicating their existing host or instance report. */
function appendPluginInstanceCleanupFailures(e, t, n) {
for (const r of n.errors) {
if (e.some((e) => e.pluginId === t && e.error === r)) continue;
e.push({
pluginId: t,
hookId: "instance",
error: r
});
}
}
//#endregion
//#region src/plugins/plugin-cache-sdk.ts
/** Derived SDK facts share the plugin cache lifetime; none owns a separate expiry. */
function createPluginCacheSdk() {
return {
hosts: /* @__PURE__ */ new Map(),
contexts: /* @__PURE__ */ new Map(),
roots: /* @__PURE__ */ new Set(),
packageNames: /* @__PURE__ */ new Map(),
packageSearches: /* @__PURE__ */ new Map(),
argvDirectories: /* @__PURE__ */ new Map(),
devSourceRoots: /* @__PURE__ */ new Map(),
runtimeModules: /* @__PURE__ */ new Map(),
normalizedJitiAliases: /* @__PURE__ */ new Map(),
aliasFacts: /* @__PURE__ */ new WeakMap(),
native: {
sdkProviders: /* @__PURE__ */ new Map(),
nextSdkProviderOrder: 0,
parents: /* @__PURE__ */ new Map(),
aliases: /* @__PURE__ */ new Map(),
registeredHosts: /* @__PURE__ */ new Set(),
hostRoots: /* @__PURE__ */ new Map(),
nearestPackageRoots: /* @__PURE__ */ new Map(),
loaderPackageRoots: /* @__PURE__ */ new Map(),
allowedParentRoots: /* @__PURE__ */ new Map()
}
};
}
//#endregion
//#region src/plugins/plugin-instance-error.ts
/** A retired plugin inventory cannot admit new work; callers start a fresh plugin operation. */
const PluginInventoryRetiredError = resolveGlobalSingleton(Symbol.for("openclaw.pluginInventoryRetiredError"), () => class InventoryRetiredError extends Error {
constructor() {
super("Plugin inventory has retired; begin a new plugin operation.");
this.name = "PluginInventoryRetiredError";
}
});
const PluginSourceRecoveryUnavailableError = resolveGlobalSingleton(Symbol.for("openclaw.pluginSourceRecoveryUnavailableError"), () => class SourceRecoveryUnavailableError extends Error {
constructor(e) {
super("Captured plugin source is missing; its previous code cannot be recovered.", { cause: e });
this.name = "PluginSourceRecoveryUnavailableError";
}
});
const PluginInstanceDrainTimeoutError = resolveGlobalSingleton(Symbol.for("openclaw.pluginInstanceDrainTimeoutError"), () => class DrainTimeoutError extends Error {
constructor(e, t, n, r) {
super(e, n);
this.settled = t;
this.forcedRetirement = r;
this.name = "PluginInstanceDrainTimeoutError";
}
});
//#endregion
//#region src/plugins/plugin-cache.ts
const state = resolveGlobalSingleton(Symbol.for("openclaw.pluginCache"), () => ({
snapshotOwners: /* @__PURE__ */ new WeakMap(),
retirements: []
}));
const cacheRetainers = resolveGlobalSingleton(Symbol.for("openclaw.pluginCacheRetainers"), () => /* @__PURE__ */ new WeakMap());
const instanceCacheOwners = resolveGlobalSingleton(Symbol.for("openclaw.pluginInstanceCacheOwners"), () => /* @__PURE__ */ new WeakMap());
/** A retiring inventory releases its own custody; terminal disposal releases every birth cache. */
function releasePluginCacheInstance(e, t) {
const n = instanceCacheOwners.get(e);
if (t) {
t.instances.delete(e);
n?.delete(t);
} else {
for (const t of n ?? []) t.instances.delete(e);
n?.clear();
}
if (n?.size === 0) instanceCacheOwners.delete(e);
}
function getPluginCacheRetainers(e) {
let t = cacheRetainers.get(e);
if (!t) {
t = {
references: /* @__PURE__ */ new Set(),
controller: new AbortController(),
settled: createDeferredCore()
};
cacheRetainers.set(e, t);
}
return t;
}
function createPluginMetadataCache() {
return {
current: {
snapshot: void 0,
owner: "operation",
configFingerprint: void 0,
agentWorkspaceFingerprint: void 0,
envFingerprint: void 0,
defaultDiscoveryCompatible: false,
compatibleConfigFingerprints: void 0,
configIdentities: /* @__PURE__ */ new WeakSet()
},
snapshots: /* @__PURE__ */ new Map(),
derivedIndexes: /* @__PURE__ */ new WeakMap(),
preparedManifests: /* @__PURE__ */ new WeakMap(),
snapshotManifestFacts: /* @__PURE__ */ new WeakMap(),
discovery: /* @__PURE__ */ new Map(),
sharedDiscovery: /* @__PURE__ */ new Map(),
projections: /* @__PURE__ */ new WeakMap(),
projectionSources: /* @__PURE__ */ new WeakMap(),
completions: /* @__PURE__ */ new WeakMap(),
indexFacts: /* @__PURE__ */ new WeakMap(),
providerPolicyOwners: /* @__PURE__ */ new WeakMap(),
channelAdapters: /* @__PURE__ */ new WeakMap(),
bundledChannelCatalogs: /* @__PURE__ */ new Map(),
bundledProviderPolicySurfaces: /* @__PURE__ */ new WeakMap(),
staticCatalogStates: /* @__PURE__ */ new WeakMap(),
modelSuppressionResolvers: /* @__PURE__ */ new WeakMap(),
mcpAuthDeclarations: /* @__PURE__ */ new WeakMap()
};
}
/** Each inventory owns its acquired facts and reusable load results; publication owns activation. */
function createPluginCache(e = {}) {
return {
async [Symbol.asyncDispose]() {
await retirePluginCache(this);
},
kind: e.kind ?? "operation",
roots: /* @__PURE__ */ new Map(),
rootAliases: /* @__PURE__ */ new Map(),
sdk: createPluginCacheSdk(),
setupModules: /* @__PURE__ */ new Map(),
instances: /* @__PURE__ */ new Set(),
metadata: createPluginMetadataCache(),
installRecords: /* @__PURE__ */ new Map(),
persistedInstalledIndex: /* @__PURE__ */ new Map(),
preparedBundledDiscoveryModes: /* @__PURE__ */ new Map(),
dependencyStatus: /* @__PURE__ */ new WeakMap(),
moduleLoaders: /* @__PURE__ */ new Map(),
sources: /* @__PURE__ */ new Map(),
sourceAliases: /* @__PURE__ */ new Map(),
runtimeRecordRoots: /* @__PURE__ */ new WeakMap()
};
}
function getProcessPluginCache() {
return state.current ??= createPluginCache({ kind: "process" });
}
function getScopedPluginCache() {
return getPluginExecutionFrame()?.cacheScope?.cache;
}
function getPluginCache() {
return getScopedPluginCache() ?? getProcessPluginCache();
}
/** Stop new setup calls immediately; the owner awaits in-flight calls and graph cleanup. */
function retirePluginCache(e, t, n) {
const r = getPluginCacheRetainers(e);
if (r.retirement) return r.retirement;
const i = createDeferredCore();
r.retirement = i.promise;
const retire = async () => {
if (r.references.size) await r.settled.promise;
const i = new AsyncWorkScope();
try {
return await i.track(() => beginPluginCacheRetirement(e, t, n));
} finally {
await i.drain();
}
};
r.controller.abort();
materializeErrorStack(r.controller.signal.reason);
runOutsideAsyncWorkScope(retire).then(i.resolve, i.reject);
return i.promise;
}
function beginPluginCacheRetirement(e, t, n) {
if (e.retirement) return e.retirement;
const r = createDeferredCore();
e.retirement = r.promise;
const cleanup = async () => {
t?.();
const r = e.retireRegistryLoads?.();
const i = /* @__PURE__ */ new Set([...e.setupModules.values(), ...e.instances]);
for (const e of i) e.quiesce();
const [a] = await Promise.allSettled([r]);
const o = await Promise.allSettled([...i].map(async (e) => ({
resource: e,
result: await e.dispose(void 0, n)
})));
const s = e.sourceAdmissions;
if (s) {
const e = o.flatMap((e) => e.status === "fulfilled" ? e.value.result.errors.flatMap((e) => e instanceof PluginInstanceDrainTimeoutError ? [e.settled] : []) : []);
if (e.length > 0) Promise.allSettled(e).then(() => s.dispose()).catch((e) => process.emitWarning(`Plugin native capture cleanup failed: ${String(e)}`));
else await s.dispose();
}
e.setupModules.clear();
for (const t of e.instances) releasePluginCacheInstance(t, e);
const c = [...a.status === "rejected" ? [a.reason] : [], ...o.flatMap((e) => e.status === "rejected" ? [e.reason] : [])];
if (c.length) throw new AggregateError(c, "Plugin cache resources failed to retire");
const l = a.status === "fulfilled" ? a.value : void 0;
const u = [...l?.failures ?? []];
for (const e of o) {
if (e.status !== "fulfilled") continue;
const { resource: t, result: n } = e.value;
appendPluginInstanceCleanupFailures(u, t.pluginId, n);
}
return {
cleanupCount: l?.cleanupCount ?? 0,
failures: u
};
};
cleanup().then(r.resolve, r.reject);
return r.promise;
}
//#endregion
//#region src/infra/openclaw-root.ts
function parsePackageName(e) {
const t = JSON.parse(e);
return typeof t.name === "string" ? t.name : null;
}
function readPackageNameSync(e) {
const t = getPluginCache().sdk.packageNames;
const n = path.join(path.resolve(e), "package.json");
if (t.has(n)) return t.get(n) ?? null;
try {
const e = parsePackageName(openClawRootFsSync.readFileSync(n, "utf-8"));
t.set(n, e);
return e;
} catch {
t.set(n, null);
return null;
}
}
function findPackageRootSync(e) {
for (const t of iterAncestorDirs(e)) if (readPackageNameSync(t) === "openclaw") return t;
return null;
}
function* iterAncestorDirs(e) {
let t = path.resolve(e);
for (let e = 0; e < 12; e += 1) {
yield t;
if (path.basename(t) === "node_modules") break;
const e = path.dirname(t);
if (e === t) break;
t = e;
}
}
function candidateDirsFromArgv1(e) {
const t = getPluginCache().sdk.argvDirectories;
const n = path.resolve(e);
const r = t.get(n);
if (r) return [...r];
const i = n;
const a = [];
try {
const e = openClawRootFsSync.realpathSync(i);
if (e !== i) a.push(path.dirname(e));
} catch {}
a.push(path.dirname(i));
const o = i.split(path.sep);
const s = o.lastIndexOf(".bin");
if (s > 0 && o[s - 1] === "node_modules") {
const e = path.basename(i);
const t = o.slice(0, s).join(path.sep);
a.push(path.join(t, e));
}
const c = dedupeCandidates(a);
t.set(n, c);
return [...c];
}
function preparePackageRootSearch(e, t) {
const n = buildCandidates(e);
const r = n.join("\0");
const i = getPluginCache().sdk.packageSearches;
const a = i.get(r);
return {
candidates: n,
first: a?.all ? a.all[0] ?? null : a?.first,
complete(e) {
i.set(r, t ? {
...i.get(r),
first: e
} : { first: e });
return e;
}
};
}
function resolveOpenClawPackageRootSync(e) {
const t = preparePackageRootSearch(e, false);
if (t.first !== void 0) return t.first;
for (const e of t.candidates) {
const n = findPackageRootSync(e);
if (n) return t.complete(n);
}
return t.complete(null);
}
function buildCandidates(e) {
const t = [];
if (e.moduleUrl) try {
t.push(path.dirname(fileURLToPath(e.moduleUrl)));
} catch {}
if (e.argv1) t.push(...candidateDirsFromArgv1(e.argv1));
if (e.cwd) t.push(e.cwd);
return dedupeCandidates(t);
}
function dedupeCandidates(e) {
return [...new Set(e.map((e) => path.resolve(e)))];
}
//#endregion
export { collectSynchronousErrors as a, createDeferredCore as c, settlesWithin as i, AsyncWorkScope as n, materializeErrorStack as o, runOutsideAsyncWorkScope as r, throwSettledAggregate as s, resolveOpenClawPackageRootSync as t };