openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
640 lines (639 loc) • 23.2 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import "./src-H3RMXyFL.mjs";
import { n as safeParseJsonRecord } from "./json-coercion-CaJLaav-.mjs";
import { t as stableStringify } from "./stable-stringify-vqde_3tT.mjs";
import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs";
import { t as appendConfigPathSegment } from "./dot-path-BJ4tyWKJ.mjs";
import "./utils-C8YECn2Q.mjs";
import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { f as resolveAgentWorkspaceDir, g as resolveDefaultAgentDir, m as resolveAmbientOwnerAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { a as createConfigRuntimeEnv } from "./config-env-vars-ByeGN-9N.mjs";
import { p as resolveConfigSecretRef } from "./resolution-facts-xaIKuREs.mjs";
import { a as resolveInstalledManifestRegistryIndexFingerprint } from "./plugin-control-plane-context-BmY6xICT.mjs";
import { l as withPluginMetadataSnapshotScope } from "./current-plugin-metadata-snapshot-H0TP3PFt.mjs";
import { c as getRuntimeConfigSourceSnapshot, j as hashRuntimeConfigValue } from "./runtime-snapshot-WbwbY5b7.mjs";
import { p as resolvePluginMetadataSnapshot } from "./plugin-metadata-snapshot-By9ySblt.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { t as MODEL_APIS } from "./model-config-vocabulary-ByNYIDvQ.mjs";
import { n as projectConfigOntoRuntimeSourceSnapshot } from "./runtime-source-projection-DTwMWCo9.mjs";
import "./types.models-BRtCm3gx.mjs";
import "./env-vars-DN2VAsXE.mjs";
import { b as resolveAuthProfileDatabasePath } from "./sqlite-B2CoJ4Om.mjs";
import { t as MODELS_JSON_STATE } from "./models-config-state-t8dMFR2d.mjs";
import { r as resolveNonEnvSecretRefApiKeyMarker } from "./provider-credential-values-pLjdcwQh.mjs";
import { f as resolveEnvSecretRefHeaderValueMarker } from "./model-auth-markers-4YSUG71a.mjs";
import { a as mergeWithExistingProviderSecrets, i as mergeProviders, n as isWritableProviderConfig, o as normalizeProviderMapKeys, t as buildSourceModelFields } from "./models-config.merge-Bn4GN0An.mjs";
import { i as ensureAuthProfileStoreAsync } from "./store-runtime-dW0pXLJI.mjs";
import { l as normalizeProviderConfigWithPlugin, y as resolveProviderConfigApiKeyWithPlugin } from "./provider-runtime-BddjXkmv.mjs";
import { r as repairPluginModelCatalogTransportMetadata, t as PLUGIN_MODEL_CATALOG_GENERATED_BY } from "./plugin-model-catalog-repair-B3GKtPvY.mjs";
import { n as normalizeProviderCatalogModelsForConfig, t as materializeConfiguredProviderCatalogModels } from "./models-config.providers.catalog-DmT2uU7_.mjs";
import { t as loadPersistedPluginModelCatalogs } from "./plugin-model-catalog-execution-D-GvxoAv.mjs";
import { c as resolvePluginModelCatalogOwnerPluginId, l as decodePluginModelCatalogRelativePathPluginId, s as replacePersistedPluginModelCatalogs, t as filterGeneratedPluginModelCatalogProviders, u as encodePluginModelCatalogRelativePath } from "./plugin-model-catalog-BafTZg7-.mjs";
import { r as withPluginModelCatalogAuthObservations, t as capturePluginModelCatalogAuth } from "./plugin-model-catalog-auth-C-eaCqDT.mjs";
import { n as resolveImplicitProviders } from "./models-config.providers.implicit-6ZK1ckua.mjs";
import { c as resolveMissingProviderApiKey, i as normalizeResolvedEnvApiKey, n as normalizeConfiguredProviderApiKey, o as resolveApiKeyFromProfiles, r as normalizeHeaderValues } from "./models-config.providers.secret-helpers-D-ksd1i8.mjs";
import { t as privateFileStore } from "./private-file-store-D564pKJx.mjs";
import path from "node:path";
import { createHash } from "node:crypto";
import fs from "node:fs/promises";
//#region src/agents/models-config.providers.policy.lookup.ts
/**
* Resolves provider plugin lookup keys from provider config aliases.
*/
const GENERIC_PROVIDER_APIS = /* @__PURE__ */ new Set([
"openai-completions",
"openai-responses",
"anthropic-messages",
"google-generative-ai",
"google-interactions"
]);
function resolveProviderPluginLookupKey(e, t) {
const n = normalizeOptionalString(t?.api) ?? "";
if (e === "google-antigravity" || e === "google-vertex" || n === "google-generative-ai") return "google";
if (t?.models?.some((e) => e.api === "google-generative-ai")) return "google";
if (n && MODEL_APIS.includes(n) && !GENERIC_PROVIDER_APIS.has(n)) return n;
return e;
}
//#endregion
//#region src/agents/models-config.providers.source-managed.ts
/**
* Enforces source-managed provider secret ownership rules.
*/
function normalizeSourceProviderLookup(e) {
if (!e) return /* @__PURE__ */ new Map();
const t = Object.fromEntries(Object.entries(e).filter(([, e]) => isRecord(e)).map(([e, t]) => [e, {
providerKey: e,
providerConfig: t
}]));
return new Map(Object.entries(normalizeProviderMapKeys(t)));
}
function resolveSourceManagedApiKeyMarker(e) {
const t = resolveConfigSecretRef({
config: e.sourceConfig,
path: `${appendConfigPathSegment("models.providers", e.sourceProvider.providerKey)}.apiKey`,
value: e.sourceProvider.providerConfig.apiKey,
defaults: e.sourceConfig?.secrets?.defaults
});
if (!t || !t.id.trim()) return;
return t.source === "env" ? t.id.trim() : resolveNonEnvSecretRefApiKeyMarker(t.source);
}
function resolveSourceManagedHeaderMarkers(e) {
const t = e.sourceProvider.providerConfig.headers;
if (!isRecord(t)) return {};
const n = {};
for (const [r, i] of Object.entries(t)) {
const t = resolveConfigSecretRef({
config: e.sourceConfig,
path: appendConfigPathSegment(`${appendConfigPathSegment("models.providers", e.sourceProvider.providerKey)}.headers`, r),
value: i,
defaults: e.sourceConfig?.secrets?.defaults
});
if (!t || !t.id.trim()) continue;
n[r] = t.source === "env" ? resolveEnvSecretRefHeaderValueMarker(t.id) : resolveNonEnvSecretRefApiKeyMarker(t.source);
}
return n;
}
/** Preserves source-managed apiKey/header markers from the original provider config. */
function enforceSourceManagedProviderSecrets(e) {
const { providers: t } = e;
if (!t) return t;
const n = normalizeSourceProviderLookup(e.sourceConfigForSecrets?.models?.providers);
if (n.size === 0) return t;
let r = null;
for (const [i, a] of Object.entries(t)) {
const o = normalizeProviderId(i);
const s = n.get(o);
if (!s) continue;
let c = a;
const l = resolveSourceManagedApiKeyMarker({
sourceProvider: s,
sourceConfig: e.sourceConfigForSecrets
});
if (l) {
e.secretRefManagedProviders?.add(o);
if (c.apiKey !== l) c = {
...c,
apiKey: l
};
}
const u = resolveSourceManagedHeaderMarkers({
sourceProvider: s,
sourceConfig: e.sourceConfigForSecrets
});
const d = c.headers;
if (Object.entries(u).some(([e, t]) => d?.[e] !== t)) c = {
...c,
headers: {
...d,
...u
}
};
if (c === a) continue;
r ??= { ...t };
r[i] = c;
}
return r ?? t;
}
//#endregion
//#region src/agents/models-config.plan.ts
/**
* Plans root and plugin-owned model catalog writes. Setup and doctor flows use
* this module to merge implicit provider discovery, explicit config, and
* preserved secrets before touching models.json.
*/
async function normalizeProviders(e) {
const { providers: t } = e;
if (!t) return t;
const n = e.env ?? process.env;
const r = normalizeSourceProviderLookup(e.sourceConfigForSecrets?.models?.providers);
let i;
const resolveProfileApiKey = async (t) => {
i ??= await ensureAuthProfileStoreAsync(e.agentDir, { allowKeychainPrompt: false });
return resolveApiKeyFromProfiles({
provider: t,
store: i,
env: n
});
};
let a = false;
const o = {};
for (const [i, s] of Object.entries(t)) {
const t = i.trim();
if (!t) {
a = true;
continue;
}
if (t !== i) a = true;
const c = r.get(normalizeProviderId(t));
const l = c && e.sourceConfigForSecrets ? {
config: e.sourceConfigForSecrets,
providerKey: c.providerKey
} : void 0;
let u = s;
const d = normalizeHeaderValues({
headers: u.headers,
secretDefaults: e.secretDefaults,
source: l
});
if (d.mutated) u = {
...u,
headers: d.headers
};
const f = c?.providerConfig.apiKey !== void 0 ? {
config: e.sourceConfigForSecrets,
path: `${appendConfigPathSegment("models.providers", c.providerKey)}.apiKey`,
value: c.providerConfig.apiKey,
defaults: e.sourceConfigForSecrets?.secrets?.defaults
} : void 0;
u = normalizeConfiguredProviderApiKey({
providerKey: t,
sourceInput: f,
provider: u,
secretDefaults: e.secretDefaults,
secretRefManagedProviders: e.secretRefManagedProviders
});
u = normalizeResolvedEnvApiKey({
providerKey: t,
provider: u,
env: n,
secretRefManagedProviders: e.secretRefManagedProviders
});
const p = u.models?.length && !u.apiKey;
const m = p ? await resolveProfileApiKey(t) : void 0;
const h = p ? resolveProviderPluginLookupKey(t).trim() : void 0;
u = resolveMissingProviderApiKey({
providerKey: t,
provider: u,
env: n,
profileApiKey: m,
secretRefManagedProviders: e.secretRefManagedProviders,
providerApiKeyResolver: h !== void 0 ? (n) => resolveProviderConfigApiKeyWithPlugin({
provider: h,
...e.manifestRegistry ? { manifestRegistry: e.manifestRegistry } : {},
context: {
provider: t,
env: n
}
}) : void 0
});
u = normalizeProviderConfigWithPlugin({
provider: resolveProviderPluginLookupKey(t, u),
...e.manifestRegistry ? { manifestRegistry: e.manifestRegistry } : {},
context: {
provider: t,
providerConfig: u
}
}) ?? u;
a ||= u !== s;
const g = o[t];
if (g) {
a = true;
o[t] = {
...g,
...u,
models: u.models ?? g.models
};
continue;
}
o[t] = u;
}
return enforceSourceManagedProviderSecrets({
providers: a ? o : t,
sourceConfigForSecrets: e.sourceConfigForSecrets,
secretRefManagedProviders: e.secretRefManagedProviders
});
}
/** Resolves providers for models.json. */
async function resolveProvidersForModelsJson(e) {
const { context: t } = e;
const { agentDir: n, env: r } = t;
const i = stripBlankProviderBaseUrls(materializeConfiguredProviderCatalogModels(t.cfg.models?.providers, { manifestPlugins: t.pluginMetadataSnapshot }) ?? {});
const a = t.cfg.models?.providers ? {
...t.cfg,
models: {
...t.cfg.models,
providers: i
}
} : t.cfg;
const o = buildSourceModelFields(i);
if (a.models?.mode === "replace") return mergeProviders({
implicit: {},
explicit: i
});
const s = await resolveImplicitProviders({
agentDir: n,
...e.authStore ? { authStore: e.authStore } : {},
config: a,
discoveryAuthConfig: t.discoveryAuthConfig,
discoveryAuthEnv: t.discoveryAuthEnv,
sourceConfigForSecrets: t.sourceConfigForSecrets,
env: r,
...t.workspaceDir ? { workspaceDir: t.workspaceDir } : {},
explicitProviders: i,
sourceModelFields: o,
pluginMetadataSnapshot: t.pluginMetadataSnapshot,
preparedStaticProviderCatalog: t.preparedStaticProviderCatalog,
providerDiscoveryProviderIds: t.providerDiscoveryProviderIds,
providerDiscoveryTimeoutMs: t.providerDiscoveryTimeoutMs,
providerDiscoveryEntriesOnly: t.providerDiscoveryEntriesOnly === true,
onProviderCatalogOutcome: t.onProviderCatalogOutcome,
discoveredProviderPluginIds: e.discoveredProviderPluginIds
});
return mergeProviders({
implicit: s,
explicit: i,
sourceModelFields: o
});
}
function stripBlankProviderBaseUrls(e) {
let t = false;
const n = {};
for (const [r, i] of Object.entries(e)) {
if (typeof i?.baseUrl === "string" && i.baseUrl.trim() === "") {
const { baseUrl: e, ...a } = i;
n[r] = a;
t = true;
continue;
}
n[r] = i;
}
return t ? n : e;
}
function resolveProvidersForMode(e) {
if (e.mode !== "merge") return e.providers;
const t = e.existingParsed;
if (!isRecord(t) || !isRecord(t.providers)) return e.providers;
return mergeWithExistingProviderSecrets({
nextProviders: e.providers,
existingProviders: t.providers,
secretRefManagedProviders: e.secretRefManagedProviders
});
}
function filterWritableProviders(e) {
const t = Object.fromEntries(Object.entries(e).filter(([, e]) => isWritableProviderConfig(e)));
return Object.keys(t).length === Object.keys(e).length ? e : t;
}
/** Plans root and plugin-owned model catalog writes for the current runtime. */
async function planOpenClawModelsJson(e) {
const { context: t } = e;
const { cfg: n, agentDir: r, env: i } = t;
const a = /* @__PURE__ */ new Map();
const o = await resolveProvidersForModelsJson({
context: t,
...e.authStore ? { authStore: e.authStore } : {},
discoveredProviderPluginIds: a
});
if (Object.keys(o).length === 0) {
if (n.models?.mode === "replace") return {
action: "write",
contents: `${JSON.stringify({ providers: {} }, null, 2)}\n`,
pluginCatalogWrites: {}
};
return { action: "skip" };
}
const s = n.models?.mode ?? "merge";
const c = /* @__PURE__ */ new Set();
const l = t.pluginMetadataSnapshot?.pluginIds === void 0 ? t.pluginMetadataSnapshot?.manifestRegistry : void 0;
const normalize = () => normalizeProviders({
providers: o,
agentDir: r,
env: i,
secretDefaults: n.secrets?.defaults,
sourceConfigForSecrets: t.sourceConfigForSecrets,
secretRefManagedProviders: c,
...l ? { manifestRegistry: l } : {}
});
const u = await (t.pluginMetadataSnapshot && l ? withPluginMetadataSnapshotScope(t.pluginMetadataSnapshot, normalize) : normalize()) ?? o;
/** Recovers only generated providers; manual root declarations never enter this source. */
const d = e.pluginCatalogs ?? [];
const f = {};
for (const { pluginId: e, contents: n } of d) {
const r = safeParseJsonRecord(n);
if (!r || !isRecord(r.providers)) continue;
Object.assign(f, filterGeneratedPluginModelCatalogProviders({
catalogPluginId: e,
config: t.cfg,
parsedCatalog: r,
pluginMetadataSnapshot: t.pluginMetadataSnapshot,
providers: r.providers
}));
}
const p = resolveProvidersForMode({
mode: s,
existingParsed: { providers: f },
providers: u,
secretRefManagedProviders: c
});
const finalizeProviders = (e) => {
const n = normalizeProviderCatalogModelsForConfig(e) ?? e;
return filterWritableProviders(enforceSourceManagedProviderSecrets({
providers: n,
sourceConfigForSecrets: t.sourceConfigForSecrets,
secretRefManagedProviders: c
}) ?? n);
};
const m = new Set(Object.keys(n.models?.providers ?? {}).map((e) => normalizeProviderId(e)));
const h = finalizeProviders(p);
const g = t.pluginMetadataSnapshot;
const _ = {};
const v = {};
for (const [e, t] of Object.entries(h)) {
const n = normalizeProviderId(e);
const r = resolvePluginModelCatalogOwnerPluginId({
providerId: e,
pluginMetadataSnapshot: g
}) ?? (m.has(n) ? void 0 : a.get(n) ?? resolvePluginModelCatalogOwnerPluginId({
providerId: e,
pluginMetadataSnapshot: g,
includeCliBackends: true
}));
if (!r) {
_[e] = t;
continue;
}
const i = v[r] ??= {};
i[e] = t;
}
const y = Object.fromEntries(Object.entries(v).map(([e, t]) => [encodePluginModelCatalogRelativePath(e), `${JSON.stringify({
generatedBy: PLUGIN_MODEL_CATALOG_GENERATED_BY,
providers: t
}, null, 2)}\n`]));
const b = resolveProvidersForMode({
mode: s,
existingParsed: e.existingParsed,
providers: _,
secretRefManagedProviders: c
});
const x = `${JSON.stringify({ providers: finalizeProviders(b) }, null, 2)}\n`;
if (e.existingRaw === x && Object.keys(y).length === 0) return {
action: "noop",
pluginCatalogWrites: y
};
return {
action: "write",
contents: x,
pluginCatalogWrites: y
};
}
//#endregion
//#region src/agents/models-config.core.ts
/**
* Ensures agent-local models.json and the SQLite-backed plugin model catalog
* match runtime config, discovered providers, auth-profile state, and
* generated catalog ownership.
*/
const MODELS_JSON_READY_CACHE_LIMIT = 128;
async function readFileMtimeMs(e) {
try {
return (await fs.stat(e)).mtimeMs;
} catch {
return null;
}
}
async function buildModelsJsonFingerprint(e, t) {
const n = resolveAuthProfileDatabasePath(e.agentDir);
const r = await readFileMtimeMs(n);
const i = await readFileMtimeMs(`${n}-wal`);
const a = await readFileMtimeMs(path.join(e.agentDir, "models.json"));
const o = createHash("sha256").update(stableStringify(t ?? await loadPersistedPluginModelCatalogs(e.agentDir, void 0, e.env))).digest("base64url");
const s = e.pluginMetadataSnapshot ? resolveInstalledManifestRegistryIndexFingerprint(e.pluginMetadataSnapshot.index) : void 0;
return stableStringify({
config: e.cfg,
discoveryAuthConfigHash: hashRuntimeConfigValue(e.discoveryAuthConfig),
sourceConfigForSecrets: e.sourceConfigForSecrets,
envShape: e.envFingerprint,
authProfilesMtimeMs: r,
authProfilesWalMtimeMs: i,
modelsFileMtimeMs: a,
pluginCatalogFingerprint: o,
workspaceDir: e.workspaceDir,
pluginMetadataSnapshotIndexFingerprint: s,
pluginMetadataSnapshotPluginIds: e.pluginMetadataSnapshot?.pluginIds === void 0 ? null : e.pluginMetadataSnapshot.pluginIds.toSorted(),
providerDiscoveryProviderIds: e.providerDiscoveryProviderIds,
providerDiscoveryTimeoutMs: e.providerDiscoveryTimeoutMs,
providerDiscoveryEntriesOnly: e.providerDiscoveryEntriesOnly === true
});
}
function modelsJsonReadyCacheKey(e, t) {
return createHash("sha256").update(e).update("\0").update(t).digest("base64url");
}
async function readExistingModelsFile(e) {
const t = await privateFileStore(path.dirname(e)).readTextIfExists(path.basename(e));
try {
return {
raw: t ?? "",
parsed: t === null ? null : JSON.parse(t)
};
} catch {
return {
raw: "",
parsed: null
};
}
}
/** Best-effort chmod for the user-visible generated models.json file. */
async function ensureModelsFileModeForModelsJson(e) {
await fs.chmod(e, 384).catch(() => {});
}
function materializePlannedPluginCatalogs(e) {
return Object.entries(e).map(([e, t]) => {
const n = decodePluginModelCatalogRelativePathPluginId(e);
if (!n) throw new Error(`Invalid generated plugin model catalog key: ${e}`);
return {
pluginId: n,
contents: repairPluginModelCatalogTransportMetadata(t).contents
};
}).toSorted((e, t) => e.pluginId.localeCompare(t.pluginId));
}
function resolveModelsConfigInput(e) {
const t = getRuntimeConfigSourceSnapshot();
const n = t ? projectConfigOntoRuntimeSourceSnapshot(e) : e;
return {
config: n,
discoveryAuthConfig: e,
sourceConfigForSecrets: n === e ? t ?? e : n
};
}
async function prepareModelsConfigContext(e, t, n = {}) {
let r = process.env;
let i;
if (typeof e !== "function") i = resolveModelsConfigInput(e);
else {
const t = await e();
r = t.env;
const n = projectConfigOntoRuntimeSourceSnapshot(t.config);
i = {
config: n,
discoveryAuthConfig: t.config,
sourceConfigForSecrets: n
};
}
const a = i.config;
const o = t?.trim() ? t.trim() : resolveDefaultAgentDir(a, r);
const s = n.workspaceDir ?? (t?.trim() ? void 0 : resolveAgentWorkspaceDir(a, resolveAmbientOwnerAgentId(a), r));
const c = createConfigRuntimeEnv(a, n.env ?? {});
const l = n.env ? c : createConfigRuntimeEnv(a, r);
const u = Boolean(n.providerDiscoveryProviderIds?.length);
const d = n.pluginMetadataSnapshot ?? resolvePluginMetadataSnapshot({
config: a,
env: l,
...s ? { workspaceDir: s } : {},
...u ? { preferPersisted: false } : {}
});
return {
cfg: a,
discoveryAuthConfig: i.discoveryAuthConfig,
discoveryAuthEnv: n.env ?? r,
sourceConfigForSecrets: i.sourceConfigForSecrets,
agentDir: o,
env: l,
envFingerprint: n.env ? hashRuntimeConfigValue(c) : c,
workspaceDir: s || void 0,
pluginMetadataSnapshot: d,
preparedStaticProviderCatalog: n.preparedStaticProviderCatalog,
providerDiscoveryProviderIds: n.providerDiscoveryProviderIds,
providerDiscoveryTimeoutMs: n.providerDiscoveryTimeoutMs,
providerDiscoveryEntriesOnly: n.providerDiscoveryEntriesOnly === true,
onProviderCatalogOutcome: n.onProviderCatalogOutcome
};
}
/** Ensures models.json and the agent SQLite catalog cache are current. */
async function ensureOpenClawModelsJsonWithInput(e, t, n = {}) {
const r = await prepareModelsConfigContext(e, t, n);
const { agentDir: i } = r;
const a = path.join(i, "models.json");
const o = MODELS_JSON_STATE.readyCache;
for (const e of o.keys()) if (e.includes("\0")) o.delete(e);
pruneMapToMaxSize(o, MODELS_JSON_READY_CACHE_LIMIT);
const s = r.onProviderCatalogOutcome ? void 0 : modelsJsonReadyCacheKey(a, await buildModelsJsonFingerprint(r));
if (s) {
const e = o.get(s);
if (e) {
o.delete(s);
o.set(s, e);
await e;
await ensureModelsFileModeForModelsJson(a);
return {};
}
}
let c;
const l = MODELS_JSON_STATE.writeQueue.enqueue(a, async () => {
const e = await readExistingModelsFile(a);
const t = await capturePluginModelCatalogAuth(i, r.env);
const n = await withPluginModelCatalogAuthObservations(t, async () => planOpenClawModelsJson({
context: r,
existingRaw: e.raw,
existingParsed: e.parsed,
pluginCatalogs: await loadPersistedPluginModelCatalogs(i, void 0, r.env)
}));
if (n.action === "write") {
await fs.mkdir(i, {
recursive: true,
mode: 448
});
if (e.raw !== n.contents) {
await privateFileStore(path.dirname(a)).writeText("models.json", n.contents);
MODELS_JSON_STATE.costCache.delete(i);
}
await ensureModelsFileModeForModelsJson(a);
}
const o = n.pluginCatalogWrites ? await replacePersistedPluginModelCatalogs({
agentDir: i,
pluginCatalogWrites: n.pluginCatalogWrites,
authSnapshot: t,
env: r.env
}) : void 0;
if (o) c = {
modelsJsonContents: n.action === "write" ? n.contents : e.raw || null,
pluginCatalogs: o.catalogs
};
if (n.action === "noop") await ensureModelsFileModeForModelsJson(a);
});
if (s) {
o.set(s, l);
pruneMapToMaxSize(o, MODELS_JSON_READY_CACHE_LIMIT);
}
try {
await l;
if (s && o.get(s) === l) {
const e = modelsJsonReadyCacheKey(a, await buildModelsJsonFingerprint(r, c?.pluginCatalogs));
if (o.get(s) === l && e !== s) {
o.delete(s);
if (!o.has(e)) {
o.set(e, Promise.resolve());
pruneMapToMaxSize(o, MODELS_JSON_READY_CACHE_LIMIT);
}
}
}
return c ? { publishedSource: c } : {};
} catch (e) {
if (s && o.get(s) === l) o.delete(s);
throw e;
}
}
/**
* Plans the complete root/plugin catalog generation without mutating agent-owned state.
* Control-plane inventory reads use this when their lifecycle generation may be superseded.
*/
async function planOpenClawModelsJsonSourceWithInput(e, t, n = {}) {
const { authStore: r } = n;
const i = await prepareModelsConfigContext(e, t, n);
const { agentDir: a } = i;
const o = await readExistingModelsFile(path.join(a, "models.json"));
const s = await loadPersistedPluginModelCatalogs(a, void 0, i.env);
const c = await planOpenClawModelsJson({
context: i,
...r ? { authStore: r } : {},
existingRaw: o.raw,
existingParsed: o.parsed,
pluginCatalogs: s
});
return {
agentDir: a,
modelsJsonContents: c.action === "write" ? c.contents : o.raw || null,
pluginCatalogs: c.pluginCatalogWrites === void 0 ? s : materializePlannedPluginCatalogs(c.pluginCatalogWrites)
};
}
//#endregion
export { planOpenClawModelsJsonSourceWithInput as n, ensureOpenClawModelsJsonWithInput as t };