openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,053 lines (1,052 loc) • 40.5 kB
JavaScript
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { D as parseStrictPositiveInteger, w as parseStrictFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { o as writeRuntimeJson, s as writeRuntimeStdout } from "./runtime-B-SLYP-m.mjs";
import { r as terminalText } from "./safe-text-C80HAQ2e.mjs";
import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import { l as shouldEnableShellEnvFallback, n as getShellEnvAppliedKeys } from "./shell-env-Dbjy7T84.mjs";
import { i as normalizeProviderIdForAuth, r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { s as parseModelPolicyWildcardRef } from "./model-policy-allowlist-migration-Dd1EwQdo.mjs";
import { c as resolveAgentNativeModelPrimary, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { s as stripSelfProviderModelPrefix } from "./provider-model-id-normalization-Yii1-7Le.mjs";
import { t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs";
import { t as dedupeByKey } from "./dedupe-by-key-Cpowmfct.mjs";
import { l as withPluginMetadataSnapshotScope } from "./current-plugin-metadata-snapshot-H0TP3PFt.mjs";
import { A as resolveProfileUnusableUntilForDisplay } from "./user-model-account-authority-CRj924IP.mjs";
import { o as resolveAgentModelFallbackValues, s as resolveAgentModelPrimaryValue } from "./model-input-DrM4DWHG.mjs";
import { i as DEFAULT_PROVIDER, n as DEFAULT_MODEL } from "./defaults-BWyoTPqn.mjs";
import { a as resolveMergedModelProviderConfig } from "./model-provider-config-Bbah_2ON.mjs";
import { i as resolveProviderIdForAuth } from "./provider-auth-aliases-CgGlzANu.mjs";
import { s as resolveProviderAuthLookupMaps } from "./provider-env-vars-DPvuIf4v.mjs";
import { l as resolveAgentModelFallbacksOverride } from "./agent-scope-BwB8YH6y.mjs";
import { s as loadManifestMetadataSnapshot } from "./manifest-contract-eligibility-DoGGge-2.mjs";
import { b as readUtilityModelSetting, h as resolveConfiguredModelRef, i as buildModelAliasIndex, m as resolveConfiguredModelPolicyAllow, y as resolveModelRefFromString } from "./model-selection-shared-9Kz63Hhm.mjs";
import { l as resolveModelCatalogIdentityKey } from "./model-catalog-entry-pfJ-_t4l.mjs";
import { r as modelKey } from "./provider-registry-index-DhPtwFh_.mjs";
import { t as OPENAI_PROVIDER_ID } from "./openai-routing-Dakz1nVk.mjs";
import { t as createConfigIO } from "./io.factory-DEa_bi2j.mjs";
import { n as loadPersistedAuthProfileStore } from "./persisted-Dv3zNYHi.mjs";
import { a as buildAuthProfileUnusableHint } from "./oauth-refresh-failure-DxrQiYzV.mjs";
import "./config-CMA-J084.mjs";
import { r as theme, t as colorize } from "./theme-BOI0xyRZ.mjs";
import { n as createModelVisibilityPolicy } from "./model-visibility-policy-CH4gPfvH.mjs";
import { t as resolveAgentHarnessPolicy } from "./policy-DzaOuofI.mjs";
import "./model-selection-C2A4Wyix.mjs";
import { t as isCliProvider } from "./model-selection-cli-CkH04Wst.mjs";
import { f as listProfilesForProvider } from "./order-jOvee2J6.mjs";
import { c as resolveCliRuntimeExecutionProvider } from "./model-runtime-aliases-DZy9Ea2c.mjs";
import { t as NON_ENV_SECRETREF_MARKER } from "./provider-credential-values-pLjdcwQh.mjs";
import { l as isNonSecretApiKeyMarker, u as isOAuthApiKeyMarker } from "./model-auth-markers-4YSUG71a.mjs";
import { o as getRuntimeAuthProfileStoreSnapshot } from "./store-Bh2lUvOT.mjs";
import { g as resolveManagedSecretRefRuntimeProviderAuth } from "./loader-runtime-load-Ba16vW6K.mjs";
import { i as listProviderEnvAuthLookupKeys, t as resolveEnvApiKey } from "./model-auth-env-kbpGo8fU.mjs";
import { S as shouldPreferExplicitConfigApiKeyAuth, b as resolveUsableCustomProviderApiKey, g as resolveProviderConfigSecretInput, n as getCustomProviderApiKey, v as resolveProviderEntryApiKeyProfileReference } from "./model-auth-provider-config-Bnc4upRS.mjs";
import { c as ensureAuthProfileStoreWithoutExternalProfilesAsync, i as ensureAuthProfileStoreAsync } from "./store-runtime-dW0pXLJI.mjs";
import { h as prepareProviderSyntheticAuthWithPlugin } from "./provider-runtime-BddjXkmv.mjs";
import { i as resolveRuntimeSyntheticAuthProviderRefs } from "./synthetic-auth.runtime.js";
import { r as resolveAuthStorePathForDisplay } from "./paths-BSElhsGi.mjs";
import { r as resolveAgentHarnessOwnerPluginIds } from "./runtime-plugin-load-plan-brah9cpT.mjs";
import { r as maskApiKey } from "./model-catalog-auth-labels-EzN4_7r-.mjs";
import { t as formatAuthProfileOAuthLabel } from "./display-DA_6g711.mjs";
import { n as buildAuthHealthSummary, r as formatRemainingShort, t as DEFAULT_OAUTH_WARN_MS } from "./auth-health-sVoXFBMP.mjs";
import { a as loadPreparedModelCatalogSnapshot } from "./prepared-model-catalog-DSktrHGK.mjs";
import { a as resolveUtilityModelRefForAgent } from "./utility-model-DHdotLLx.mjs";
import { n as requestExitAfterOneShotOutput } from "./one-shot-exit-DkbGSQD5.mjs";
import "./profiles-DbLHYG1P.mjs";
import "./usage-wMHUW27k.mjs";
import "./model-auth-CEsyk_Yg.mjs";
import { n as resolveAgentHarnessRuntimeAvailability } from "./runtime-plugin-Cug3vi2h.mjs";
import { t as createModelAuthAvailabilityResolver } from "./model-auth-availability-DC3d9ngc.mjs";
import { h as isRich, l as resolveModelsTargetAgent, m as groupByProvider, n as ensureFlagCompatibility, r as formatMs } from "./shared-jZuoMzdG.mjs";
import { t as listUnavailableAuthProfiles } from "./auth-unavailability-CTJJVKWL.mjs";
import { n as readModelCatalog, t as getModelCatalogWarnings } from "./catalog-warnings-DifFmrGP.mjs";
import { t as loadModelsConfig } from "./load-config-CTxoGQxg.mjs";
import path from "node:path";
//#region src/commands/models/list.auth-overview.ts
/**
* Count-first wording on purpose: `token=1`/`api_key=0` would match the console
* secret redactor's key=value patterns and get masked into garbled output.
*/
function formatProviderAuthProfileCounts(e) {
return `${e.count} (${e.oauth} oauth, ${e.token} token, ${e.apiKey} api-key)`;
}
function formatMarkerOrSecret(e) {
return isNonSecretApiKeyMarker(e, { includeEnvVarName: false }) ? `marker(${e.trim()})` : maskApiKey(e);
}
function resolveProviderAuthOverview(e) {
const { provider: t, cfg: n, store: r } = e;
const i = Date.now();
const a = listProfilesForProvider(r, t);
const withUnusableSuffix = (e, t) => {
const n = resolveProfileUnusableUntilForDisplay(r, t);
if (!n || i >= n) return e;
const a = r.usageStats?.[t];
return `${e} [${typeof a?.disabledUntil === "number" && i < a.disabledUntil ? `disabled${a.disabledReason ? `:${a.disabledReason}` : ""}` : "cooldown"} ${formatRemainingShort(n - i)}]`;
};
const o = a.map((e) => {
const t = r.profiles[e];
if (!t) return `${e}=missing`;
if (t.type === "api_key" || t.type === "token") {
const n = t.type === "api_key" ? t.key : t.token;
const r = t.type === "api_key" ? t.keyRef : t.tokenRef;
const i = t.type === "api_key" ? "api-key" : "token";
const a = normalizeOptionalString(n) ?? "";
const o = a ? formatMarkerOrSecret(a) : r ? `ref(${r.source}:${r.id})` : "missing";
return withUnusableSuffix(`${e}=${i === "token" ? `token:${o}` : o}`, e);
}
const i = formatAuthProfileOAuthLabel({
cfg: n,
store: r,
profileId: e
});
return withUnusableSuffix(i, e);
});
const s = a.filter((e) => r.profiles[e]?.type === "oauth").length;
const c = a.filter((e) => r.profiles[e]?.type === "token").length;
const l = a.filter((e) => r.profiles[e]?.type === "api_key").length;
const u = normalizeProviderIdForAuth(t);
const d = e.aliasMap?.[u] ?? u;
const f = e.envCandidateMap !== void 0 && Object.hasOwn(e.envCandidateMap, d);
const p = e.authEvidenceMap !== void 0 && Object.hasOwn(e.authEvidenceMap, d);
const m = resolveEnvApiKey(t, process.env, {
config: n,
workspaceDir: e.workspaceDir,
aliasMap: e.aliasMap,
candidateMap: e.envCandidateMap,
authEvidenceMap: e.authEvidenceMap,
skipSetupProviderFallback: f || p
});
const h = m ? {
value: m.source.includes("OAUTH_TOKEN") || normalizeLowercaseStringOrEmpty(m.source).includes("oauth") ? "OAuth (env)" : maskApiKey(m.apiKey),
source: m.source
} : void 0;
const g = getCustomProviderApiKey(n, t);
const _ = resolveUsableCustomProviderApiKey({
cfg: n,
provider: t
});
const v = resolveProviderConfigSecretInput(n, t).ref;
return {
provider: t,
effective: (() => {
if (v) {
if (v.source !== "env" && resolveManagedSecretRefRuntimeProviderAuth({
cfg: n,
provider: t
})) return {
kind: "models.json",
detail: formatMarkerOrSecret(NON_ENV_SECRETREF_MARKER)
};
if (!_) return {
kind: "missing",
detail: "missing"
};
return v.source === "env" ? {
kind: "env",
detail: maskApiKey(_.apiKey)
} : {
kind: "models.json",
detail: formatMarkerOrSecret(_.apiKey)
};
}
const i = resolveProviderEntryApiKeyProfileReference({
cfg: n,
provider: t,
store: r
});
if (i.kind === "literal" && shouldPreferExplicitConfigApiKeyAuth(n, t)) return {
kind: "models.json",
detail: formatMarkerOrSecret(i.apiKey)
};
if (a.length > 0) return {
kind: "profiles",
detail: shortenHomePath(resolveAuthStorePathForDisplay((() => {
const t = e.agentDir;
if (!t || a.length === 0) return t;
const n = loadPersistedAuthProfileStore(t);
if (a.some((e) => Boolean(n?.profiles[e]))) return t;
const r = loadPersistedAuthProfileStore(void 0);
return a.every((e) => Boolean(r?.profiles[e])) ? void 0 : t;
})()))
};
if (h) return {
kind: "env",
detail: h.value
};
if (_) return {
kind: "models.json",
detail: formatMarkerOrSecret(_.apiKey)
};
if (e.syntheticAuth) return {
kind: "synthetic",
detail: e.syntheticAuth.source
};
if (g && isOAuthApiKeyMarker(g)) return {
kind: "models.json",
detail: formatMarkerOrSecret(g)
};
return {
kind: "missing",
detail: "missing"
};
})(),
profiles: {
count: a.length,
oauth: s,
token: c,
apiKey: l,
labels: o
},
...h ? { env: h } : {},
...g ? { modelsJson: {
value: formatMarkerOrSecret(g),
source: `models.json: ${shortenHomePath(e.modelsPath)}`
} } : {},
...e.syntheticAuth ? { syntheticAuth: {
value: e.syntheticAuth.value,
source: e.syntheticAuth.source
} } : {}
};
}
//#endregion
//#region src/commands/models/list.status-utility.ts
/**
* Narration/titles ride the utility model on a plain API auth path that can differ
* from the primary's (e.g. OAuth primary, api_key utility); status shows the resolved
* ref so a broken utility credential is inspectable. A routed automatic model needs
* the router's inventory, which the Gateway's published catalog supplies.
*/
function resolveStatusUtilityModel(e) {
const t = readUtilityModelSetting(e.cfg, e.agentId);
const n = resolveUtilityModelRefForAgent({
cfg: e.cfg,
agentId: e.agentId,
...e.gatewayCatalog ? { catalog: { entries: e.gatewayCatalog.models } } : {}
});
const r = t.kind === "disabled" ? [] : t.fallbacks;
return {
ref: n,
fallbacks: r,
source: t.kind === "explicit" || r.some((e) => e.trim() === n) ? "config" : t.kind === "disabled" ? "disabled" : n ? "provider-default" : "none"
};
}
//#endregion
//#region src/commands/models/list.status-command.ts
const listProbeRuntimeLoader = createLazyImportLoader(() => import("./list.probe-BEAp5ncy.mjs"));
const DISPLAY_MODEL_PARSE_OPTIONS = { allowPluginNormalization: false };
function resolveStatusProviderUseIncompatibility(e) {
const t = e.evaluation.routeResolution;
return t?.kind === "incompatible" ? t : e.runtimeIncompatibility;
}
function parseProbeOption(e, t, n, r = "number") {
if (e === void 0 || e === null) return n;
const i = r === "integer" ? parseStrictPositiveInteger(e) : parseStrictFiniteNumber(e);
if (i === void 0 || i <= 0) throw new Error(`${t} must be a positive ${r}.`);
return i;
}
function syntheticAuthCredential(e, t) {
if (!t.mode) return;
if (t.mode === "api-key") return {
type: "api_key",
provider: e,
key: t.credential
};
if (t.mode === "token" || t.mode === "oauth") return {
type: "token",
provider: e,
token: t.credential,
expires: t.expiresAt
};
}
function finishModelsStatusOutput(e, t, n) {
if (!requestExitAfterOneShotOutput(e, t ? n : void 0) && t) e.exit(n);
}
async function modelsStatusCommand(e, t) {
ensureFlagCompatibility(e);
if (e.plain && e.probe) throw new Error("--probe cannot be used with --plain output.");
const n = createConfigIO().configPath;
const r = await loadModelsConfig({
commandName: "models status",
runtime: t,
skipPluginValidation: e.probe !== true
});
const i = await readModelCatalog(r, e.agent?.trim());
for (const e of getModelCatalogWarnings(i)) t.error(terminalText`${e.message} ${e.fixHint}`);
const a = e.agent?.trim();
const o = process.env.OPENCLAW_AGENT_DIR?.trim() || process.env.PI_CODING_AGENT_DIR?.trim();
const { agentId: s, agentDir: c } = resolveModelsTargetAgent(r, e.agent, {
agentDirOverride: !a && o ? resolveUserPath(o) : void 0,
kind: "read"
});
const l = a ? s : void 0;
const u = resolveAgentWorkspaceDir(r, s);
const d = l ? resolveAgentNativeModelPrimary(r, l) : void 0;
const f = l ? resolveAgentModelFallbacksOverride(r, l) : void 0;
const p = loadManifestMetadataSnapshot({
config: r,
workspaceDir: u,
env: process.env
});
const m = new Map([...p.byPluginId].map(([e, t]) => [e, t.rootDir]));
const h = /* @__PURE__ */ new Map();
const resolveCodexRuntimeAvailability = (e) => {
const t = h.get(e);
if (t) return t;
const n = (async () => {
const { runPluginPayloadSmokeCheckForManifestRecords: t } = await import("./payload-verification-CqyRDZwO.mjs");
const n = await t({
plugins: resolveAgentHarnessOwnerPluginIds({
runtime: "codex",
provider: e,
config: r,
workspaceDir: u
}).flatMap((e) => {
const t = p.byPluginId.get(e);
return t ? [t] : [];
}),
env: process.env
});
return resolveAgentHarnessRuntimeAvailability({
runtime: "codex",
provider: e,
config: r,
workspaceDir: u,
payloadFailures: n.failures,
payloadCheckedPluginIds: n.checked,
selectedPluginRootDirs: m
});
})();
h.set(e, n);
return n;
};
return withPluginMetadataSnapshotScope(p, async () => {
const a = resolveConfiguredModelRef({
cfg: r,
agentId: l,
defaultProvider: DEFAULT_PROVIDER,
defaultModel: DEFAULT_MODEL,
...DISPLAY_MODEL_PARSE_OPTIONS
});
const o = resolveAgentModelPrimaryValue(r.agents?.defaults?.model) ?? "";
const m = d ?? o;
const h = modelKey(a.provider, a.model);
const g = m || h;
const _ = resolveAgentModelFallbackValues(r.agents?.defaults?.model);
const v = f ?? _;
const y = resolveAgentModelPrimaryValue(r.agents?.defaults?.imageModel) ?? "";
const b = resolveAgentModelFallbackValues(r.agents?.defaults?.imageModel);
const { ref: x, fallbacks: S, source: C } = resolveStatusUtilityModel({
cfg: r,
agentId: s,
gatewayCatalog: i
});
const ee = [...resolveConfiguredModelPolicyAllow({
cfg: r,
agentId: s
}).refs];
const te = path.join(c, "models.json");
const ne = buildModelAliasIndex({
cfg: r,
agentId: l,
defaultProvider: DEFAULT_PROVIDER,
...DISPLAY_MODEL_PARSE_OPTIONS
});
const re = Object.fromEntries([...ne.byAlias.values()].map((e) => [e.alias, modelKey(e.ref.provider, e.ref.model)]));
const resolveStatusModelRef = (e) => {
const t = e?.trim();
if (!t) return;
return resolveModelRefFromString({
cfg: r,
agentId: l,
raw: t,
defaultProvider: DEFAULT_PROVIDER,
aliasIndex: ne,
...DISPLAY_MODEL_PARSE_OPTIONS
})?.ref;
};
const w = [g, ...v].some((e) => normalizeProviderId(resolveStatusModelRef(e)?.provider ?? "") === "openai") ? await ensureAuthProfileStoreAsync(c, {
allowKeychainPrompt: false,
config: r,
externalCliProviderIds: [OPENAI_PROVIDER_ID],
readOnly: true
}) : await ensureAuthProfileStoreWithoutExternalProfilesAsync(c);
const ie = new Set(Object.values(w.profiles).map((e) => normalizeProviderId(e.provider)).filter((e) => Boolean(e)));
const ae = new Set(Object.keys(r.models?.providers ?? {}).map(normalizeProviderId).filter(Boolean));
const oe = /* @__PURE__ */ new Set();
const se = [];
const ce = [];
for (const [e, t, n] of [
[
[g, ...v],
"text",
true
],
[
[y, ...b],
"image",
false
],
[
[x, ...S],
"text",
false
],
[
ee,
void 0,
false
]
]) for (const r of e) {
const e = resolveStatusModelRef(r);
if (!e) continue;
se.push(`${e.provider}/${e.model}`);
if (e.provider) {
const r = normalizeProviderId(e.provider);
oe.add(r);
if (t) ce.push({
provider: r,
model: e.model,
allowCodexRuntimeFallback: n,
routeScope: t
});
}
}
const T = x ? resolveStatusModelRef(x) : void 0;
const E = T ? modelKey(normalizeProviderId(T.provider), T.model) : x ?? null;
const le = /* @__PURE__ */ new Set();
const D = {
config: r,
workspaceDir: u,
env: process.env,
metadataSnapshot: p
};
const { aliasMap: O, envCandidateMap: k, authEvidenceMap: A } = resolveProviderAuthLookupMaps(D);
for (const e of listProviderEnvAuthLookupKeys({
envCandidateMap: k,
authEvidenceMap: A
})) if (resolveEnvApiKey(e, process.env, {
config: r,
workspaceDir: u,
aliasMap: O,
candidateMap: k,
authEvidenceMap: A,
skipSetupProviderFallback: true
})) le.add(e);
const ue = new Set(resolveRuntimeSyntheticAuthProviderRefs({
index: p.index,
registryDiagnostics: p.registryDiagnostics
}).map((e) => normalizeProviderId(e)));
const createStatusAuthResolver = (e, t) => createModelAuthAvailabilityResolver({
cfg: r,
agentId: s,
authStore: e,
agentDir: c,
workspaceDir: u,
env: process.env,
syntheticAuthProviderRefs: [...ue],
preparedRuntimeAuthModes: t ? { codex: {
source: "native",
mode: t
} } : {},
metadataSnapshot: p
});
let j = createStatusAuthResolver(w);
const de = normalizeOptionalString(e.probeProvider);
const fe = [.../* @__PURE__ */ new Set([
...j.providerDiscoveryProviderIds,
...ae,
...oe,
...de ? [normalizeProviderId(de)] : []
])].toSorted((e, t) => e.localeCompare(t));
const M = await loadPreparedModelCatalogSnapshot({
config: r,
agentId: s,
providerDiscoveryProviderIds: fe,
readOnly: true
});
const pe = createModelVisibilityPolicy({
cfg: r,
catalog: M.entries,
defaultProvider: a.provider,
defaultModel: a,
agentId: s,
...DISPLAY_MODEL_PARSE_OPTIONS
});
const me = pe.allowAny ? [] : [.../* @__PURE__ */ new Set([...pe.allowedCatalog.map((e) => modelKey(e.provider, e.id)), ...ee.flatMap((e) => {
const t = parseModelPolicyWildcardRef(e);
if (!t) return [];
const n = t.key.slice(0, -1);
return M.entries.some((e) => modelKey(e.provider, e.id).startsWith(n)) ? [] : [t.key];
})])].toSorted();
const N = /* @__PURE__ */ new Map();
const resolveStatusRouteIdentityKey = (e) => {
const t = normalizeProviderId(e.provider);
return resolveModelCatalogIdentityKey({
provider: t,
id: stripSelfProviderModelPrefix(t, modelKey(t, e.id))
});
};
for (const e of M.routeVariants) {
if (e.api === void 0 && e.baseUrl === void 0) continue;
const t = resolveStatusRouteIdentityKey(e);
const n = N.get(t) ?? [];
n.push({
api: e.api,
baseUrl: e.baseUrl
});
N.set(t, n);
}
const resolveProviderUses = async (e) => await Promise.all(ce.map(async (t) => {
const n = N.get(resolveStatusRouteIdentityKey({
provider: t.provider,
id: t.model
}));
const i = {
modelId: t.model,
...n ? { observedRoutes: n } : {}
};
const a = t.routeScope === "text" ? t.allowCodexRuntimeFallback ? e.evaluateRuntimeModelAuth(t.provider, i) : e.evaluateModelAuth(t.provider, i) : {
availability: e.resolveProviderAuthAvailability(t.provider, i),
routeResolution: null
};
const o = !(a.routeResolution?.kind === "incompatible") && t.allowCodexRuntimeFallback && resolveAgentHarnessPolicy({
provider: t.provider,
modelId: t.model,
...a.selectedRoute ? {
modelApi: a.selectedRoute.api,
modelBaseUrl: a.selectedRoute.baseUrl
} : {},
config: r,
agentId: s
}).runtime === "codex";
const c = o && t.provider !== "openai" && t.provider !== "codex" ? {
code: "unsupported-codex-runtime-provider",
message: `The Codex runtime does not support provider ${t.provider}.`
} : void 0;
const l = o && c === void 0;
const u = l ? await resolveCodexRuntimeAvailability(t.provider) : void 0;
return {
provider: t.provider,
model: t.model,
allowCodexRuntimeFallback: t.allowCodexRuntimeFallback,
evaluation: a,
usesCodexRuntimeAuth: l,
runtimeAvailability: u,
runtimeIncompatibility: c
};
}));
let P = await resolveProviderUses(j);
const F = /* @__PURE__ */ new Map();
const he = /* @__PURE__ */ new Map();
const I = P.filter((e) => e.allowCodexRuntimeFallback && !e.usesCodexRuntimeAuth).map((e) => {
const t = resolveCliRuntimeExecutionProvider({
provider: e.provider,
modelId: e.model,
cfg: r,
agentId: s
});
const n = t ? normalizeProviderId(t) : void 0;
return n && n !== e.provider ? {
provider: e.provider,
model: e.model,
allowCodexRuntimeFallback: e.allowCodexRuntimeFallback,
runtime: n
} : void 0;
}).filter((e) => Boolean(e));
const L = Array.from(/* @__PURE__ */ new Set([
...ie,
...ae,
...oe,
...le,
...I.map((e) => e.runtime)
])).map((e) => normalizeOptionalString(e) ?? "").filter(Boolean).toSorted((e, t) => e.localeCompare(t));
const R = new Set(L.map((e) => normalizeProviderId(e)));
const z = normalizeProviderId(OPENAI_PROVIDER_ID);
const ge = O[z] ?? z;
let B = P.filter((e) => e.usesCodexRuntimeAuth);
if (B.length > 0) {
R.add(z);
R.add(ge);
R.add("codex");
}
for (const e of R) {
const t = normalizeProviderId(e);
if (!ue.has(t)) continue;
const n = await prepareProviderSyntheticAuthWithPlugin({
provider: t,
config: r,
workspaceDir: u,
context: {
config: r,
provider: t,
providerConfig: resolveMergedModelProviderConfig(r, t)
}
});
if (!n) continue;
const i = {
value: "plugin-owned",
source: n.source,
credential: n.apiKey,
mode: n.mode,
expiresAt: n.expiresAt
};
F.set(t, i);
if (t !== "codex") he.set(t, i);
if (t !== "codex" && t === ge) F.set(z, i);
}
const V = new Map(Array.from(he.entries()).map(([e, t]) => [e, syntheticAuthCredential(e, t)]).filter((e) => Boolean(e[1])));
const H = F.get("codex")?.mode;
if (V.size > 0 || H) {
const e = Object.fromEntries(Array.from(V.entries()).map(([e, t]) => [`${e}:runtime-synthetic`, t]));
j = createStatusAuthResolver({
...w,
profiles: {
...w.profiles,
...e
}
}, H === "api-key" ? "api_key" : H);
P = await resolveProviderUses(j);
B = P.filter((e) => e.usesCodexRuntimeAuth);
}
const U = getShellEnvAppliedKeys();
const W = shouldEnableShellEnvFallback(process.env) || r.env?.shellEnv?.enabled === true;
const G = Array.from(/* @__PURE__ */ new Set([...L, ...B.length > 0 && F.has(z) ? [z] : []])).toSorted((e, t) => e.localeCompare(t)).map((e) => resolveProviderAuthOverview({
provider: e,
cfg: r,
store: w,
modelsPath: te,
agentDir: c,
workspaceDir: u,
syntheticAuth: F.get(e),
aliasMap: O,
envCandidateMap: k,
authEvidenceMap: A
})).filter((e) => e.profiles.count > 0 || Boolean(e.env) || Boolean(e.modelsJson) || Boolean(e.syntheticAuth));
const K = new Map(G.map((e) => [e.provider, e]));
const q = {
kind: "missing",
detail: "missing"
};
const _e = getRuntimeAuthProfileStoreSnapshot(c);
const ve = _e ? {
...w,
profiles: {
...w.profiles,
..._e.profiles
}
} : w;
const J = buildAuthHealthSummary({
store: ve,
cfg: r,
warnAfterMs: DEFAULT_OAUTH_WARN_MS,
runtimeCredentialsByProvider: V
});
const ye = new Map(J.profiles.map((e) => [e.profileId, e]));
const resolveRuntimeAuthRouteEffective = (e, t) => {
if (!t) return K.get(e)?.effective ?? q;
if (t?.availability === false) return q;
if (t.runtimeAuth?.source === "native") return {
kind: "synthetic",
detail: F.get(t.runtimeAuth.id)?.source ?? "native login"
};
const n = Array.from(/* @__PURE__ */ new Set([normalizeProviderId(e), resolveProviderIdForAuth(e, D)]));
const r = t.selectedProfileId;
if (r) {
const t = w.profiles[r]?.provider ?? e;
const n = K.get(resolveProviderIdForAuth(t, D))?.effective;
return n && n.kind !== "missing" ? n : {
kind: "profiles",
detail: r
};
}
for (const e of n) {
const n = K.get(e);
if (t.evidence === "environment" && n?.env) return {
kind: "env",
detail: n.env.value
};
if ((t.evidence === "provider-config" || t.evidence === "runtime") && n?.modelsJson) return {
kind: "models.json",
detail: n.modelsJson.value
};
if (t.evidence === "synthetic" && F.has(e)) return {
kind: "synthetic",
detail: F.get(e)?.source ?? "plugin-owned"
};
}
return K.get(e)?.effective ?? q;
};
const resolveCliRuntimeAuthProvider = (e) => I.find((t) => t.provider === e.provider && t.model === e.model && t.allowCodexRuntimeFallback === e.allowCodexRuntimeFallback)?.runtime;
const evaluateProviderUseAuth = (e) => {
const t = resolveCliRuntimeAuthProvider(e);
return t ? j.evaluateModelAuth(t) : e.evaluation;
};
const hasUsableAuthForProviderInUse = (e) => {
const t = resolveCliRuntimeAuthProvider(e);
if (t) return j.resolveProviderAuthAvailability(t) !== false;
if (resolveStatusProviderUseIncompatibility(e)) return true;
return e.evaluation.availability !== false;
};
const be = [...Array.from(groupByProvider(B)).map(([e, t]) => {
const n = t.find((e) => e.evaluation.availability === true) ?? t[0];
const r = resolveRuntimeAuthRouteEffective(z, n?.evaluation);
const i = t.map((e) => e.evaluation.availability);
const a = i.every((e) => e === true) ? "usable" : i.some((e) => e === false) ? "missing" : "indeterminate";
const o = n?.runtimeAvailability;
const s = {
provider: e,
runtime: "codex",
authProvider: z,
status: a,
effective: r
};
const c = o?.status === "unavailable" ? {
...s,
status: "unavailable",
authStatus: a,
runtimeStatus: o.status,
runtimeReason: o.reason,
runtimeDetail: o.detail,
runtimePluginIds: o.ownerPluginIds
} : s;
return [`${e}:codex:${z}`, c];
}), ...I.map((e) => {
const t = j.evaluateModelAuth(e.runtime);
const n = resolveRuntimeAuthRouteEffective(e.runtime, t);
return [`${e.provider}:${e.runtime}:${e.runtime}`, {
provider: e.provider,
runtime: e.runtime,
authProvider: e.runtime,
status: t.availability === true ? "usable" : t.availability === false ? "missing" : "indeterminate",
effective: n
}];
})];
const Y = Array.from(new Map(be).values()).toSorted((e, t) => e.provider.localeCompare(t.provider));
const xe = P.flatMap((e) => {
const t = evaluateProviderUseAuth(e);
const n = resolveStatusProviderUseIncompatibility(e);
if (n) return {
kind: "incompatible",
provider: e.provider,
model: e.model,
code: n.code,
message: n.message
};
if (t.availability === void 0) return {
kind: "indeterminate",
provider: e.provider,
model: e.model,
...t.evidence ? { evidence: t.evidence } : {},
message: `Auth readiness could not be confirmed for ${e.provider}/${e.model}.`
};
if (!e.evaluation.selectedRoute || t.availability) return [];
const r = e.evaluation.selectedRoute.authRequirement;
return {
kind: "missing-auth",
provider: e.provider,
model: e.model,
authRequirement: r,
message: `No usable ${r} authentication is available for ${e.provider}/${e.model}.`
};
});
const X = dedupeByKey(xe, (e) => JSON.stringify(e));
const Z = Array.from(new Set(P.filter((e) => !hasUsableAuthForProviderInUse(e)).map((e) => resolveCliRuntimeAuthProvider(e) ?? e.provider))).filter((e) => !isCliProvider(e, r) || I.some((t) => t.runtime === e)).toSorted((e, t) => e.localeCompare(t));
const Se = [e.probeProfile ?? []].flat().flatMap((e) => (e ?? "").split(",")).map((e) => e.trim()).filter(Boolean);
const Ce = parseProbeOption(e.probeTimeout, "--probe-timeout", 8e3);
const we = parseProbeOption(e.probeConcurrency, "--probe-concurrency", 2, "integer");
const Te = parseProbeOption(e.probeMaxTokens, "--probe-max-tokens", 8, "integer");
let Q;
if (e.probe) {
const [{ withProgressTotals: t }, { runAuthProbes: n }] = await Promise.all([import("./progress-CNwY7Ykv.mjs"), listProbeRuntimeLoader.load()]);
Q = await t({
label: "Checking auth profiles…",
total: 1
}, async (t) => {
return await n({
cfg: r,
agentId: s,
agentDir: c,
workspaceDir: u,
providers: L,
modelCandidates: se,
options: {
provider: e.probeProvider,
profileIds: Se,
timeoutMs: Ce,
concurrency: we,
maxTokens: Te
},
stateOwnership: { mode: "exclusive" },
onProgress: t
});
});
}
const Ee = G.flatMap((e) => {
const t = e.profiles.oauth + e.profiles.token + (e.env?.value === "OAuth (env)" ? 1 : 0);
return t > 0 ? [`${e.provider} (${t})`] : [];
});
const De = J.profiles.filter((e) => e.type === "oauth" || e.type === "token");
const Oe = listUnavailableAuthProfiles(w).map(({ profileId: e, provider: t, kind: n, reason: r, classification: i, until: a, remainingMs: o }) => Object.assign({
profileId: e,
provider: t,
kind: n,
reason: r
}, i ? { classification: i } : {}, {
recoveryHint: buildAuthProfileUnusableHint({
kind: n,
reason: r,
provider: t ?? e,
profileId: e
}),
until: a,
remainingMs: o
})).toSorted((e, t) => e.remainingMs - t.remainingMs);
const ke = (() => {
const resolveRouteAuthHealth = (e) => {
if (resolveStatusProviderUseIncompatibility(e)) return "missing";
const t = evaluateProviderUseAuth(e);
if (t.availability === void 0) return "indeterminate";
if (!t.availability) return "missing";
const n = t.selectedProfileId;
if (!n) return "ok";
const r = ye.get(n);
if (r?.status === "expiring") return "expiring";
if (r?.status === "expired" || r?.status === "missing") return "missing";
return "ok";
};
const e = new Set(P.map(resolveRouteAuthHealth));
const t = X.some((e) => e.kind === "incompatible" || e.kind === "indeterminate") || e.has("missing") || e.has("indeterminate") || Y.some((e) => e.status === "unavailable") || Z.length > 0;
const n = e.has("expiring");
if (t) return 1;
if (n) return 2;
return 0;
})();
if (e.json) {
writeRuntimeJson(t, {
configPath: n,
...l ? { agentId: l } : {},
agentDir: c,
defaultModel: g,
resolvedDefault: h,
fallbacks: v,
imageModel: y || null,
imageFallbacks: b,
utilityModel: {
ref: E,
source: C
},
utilityFallbacks: S,
...l ? { modelConfig: {
defaultSource: d ? "agent" : "defaults",
fallbacksSource: f !== void 0 ? "agent" : "defaults"
} } : {},
aliases: re,
allowed: me,
auth: {
storePath: resolveAuthStorePathForDisplay(c),
shellEnvFallback: {
enabled: W,
appliedKeys: U
},
providersWithOAuth: Ee,
missingProvidersInUse: Z,
modelRouteIssues: X,
runtimeAuthRoutes: Y,
providers: G,
unusableProfiles: Oe,
oauth: {
warnAfterMs: J.warnAfterMs,
profiles: J.profiles,
providers: J.providers
},
probes: Q
}
});
finishModelsStatusOutput(t, e.check, ke);
return;
}
if (e.plain) {
writeRuntimeStdout(t, terminalText`${h}`);
finishModelsStatusOutput(t, e.check, ke);
return;
}
const $ = isRich(e);
const label = (e) => colorize($, theme.accent, e.padEnd(14));
const logRow = (e, n, r) => t.log(`${label(r ? `${e} (${r})` : e)}${colorize($, theme.muted, ":")} ${n}`);
const logField = (e, t, n, r) => logRow(e, colorize($, n, terminalText`${t}`), r);
const logList = (e, t, n, r, i = "-") => logField(`${e} (${t.length})`, t.length ? t.join(", ") : i, t.length ? n : theme.muted, r);
const logSection = (e) => {
t.log("");
t.log(colorize($, theme.heading, e));
};
const Ae = m && m !== h ? `${h} (from ${m})` : h;
logField("Config", shortenHomePath(n), theme.info);
logField("Agent dir", shortenHomePath(c), theme.info);
logField("Default", Ae, theme.success, l ? d ? "agent" : "defaults" : void 0);
logList("Fallbacks", v, theme.warn, l ? f !== void 0 ? "agent" : "defaults" : void 0);
logField("Utility model", E ? `${E}${C === "provider-default" ? " (provider default)" : ""}` : C === "disabled" ? "off" : "-", E ? theme.success : theme.muted);
logList("Utility fallbacks", S, theme.warn);
logField("Image model", y || "-", y ? theme.accentBright : theme.muted, l ? "defaults" : void 0);
logList("Image fallbacks", b, theme.accentBright, l ? "defaults" : void 0);
const je = Object.entries(re).map(([e, t]) => {
return $ ? `${theme.accentDim(terminalText`${e}`)} ${theme.muted("->")} ${theme.info(terminalText`${t}`)}` : terminalText`${e} -> ${t}`;
});
logRow(`Aliases (${je.length})`, je.length ? colorize($, theme.accent, je.join(", ")) : colorize($, theme.muted, "-"));
logList("Allowed models", me, theme.info, void 0, "all");
logSection("Auth overview");
logField("Auth store", shortenHomePath(resolveAuthStorePathForDisplay(c)), theme.info);
t.log(`${label("Shell env")}${colorize($, theme.muted, ":")} ${colorize($, W ? theme.success : theme.muted, W ? "on" : "off")}${U.length ? colorize($, theme.muted, terminalText` (applied: ${U.join(", ")})`) : ""}`);
logList("Providers w/ OAuth/tokens", Ee, theme.info);
const formatKey = (e) => colorize($, theme.warn, terminalText`${e}`);
const formatKeyValue = (e, t) => `${formatKey(e)}=${colorize($, theme.info, terminalText`${t}`)}`;
const formatSeparator = () => colorize($, theme.muted, " | ");
const formatEffective = (e) => `${formatKey("effective")}=${colorize($, theme.info, `${colorize($, theme.accentBright, terminalText`${e.kind}`)}:${colorize($, theme.muted, terminalText`${e.detail}`)}`)}`;
for (const e of G) {
const n = formatSeparator();
const r = [formatEffective(e.effective)];
if (e.profiles.count > 0) {
r.push(formatKeyValue("profiles", formatProviderAuthProfileCounts(e.profiles)));
if (e.profiles.labels.length > 0) r.push(colorize($, theme.info, terminalText`${e.profiles.labels.join(", ")}`));
}
for (const [t, i] of [
["env", e.env],
["models.json", e.modelsJson],
["synthetic", e.syntheticAuth]
]) if (i) r.push(`${formatKeyValue(t, i.value)}${n}${formatKeyValue("source", i.source)}`);
t.log(`- ${theme.heading(terminalText`${e.provider}`)} ${r.join(n)}`);
}
if (Y.length > 0) {
logSection("Runtime auth");
for (const e of Y) {
const n = e.status === "unavailable" ? `${formatSeparator()}${formatKeyValue("auth", e.authStatus)}${formatSeparator()}${formatKeyValue("runtime", e.runtimeStatus)}${e.runtimeDetail ? `${formatSeparator()}${colorize($, theme.muted, terminalText`${e.runtimeDetail}`)}` : ""}` : "";
t.log(`- ${theme.heading(terminalText`${e.provider}`)} via ${colorize($, theme.accentBright, terminalText`${e.runtime}`)} uses ${theme.heading(terminalText`${e.authProvider}`)} ${formatEffective(e.effective)}${formatSeparator()}${formatKeyValue("status", e.status)}${n}`);
}
}
if (X.length > 0) {
logSection("Model route issues");
for (const e of X) {
const n = `${e.provider}/${e.model}`;
const r = e.kind === "missing-auth" ? `requires ${e.authRequirement} auth:` : `[${e.kind === "incompatible" ? e.code : "indeterminate"}]`;
t.log(`- ${theme.heading(terminalText`${n}`)}` + terminalText` ${r} ${e.message}`);
}
}
if (Z.length > 0) {
const { buildProviderAuthRecoveryHint: e } = await import("./provider-auth-recovery-hint-DJmWmCch.mjs");
logSection("Missing auth");
for (const n of Z) {
const i = X.some((e) => e.kind === "missing-auth" && e.provider === n && e.authRequirement === "subscription");
const a = e({
provider: n,
config: r,
includeEnvVar: !i
});
t.log(`- ${theme.heading(terminalText`${n}`)}` + terminalText` ${a}`);
}
}
if (Oe.length > 0) {
logSection("Unavailable auth profiles");
for (const e of Oe) {
const n = e.classification ?? e.reason;
const r = n ? `:${n}` : "";
const i = e.provider ? ` (${e.provider})` : "";
t.log(`- ${theme.heading(terminalText`${e.profileId}`)}` + terminalText`${i} ${e.kind}${r} (${formatRemainingShort(e.remainingMs)}) — ${e.recoveryHint}`);
}
}
logSection("OAuth/token status");
if (De.length === 0) t.log(colorize($, theme.muted, "- none"));
else {
const { formatUsageWindowSummary: e, loadProviderUsageSummary: n, resolveUsageProviderId: r } = await import("./provider-usage-C2xm3TuG.mjs");
const i = /* @__PURE__ */ new Map();
const a = Array.from(new Set(De.map((e) => r(e.provider, { credentialType: e.type })).filter((e) => Boolean(e))));
if (a.length > 0) try {
const t = await n({
providers: a,
agentDir: c,
timeoutMs: 3500
});
for (const n of t.providers) {
const t = e(n);
if (t) i.set(n.provider, t);
}
} catch {}
const o = /* @__PURE__ */ new Map([
["ok", colorize($, theme.success, "ok")],
["static", colorize($, theme.muted, "static")],
["expiring", colorize($, theme.warn, "expiring")],
["missing", colorize($, theme.warn, "unknown")]
]);
for (const [e, n] of groupByProvider(De)) {
const a = r(e, { credentialType: n[0]?.type });
const s = a ? i.get(a) : void 0;
const c = s ? colorize($, theme.muted, terminalText` usage: ${s}`) : "";
t.log(`- ${colorize($, theme.heading, terminalText`${e}`)}${c}`);
for (const e of n) {
const n = e.label || e.profileId;
const r = colorize($, theme.accent, terminalText`${n}`);
const i = o.get(e.status) ?? colorize($, theme.error, "expired");
const a = e.status === "static" ? "" : e.expiresAt ? ` expires in ${formatRemainingShort(e.remainingMs)}` : " expires unknown";
t.log(` - ${r} ${i}${a}`);
}
}
}
if (Q) {
const [{ getTerminalTableWidth: e, renderTable: n }, { describeProbeSummary: r, sortProbeResults: i }] = await Promise.all([import("./terminal-core/table.js"), listProbeRuntimeLoader.load()]);
logSection("Auth checks");
if (Q.results.length === 0) t.log(colorize($, theme.muted, "- none"));
else {
const a = e();
const o = i(Q.results);
const statusColor = (e) => {
if (e === "ok") return theme.success;
if (e === "rate_limit" || e === "timeout" || e === "billing") return theme.warn;
if (e === "auth" || e === "format") return theme.error;
return theme.muted;
};
const s = o.map((e) => {
const t = colorize($, statusColor(e.status), e.status);
const n = formatMs(e.latencyMs);
const r = e.model ?? `${e.provider}/-`;
const i = e.mode ? ` ${colorize($, theme.muted, terminalText`(${e.mode})`)}` : "";
const a = `${colorize($, theme.accent, terminalText`${e.label}`)}${i}`;
const o = e.error?.trim();
const s = o ? `\n${colorize($, theme.muted, terminalText`↳ ${o}`)}` : "";
const c = `${t}${colorize($, theme.muted, ` · ${n}`)}${s}`;
return {
Model: colorize($, theme.heading, terminalText`${r}`),
Profile: a,
Status: c
};
});
t.log(n({
width: a,
columns: [
{
key: "Model",
header: "Model",
minWidth: 18
},
{
key: "Profile",
header: "Profile",
minWidth: 24
},
{
key: "Status",
header: "Status",
minWidth: 12
}
],
rows: s
}).trimEnd());
t.log(colorize($, theme.muted, r(Q)));
}
}
finishModelsStatusOutput(t, e.check, ke);
}, {
config: r,
workspaceDir: u,
env: process.env
});
}
//#endregion
export { modelsStatusCommand };