openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
518 lines (517 loc) • 18 kB
JavaScript
import { W as resolveGlobalSingleton } from "./path-guards-quCEQx1i.mjs";
import { n as materializeErrorStack } from "./error-graph-internal-G5_kmB_7.mjs";
import { n as getPluginExecutionFrame, r as runWithAsyncStore } from "./plugin-instance-invocation-DLc0_aJ8.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import "./settle-within-xlNWuWou.mjs";
import "./runtime-process-manifest-BxvHhnYN.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
import openClawRootFsSync from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
//#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();
});
}
function getAsyncWorkSignal() {
return currentWorkScope.getStore()?.signal;
}
//#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;
}
/** Cache retirement revokes cached publications before waiting for admitted borrowers. */
function getPluginCacheRetirementSignal(e) {
return getPluginCacheRetainers(e).controller.signal;
}
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()
};
}
/** Invalidate discovery facts without retiring callbacks owned by this operation. */
function invalidatePluginCacheMetadata(e) {
e.inspectionNativeEsmPolicy = void 0;
e.sourceAdmissions?.invalidate();
e.metadata = createPluginMetadataCache();
e.sdk.native.parents.clear();
for (const t of e.roots.values()) {
t.files.clear();
t.checkedEntries.clear();
t.paths.clear();
t.directory = void 0;
t.artifacts.clear();
t.runtimeArtifacts.clear();
t.entryBoundaries.clear();
t.entryPaths.clear();
}
e.rootAliases.clear();
e.installRecords.clear();
e.persistedInstalledIndex.clear();
e.preparedBundledDiscoveryModes.clear();
e.dependencyStatus = /* @__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;
}
/** An explicit install refreshes its enclosing command's metadata phases. */
function getScopedPluginCaches() {
const e = [];
for (let t = getPluginExecutionFrame()?.cacheScope; t; t = t.parent) e.push(t.cache);
return e;
}
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;
}
function getPluginCacheRoot(e) {
const t = getPluginCache();
const n = t.roots.get(t.rootAliases.get(e) ?? e);
if (n) return n;
const r = path.resolve(e);
const i = t.rootAliases.get(r) ?? r;
let a = t.roots.get(i);
if (!a) {
a = {
rootDir: i,
files: /* @__PURE__ */ new Map(),
checkedEntries: /* @__PURE__ */ new Map(),
paths: /* @__PURE__ */ new Map(),
artifacts: /* @__PURE__ */ new Map(),
runtimeArtifacts: /* @__PURE__ */ new Map(),
entryBoundaries: /* @__PURE__ */ new Map(),
entryPaths: /* @__PURE__ */ new Map()
};
t.roots.set(i, a);
}
return a;
}
function mergeRootFacts(e, t) {
for (const [n, r] of t) if (!e.has(n)) e.set(n, r);
}
/** Bind aliases only after a checked file establishes their shared package boundary. */
function bindPluginCacheRoot(e, t) {
const n = getPluginCacheRoot(e);
if (n.rootDir === t) return n;
const r = getPluginCache();
const i = path.resolve(e);
const a = path.resolve(t);
n.rootDir = a;
const o = r.roots.get(a);
if (o && o !== n) {
mergeRootFacts(n.files, o.files);
mergeRootFacts(n.checkedEntries, o.checkedEntries);
mergeRootFacts(n.paths, o.paths);
mergeRootFacts(n.artifacts, o.artifacts);
mergeRootFacts(n.runtimeArtifacts, o.runtimeArtifacts);
mergeRootFacts(n.entryBoundaries, o.entryBoundaries);
mergeRootFacts(n.entryPaths, o.entryPaths);
n.directory ??= o.directory;
n.publicSurfaceBoundary ??= o.publicSurfaceBoundary;
Object.assign(o, n);
}
r.roots.set(a, n);
r.rootAliases.set(i, a);
return n;
}
//#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 { getPluginCacheRoot as a, getScopedPluginCaches as c, getAsyncWorkSignal as d, runOutsideAsyncWorkScope as f, getPluginCacheRetirementSignal as i, invalidatePluginCacheMetadata as l, bindPluginCacheRoot as n, getProcessPluginCache as o, getPluginCache as r, getScopedPluginCache as s, resolveOpenClawPackageRootSync as t, AsyncWorkScope as u };