Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351/** * Pure model resolver (saga 9mre6k / MC2). * * Implements the 6-step resolution + override matrix from the parent plan. Pure (no I/O): * takes config + env + flags as params, so the future smoke harness can call it without a * subprocess. Throws on all stuck cases (fail-loudly; the CLI layer in MC4 turns throws * into exit 2, matching the `src/cli/index.ts:118` precedent). * * Env override precedence (high → low): flag > env > config (so CI / one-off runs win). * * Layer: L4. Imports only `@/cli/config` (same layer) + stdlib types. No `@/core`. */import type { AuthConfig, ModelOverride, ShardConfig } from '@/cli/config/schema';
/** The auth as the provider consumes it — `token` present only for bearer (runtime-resolved). */export type ResolvedAuth = | { kind: 'bearer'; token: string } | { kind: 'none' };
/** * The triple `OpenAIProvider` consumes (mapped to its `apiKey`/`baseURL`/`model`). * `provider` is the provider key (for messages); `modelName` is the literal id sent in the * request body's `model` field. */export interface ResolvedModel { provider: string; baseURL: string; auth: ResolvedAuth; modelName: string; /** * The resolved model's context window in tokens (saga dfcvo6), from the per-model * override `models[alias].contextWindow` when set; otherwise `undefined` → the CLI * falls back to the global `compaction.contextWindow` then `DEFAULT_CONTEXT_WINDOW`. * Surfaced here so the CLI can wire compaction without re-reading config.models. */ contextWindow?: number; /** * Wire adapter (saga hihsjg). `'responses'` → the OpenAI Responses API provider * (readable reasoning summaries); `'chat-completions'` → the existing OpenAI-compatible * provider. Surfaced so the provider factory can branch without re-reading config. */ api?: 'chat-completions' | 'responses'; /** * Whether the model is a reasoning model (saga hihsjg). Surfaced so the provider factory * can pass it to the Responses provider (opts into reasoning summaries + developer role). */ reasoning?: boolean; /** * The resolved effective reasoning effort for this model (saga p7m8jp.1). Surfaced so * the provider factory can pass it to the Responses / Chat Completions provider. When * absent the provider applies its own adapter default (Responses currently uses `medium`; * Chat Completions sends nothing unless `reasoningEfforts` is declared). An explicit * value is never silently dropped — it is validated as a member of `reasoningEfforts` * during config load and resolution. */ reasoningEffort?: string; /** * The supported reasoning effort IDs for this model (saga p7m8jp.1). Surfaced so the * runtime authority can serve `list_reasoning_levels` and advertise capabilities. When * absent the model has no selectable effort surface. Omission is valid — generic * OpenAI-compatible endpoints receive no new field by default. */ reasoningEfforts?: string[];}
/** Inputs to `resolveModel`. Env is a param (not `process.env`) so the fn stays pure. */export interface ResolveInput { /** `--provider` flag (highest precedence). */ providerKey?: string; /** `--model`/`-m` flag (highest precedence for the model alias/name). */ modelName?: string; config: ShardConfig; /** Env snapshot (e.g. `process.env` or an injected test env). */ env: Record<string, string | undefined>;}
// ─── Step helpers (each < 50 lines; fail-loudly) ───────────────────────────────
/** Step 1 — resolve the provider key: flag → SHARD_PROVIDER → config.defaultProvider. */function resolveProviderKey(input: ResolveInput): string { const fromFlag = input.providerKey; if (fromFlag && fromFlag.length > 0) return fromFlag; const fromEnv = input.env['SHARD_PROVIDER']; if (fromEnv && fromEnv.length > 0) return fromEnv; const fromConfig = input.config.defaultProvider; if (fromConfig && fromConfig.length > 0) return fromConfig; const configured = Object.keys(input.config.providers); const hint = configured.length > 0 ? ` (configured providers: ${configured.join(', ')})` : ' (no providers configured; run "shard config init" to create one)'; throw new Error(`shard: no provider resolved. Pass --provider <key> or set SHARD_PROVIDER${hint}`);}
/** Step 2 — resolve the model alias/name: flag → SHARD_MODEL/OPENAI_MODEL → defaultModel[provider]. */function resolveModelAlias(input: ResolveInput, providerKey: string): string { const fromFlag = input.modelName; if (fromFlag && fromFlag.length > 0) return fromFlag; const fromEnvShard = input.env['SHARD_MODEL']; if (fromEnvShard && fromEnvShard.length > 0) return fromEnvShard; const fromEnvOpenAI = input.env['OPENAI_MODEL']; if (fromEnvOpenAI && fromEnvOpenAI.length > 0) return fromEnvOpenAI; const fromConfig = input.config.defaultModel?.[providerKey]; if (fromConfig && fromConfig.length > 0) return fromConfig; // List override keys for this provider as a hint (discovery lives in MC3). const overrides = input.config.models ? Object.entries(input.config.models) .filter(([, m]) => m.provider === providerKey) .map(([alias]) => alias) : []; const hint = overrides.length > 0 ? ` (aliases for provider "${providerKey}": ${overrides.join(', ')}; or run "shard models list")` : ' (run "shard models list" to see available models)'; throw new Error( `shard: no model resolved for provider "${providerKey}". Pass --model <name> or set SHARD_MODEL/OPENAI_MODEL${hint}`, );}
/** Steps 4–5 — look up the provider + resolve auth at runtime from env (token never persisted). */function resolveProviderAuth( config: ShardConfig, providerKey: string, env: Record<string, string | undefined>,): { baseURL: string; auth: ResolvedAuth } { const provider = config.providers[providerKey]; if (!provider) { const configured = Object.keys(config.providers); throw new Error( `shard: provider "${providerKey}" not in config (configured: ${configured.join(', ') || 'none'})`, ); } const auth = resolveAuthValue(provider.auth, env, providerKey); return { baseURL: provider.baseURL, auth };}
/** Step 5 — resolve auth.kind to a runtime token (bearer) or none. Fail-loudly if env unset. */function resolveAuthValue( auth: AuthConfig, env: Record<string, string | undefined>, providerKey: string,): ResolvedAuth { if (auth.kind === 'none') return { kind: 'none' }; const token = env[auth.envVar]; if (!token || token.length === 0) { throw new Error( `shard: auth env var "${auth.envVar}" for provider "${providerKey}" is not set; export it or set auth.kind:"none"`, ); } return { kind: 'bearer', token };}
// ─── Reasoning-model auto-detection (saga hihsjg) ─────────────────────────────
/** OpenAI reasoning model name patterns. Matched case-insensitively against the model * id sent in the request body. Used only to auto-default `api:'responses'` + * `reasoning:true` when the override does not specify `api`; never overrides an explicit * `api`/`reasoning`. Kept conservative: only genuine OpenAI reasoning families. */const REASONING_MODEL_PATTERN = /^(gpt-5|o1|o3|o4-mini|gpt-oss)/i;
/** True when `baseURL` points at OpenAI's hosted API (the only endpoint that implements * `/v1/responses`). Compat providers (Ollama / vLLM / OpenRouter / etc.) are never * auto-switched to the Responses API surface even if they serve a gpt-5-like name. */function isGenuineOpenAIBaseURL(baseURL: string): boolean { try { const host = new URL(baseURL).host; return host === 'api.openai.com'; } catch { return false; }}
/** Resolve `api` + `reasoning` for a model, applying the auto-default heuristic when the * override omits either field. Returns the effective pair; `providerKey`/`baseURL` gate * the auto-switch so compat endpoints stay on chat-completions. */function resolveApiAndReasoning(opts: { override: ModelOverride | undefined; providerKey: string; baseURL: string; modelName: string;}): { api: 'chat-completions' | 'responses'; reasoning: boolean } { const explicitApi = opts.override?.api; const explicitReasoning = opts.override?.reasoning; // Only auto-switch when unset AND the endpoint is genuine OpenAI AND the name matches. const autoResponses = explicitApi === undefined && isGenuineOpenAIBaseURL(opts.baseURL) && REASONING_MODEL_PATTERN.test(opts.modelName); const api: 'chat-completions' | 'responses' = explicitApi ?? (autoResponses ? 'responses' : 'chat-completions'); // Reasoning defaults to true only on the responses adapter for a matching name; the // explicit override wins in all directions. const reasoning = explicitReasoning ?? (api === 'responses' && autoResponses ? true : false); return { api, reasoning };}
/** * Resolve the effective reasoning effort and carry the support list (saga p7m8jp.1). * * Rules (parent saga plan): * - `reasoningEfforts` (when present) has already been schema-validated for non-empty * strings + non-empty array and semantic-validated for uniqueness during `loadConfig`. * - An explicit `reasoningEffort` requires `reasoningEfforts` and must be a member — this * is also validated during `loadConfig`, but the resolver re-checks defensively (a * hand-built config bypassing `loadConfig` must still fail loudly). * - When no explicit default exists and `reasoningEfforts` includes `medium`, preserve the * current Responses behavior by defaulting to `medium`. * - Otherwise the effort is `undefined` — the provider applies its own adapter default * (Responses currently uses `medium`; Chat Completions sends nothing unless * `reasoningEfforts` is declared). * * The support list is carried regardless of adapter — the capability advertisement * (p7m8jp.3) and provider payload translation (p7m8jp.2) decide what to send. Unsupported * adapters do not acquire capabilities merely because `reasoning: true` exists; the * presence of `reasoningEfforts` is what gates the capability. */function resolveReasoningEffort(opts: { override: ModelOverride | undefined;}): { effort: string | undefined; efforts: string[] | undefined } { const efforts = opts.override?.reasoningEfforts; const explicitEffort = opts.override?.reasoningEffort; // Defensive re-validation (loadConfig already checks this, but a hand-built config // bypassing the loader must still fail loudly — never silently drop an explicit value). if (explicitEffort !== undefined) { if (efforts === undefined) { throw new Error( `shard: reasoningEffort "${explicitEffort}" requires reasoningEfforts to be set`, ); } if (!efforts.includes(explicitEffort)) { throw new Error( `shard: reasoningEffort "${explicitEffort}" is not in reasoningEfforts [${efforts.join(', ')}]`, ); } } // Preserve current Responses behavior: no explicit default + medium supported → medium. let effort = explicitEffort; if (effort === undefined && efforts !== undefined && efforts.includes('medium')) { effort = 'medium'; } return { effort, efforts };}
/** * Resolve `--provider` / `--model` + env + config → the triple `OpenAIProvider` consumes. * Pure (no `process.env` / `fs` / `fetch`). Throws on every stuck case (fail-loudly). * * Order (parent plan): * 1. Provider key: flag → SHARD_PROVIDER → config.defaultProvider. * 2. Model alias/name: flag → SHARD_MODEL/OPENAI_MODEL → config.defaultModel[provider]. * 3. Alias resolution: if in config.models, take its {provider, name} (switching provider * if the override specifies one). Otherwise treat as a literal model name. * 4. Look up providers[providerKey] {baseURL, auth}. Missing → throw. * 5. Resolve auth: bearer → read env[auth.envVar] (unset → throw); none → no token. * 6. Emit { provider, baseURL, auth, modelName }. *//** Resolve an already-selected concrete provider/model pair without alias lookup. */export function resolveConcreteModel(input: { config: ShardConfig; env: Record<string, string | undefined>; providerKey: string; modelName: string; /** * Optional per-alias override (saga hihsjg). When supplied (the catalog path recovers it * from the descriptor id), its `api`/`reasoning` win over the auto-default heuristic — * so an explicit `api:'responses'` set on `models[alias]` survives a runtime model switch. * Without it the auto-default applies (genuine-OpenAI + reasoning name). */ override?: ModelOverride;}): ResolvedModel { if (input.providerKey.length === 0 || input.modelName.length === 0) { throw new Error('shard: concrete model selection requires non-empty provider and model'); } const { baseURL, auth } = resolveProviderAuth(input.config, input.providerKey, input.env); // saga hihsjg: resolve api/reasoning. Pass the recovered override (if any) so an explicit // per-alias api/reasoning wins over the auto-default — without it, a runtime model switch // via the catalog would lose `api:'responses'` for a non-OpenAI-hosted reasoning model. const { api, reasoning } = resolveApiAndReasoning({ override: input.override, providerKey: input.providerKey, baseURL, modelName: input.modelName, }); // saga p7m8jp.1: resolve the effective reasoning effort + carry the support list. const { effort: reasoningEffort, efforts: reasoningEfforts } = resolveReasoningEffort({ override: input.override, }); const result: ResolvedModel = { provider: input.providerKey, baseURL, auth, modelName: input.modelName, api, reasoning, ...(reasoningEffort !== undefined ? { reasoningEffort } : undefined), ...(reasoningEfforts !== undefined ? { reasoningEfforts } : undefined), }; return result;}
export function resolveModel(input: ResolveInput): ResolvedModel { // Step 1 + 2: resolve providerKey + model alias from the override matrix. let providerKey = resolveProviderKey(input); let modelAlias = resolveModelAlias(input, providerKey);
// Step 3: alias resolution. If the alias is a key in config.models, switch to its // {provider, name} (override may switch the provider). Otherwise treat as a literal // model name for the chosen provider. let modelName = modelAlias; const override = input.config.models?.[modelAlias]; if (override) { modelName = override.name; if (override.provider !== providerKey) { providerKey = override.provider; } }
// Steps 4–5: look up provider + resolve auth (fail-loudly if missing). const { baseURL, auth } = resolveProviderAuth(input.config, providerKey, input.env);
// saga hihsjg: resolve api/reasoning from the override (when an alias matched) + the // auto-default heuristic (genuine-OpenAI + reasoning name). const { api, reasoning } = resolveApiAndReasoning({ override: override, providerKey, baseURL, modelName, });
// saga p7m8jp.1: resolve the effective reasoning effort + carry the support list. const { effort: reasoningEffort, efforts: reasoningEfforts } = resolveReasoningEffort({ override, });
// Step 6: emit the triple OpenAIProvider consumes + the per-model contextWindow when // the override supplied one (saga dfcvo6 — surfaced so the CLI can wire compaction). const result: ResolvedModel = { provider: providerKey, baseURL, auth, modelName, api, reasoning, ...(reasoningEffort !== undefined ? { reasoningEffort } : undefined), ...(reasoningEfforts !== undefined ? { reasoningEfforts } : undefined), }; if (override && typeof override.contextWindow === 'number') { result.contextWindow = override.contextWindow; } return result;}