openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
453 lines (452 loc) • 19.7 kB
JavaScript
import { t as AsyncWorkScope } from "../async-work-scope-BXagjUap.mjs";
import { r as normalizeProviderId } from "../provider-id-b5XGSf9C.mjs";
import { n as normalizeAgentId } from "../agent-id-CQjtp2ft.mjs";
import "../session-key-CqAyZeVk.mjs";
import { n as freezeTrustedJsonSnapshot, r as isDeeplyFrozenPlainData } from "../immutable-data-Y7xVjZoy.mjs";
import { F as resolveRegisteredAgentIdForDir, L as unregisterResolvedAgentDir, P as registerResolvedAgentDir } from "../agent-scope-config-DmXgFGKP.mjs";
import { t as _usingCtx } from "../usingCtx-rhpPzaNq.mjs";
import { i as installDatabaseEngineSelection } from "../context-DE59wyBs.mjs";
import { C as normalizePluginsConfigWithResolverCore } from "../config-state-B1JlHgba.mjs";
import { i as copyConfigResolutionFacts, m as restoreConfigResolutionFacts } from "../resolution-facts-xaIKuREs.mjs";
import { X as withWorkerAuthProfileWrites, a as captureAuthProfileCredentialCommits } from "../user-model-account-authority-CRj924IP.mjs";
import { O as setRuntimeConfigSnapshot, a as getRuntimeConfigSnapshot, c as getRuntimeConfigSourceSnapshot } from "../runtime-snapshot-WbwbY5b7.mjs";
import { _ as restorePluginMetadataSnapshot } from "../plugin-metadata-snapshot-By9ySblt.mjs";
import { f as withPluginSourceCaptureDirectory } from "../plugin-package-metadata-capture-D1O_HaHi.mjs";
import { a as nativeReferenceProgress } from "../plugin-recovery-source-copy-BgrLByBL.mjs";
import { n as withPluginRuntimeGenerationScope } from "../generation-scope-Cq7RLFex.mjs";
import { d as withRemoteModelCatalogSnapshot, n as captureRemoteModelCatalogStartupSnapshot } from "../remote-overlay-ifi3kxLn.mjs";
import { n as isManifestPluginAvailableForControlPlane } from "../manifest-contract-eligibility-DoGGge-2.mjs";
import { u as mergeRuntimeExternalProfileReferences } from "../persisted-Dv3zNYHi.mjs";
import { i as noteCommittedSharedAuthStoreOwnership } from "../path-resolve-CpNl_n1M.mjs";
import { G as preserveResolvedSecretBackedCredentials, b as measureRuntimeAuthProfileStores, k as replaceRuntimeAuthProfileStoreSnapshotsAsync } from "../runtime-snapshots-1lyYKb7Y.mjs";
import { t as estimateRetainedDataSize } from "../retained-data-size-C90rJBvZ.mjs";
import { a as withTemplateInstallSchemaVersionFacts } from "../provenance-runtime-read-CXIQNtS8.mjs";
import { n as getPluginRegistryInspectionResources } from "../registry-inspection-resources-CDO3vUtM.mjs";
import "../store-Bh2lUvOT.mjs";
import { r as listExternalCliSyncProviderIds } from "../external-cli-sync-_MwEKD82.mjs";
import { r as getPluginRuntimeLoadContext } from "../load-context-CwTU1iXB.mjs";
import { t as manifestPluginResolvesRuntimeModelCatalogAugment } from "../providers-B9AkUbSZ.mjs";
import { u as loadAuthProfileStoreForCatalogAsync } from "../store-runtime-dW0pXLJI.mjs";
import { n as PREPARED_MODEL_CATALOG_WORKER_TIMEOUT_MS } from "../model-catalog-timeouts-CWTmGWX-.mjs";
import { r as planRuntimePluginDiscovery } from "../provider-discovery-C1BnGfVa.mjs";
import { G as restorePreparedSyntheticAuthFacts } from "../provider-runtime-BddjXkmv.mjs";
import { i as resolveRuntimeSyntheticAuthProviderRefs, t as listManifestSyntheticAuthProviderRefs } from "../synthetic-auth.runtime-DJz2VeJs.mjs";
import { c as PreparedModelRuntimeBuildResources, h as resolveUsableAgentCredentialModes, m as resolveAgentCredentialMapFromStore, n as ownPreparedPluginGeneration, p as resolveAmbientAgentCredentialsForDiscovery, s as retainPreparedPluginRegistry } from "../prepared-model-runtime.plugin-lifetime-Cp7P2Ujy.mjs";
import { t as AuthStorage } from "../auth-storage.core-C5ytUL3b.mjs";
import { a as scopeSyntheticAuthProviderRefs } from "../prepared-model-runtime.synthetic-auth-BaNlqur1.mjs";
import { n as prepareModelCatalogAuthLabels } from "../model-catalog-auth-labels-EzN4_7r-.mjs";
import { i as resolveImplicitProviderDiscoveryScope, t as prepareImplicitProviderStaticCatalog } from "../models-config.providers.implicit-6ZK1ckua.mjs";
import { n as serveWorkerTasks } from "../worker-task-server-J1vG-XRl.mjs";
import { r as getLiveCatalogRetainedData } from "../provider-live-catalog-cache-BIG8VvFH.mjs";
import { n as overlayExternalAuthProfiles } from "../external-auth-runtime-DzT7vDzQ.mjs";
import { parentPort, workerData } from "node:worker_threads";
//#region src/agents/prepared-model-catalog-retained-data.ts
const row = (e, t, n, r = {}) => ({
structure: e,
entries: n,
...r,
...estimateRetainedDataSize(t)
});
const publishedCensuses = /* @__PURE__ */ new Map();
function measurePublishedRoots(e, t, n, r) {
const i = publishedCensuses.get(e);
if (i?.roots.length === t.length && i.roots.every((e, n) => e.deref() === t[n])) return i.rows;
const a = n();
if (!r || t.every(r)) publishedCensuses.set(e, {
roots: t.map((e) => new WeakRef(e)),
rows: a
});
else publishedCensuses.delete(e);
return a;
}
function measureRemoteCatalogs(e) {
const t = e.filter((e) => e !== null);
return measurePublishedRoots("catalog-remote", t, () => [row("catalog-remote", t.map((e) => e.providers), t.reduce((e, t) => e + Object.values(t.providers).reduce((e, t) => e + t.models.length, 0), 0), {
generations: t.length,
providers: t.reduce((e, t) => e + Object.keys(t.providers).length, 0)
}), row("catalog-pricing", t.flatMap((e) => [e.pricing, e.upstreamPricing]), t.reduce((e, t) => e + Object.keys(t.pricing).length + Object.keys(t.upstreamPricing).length, 0))], isDeeplyFrozenPlainData);
}
/** Inspect only explicit data roots; registry callbacks and hidden runtime graphs are excluded. */
function measurePreparedCatalogRetainedData(e, t) {
const n = [...e];
const r = n.map((e) => getPluginRuntimeLoadContext(e.pluginRegistry));
const i = /* @__PURE__ */ new Set([
getRuntimeConfigSnapshot(),
getRuntimeConfigSourceSnapshot(),
...r.flatMap((e) => e ? [
e.rawConfig,
e.config,
e.activationSourceConfig
] : [])
]);
i.delete(null);
const a = /* @__PURE__ */ new Set([captureRemoteModelCatalogStartupSnapshot(), ...n.map((e) => e.remoteCatalog)]);
a.delete(null);
const o = new Set(n.map((e) => e.pluginMetadataSnapshot));
const s = n.flatMap((e) => e.preparedStaticProviderCatalog?.entries ?? []).flatMap((e) => Object.values(e.providerConfigs));
return [
row("catalog-index", [], n.length, { generations: n.length }),
row("catalog-config", i, i.size),
...measurePublishedRoots("catalog-metadata", [...o], () => [row("catalog-metadata", o, o.size)]),
row("catalog-static", s, s.length, { providers: s.length }),
...measureRemoteCatalogs([...a]),
row("catalog-request", t ? [t] : [], t ? 1 : 0),
...measureRuntimeAuthProfileStores()
];
}
//#endregion
//#region src/agents/prepared-model-catalog.worker.ts
/** Worker-thread entrypoint for complete model-catalog discovery. */
function restoreWorkerConfig(e) {
restoreConfigResolutionFacts(e.input.config, e.configResolutionFacts);
if (e.sourceConfigResolutionFacts === e.configResolutionFacts) copyConfigResolutionFacts(e.input.config, e.sourceConfigForSecrets);
else restoreConfigResolutionFacts(e.sourceConfigForSecrets, e.sourceConfigResolutionFacts);
setRuntimeConfigSnapshot(e.input.config, e.sourceConfigForSecrets);
}
async function prepareWorkerGeneration(e, t, n) {
try {
var r = _usingCtx();
const i = t?.pluginGeneration.pluginMetadataSnapshot ?? restorePluginMetadataSnapshot(e.pluginMetadataSnapshot);
const a = normalizePluginsConfigWithResolverCore(e.input.config.plugins, i.normalizePluginId);
const o = n ?? i.plugins.filter((t) => manifestPluginResolvesRuntimeModelCatalogAugment(t) && isManifestPluginAvailableForControlPlane({
snapshot: i,
plugin: t,
config: e.input.config,
normalizedConfig: a,
...e.input.env ? { env: e.input.env } : {}
})).map((e) => e.id).toSorted((e, t) => e.localeCompare(t));
const s = await r.a(new PreparedModelRuntimeBuildResources(retainPreparedPluginRegistry)).load({
...e.input,
metadataSnapshot: i,
preferBuiltPluginArtifacts: e.preferBuiltPluginArtifacts,
basePluginIds: o,
reusableRegistry: t?.pluginGeneration.pluginRegistry,
purpose: "model-catalog"
}, () => {});
const c = Object.freeze({
...t?.pluginGeneration,
remoteCatalog: e.remoteCatalog,
pluginMetadataSnapshot: i,
pluginRegistry: s,
preparedStaticProviderCatalog: void 0,
preferBuiltPluginArtifacts: e.preferBuiltPluginArtifacts
});
return {
pluginGeneration: c,
pluginIds: /* @__PURE__ */ new Set([...o, ...s.plugins.map((e) => e.id)]),
staticProviderIds: t?.staticProviderIds ?? /* @__PURE__ */ new Set(),
release: ownPreparedPluginGeneration(c).retain()
};
} catch (e) {
r.e = e;
} finally {
await r.d();
}
}
async function runCatalogRequest(e, t, n, r, i) {
const a = e.input.agentId ? {
agentId: e.input.agentId,
agentDir: e.input.agentDir,
env: e.input.env
} : void 0;
let o = false;
let s;
let c;
try {
if (e.sharedAuthStoreOwnership) noteCommittedSharedAuthStoreOwnership(e.sharedAuthStoreOwnership, e.input.env);
if (a) {
o = registerResolvedAgentDir(a);
if (resolveRegisteredAgentIdForDir(a.agentDir, a.env) !== normalizeAgentId(a.agentId)) throw new Error(`Conflicting registered agent owners for ${a.agentDir}`);
}
restoreWorkerConfig(e);
restorePreparedSyntheticAuthFacts(e.input.config, t.syntheticAuth, {
env: e.input.env,
workspaceDir: e.input.workspaceDir
});
restorePreparedSyntheticAuthFacts(e.input.config, t.syntheticAuth, { workspaceDir: e.input.workspaceDir });
s = await r();
const l = {
metadataSnapshot: s.pluginGeneration.pluginMetadataSnapshot,
pluginRegistry: s.pluginGeneration.pluginRegistry
};
const resolveSyntheticCredentials = (n) => withPluginRuntimeGenerationScope(l, () => resolveAmbientAgentCredentialsForDiscovery({
config: e.input.config,
env: e.input.env,
authoritativeSyntheticAuthProviderRefs: l.metadataSnapshot.owners.cliBackends.keys(),
syntheticAuthProviderRefs: scopeSyntheticAuthProviderRefs([.../* @__PURE__ */ new Set([
...listManifestSyntheticAuthProviderRefs(l.metadataSnapshot.index),
...resolveRuntimeSyntheticAuthProviderRefs(),
...t.syntheticAuth.map(({ providerRef: e }) => e)
])], n),
...e.input.workspaceDir ? { workspaceDir: e.input.workspaceDir } : {}
}));
if (t.kind === "auth-refresh") await i();
const { agentDir: u, inheritedAuthDir: d, config: f, env: p } = e.input;
const m = t.kind === "auth-refresh" ? t.profileIds : void 0;
const h = t.providerIds ?? listExternalCliSyncProviderIds();
const { store: g, displayPath: _ } = await loadAuthProfileStoreForCatalogAsync(u, {
allowKeychainPrompt: false,
...d ? { inheritedAuthDir: d } : {}
});
const v = preserveResolvedSecretBackedCredentials({
next: g,
existing: e.authStore
});
const y = new Set(e.authStore.runtimePersistedProfileIds ?? []);
const b = new Set(e.authStore.runtimeExternalProfileIds ?? []);
for (const [t, n] of Object.entries(e.authStore.profiles)) if (!y.has(t) && !b.has(t) && v.profiles[t] === void 0) v.profiles[t] = n;
const x = mergeRuntimeExternalProfileReferences({
next: v,
existing: e.authStore
});
const S = withPluginRuntimeGenerationScope(l, () => overlayExternalAuthProfiles(x, {
config: f,
env: p,
...h ? { externalCliProviderIds: h } : {},
...m ? { externalCliProfileIds: m } : {}
}));
if (t.kind === "catalog") await replaceRuntimeAuthProfileStoreSnapshotsAsync([{
agentDir: e.input.agentDir,
store: S
}]);
const C = {
...resolveSyntheticCredentials(t.providerIds ?? e.providerIds),
...resolveAgentCredentialMapFromStore(S, { config: e.input.config })
};
if (t.kind === "auth-refresh") return {
status: "ok",
kind: "auth-refresh",
authStore: S,
credentials: C,
authModes: resolveUsableAgentCredentialModes(C)
};
const { prepareAgentCatalogSource: w } = await import("../prepared-model-runtime.scoped-catalog-Dg9LGo-e.mjs");
const { prepareFullCatalogFacts: T } = await import("../prepared-model-runtime.full-catalog-Db6ni-vz.mjs");
const E = new Set(e.providerIds.map(normalizeProviderId));
const D = {
...e.catalogFacts,
input: e.input,
env: e.input.env,
templateAuthStorage: AuthStorage.inMemory(C),
credentials: C,
providerIds: [...new Set(t.providerIds ?? [...e.providerIds, ...Object.keys(C)])].toSorted((e, t) => e.localeCompare(t))
};
const { pluginMetadataSnapshot: O } = s.pluginGeneration;
const k = [...resolveImplicitProviderDiscoveryScope({
config: e.input.config,
env: e.input.env,
workspaceDir: e.input.workspaceDir,
pluginMetadataSnapshot: O,
providerDiscoveryProviderIds: [.../* @__PURE__ */ new Set([
...e.providerIds,
...Object.keys(C),
...D.providerIds
])]
})?.keys() ?? []];
const A = await withPluginRuntimeGenerationScope(l, () => planRuntimePluginDiscovery({
config: e.input.config,
env: e.input.env,
workspaceDir: e.input.workspaceDir,
pluginMetadataSnapshot: O,
onlyPluginIds: k
}));
let j = s.pluginGeneration;
if (A.kind === "runtime") {
const t = [.../* @__PURE__ */ new Set([...s.pluginIds, ...A.pluginIds ?? k])].toSorted();
if (t.length > s.pluginIds.size) {
c = await prepareWorkerGeneration(e, s, t);
j = c.pluginGeneration;
l.pluginRegistry = j.pluginRegistry;
}
}
const M = c ?? s;
await i();
const N = /* @__PURE__ */ new Set([...M.staticProviderIds, ...D.providerIds]);
if (!j.preparedStaticProviderCatalog || N.size > M.staticProviderIds.size) {
M.pluginGeneration = Object.freeze({
...j,
preparedStaticProviderCatalog: await withPluginRuntimeGenerationScope(l, () => prepareImplicitProviderStaticCatalog({
config: e.input.config,
env: e.input.env,
workspaceDir: e.input.workspaceDir,
pluginMetadataSnapshot: O,
providerDiscoveryProviderIds: [...N]
}))
});
M.staticProviderIds = N;
}
j = M.pluginGeneration;
const P = await w(D, j, "live", false, {
authStore: S,
refresh: t.refresh,
providerDiscoveryProviderIds: t.providerIds,
providerDiscoveryTimeoutMs: PREPARED_MODEL_CATALOG_WORKER_TIMEOUT_MS
});
const F = await T(D, j, "live", P, {
includeNative: false,
providerIds: t.providerIds
});
const I = {
...resolveSyntheticCredentials([...F.modelCatalog.entries, ...F.modelCatalog.routeVariants].map((e) => e.provider).filter((e) => !t.providerIds || t.providerIds.includes(normalizeProviderId(e))).filter((e) => !E.has(normalizeProviderId(e)))),
...C
};
const L = /* @__PURE__ */ new Map();
const { catalogModels: R } = F;
for (const e of R) {
const t = normalizeProviderId(e.provider);
const n = L.get(t) ?? [];
n.push(e);
L.set(t, n);
}
const z = P.pluginCatalogs.flatMap(({ contents: e }) => Object.keys(JSON.parse(e).providers ?? {}));
for (const e of [...(F.modelCatalog.providerOutcomes ?? []).map((e) => e.provider), ...z].map(normalizeProviderId)) if (!L.has(e)) L.set(e, []);
const B = [
...D.providerIds,
...Object.keys(I),
...Object.keys(e.input.config.models?.providers ?? {}),
...F.modelCatalog.entries.map((e) => e.provider),
...F.modelCatalog.routeVariants.map((e) => e.provider),
...(F.modelCatalog.staticEntries ?? []).map((e) => e.provider),
...Object.values(S.profiles).map((e) => e.provider)
];
const V = {
status: "ok",
kind: "catalog",
snapshot: F.modelCatalog,
runtimeModels: L,
providerExpiries: P.providerExpiries ?? /* @__PURE__ */ new Map(),
pluginCatalogs: P.pluginCatalogs,
configuredRuntimeModels: F.configuredRuntimeModels,
credentials: I,
providerAuthLabels: B.length === 0 ? /* @__PURE__ */ new Map() : withPluginRuntimeGenerationScope(l, () => prepareModelCatalogAuthLabels({
config: e.input.config,
agentDir: e.input.agentDir,
authStorePath: _,
workspaceDir: e.input.workspaceDir,
env: e.input.env,
store: S,
providers: B
})),
authStore: S,
authModes: resolveUsableAgentCredentialModes(I)
};
n.beginClose();
await n.runWhenIdle(() => void 0);
if (c) {
const e = getPluginRegistryInspectionResources(c.pluginGeneration.pluginRegistry);
if (!e) throw new Error("Catalog scope growth has no inspection resource owner");
e.adoptRetainedRegistrations(s.pluginGeneration.pluginRegistry);
const t = s.release;
Object.assign(s, c);
c = void 0;
await t();
}
return V;
} catch (e) {
return {
status: "failed",
error: e instanceof Error ? e.message : String(e)
};
} finally {
try {
n.beginClose();
await n.runWhenIdle(() => void 0);
await c?.release();
} finally {
await n.drain();
if (a && o) unregisterResolvedAgentDir(a);
}
}
}
if (parentPort) {
const e = workerData;
if (e.databaseEngineSelection) installDatabaseEngineSelection(e.databaseEngineSelection);
const t = /* @__PURE__ */ new Map();
let n;
serveWorkerTasks(async (r, i) => {
const a = r;
const { request: o, context: s } = a;
let c;
if ("pluginMetadataSnapshot" in a.value) c = a.value;
else {
const e = t.get(s.workspaceDir);
if (e?.fingerprint !== s.fingerprint) throw new Error("Prepared model catalog worker context is unavailable");
c = {
...a.value,
remoteCatalog: e.prepared.pluginGeneration.remoteCatalog,
pluginMetadataSnapshot: e.prepared.pluginGeneration.pluginMetadataSnapshot
};
}
if (c.remoteCatalog) {
const e = [captureRemoteModelCatalogStartupSnapshot(), ...Array.from(t.values(), ({ prepared: e }) => e.pluginGeneration.remoteCatalog)].find((e) => e?.sourceUrl === c.remoteCatalog?.sourceUrl && e?.revision === c.remoteCatalog?.revision);
if (e) c = {
...c,
remoteCatalog: e
};
}
n = c;
let l = 0;
let u;
const reportProgress = (e) => {
const t = e;
const n = performance.now();
if (n >= l || t.pluginId !== u) {
l = n + 1e3;
u = t.pluginId;
i?.notify(t);
}
};
nativeReferenceProgress.subscribe(reportProgress);
const stopProgress = () => nativeReferenceProgress.unsubscribe(reportProgress);
return withRemoteModelCatalogSnapshot(freezeTrustedJsonSnapshot(c.remoteCatalog), () => withPluginSourceCaptureDirectory(e.sourceCaptureDirectory, async () => {
const { result: e, receipts: n } = await captureAuthProfileCredentialCommits(async () => {
const { workspaceDir: e, fingerprint: n } = s;
let r = t.get(e);
let a;
let l = false;
try {
const s = new AsyncWorkScope();
const u = await withWorkerAuthProfileWrites(c.input.env, s, () => withTemplateInstallSchemaVersionFacts(o.templateInstallSchemaVersions, () => s.run(() => runCatalogRequest(c, o, s, async () => {
if (r?.fingerprint === n) return r.prepared;
l = true;
return a = await prepareWorkerGeneration(c);
}, async () => {
stopProgress();
const e = await i?.request(null);
e?.consumed();
if (e && e.input !== true) throw new Error("prepared model catalog request retired before discovery");
}))));
if (a && u.status === "ok") {
t.set(e, {
fingerprint: n,
prepared: a
});
a = void 0;
l = false;
await r?.prepared.release();
r = void 0;
}
return u;
} finally {
try {
if (l) {
t.delete(e);
await r?.prepared.release();
}
} finally {
await a?.release();
}
}
});
return {
...e,
authCredentials: n
};
}, e.sourceCaptureManagedRoot)).finally(() => {
n = void 0;
stopProgress();
});
}, { retainedData: () => [...measurePreparedCatalogRetainedData(Array.from(t.values(), ({ prepared: e }) => e.pluginGeneration), n), ...getLiveCatalogRetainedData()] });
}
//#endregion
export {};