/** * Pure keypress reducer for the devflow agents TUI. * * CLI-layer view module; consumes src/core/ imports only. * Pure functions only — no process.exit(), no I/O. * * Model cycle: default → Claude aliases → enabled provider choices → default. * Catalog rows offer aliases, or the canonical id if there are no aliases. * Cursor offers only qualified ids from the catalog's base pool. * Effort cycle: default → low → medium → high → xhigh → max → inherit → default * Worker rows (D-WORKER-AGENTS) cycle only what a worker accepts: the model * cycle is default and the Claude aliases, the effort cycle has no inherit. * * Dormancy semantics (plan D5 / Phase 1): * When proxy is off and a row's saved model is a GPT model, configuredModel * starts as 'default' and the saved GPT name is kept in dormantModel for * display annotation and untouched-preservation on save. * * Off-cycle pin semantics (Phase D): * When proxy is on and a row's saved model is absent from the discovered * selectableNames (retired model), offCyclePin holds the saved model. * The per-row effective cycle is [...modelCycle, offCyclePin], so the * pin is always reachable after a full cycle without pressing 'd'. * * Dirty detection: current !== original (touch-then-revert → not dirty). * * Performance (AC-P6): modelCycle is built ONCE in buildTuiState and stored * on the state — never reallocated per keypress. The reducer receives it as * state.modelCycle and threads it through without reconstructing. */ import { EFFORT_INHERIT, EFFORT_LEVELS, type EffortLevel, type StoredEffort, } from '../../core/agent-models.js'; import { CLAUDE_MODEL_ALIASES, isDormantExternalModel, } from '../../core/external-models.js'; import { classifyAgentState, type AgentState, } from '../../core/agent-state.js'; import { type ExternalModel, type ExternalModelCatalog } from '../../core/model-discovery.js'; import { isRoutingProviderId, ROUTING_PROVIDERS, type RoutingProviderId } from '../../core/routing-providers.js'; // --------------------------------------------------------------------------- // Public types // --------------------------------------------------------------------------- /** A single row in the agents TUI. */ export interface AgentRow { readonly name: string; /** Shipped default model from source agent file (e.g., 'opus'). */ readonly shippedDefault: string; /** Shipped default effort from the source agent file; undefined when it ships none. */ readonly shippedEffort: EffortLevel | undefined; /** Current session model value: 'default' | model name. */ readonly configuredModel: string; /** Model value at state init — used for dirty detection. */ readonly originalModel: string; /** Current session effort value: 'default' | effort level | 'inherit'. */ readonly configuredEffort: StoredEffort | 'default'; /** Effort value at state init — used for dirty detection. */ readonly originalEffort: StoredEffort | 'default'; /** * Non-null only when: savedModel is an external model AND proxy is off. * Holds the saved model name for display annotation and * byte-identical preservation on save if the field was not touched. */ readonly dormantModel: string | null; /** * Non-null only when: proxy is on AND the saved model is absent from the * main modelCycle (e.g. a retired canonical id). The pin stays reachable * as the last choice on this row only. */ readonly offCyclePin: string | null; /** True when the agent's .md file is present in the install directory. */ readonly installed: boolean; /** True when the agent name exists in the plugin registry. False for orphan rows. */ readonly inRegistry: boolean; /** * True for the row of a background worker (D-WORKER-AGENTS). It has no * installed agent file, takes only the worker value domain, and its STATE is * always 'worker'. */ readonly worker: boolean; } /** Full TUI state — immutable by convention. */ export interface AgentsViewState { readonly rows: readonly AgentRow[]; readonly cursor: number; readonly activeField: 'model' | 'effort'; /** Index of the first visible row in the viewport. */ readonly viewportOffset: number; /** Number of rows the terminal viewport can display. */ readonly viewportHeight: number; readonly proxyEnabled: boolean; /** * Prebuilt flat cycle for all rows: ['default', ...claude, ...external]. * Built once in buildTuiState; never reallocated per keypress (AC-P6). * A non-null offCyclePin adds a final choice on its row only. */ readonly modelCycle: readonly string[]; } export type Intent = 'none' | 'save' | 'cancel'; export interface ReduceResult { readonly state: AgentsViewState; readonly intent: Intent; } // --------------------------------------------------------------------------- // Cycle builders (pure) // --------------------------------------------------------------------------- /** * The picker names for a single model: all aliases when the model has any, * or the canonical id when it has none. This is the single alias-selection * site — both `pickerNames` (cycle builder) and `buildPickerNameMap` (id→alias * normaliser) call it so the two can never drift. * * Module-private: callers consume the public wrappers below. * Pure function, no I/O. */ function pickerNamesFor(model: ExternalModel): readonly string[] { return model.aliases.length > 0 ? model.aliases : [model.id]; } /** * Extract the picker name list from a model list. * * Zero-maintenance rule (Fix 1): * - For each model IN REGISTRY ORDER: contribute ALL of its aliases. * - Contribute the canonical ID if and only if the model has NO aliases. * * This means: * gpt-6.2-sol [aliases: ['sol']] → 'sol' * gpt-6.1-terra [aliases: []] → 'gpt-6.1-terra' * gpt-x [aliases: ['a','b']] → 'a', 'b' * * If a model gains an alias, the picker uses that alias with no code change. * * NOTE: catalog.selectableNames is NOT used here — it doubles as the --set * validation allowlist (includes both aliases and canonical ids). Narrowing * it would reject `devflow agents --set code --model gpt-6.2-sol`. * * Pure function, no I/O. */ export function pickerNames(models: readonly ExternalModel[]): readonly string[] { return models.flatMap(pickerNamesFor); } /** * Build a map from every stored identifier (alias or canonical id) to the * picker name that represents it in the TUI cycle. * * Used by buildRow to normalize a stored canonical id to its alias on read, * e.g. 'gpt-6.2-sol' → 'sol', so the value stays in-cycle and does not * appear as an off-cycle pin. NEVER rewrites the value on disk — only for * display. * * Returns an empty map when the catalog is unknown. * * Pure function, no I/O. */ export function buildPickerNameMap( catalog: ExternalModelCatalog, ): ReadonlyMap { if (!catalog.known) return new Map(); const map = new Map(); for (const model of catalog.models) { const names = pickerNamesFor(model); const [representative] = names; // Canonical id → first picker name (first alias if any, else canonical id) map.set(model.id, representative); // Each picker name → itself (identity, already a picker name) for (const name of names) { map.set(name, name); } } return map; } /** * Build one flat cycle at startup. After the Claude aliases, follow provider * table order and preserve registry order within each provider. The proxy can * be off: the cache still supplies choices for mappings saved before enable. */ export function buildModelCycle( catalog: ExternalModelCatalog, enabled: ReadonlySet, ): readonly string[] { const cycle: string[] = ['default', ...CLAUDE_MODEL_ALIASES]; if (!catalog.known) return cycle; for (const provider of Object.keys(ROUTING_PROVIDERS).filter(isRoutingProviderId)) { if (!enabled.has(provider)) continue; const policy = ROUTING_PROVIDERS[provider]; if (policy.catalog === 'rows') { for (const name of pickerNames(catalog.models.filter(model => model.provider === provider))) { cycle.push(name); } } else if (policy.catalog === 'pool' && catalog.cursorPool !== null) { for (const id of catalog.cursorPool) cycle.push(`${policy.qualifier}${id}`); } } return cycle; } /** * The effort cycle of an agent row: default, the levels in order, then the * `inherit` sentinel (D-SHIPPED-EFFORT). `inherit` sits after the levels so the * forward order of the levels is unchanged. */ export const EFFORT_CYCLE: readonly string[] = ['default', ...EFFORT_LEVELS, EFFORT_INHERIT]; /** * The cycles of a worker row (D-WORKER-AGENTS). A worker takes only Claude * models and has no session effort to inherit, so neither the catalog's external * models nor `inherit` is a stop. Built once at load, never per keypress. */ const WORKER_MODEL_CYCLE: readonly string[] = ['default', ...CLAUDE_MODEL_ALIASES]; const WORKER_EFFORT_CYCLE: readonly string[] = ['default', ...EFFORT_LEVELS]; // Treat the off-cycle pin as a final stop without copying the cycle. export function cycleNext(cycle: readonly string[], current: string, pin: string | null = null): string { const idx = cycle.indexOf(current); if (idx === -1) return cycle[0]; return cycle[idx + 1] ?? pin ?? cycle[0]; } export function cyclePrev(cycle: readonly string[], current: string, pin: string | null = null): string { const idx = cycle.indexOf(current); if (idx > 0) return cycle[idx - 1]; const last = cycle[cycle.length - 1]; if (current === pin) return last; return pin ?? last; } /** * True when `model` is not present in `cycle`. * Named predicate for intent visibility at every call site. */ export function isOffCycle(cycle: readonly string[], model: string): boolean { return !cycle.includes(model); } // --------------------------------------------------------------------------- // Dirty helpers (pure, exported for render and tests) // --------------------------------------------------------------------------- export function isDirtyModel(row: AgentRow): boolean { // Suppress dirty when the selected model matches the saved dormant GPT model — // cycling back to that value is not a change from the persisted mapping entry. if (row.dormantModel !== null && row.configuredModel === row.dormantModel) return false; return row.configuredModel !== row.originalModel; } export function isDirtyEffort(row: AgentRow): boolean { return row.configuredEffort !== row.originalEffort; } /** * The model value that will be persisted to disk for this row. * * For a dirty row: the in-session selection (configuredModel). * For an untouched dormant row: the saved GPT model (dormantModel), which * preserves the mapping entry byte-identical even though configuredModel * shows 'default' while the proxy is off. * For all other untouched rows: configuredModel (which equals originalModel). * * Used by both rowState (STATE column display) and mergeTuiRowsIntoMapping * (save merge) so the two surfaces share a single persisted-value predicate. */ export function persistedModelFor(row: AgentRow): string { return isDirtyModel(row) ? row.configuredModel : (row.dormantModel ?? row.configuredModel); } /** * The effort value that will be persisted to disk for this row. * * For a dirty row: the in-session selection (configuredEffort). * For an untouched row: the original effort (originalEffort). * * Used by both rowState (STATE column display) and mergeTuiRowsIntoMapping * (save merge) so the two surfaces share a single persisted-value predicate. */ export function persistedEffortFor(row: AgentRow): StoredEffort | 'default' { return isDirtyEffort(row) ? row.configuredEffort : row.originalEffort; } /** Count of rows with any dirty field (model OR effort). */ export function unsavedCount(rows: readonly AgentRow[]): number { let count = 0; for (const row of rows) { if (isDirtyModel(row) || isDirtyEffort(row)) count++; } return count; } /** * Classify the live state of a TUI row for display in the STATE column. * * Single source of truth — delegates to classifyAgentState, so the TUI STATE * column and `--list`'s STATE column share one vocabulary and cannot drift. * * The classified value is the model this row WILL persist, which is what makes * the dormancy marker track the KEYPRESS rather than the last save: * - dirty row → configuredModel (the in-session selection) * - untouched row → dormantModel when set, else configuredModel * * The untouched branch exists because mergeTuiRowsIntoMapping writes nothing * for a clean row: its persisted value survives as-is, and for a dormant row * that value lives in dormantModel (configuredModel falls back to 'default' * while the proxy is off). Keying on dormantModel unconditionally would pin * the marker to the pre-edit value — cycling a dormant row onto a live Claude * model would keep showing 'saved-inactive' even though 'opus' is what gets * written. Mirroring the merge rule keeps display and persistence in lockstep. * * A worker row (D-WORKER-AGENTS) has no installed file and cannot be dormant, * so it bypasses classification and is always 'worker'. * * Pure function, no I/O. */ export function rowState(row: AgentRow, proxyEnabled: boolean): AgentState { if (row.worker) return 'worker'; return classifyAgentState({ configured: persistedModelFor(row), proxyEnabled, installed: row.installed, inRegistry: row.inRegistry, }); } // --------------------------------------------------------------------------- // Row and field helpers (pure) — single-row update and cycle direction // --------------------------------------------------------------------------- /** * Return a new rows array with the row at `cursor` replaced by `newRow`. * All other rows are returned by reference (no unnecessary copies). */ function replaceRow( rows: readonly AgentRow[], cursor: number, newRow: AgentRow, ): readonly AgentRow[] { return rows.map((r, i) => (i === cursor ? newRow : r)); } /** * Return a new AgentRow with the named field cycled one step in the given direction. * * Reuse the prebuilt cycle. The saved off-cycle pin stays reachable on its * row without a second cycle array (AC-F4, AC-P6). * * Pure: no I/O, no side effects. */ function cycleField( row: AgentRow, field: 'model' | 'effort', dir: 'forward' | 'backward', modelCycle: readonly string[], ): AgentRow { if (field === 'model') { // A worker row cycles its own Claude-only stops, not the catalog cycle. const baseCycle = row.worker ? WORKER_MODEL_CYCLE : modelCycle; const next = dir === 'forward' ? cycleNext(baseCycle, row.configuredModel, row.offCyclePin) : cyclePrev(baseCycle, row.configuredModel, row.offCyclePin); return { ...row, configuredModel: next }; } else { const effortCycle = row.worker ? WORKER_EFFORT_CYCLE : EFFORT_CYCLE; const next = dir === 'forward' ? cycleNext(effortCycle, row.configuredEffort) : cyclePrev(effortCycle, row.configuredEffort); // Sound narrowing: both effort cycles are built from 'default', EFFORT_LEVELS // and (agents only) the inherit sentinel, so next is always StoredEffort | 'default'. // cycleNext/cyclePrev return string because their signature is intentionally // generic (also used for model cycles). return { ...row, configuredEffort: next as StoredEffort | 'default' }; } } // --------------------------------------------------------------------------- // Viewport adjustment (pure) // --------------------------------------------------------------------------- function adjustViewport( cursor: number, viewportOffset: number, viewportHeight: number, rowCount: number, ): number { if (viewportHeight <= 0 || rowCount === 0) return 0; let offset = viewportOffset; if (cursor < offset) offset = cursor; if (cursor >= offset + viewportHeight) offset = cursor - viewportHeight + 1; const maxOffset = Math.max(0, rowCount - viewportHeight); return Math.max(0, Math.min(offset, maxOffset)); } // --------------------------------------------------------------------------- // buildRow — init helper // --------------------------------------------------------------------------- export interface InitRowInput { name: string; shippedDefault: string; /** Saved model from mapping file (undefined = no entry). */ savedModel?: string; /** Saved effort from mapping file (undefined = no entry). */ savedEffort?: StoredEffort; /** Effort the shipped source carries (undefined = ships none). */ shippedEffort?: EffortLevel; proxyEnabled: boolean; /** * Prebuilt model cycle for off-cycle pin detection. * Optional: omit (or pass []) to disable off-cycle detection. */ modelCycle?: readonly string[]; /** * Map from stored identifier (alias or canonical id) to picker name. * Built by buildPickerNameMap(catalog). When provided, normalizes a stored * canonical id (e.g. 'gpt-6.2-sol') to its alias ('sol') so the configured * model stays in-cycle and does not appear as an off-cycle pin. * NEVER writes the normalized value back to disk. * Optional: omit on the proxy-off / cache-miss path where normalization * has no effect (canonical ids not in the picker cycle become off-cycle pins * which is the correct behavior when the catalog is unknown). */ pickerNameMap?: ReadonlyMap; /** * Whether the agent .md file is present in the install directory. * Required — tsc enumerates every construction site so each caller must decide * the correct value. True for installed agents, false for not-installed agents. * Provided by buildTuiState via readInstalledAgentNames. */ installed: boolean; /** * Whether this agent name exists in the plugin registry. * Required — tsc enumerates every construction site so each caller must decide * the correct value. True for normal registry rows, false for orphan rows * (keys in agent-models.json not present in the registry). */ inRegistry: boolean; /** * True for the row of a background worker (D-WORKER-AGENTS). Optional: omitted * means an ordinary agent row. A worker's off-cycle pin is judged against the * worker model cycle, not the catalog cycle. */ worker?: boolean; } /** * Build an AgentRow from initial mapping state. * * Handles dormancy: if savedModel is an external model and proxy is off, * configuredModel starts as 'default' and dormantModel holds the saved model. * * Handles off-cycle pin: if proxy is on, savedModel is configured, but is * absent from modelCycle (retired/unavailable model), offCyclePin is set so * the model remains reachable in the per-row effective cycle. */ export function buildRow(input: InitRowInput): AgentRow { const worker = input.worker === true; const dormant = isDormantExternalModel(input.savedModel, input.proxyEnabled); const cycle = worker ? WORKER_MODEL_CYCLE : (input.modelCycle ?? []); // Normalize stored canonical id to picker name (Fix 1: in-memory only, never // written back to disk). E.g. 'gpt-6.2-sol' → 'sol' when pickerNameMap is known. // This keeps the value in-cycle so it does not become a spurious off-cycle pin. const normalizedSavedModel = input.savedModel !== undefined && input.pickerNameMap !== undefined ? (input.pickerNameMap.get(input.savedModel) ?? input.savedModel) : input.savedModel; const configuredModel = dormant ? 'default' : (normalizedSavedModel ?? 'default'); const configuredEffort = input.savedEffort ?? 'default'; // Off-cycle pin detection: proxy on, model configured but absent from cycle. // Use the normalized model for cycle lookup — the saved model (pre-norm) for // the pin value so the original identifier is preserved on display. const offCyclePin = !dormant && normalizedSavedModel !== undefined && normalizedSavedModel !== 'default' && cycle.length > 0 && isOffCycle(cycle, normalizedSavedModel) ? normalizedSavedModel : null; return { name: input.name, shippedDefault: input.shippedDefault, shippedEffort: input.shippedEffort, configuredModel, originalModel: configuredModel, configuredEffort, originalEffort: configuredEffort, dormantModel: dormant ? (input.savedModel ?? null) : null, offCyclePin, installed: input.installed, inRegistry: input.inRegistry, worker, }; } // --------------------------------------------------------------------------- // reduce // --------------------------------------------------------------------------- /** * Pure keypress reducer. * * Recognized key strings (normalized by terminal.ts): * 'up', 'down', 'left', 'right', 'k', 'j', 'tab', 'space', * 'd', 'enter', 'escape', 'q', 'ctrl-c' * * Unknown keys → intent 'none', state unchanged (same reference). * * Performance: modelCycle is read from state (prebuilt, startup-constant); * the modelCycle reference is threaded unchanged through every * non-cycle reduce path (AC-P6: Object.is(s1.modelCycle, s2.modelCycle)). */ export function reduce(state: AgentsViewState, key: string): ReduceResult { const { rows, cursor, activeField, viewportOffset, viewportHeight, modelCycle } = state; const n = rows.length; switch (key) { case 'up': case 'k': { if (n === 0) return { state, intent: 'none' }; const newCursor = Math.max(0, cursor - 1); const newOffset = adjustViewport(newCursor, viewportOffset, viewportHeight, n); if (newCursor === cursor && newOffset === viewportOffset) return { state, intent: 'none' }; return { state: { ...state, cursor: newCursor, viewportOffset: newOffset }, intent: 'none', }; } case 'down': case 'j': { if (n === 0) return { state, intent: 'none' }; const newCursor = Math.min(n - 1, cursor + 1); const newOffset = adjustViewport(newCursor, viewportOffset, viewportHeight, n); if (newCursor === cursor && newOffset === viewportOffset) return { state, intent: 'none' }; return { state: { ...state, cursor: newCursor, viewportOffset: newOffset }, intent: 'none', }; } case 'tab': { const newField: 'model' | 'effort' = activeField === 'model' ? 'effort' : 'model'; return { state: { ...state, activeField: newField }, intent: 'none' }; } case 'right': case 'space': { if (n === 0) return { state, intent: 'none' }; const newRow = cycleField(rows[cursor], activeField, 'forward', modelCycle); return { state: { ...state, rows: replaceRow(rows, cursor, newRow) }, intent: 'none', }; } case 'left': { if (n === 0) return { state, intent: 'none' }; const newRow = cycleField(rows[cursor], activeField, 'backward', modelCycle); return { state: { ...state, rows: replaceRow(rows, cursor, newRow) }, intent: 'none', }; } case 'd': { if (n === 0) return { state, intent: 'none' }; const row = rows[cursor]; const newRow: AgentRow = activeField === 'model' ? { ...row, configuredModel: 'default' } : { ...row, configuredEffort: 'default' }; return { state: { ...state, rows: replaceRow(rows, cursor, newRow) }, intent: 'none', }; } case 'enter': { return { state, intent: 'save' }; } case 'escape': case 'q': case 'ctrl-c': { return { state, intent: 'cancel' }; } default: { return { state, intent: 'none' }; } } }