openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
388 lines (387 loc) • 15.5 kB
JavaScript
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import "./model-ref-shared-DqE2RqZv.mjs";
import { n as createLazyPromise } from "./lazy-promise-DiCvjz9w.mjs";
import { s as resolveNativeOwnedRuntimeModel } from "./defaults-BWyoTPqn.mjs";
import { n as resolveProviderModelMaterializationAuthMode } from "./provider-model-route-auth-dD2KD9io.mjs";
import { C as findModelInCatalog } from "./model-selection-shared-9Kz63Hhm.mjs";
import { a as createModelCatalogIdentityKeyResolver } from "./model-catalog-entry-pfJ-_t4l.mjs";
import { r as modelKey } from "./provider-registry-index-DhPtwFh_.mjs";
import { i as FailoverError } from "./error-BCRqSFIY.mjs";
import { t as resolveAgentHarnessPolicy } from "./policy-DzaOuofI.mjs";
import { r as PreparedModelRuntimePublicationSupersededError } from "./prepared-model-runtime-admission-errors-LxrcCg4d.mjs";
import "./prepared-model-runtime.errors-BRsU9-dm.mjs";
import { n as resolveModelRuntimeRoute, t as CLAUDE_CLI_SETUP_GUIDANCE } from "./model-runtime-route-BV9eIh4b.mjs";
//#region src/agents/model-runtime-choice.ts
const loadPreparedModelCatalog = createLazyPromise(() => import("./prepared-model-catalog-guV7T9CV.mjs"));
const loadModelResolver = createLazyPromise(() => import("./model-BGxC_MMq.mjs"));
const loadModelSelection = createLazyPromise(() => import("./model-selection-MVvzg347.mjs"));
const loadModelRefProfile = createLazyPromise(() => import("./model-ref-profile-BwMeKozM.mjs"));
const loadModelCatalogDecisions = createLazyPromise(() => import("./model-catalog-decisions-BD72dc6E.mjs"));
const loadPreparedRuntimeAuth = createLazyPromise(() => import("./prepared-model-runtime-auth-BUHEJm6o.mjs"));
const loadProviderModelRoute = createLazyPromise(() => import("./provider-model-route-Bhi4T3ko.mjs"));
const loadRuntimeModelMaterializer = createLazyPromise(() => import("./materialize-model-KX4PNNPm.mjs"));
const loadModelFallbackCandidates = createLazyPromise(() => import("./model-fallback-candidates-C0fK1oKE.mjs"));
const loadProviderAuthAliases = createLazyPromise(() => import("./provider-auth-aliases-BW69I6bH.mjs"));
const loadPluginGenerationScope = createLazyPromise(() => import("./generation-scope-i9Mfibm9.mjs"));
const loadModelCatalogEntry = createLazyPromise(() => import("./model-catalog-entry-I737B4Q7.mjs"));
const loadCatalogDecisionRuntime = createLazyPromise(() => import("./model-catalog-decision-runtime-4-81d1Oj.mjs"));
/** Resolve support independently of whether this request needs manual-override permission. */
async function prepareModelChoice(e) {
const { withPreparedModelCatalogOwner: t, materializePreparedModelCatalogOwner: n } = await loadPreparedModelCatalog();
const { resolveModelAsync: r } = await loadModelResolver();
const { buildModelAliasIndex: i, resolveAllowedModelRef: a, resolveDefaultModelForAgent: o, resolveModelRefFromString: s } = await loadModelSelection();
const { splitTrailingAuthProfile: c } = await loadModelRefProfile();
const { prepareModelCatalogDecisions: l, resolveCatalogDecisionRuntime: u } = await loadModelCatalogDecisions();
const { getPreparedModelRuntimeAuthStore: d } = await loadPreparedRuntimeAuth();
const { projectProviderModelRouteConfig: f } = await loadProviderModelRoute();
const { validatePreparedRuntimeModel: p } = await loadRuntimeModelMaterializer();
const { resolveModelCandidateChain: m } = await loadModelFallbackCandidates();
const { resolveProviderIdForAuth: h } = await loadProviderAuthAliases();
const { withPluginRuntimeGenerationScope: g } = await loadPluginGenerationScope();
return await t({
config: e.cfg,
agentId: e.agentId,
workspaceDir: e.workspaceDir,
readOnly: true
}, (t) => {
let _ = t;
return g(_, async () => {
const t = o({
cfg: _.config,
agentId: e.agentId
});
const g = {
cfg: _.config,
agentId: e.agentId,
defaultProvider: t.provider,
defaultModel: t,
catalog: _.modelCatalog.entries,
manifestPlugins: _.metadataSnapshot.plugins,
raw: e.raw
};
const v = e.source === "automatic" && e.resolvedRef ? { ref: e.resolvedRef } : e.source === "override" ? a(g) : s({
...g,
aliasIndex: i(g)
});
if (!v) return {
kind: "unavailable",
error: `invalid model: ${e.raw}`
};
if ("error" in v) return {
kind: "unavailable",
error: v.error
};
const y = v.ref;
const authOwner = (e) => h(e, {
config: _.config,
workspaceDir: _.workspaceDir,
metadataSnapshot: _.metadataSnapshot
});
const b = authOwner(y.provider);
const prepare = async (t) => {
const i = d(_);
if (!i) return {
kind: "unavailable",
error: "Model account facts are not prepared. Retry after configuration finishes loading."
};
const a = authOwner(t.provider) === b ? c(e.raw).profile : void 0;
const o = modelKey(t.provider, t.model);
const decide = async (n) => {
const r = await l({
cfg: _.config,
agentId: e.agentId,
agentDir: _.agentDir,
workspaceDir: _.workspaceDir,
snapshot: n,
metadataSnapshot: _.metadataSnapshot,
preparedAuthStore: i,
preparedRuntimeAuthModes: _.authModes,
pluginRegistry: _.pluginRegistry,
observationConfig: _.observationConfig,
isCurrent: _.isCurrent,
preferredProfileId: a,
pinnedProfileId: a,
profileProvider: t.provider
});
const s = r.snapshot.entries.find((e) => modelKey(e.provider, e.id) === o) ?? {
provider: t.provider,
id: t.model,
name: t.model
};
const c = r.snapshot.routeVariants.filter((e) => modelKey(e.provider, e.id) === o);
const u = r.evaluateEntry(s, c);
return {
decisions: r,
entry: s,
auth: r.evaluateNative(s, u)
};
};
let { decisions: s, entry: m, auth: h } = await decide(_.modelCatalog);
let g;
if (h.runtimeAuth?.source === "native" && h.availability !== true) {
await _.recheckNativeLogin?.({ force: true });
_ = n(_);
({decisions: s, entry: m, auth: h} = await decide(_.modelCatalog));
}
if (h.availability !== true && h.runtimeAuth?.source === "native" && _.loadNativeModelCatalog) {
const e = await _.loadNativeModelCatalog({
provider: t.provider,
modelId: t.model,
runtime: h.runtimeAuth.id
}).catch((e) => {
g = e;
});
if (e) {
if (!e.entries.some((e) => modelKey(e.provider, e.id) === o)) return {
kind: "unavailable",
error: `The native runtime no longer offers ${o}. Refresh the model catalog and choose again.`
};
({decisions: s, entry: m, auth: h} = await decide(e));
}
}
if (h.routeResolution?.kind === "incompatible") return {
kind: "unavailable",
error: h.routeResolution.message
};
if (h.runtimeAuth?.source === "native" && h.availability !== true || (a || h.availabilityAuthoritative) && h.availability === false) return {
kind: "unavailable",
error: g === void 0 ? `The selected account or native runtime is unavailable for ${o}. Restore that account before spawning this model.` : `The native runtime is unavailable for ${o}: native catalog renewal failed: ${formatErrorMessage(g)}`
};
const v = u({
cfg: _.config,
agentId: e.agentId,
entry: m,
evaluation: h,
pluginRegistry: _.pluginRegistry,
resolveOpenAIProviderRoutes: s.resolveOpenAIProviderRoutes
})?.id;
const y = resolveNativeOwnedRuntimeModel({
catalog: s.snapshot,
provider: t.provider,
modelId: t.model,
runtimeId: v
});
if (y) return s.isCurrent() ? {
kind: "resolved",
ref: t,
model: y
} : {
kind: "unavailable",
error: "Model configuration changed during selection. Retry the request."
};
const x = h.selectedRoute ? f({
provider: t.provider,
config: _.config,
route: h.selectedRoute
}) : _.config;
const S = await r(t.provider, t.model, _.agentDir, x, {
agentId: e.agentId,
workspaceDir: _.workspaceDir,
preparedModelRuntime: _,
assertCurrent: s.assertCurrent,
modelIdSource: "selected",
authProfileId: h.selectedProfileId,
authProfileMode: resolveProviderModelMaterializationAuthMode(h.selectedAuthMode),
...v ? { agentRuntimeId: v } : {},
allowBundledStaticCatalogFallback: true,
deferProviderDynamicModelPreparation: e.source === "automatic"
}).catch((e) => {
if (e instanceof PreparedModelRuntimePublicationSupersededError) return;
throw e;
});
if (!S || !s.isCurrent()) return {
kind: "unavailable",
error: "Model configuration changed during selection. Retry the request."
};
if (S.model) try {
const e = p({
provider: t.provider,
modelId: t.model,
config: x,
workspaceDir: _.workspaceDir,
metadataSnapshot: _.metadataSnapshot,
route: h.selectedRoute ? {
...h.selectedRoute,
provider: t.provider,
modelId: t.model
} : void 0,
model: S.model
});
return {
kind: "resolved",
ref: S.logicalRef,
model: e
};
} catch (e) {
if (e instanceof FailoverError && e.reason === "model_not_found") return {
kind: "unavailable",
error: e.message
};
throw e;
}
return S.deferred === "provider-dynamic-model" ? {
kind: "pending",
ref: t
} : {
kind: "unavailable",
error: S.error
};
};
const x = await prepare(y);
if (e.source !== "automatic" || x.kind !== "unavailable") return x;
const S = m({
cfg: _.config,
agentId: e.agentId,
provider: y.provider,
model: y.model,
requestedRouteResolution: "resolved",
allowPluginNormalization: false,
manifestPlugins: _.metadataSnapshot.plugins,
fallbacksOverride: e.fallbacks ?? []
}).slice(1);
const C = await Promise.all(S.map(prepare));
if (!_.isCurrent()) return {
kind: "unavailable",
error: "Model configuration changed during selection. Retry the request."
};
return C.some((e) => e.kind !== "unavailable") ? {
kind: "automatic",
ref: y
} : x;
});
});
}
/** Bind runtime selection and its commit check to the current published model owner. */
async function preparePublishedModelRuntimeChoice(e) {
const t = await loadPreparedModelCatalog();
const { getPublishedPreparedModelCatalogOwnerSnapshot: n, materializePreparedModelCatalogOwner: r } = t;
const { getPreparedModelRuntimeAuthStore: i } = await loadPreparedRuntimeAuth();
const { prepareModelCatalogDecisions: a } = await loadModelCatalogDecisions();
const o = {
config: e.cfg,
agentId: e.agentId,
workspaceDir: e.workspaceDir
};
const s = e.prepareNativeCatalog ? await e.prepareNativeCatalog(() => t.loadPublishedPreparedModelCatalogOwnerSnapshot(o)) : n(o);
const c = `${e.runtimeId ? `Runtime "${e.runtimeId}"` : "A runtime"} is not available for ${e.provider}/${e.model}`;
const l = `${c}. Refresh the model catalog and choose again.`;
if (!s) return {
kind: "unavailable",
message: l
};
let u;
if (e.prepareNativeCatalog) {
const t = findModelInCatalog(s.modelCatalog.entries, e.provider, e.model);
const n = e.runtimeId ?? e.preferredRuntimeId ?? resolveAgentHarnessPolicy({
config: s.config,
agentId: e.agentId,
provider: e.provider,
modelId: e.model,
modelApi: t?.api,
modelBaseUrl: t?.baseUrl
}).runtime;
if (s.pluginRegistry?.agentHarnesses.some((e) => e.harness.id === n && typeof e.harness.loadModelCatalog === "function")) u = await e.prepareNativeCatalog(async () => s.loadNativeModelCatalog?.({
provider: e.provider,
modelId: e.model,
runtime: n
}));
}
const d = r(s, u);
const f = i(d);
if (!f) return {
kind: "unavailable",
message: l
};
const p = await a({
cfg: d.config,
agentId: d.agentId ?? e.agentId,
agentDir: d.agentDir,
workspaceDir: d.workspaceDir,
snapshot: d.modelCatalog,
metadataSnapshot: d.metadataSnapshot,
preparedAuthStore: f,
preparedRuntimeAuthModes: d.authModes,
pluginRegistry: d.pluginRegistry,
observationConfig: d.observationConfig,
isCurrent: d.isCurrent,
preferredProfileId: e.sessionEntry?.authProfileOverride,
pinnedProfileId: e.sessionEntry?.authProfileOverrideSource === "user" ? e.sessionEntry.authProfileOverride : void 0,
profileProvider: e.sessionEntry?.providerOverride ?? e.sessionEntry?.modelProvider
});
const describeUnavailable = async (t, n, r) => {
const i = n.availability === true ? void 0 : n.unavailableReason;
if (!i) return l;
const { resolveCatalogDecisionRuntime: a } = await loadCatalogDecisionRuntime();
const o = r ?? a({
cfg: d.config,
agentId: d.agentId ?? e.agentId,
entry: t,
evaluation: n,
pluginRegistry: d.pluginRegistry,
resolveOpenAIProviderRoutes: p.resolveOpenAIProviderRoutes
})?.id;
const s = resolveModelRuntimeRoute(e.provider, o) === "claudeCli";
switch (i) {
case "missing-auth": return `${c}: sign-in needed. ${s ? CLAUDE_CLI_SETUP_GUIDANCE : "Connect its provider account, or choose another model."}`;
case "auth-failed": return `${c}: sign-in failed. ${s ? CLAUDE_CLI_SETUP_GUIDANCE : "Sign in to its provider again, or choose another model."}`;
case "cooldown": return `${c}: temporarily unavailable. Try again later or choose another model.`;
default: return l;
}
};
let m = findModelInCatalog(p.snapshot.entries, e.provider, e.model) ?? p.snapshot.entries.find((t) => modelKey(t.provider, t.id) === modelKey(e.provider, e.model));
if (!m) {
const { resolveModelAsync: t } = await loadModelResolver();
const { modelCatalogRowToEntry: n } = await loadModelCatalogEntry();
const r = {
provider: e.provider,
id: e.model,
name: e.model
};
const i = e.runtimeId ?? (e.preferredRuntimeId && p.runtimeChoices(r, [r])?.includes(e.preferredRuntimeId) ? e.preferredRuntimeId : void 0);
const a = p.evaluateEntry(r, void 0, i);
const o = resolveProviderModelMaterializationAuthMode(a.selectedAuthMode);
if (a.availability !== true || !o) return {
kind: "unavailable",
message: await describeUnavailable(r, a, i)
};
const s = await t(e.provider, e.model, d.agentDir, d.config, {
agentId: d.agentId ?? e.agentId,
workspaceDir: d.workspaceDir,
preparedModelRuntime: d,
agentRuntimeId: i,
allowBundledStaticCatalogFallback: true,
assertCurrent: p.assertCurrent,
authProfileMode: o,
...a.selectedProfileId ? { authProfileId: a.selectedProfileId } : {}
});
if (!s.model) return {
kind: "unavailable",
message: l
};
m = n(s.model);
}
const h = createModelCatalogIdentityKeyResolver();
const g = h(m);
const _ = p.snapshot.routeVariants.filter((e) => h(e) === g);
const v = _.length ? _ : [m];
const y = p.runtimeChoices(m, v);
const b = e.runtimeId ?? (e.preferredRuntimeId && y?.includes(e.preferredRuntimeId) ? e.preferredRuntimeId : y?.[0]);
if (!b || !y?.includes(b)) {
const t = e.runtimeId ?? e.preferredRuntimeId;
const n = p.evaluateNative(m, p.evaluateEntry(m, v, t), t);
return {
kind: "unavailable",
message: await describeUnavailable(m, n, t)
};
}
const x = p.evaluateEntry(m, v, b);
const validate = () => p.isCurrent() && p.evaluateNative(m, x, b).availability === true ? void 0 : l;
return {
kind: "ready",
runtimeId: b,
validate,
harness: d.pluginRegistry?.agentHarnesses.find((e) => e.harness.id === b)?.harness
};
}
//#endregion
export { preparePublishedModelRuntimeChoice as n, prepareModelChoice as t };