diff --git a/src/plugins/tui/dist/tui.js b/src/plugins/tui/dist/tui.js index dede7651..473cbc22 100644 --- a/src/plugins/tui/dist/tui.js +++ b/src/plugins/tui/dist/tui.js @@ -2705,31 +2705,32 @@ function buildUpdatesTab(input) { }, { id: "update.check", name: isPt ? "Verificar agora" : "Check now", - value: input.checking ? isPt ? "verificando…" : "checking…" : lastCheckMs ? isPt ? `última verificação ${formatAgo(nowMs - lastCheckMs, true)}` : `last check ${formatAgo(nowMs - lastCheckMs, false)}` : isPt ? "nunca verificado" : "never checked", + value: input.checking ? isPt ? "verificando…" : "checking…" : lastCheckMs ? isPt ? `verificado ${formatAgo(nowMs - lastCheckMs, true)}` : `last check ${formatAgo(nowMs - lastCheckMs, false)}` : isPt ? "nunca verificado" : "never checked", action: "update-check", note: isPt ? "enter consulta o registro npm para o canal ativo" : "enter probes the registry for the running channel" }]; - const pluginCommand = channel === "beta" ? "opencode plugin add pantheon-opencode@beta" : "opencode plugin add pantheon-opencode"; + const pluginCommand = `opencode plugin update ${channel === "beta" ? "pantheon-opencode@beta" : "pantheon-opencode"}`; if (latest) { rows.push({ id: "update.latest", name: isPt ? "Registro (npm)" : "Registry", value: newer ? `v${latest} ${isPt ? "disponível" : "available"}` : isPt ? "atualizado" : "up to date", - note: newer ? isPt ? `atualize via \`${pluginCommand}\`` : `update via \`${pluginCommand}\`` : isPt ? "nenhuma versão mais recente compatível" : "no newer compatible version" + ...newer ? { action: "update-run" } : {}, + note: newer ? isPt ? `enter atualiza agora · ou rode \`${pluginCommand}\`` : `enter updates now · or run \`${pluginCommand}\`` : isPt ? "nenhuma versão mais recente compatível" : "no newer compatible version" }); rows.push({ id: "update.run", name: isPt ? "Atualizar plugin" : "Update plugin", - value: input.updating ? isPt ? "atualizando…" : "updating…" : newer ? `${isPt ? "instalar" : "install"} v${latest}` : isPt ? "reinstalar / atualizar" : "reinstall / refresh", + value: input.updating ? isPt ? "atualizando…" : "updating…" : newer ? `${isPt ? "atualizar" : "update"} v${latest}` : isPt ? "reinstalar plugin" : "refresh plugin", action: "update-run", - note: newer ? isPt ? `enter executa \`${pluginCommand}\`` : `enter runs \`${pluginCommand}\`` : isPt ? "enter atualiza o plugin instalado" : "enter refreshes the installed plugin" + note: newer ? isPt ? `enter executa \`${pluginCommand}\` + reload` : `enter runs \`${pluginCommand}\` + reload` : isPt ? "enter força atualização do plugin instalado" : "enter refreshes the installed plugin" }); } rows.push({ id: "update.command", - name: isPt ? "Comando Nativo" : "Plugin Command", - value: pluginCommand, - note: isPt ? "instalação nativa sem npx · funciona global ou no projeto" : "native plugin install (no npx) · works global or per-project" + name: isPt ? "Comando no terminal" : "CLI Command", + value: "opencode plugin update", + note: isPt ? `sem npx: \`${pluginCommand} && opencode reload\`` : `native CLI (no npx): \`${pluginCommand} && opencode reload\`` }); const audit = input.legacyAudit; const legacyRows = [ @@ -2742,7 +2743,7 @@ function buildUpdatesTab(input) { { id: "legacy.scan", name: isPt ? "Escanear obsoletos" : "Scan legacy & drift", - value: input.legacyScanning ? isPt ? "escaneando…" : "scanning…" : isPt ? "verificar global + projeto" : "check global + project", + value: input.legacyScanning ? isPt ? "escaneando…" : "scanning…" : isPt ? "escanear agora" : "scan global + project", action: "legacy-scan", note: isPt ? "enter escaneia sem modificar ou apagar nenhum arquivo" : "enter scans read-only without deleting anything" }, @@ -3197,7 +3198,7 @@ function persistUpdateCheckState(previous, latest) { function resolveRunningVersion() { return "2.2.0-beta.11"; } -const VALUE_WIDTH = 24; +const VALUE_WIDTH = 30; function SettingsWindow(props) { const isPt = () => resolveLanguage(tuiPrefs().layout?.language) === "pt-BR"; const formatValueDisplay = (val) => { @@ -3355,11 +3356,11 @@ function SettingsWindow(props) { props.onSelectRow?.(row.id); } }), true); insertNode(_el$32, _el$33); - setProp(_el$32, "width", 28); + setProp(_el$32, "width", 26); spread(_el$33, mergeProps({ get fg() { return memo(() => !!isSelected())() ? props.warn ?? "#fba970" : props.fg; } }, () => isSelected() ? { attributes: 1 } : {}), true); - insert(_el$33, () => `${gutter()}${row.name}`.padEnd(28)); + insert(_el$33, () => `${gutter()}${row.name}`.padEnd(26)); insert(_el$31, createComponent(Show, { get when() { return memo(() => row.value !== "")() && row.value !== void 0; @@ -3367,7 +3368,7 @@ function SettingsWindow(props) { get children() { var _el$34 = createElement("box"), _el$35 = createElement("text"); insertNode(_el$34, _el$35); - setProp(_el$34, "width", 24); + setProp(_el$34, "width", 30); setProp(_el$34, "onMouseDown", () => { props.onSelectRow?.(row.id); props.onCycleValue?.(row.id, 1); diff --git a/src/plugins/tui/dist/tui.js.map b/src/plugins/tui/dist/tui.js.map index f21ac640..25184244 100644 --- a/src/plugins/tui/dist/tui.js.map +++ b/src/plugins/tui/dist/tui.js.map @@ -1 +1 @@ -{"version":3,"file":"tui.js","names":["numberOrNull","resolveRunningVersion"],"sources":["../src/context-gauge.ts","../src/model-usage-limits.ts","../src/autonomy-state.ts","../src/decision-router-state.ts","../src/pantheon-settings-state.ts","../src/update-notice.ts","../src/doctor-state.ts","../src/settings-i18n.ts","../src/j1-gate-status.ts","../src/legacy-audit.ts","../src/preset-state.ts","../src/quota-state.ts","../src/tui-prefs.ts","../src/update-status.ts","../src/whats-new-highlights.ts","../src/sidebar-width.ts","../src/whats-new-state.ts","../src/whats-new-open.ts"],"sourcesContent":["/** Shared, data-only formatting and visual helpers for compact context gauges. */\n\nexport type ContextProgressTone = 'info' | 'success' | 'warning' | 'error'\n\nexport const CONTEXT_BAR_CELLS = 12\nexport const CONTEXT_BAR_FILLED_CELL = '\\u25B0'\nexport const CONTEXT_BAR_EMPTY_CELL = '\\u25B1'\n\nexport type BarShape = 'block' | 'line' | 'smooth' | 'ascii' | 'dots' | 'braille'\n\nexport interface BarShapeGlyphs {\n filled: string\n empty: string\n mark?: string\n}\n\nexport const BAR_SHAPES: Record = {\n block: { filled: '\\u25B0', empty: '\\u25B1', mark: '│' },\n line: { filled: '━', empty: '─', mark: '┼' },\n smooth: { filled: '█', empty: '░', mark: '┆' },\n ascii: { filled: '=', empty: '-', mark: '|' },\n dots: { filled: '●', empty: '○', mark: '│' },\n braille: { filled: '⣿', empty: '⣀', mark: '⡇' },\n}\n\nexport interface ContextBarOptions {\n cells?: number\n shape?: BarShape\n evenMark?: boolean\n}\n\nfunction numberOrNull(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null\n}\n\nexport function contextUsageTone(percent: number): ContextProgressTone {\n if (percent > 90) return 'error'\n if (percent > 50) return 'warning'\n if (percent > 25) return 'success'\n return 'info'\n}\n\nexport function formatTokenCount(tokens: number | null | undefined): string | null {\n const value = numberOrNull(tokens)\n if (value === null || value < 0) return null\n return Math.round(value).toLocaleString('en-US')\n}\n\nexport function formatContextWindow(limit: number | null | undefined): string | null {\n const value = numberOrNull(limit)\n if (value === null || value <= 0) return null\n if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`\n if (value >= 1_000) return `${Math.floor(value / 1_000)}K`\n return `${Math.floor(value)}`\n}\n\nexport function contextBarFilled(percent: number, cells = CONTEXT_BAR_CELLS): number {\n const total = Math.max(1, Math.floor(cells))\n const filled = Math.round((percent / 100) * total)\n if (!Number.isFinite(filled)) return 0\n return Math.min(total, Math.max(0, filled))\n}\n\nexport function contextBar(\n percent: number | null | undefined,\n options: number | ContextBarOptions = CONTEXT_BAR_CELLS,\n): { filled: string; empty: string } | null {\n const value = numberOrNull(percent)\n if (value === null) return null\n const total = Math.max(\n 1,\n Math.floor(typeof options === 'number' ? options : (options?.cells ?? CONTEXT_BAR_CELLS)),\n )\n const shapeKey =\n typeof options === 'object' && options?.shape && options.shape in BAR_SHAPES\n ? options.shape\n : 'block'\n const glyphs = BAR_SHAPES[shapeKey] ?? BAR_SHAPES.block\n const evenMark = typeof options === 'object' ? Boolean(options?.evenMark) : false\n\n const filledCount = contextBarFilled(value, total)\n const emptyCount = total - filledCount\n\n if (!evenMark || total < 4) {\n return {\n filled: glyphs.filled.repeat(filledCount),\n empty: glyphs.empty.repeat(emptyCount),\n }\n }\n\n // Insert even-use mark at the midpoint (50%)\n const mid = Math.floor(total / 2)\n const mark = glyphs.mark ?? '|'\n\n if (filledCount <= mid) {\n // Mark is in the empty portion\n const emptyBefore = mid - filledCount\n const emptyAfter = Math.max(0, emptyCount - emptyBefore - 1)\n return {\n filled: glyphs.filled.repeat(filledCount),\n empty: `${glyphs.empty.repeat(emptyBefore)}${mark}${glyphs.empty.repeat(emptyAfter)}`,\n }\n }\n\n // Mark is in the filled portion\n const filledBefore = mid\n const filledAfter = Math.max(0, filledCount - filledBefore - 1)\n return {\n filled: `${glyphs.filled.repeat(filledBefore)}${mark}${glyphs.filled.repeat(filledAfter)}`,\n empty: glyphs.empty.repeat(emptyCount),\n }\n}\n\nexport function formatSpent(cost: number | null | undefined): string | null {\n const value = numberOrNull(cost)\n if (value === null || value < 0) return null\n return `$${value.toFixed(2)}`\n}\n","/** Shared bounds for cached recent model-usage aggregation. */\nexport const MODEL_USAGE_VISIBLE_CEILING = 3\nexport const MODEL_USAGE_MESSAGE_LIMIT = 400\nexport const MODEL_USAGE_SESSION_LIMIT = 8\n","/**\n * autonomy-state.ts — the Autonomy tab of the settings window.\n *\n * TUI-local copy doctrine. Two surfaces live here:\n *\n * 1. GOAL LOOP — the persisted-mission loop (Wave 3 mechanics) read/written\n * to `options.goal_loop` in the user's opencode.json (the same V2 config\n * copy the context pruner uses). Startup-applied: the runtime resolves it\n * once at plugin setup, so saving requires an OpenCode restart — the tab\n * says so.\n *\n * 2. DECISION BUDGETS — monthly/per-decision USD caps stored in\n * decision-router.json's companion `decision-budget` semantics. The caps\n * the CLI writes via setup-model flags; here they are read from the\n * decision-router.json envelope extension `budget` (v2 superset — the\n * exact-key validator tolerates it via the documented envelope) and\n * applied live per gated call.\n *\n * The decision-gradiente (decide-solo → Jev → human) is DOCUMENTED here, not\n * enforced: J1 owns the risk axis, budgets own the money axis — this tab\n * shows where the thresholds sit today.\n */\nimport type { SettingsTab } from './pantheon-settings-state.ts'\n\nexport interface GoalLoopPrefs {\n enabled: boolean\n cooldownMs: number\n maxContinuations: number\n}\n\nexport const DEFAULT_GOAL_LOOP_PREFS: GoalLoopPrefs = {\n enabled: false,\n cooldownMs: 5000,\n maxContinuations: 25,\n}\n\nexport const GOAL_LOOP_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const MAX_CONTINUATIONS_CYCLE: readonly string[] = Object.freeze([\n '10',\n '25',\n '50',\n '100',\n '200',\n])\n\nexport const COOLDOWN_MS_CYCLE: readonly string[] = Object.freeze(['1000', '2000', '5000', '10000'])\n\nexport interface DecisionBudgets {\n monthlyUsd: number\n perDecisionUsd: number\n}\n\nexport const DEFAULT_DECISION_BUDGETS: DecisionBudgets = {\n monthlyUsd: 5,\n perDecisionUsd: 0.1,\n}\n\n/** Format USD compactly for a cycler cell (\"$5\", \"$0.10\"). */\nexport function formatUsd(value: number): string {\n return `$${value < 1 ? value.toFixed(2) : String(Math.round(value))}`\n}\n\n/** Build the USD step ladder used by the budget cyclers. */\nexport const MONTHLY_USD_CYCLE: readonly string[] = Object.freeze(\n [1, 2, 5, 10, 20, 50, 100].map((value) => formatUsd(value)),\n)\nexport const PER_DECISION_USD_CYCLE: readonly string[] = Object.freeze(\n [0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1].map((value) => formatUsd(value)),\n)\n\n/** Parse a staged USD cell back to a number; junk keeps the input. */\nexport function parseUsd(cell: string): number | null {\n const value = Number(cell.replace('$', ''))\n return Number.isFinite(value) && value > 0 ? value : null\n}\n\nexport function buildAutonomyTab(input: {\n goalLoop: GoalLoopPrefs\n budgets: DecisionBudgets\n goalLoopRestartPending?: boolean | undefined\n languagePref?: string | undefined\n}): SettingsTab {\n const isPt = input.languagePref === 'pt-BR'\n\n return {\n id: 'autonomy',\n title: isPt ? 'Autonomia' : 'Autonomy',\n groups: [\n {\n title: isPt\n ? 'Loop Contínuo (auto-continuação de sessões multi-turn)'\n : 'Auto-Continue Loop (multi-turn session auto-continuation)',\n rows: [\n {\n id: 'autonomy.goal_loop.enabled',\n name: isPt ? 'Loop Contínuo' : 'Auto-Continue Loop',\n value: input.goalLoop.enabled ? 'enabled' : 'disabled',\n cycle: GOAL_LOOP_ENABLED_CYCLE,\n note: isPt\n ? 'continua tarefas multi-turn quando a sessão fica ociosa' +\n (input.goalLoopRestartPending\n ? ' · [!] reinício necessário para aplicar (restart)'\n : ' · aplicado após reiniciar o OpenCode')\n : 'auto-continues multi-turn tasks when session goes idle' +\n (input.goalLoopRestartPending\n ? ' · [!] restart required to apply'\n : ' · applies after OpenCode restart'),\n },\n {\n id: 'autonomy.goal_loop.maxContinuations',\n name: isPt ? 'Limite continuações' : 'Max continuations',\n value: String(input.goalLoop.maxContinuations),\n cycle: MAX_CONTINUATIONS_CYCLE,\n note: isPt\n ? '1..200 — teto de segurança contra loops infinitos'\n : '1..200 — safety ceiling to prevent runaway tasks',\n },\n {\n id: 'autonomy.goal_loop.cooldownMs',\n name: isPt ? 'Pausa entre turnos (ms)' : 'Cooldown (ms)',\n value: String(input.goalLoop.cooldownMs),\n cycle: COOLDOWN_MS_CYCLE,\n note: isPt\n ? 'intervalo entre turnos autônomos (mín 1000ms)'\n : 'delay between autonomous turns (min 1000ms)',\n },\n ],\n },\n {\n title: isPt ? 'Orçamentos de Decisão (Jev)' : 'Decision Budgets (Jev)',\n rows: [\n {\n id: 'autonomy.budget.monthly',\n name: isPt ? 'Teto Mensal (USD)' : 'Monthly Budget Cap',\n value: formatUsd(input.budgets.monthlyUsd),\n cycle: MONTHLY_USD_CYCLE,\n note: isPt\n ? 'teto mensal em USD para arbitragem do Jev'\n : 'monthly USD ceiling for gated arbitrator decisions',\n },\n {\n id: 'autonomy.budget.perDecision',\n name: isPt ? 'Teto por Consulta' : 'Per-Decision Cap',\n value: formatUsd(input.budgets.perDecisionUsd),\n cycle: PER_DECISION_USD_CYCLE,\n note: isPt\n ? 'teto de custo por decisão — acima disso é recusada'\n : 'price cap — gated decisions above this are refused',\n },\n ],\n },\n {\n title: isPt\n ? 'Gradiente de Decisão (política de referência · governado por J1 e Orçamentos)'\n : 'Decision Gradient (reference policy · governed by J1 & Budgets)',\n rows: [\n {\n id: 'autonomy.gradient.solo',\n name: isPt ? 'Decisão solo' : 'Decide solo',\n value: isPt ? 'autônomo' : 'autonomous',\n note: isPt\n ? 'ações rotineiras de baixo risco · reversível sem travas (sem portão)'\n : 'reversible & low-risk edits, routine fixes (no gate)',\n },\n {\n id: 'autonomy.gradient.jev',\n name: isPt ? 'Decisão Jev' : 'Jev decides',\n value: isPt ? 'arbitrado' : 'arbitrated',\n note: isPt\n ? 'ambiguidade de tipos e rotas · configurado nos Tetos de Orçamento acima'\n : 'typed ambiguity & candidate ranking · configured via Budgets above',\n },\n {\n id: 'autonomy.gradient.human',\n name: isPt ? 'Aprovação humana' : 'Human decides',\n value: isPt ? 'revisão humana' : 'human review',\n note: isPt\n ? 'ações destrutivas e de alto risco · configurado no limiar do Portão J1'\n : 'high-risk & destructive operations · configured via J1 Gate',\n },\n ],\n },\n ],\n }\n}\n","/**\n * decision-router-state.ts — the Decision Model section of the settings window.\n *\n * TUI-local replica of the user-level decision-router config\n * (scripts/install/decision-router-config.mjs — the bundle must stay\n * self-contained); tests/tui-decision-router-state.test.mjs pins the schema\n * version, the exact key set and the provider matrix against that source.\n *\n * The runtime re-reads this file on EVERY gated call (jev-decision-tool.ts),\n * so a write here applies live — no restart. The strict exact-key schema is\n * load-bearing: any unknown key fail-closes the runtime to disabled/local,\n * so the writer validates before persisting.\n *\n * Egress consent is CLI-owned: the window never writes `egress_consent`, and\n * refuses to enable the router while remote candidates exist without it.\n */\nimport { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\n\nexport const DECISION_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const DECISION_CONFIG_SCHEMA_VERSION = 2\n\n/** Exact top-level key set — anything else fail-closes the runtime. */\nexport const DECISION_CONFIG_KEYS: readonly string[] = Object.freeze([\n 'egress_consent',\n 'enabled',\n 'enabled_candidates',\n 'schema_version',\n 'selection',\n])\n\nexport type DecisionSelectionMode = 'local' | 'auto' | 'explicit'\n\nexport interface DecisionSelection {\n mode: DecisionSelectionMode\n provider?: string\n model?: string\n}\n\nexport interface DecisionCandidate {\n provider: string\n model: string\n}\n\nexport interface DecisionRouterConfig {\n schema_version: number\n enabled: boolean\n selection: DecisionSelection\n egress_consent: boolean\n enabled_candidates: readonly DecisionCandidate[]\n}\n\nexport const DEFAULT_DECISION_CONFIG: DecisionRouterConfig = Object.freeze({\n schema_version: DECISION_CONFIG_SCHEMA_VERSION,\n enabled: false,\n selection: Object.freeze({ mode: 'local' as const }),\n egress_consent: false,\n enabled_candidates: Object.freeze([]),\n})\n\n/** The runtime's provider→model matrix (drift-pinned against the installer source). */\nexport const DECISION_KNOWN_PROVIDERS: readonly string[] = Object.freeze([\n 'openai-decisions',\n 'typesafe-jev',\n 'opencode-console-jev',\n 'openrouter-jev',\n 'vercel-gateway-jev',\n 'cloudflare-workers-jev',\n])\n\nexport const DECISION_CONSENT_CYCLE: readonly string[] = Object.freeze(['not granted', 'granted'])\n/** provider → model, straight from the runtime matrix (drift-pinned in tests). */\nexport const DECISION_KNOWN_MODELS: Readonly> = Object.freeze({\n 'openai-decisions': 'gpt-6-luna',\n 'typesafe-jev': 'jev-1.14.0',\n 'opencode-console-jev': 'jev-1.13',\n 'openrouter-jev': 'typesafe/jev-1.13',\n 'vercel-gateway-jev': 'typesafe-ai/jev',\n 'cloudflare-workers-jev': 'clef',\n})\n\n/**\n * Credential surface per provider: the ENV VAR the host provider entry reads\n * (`{env:VAR}` indirection — the window NEVER holds key values) plus the setup\n * note. Drift-pinned against the installer/runtime sources in tests.\n */\nexport const DECISION_PROVIDER_CREDENTIALS: Readonly<\n Record\n> = Object.freeze({\n 'openai-decisions': {\n note: 'host-configured model — provision via `decision-router setup-model openai-decisions`',\n notePt: 'modelo do host — configure via `decision-router setup-model openai-decisions`',\n },\n 'typesafe-jev': {\n env: 'TYPESAFE_API_KEY',\n note: 'export TYPESAFE_API_KEY=… then restart',\n notePt: 'export TYPESAFE_API_KEY=… e depois reinicie',\n },\n 'opencode-console-jev': {\n note: 'rides your OpenCode login — no separate key',\n notePt: 'utiliza login do OpenCode — sem chave separada',\n },\n 'openrouter-jev': {\n env: 'OPENROUTER_API_KEY',\n note: 'export OPENROUTER_API_KEY=… then restart',\n notePt: 'export OPENROUTER_API_KEY=… e depois reinicie',\n },\n 'vercel-gateway-jev': {\n env: 'AI_GATEWAY_API_KEY',\n note: 'export AI_GATEWAY_API_KEY=… then restart',\n notePt: 'export AI_GATEWAY_API_KEY=… e depois reinicie',\n },\n 'cloudflare-workers-jev': {\n env: 'CLOUDFLARE_API_TOKEN',\n note: 'needs accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN',\n notePt: 'requer accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN',\n },\n})\n\nexport const DECISION_TARGET_CYCLE: readonly string[] = Object.freeze(\n DECISION_KNOWN_PROVIDERS.map((provider) => `${provider}/${DECISION_KNOWN_MODELS[provider]}`),\n)\n\nexport function decisionRouterConfigPath(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'pantheon', 'decision-router.json')\n}\n\nexport interface DecisionConfigRead {\n config: DecisionRouterConfig\n /** The file exists but is not a valid v2 config — the runtime fail-closes. */\n corrupt: boolean\n}\n\n/** Fail-open read: a missing file is the default; an invalid one is reported, not guessed. */\nexport function readDecisionRouterConfig(\n env: Record = process.env,\n): DecisionConfigRead {\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(decisionRouterConfigPath(env), 'utf8'))\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') {\n return { config: cloneDefault(), corrupt: false }\n }\n return { config: cloneDefault(), corrupt: true }\n }\n if (isValidDecisionConfig(raw)) return { config: raw, corrupt: false }\n return { config: cloneDefault(), corrupt: true }\n}\n\nfunction cloneDefault(): DecisionRouterConfig {\n return {\n schema_version: DEFAULT_DECISION_CONFIG.schema_version,\n enabled: DEFAULT_DECISION_CONFIG.enabled,\n selection: { ...DEFAULT_DECISION_CONFIG.selection },\n egress_consent: DEFAULT_DECISION_CONFIG.egress_consent,\n enabled_candidates: [...DEFAULT_DECISION_CONFIG.enabled_candidates],\n }\n}\n\n/** The exact-key, exact-shape validation the runtime applies (fail-closed otherwise). */\nexport function isValidDecisionConfig(value: unknown): value is DecisionRouterConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const record = value as Record\n const keys = Object.keys(record).sort()\n if (keys.length !== DECISION_CONFIG_KEYS.length) return false\n for (const key of DECISION_CONFIG_KEYS) {\n if (!keys.includes(key)) return false\n }\n if (record.schema_version !== DECISION_CONFIG_SCHEMA_VERSION) return false\n if (typeof record.enabled !== 'boolean') return false\n if (typeof record.egress_consent !== 'boolean') return false\n if (!isValidSelection(record.selection)) return false\n if (!Array.isArray(record.enabled_candidates)) return false\n for (const candidate of record.enabled_candidates) {\n if (typeof candidate !== 'object' || candidate === null) return false\n const entry = candidate as Record\n if (typeof entry.provider !== 'string' || typeof entry.model !== 'string') return false\n if (Object.keys(entry).length !== 2) return false\n }\n return true\n}\n\nfunction isValidSelection(value: unknown): value is DecisionSelection {\n if (typeof value !== 'object' || value === null) return false\n const selection = value as Record\n if (selection.mode !== 'local' && selection.mode !== 'auto' && selection.mode !== 'explicit') {\n return false\n }\n const keys = Object.keys(selection).sort()\n for (const key of keys) {\n if (key !== 'mode' && key !== 'provider' && key !== 'model') return false\n }\n if (selection.provider !== undefined && typeof selection.provider !== 'string') return false\n if (selection.model !== undefined && typeof selection.model !== 'string') return false\n return true\n}\n\n/** Stable serializer: exact keys in sorted order, 2-space, trailing newline. */\nexport function serializeDecisionConfig(config: DecisionRouterConfig): string {\n const ordered = {\n egress_consent: config.egress_consent,\n enabled: config.enabled,\n enabled_candidates: config.enabled_candidates.map((candidate) => ({\n model: candidate.model,\n provider: candidate.provider,\n })),\n schema_version: config.schema_version,\n selection: {\n mode: config.selection.mode,\n ...(config.selection.model !== undefined ? { model: config.selection.model } : {}),\n ...(config.selection.provider !== undefined ? { provider: config.selection.provider } : {}),\n },\n }\n return `${JSON.stringify(ordered, null, 2)}\\n`\n}\n\n/**\n * Enable/disable the router in a config copy. The guard mirrors the runtime's\n * fail-close: with remote candidates and no egress consent, an enabled flag\n * would be a lie — enabling requires consent, or a local-only selection.\n * Never touches `egress_consent` (CLI-owned).\n */\nexport function setDecisionEnabled(\n config: DecisionRouterConfig,\n enabled: boolean,\n): { ok: true; config: DecisionRouterConfig } | { ok: false; reason: string } {\n if (enabled) {\n const localOnly = config.selection.mode === 'local' || config.enabled_candidates.length === 0\n if (!localOnly && !config.egress_consent) {\n return {\n ok: false,\n reason:\n 'remote candidates need egress consent — toggle Egress consent in this tab, then enable',\n }\n }\n }\n return { ok: true, config: { ...config, enabled } }\n}\n\n/** Atomic-ish write mirroring the canonical writer's privacy posture (0600). */\nexport function writeDecisionRouterConfig(\n config: DecisionRouterConfig,\n env: Record = process.env,\n): void {\n if (!isValidDecisionConfig(config)) {\n throw new TypeError('Refusing to persist an invalid decision-router configuration')\n }\n const path = decisionRouterConfigPath(env)\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 })\n const temp = `${path}.tui.tmp`\n writeFileSync(temp, serializeDecisionConfig(config), { mode: 0o600 })\n renameSync(temp, path)\n chmodSync(path, 0o600)\n}\n\nexport const DECISION_SELECTION_CYCLE: readonly string[] = Object.freeze([\n 'local',\n 'auto',\n 'explicit',\n])\n\n/** Stage a selection/consent row into a config copy; unknown rows are no-ops. */\nexport function applyDecisionRow(\n config: DecisionRouterConfig,\n id: string,\n value: string,\n): DecisionRouterConfig {\n const next: DecisionRouterConfig = {\n ...config,\n selection: { ...config.selection },\n enabled_candidates: [...config.enabled_candidates],\n }\n switch (id) {\n case 'decision.selection.mode': {\n const mode = value as DecisionSelectionMode\n if (mode !== 'local' && mode !== 'auto' && mode !== 'explicit') return config\n next.selection.mode = mode\n if (mode === 'local') next.enabled_candidates = []\n return next\n }\n case 'decision.selection.target': {\n const separator = value.indexOf('/')\n if (separator <= 0) return config\n const provider = value.slice(0, separator)\n const model = value.slice(separator + 1)\n if (!DECISION_KNOWN_PROVIDERS.includes(provider)) return config\n if (DECISION_KNOWN_MODELS[provider] !== model) return config\n next.selection = { mode: 'explicit', provider, model }\n next.enabled_candidates = [{ provider, model }]\n return next\n }\n case 'decision.consent': {\n next.egress_consent = value === 'granted'\n return next\n }\n default:\n return config\n }\n}\n\n/** The host's provider auth store (`opencode auth login` writes here). */\nexport function decisionAuthStorePath(env: Record = process.env) {\n const xdgData = env.XDG_DATA_HOME\n const home = env.HOME ?? ''\n const root = xdgData ?? join(home, '.local', 'share')\n return join(root, 'opencode', 'auth.json')\n}\n\n/** Provider ids as they appear in the host auth store / config providers. */\nconst PROVIDER_AUTH_NAMES: Readonly> = Object.freeze({\n 'openai-decisions': Object.freeze(['openai']),\n 'typesafe-jev': Object.freeze(['typesafe-ai']),\n 'opencode-console-jev': Object.freeze([]),\n 'openrouter-jev': Object.freeze(['openrouter']),\n 'vercel-gateway-jev': Object.freeze(['vercel-ai-gateway', 'vercel']),\n 'cloudflare-workers-jev': Object.freeze(['cloudflare-workers-ai']),\n})\n\nexport type CredentialForm = 'env' | 'auth store' | 'config' | 'missing'\n\n/**\n * TWO recognition forms (field feedback beta.6: keys registered via\n * `opencode auth login` showed MISSING because only env vars were checked):\n * env var set → 'env'; provider present in the host auth store → 'auth\n * store'; provider entry in opencode.json providers → 'config'. Values are\n * NEVER read — existence only.\n */\nexport function credentialStatus(\n provider: string,\n env: Record,\n authProviders: ReadonlySet,\n configProviders: ReadonlySet,\n): CredentialForm {\n const credential = DECISION_PROVIDER_CREDENTIALS[provider]\n if (credential?.env !== undefined && env[credential.env]) return 'env'\n for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) {\n if (authProviders.has(name)) return 'auth store'\n }\n for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) {\n if (configProviders.has(name)) return 'config'\n }\n if (provider === 'opencode-console-jev') return 'auth store'\n return 'missing'\n}\n\nexport function buildDecisionTab(\n read: DecisionConfigRead,\n env: Record = process.env,\n authProviders: ReadonlySet = new Set(),\n configProviders: ReadonlySet = new Set(),\n languagePref?: string | undefined,\n): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const { config, corrupt } = read\n const rows: SettingsRow[] = [\n {\n id: 'decision.enabled',\n name: isPt ? 'Assistente Jev' : 'Jev Assistant',\n value: config.enabled ? 'enabled' : 'disabled',\n // Corrupt config → read-only; the notice (glue) carries the remedy.\n ...(corrupt ? {} : { cycle: DECISION_ENABLED_CYCLE }),\n note: corrupt\n ? isPt\n ? 'config inválida — runtime fail-closes; repare via `decision-router setup-model`'\n : 'config unreadable/invalid — runtime fail-closes; repair via `decision-router setup-model`'\n : isPt\n ? 'aplica em tempo real — arbitragem de decisões relida a cada chamada'\n : 'applies live — the runtime re-reads this on every gated call',\n },\n {\n id: 'decision.selection.mode',\n name: isPt ? 'Modo de Operação' : 'Operation Mode',\n value: config.selection.mode,\n ...(corrupt ? {} : { cycle: DECISION_SELECTION_CYCLE }),\n note: isPt\n ? 'local = no seu PC (grátis); auto/explícito = modelo nuvem (OpenRouter)'\n : 'local routes on-device; auto/explicit pick a remote decision model',\n },\n ]\n\n // Model selection row: always visible so the user can choose the decision model\n const explicitTarget = config.selection.provider\n ? `${config.selection.provider}/${config.selection.model ?? ''}`\n : (DECISION_TARGET_CYCLE[0] ?? 'openrouter-jev/typesafe/jev-1.13')\n rows.push({\n id: 'decision.selection.target',\n name: isPt ? 'Modelo de Decisão' : 'Decision Model',\n value:\n config.selection.mode === 'local'\n ? config.selection.provider\n ? `${config.selection.provider}/${config.selection.model ?? ''}`\n : 'local (on-device)'\n : explicitTarget,\n ...(corrupt ? {} : { cycle: DECISION_TARGET_CYCLE }),\n note: isPt\n ? config.selection.mode === 'local'\n ? 'ciclar seleciona modelo remoto e ativa modo explícito'\n : 'provedor/modelo ativo — define candidato para arbitragem'\n : config.selection.mode === 'local'\n ? 'cycle to select a remote model and activate explicit mode'\n : 'provider/model — sets the candidate list',\n })\n\n if ((config.enabled_candidates?.length ?? 0) > 0) {\n rows.push({\n id: 'decision.candidates',\n name: isPt ? 'Candidatos ativos' : 'Candidates',\n value: String(config.enabled_candidates.length),\n note: config.egress_consent\n ? config.enabled_candidates\n .map((candidate) => `${candidate.provider}/${candidate.model}`)\n .join(', ')\n : isPt\n ? 'egress consent NÃO concedido — rotas remotas bloqueadas'\n : 'egress consent NOT granted — remote routes fail closed',\n })\n }\n\n rows.push({\n id: 'decision.consent',\n name: isPt ? 'Acesso à Nuvem' : 'Cloud API Access',\n value: config.egress_consent ? 'granted' : 'not granted',\n ...(corrupt ? {} : { cycle: DECISION_CONSENT_CYCLE }),\n note: isPt\n ? config.egress_consent\n ? 'granted = rotas remotas podem consultar gateway de API (com teto de custo)'\n : 'not granted = chamadas remotas bloqueadas; requer granted para nuvem'\n : config.egress_consent\n ? 'granted = remote decision routes may call their gateway (budget-capped)'\n : 'not granted = remote routes fail closed; grant to allow cloud calls',\n })\n\n return {\n id: 'decision',\n title: isPt ? 'Decisão' : 'Decision',\n groups: [\n { title: isPt ? 'Assistente de Decisão (Jev)' : 'Decision Assistant (Jev)', rows },\n {\n title: isPt\n ? 'Credenciais (status apenas — valores nunca gravados na janela)'\n : 'Credentials (status only — values never enter the window)',\n rows: DECISION_KNOWN_PROVIDERS.map((provider) => {\n const status = credentialStatus(provider, env, authProviders, configProviders)\n const credential = DECISION_PROVIDER_CREDENTIALS[provider] ?? { note: '' }\n return {\n id: `decision.key.${provider}`,\n name: provider,\n value: status === 'missing' ? 'MISSING' : status,\n note: isPt ? (credential.notePt ?? credential.note) : credential.note,\n }\n }),\n },\n ],\n }\n}\n","/**\n * pantheon-settings-state.ts — the pure state core of the settings window.\n *\n * TUI-local copy doctrine (same as cost-data.ts): the bundle must stay\n * self-contained. The behaviors registry mirrors routing.yml's `behaviors:`\n * (drift-pinned by tests/pantheon-settings-state.test.mjs).\n *\n * Model (2.0.0-beta.4, the quota-style full window): the window is a set of\n * TABS; each tab holds GROUPS of setting ROWS; a row carries a display VALUE\n * and — when the setting is editable — the CYCLE of allowed values that\n * ←/→ steps through. Edits stage into a DRAFT (id → pending value); `save`\n * applies the draft through injected writers, `reset` drops it. The disk\n * never changes before save.\n */\n\nexport interface SettingsBehavior {\n id: string\n kind: 'install' | 'runtime'\n title: string\n description: string\n}\n\n/** Mirrors routing.yml `behaviors:` — drift-pinned by the registry test. */\nexport const SETTINGS_BEHAVIORS: readonly SettingsBehavior[] = Object.freeze([\n {\n id: 'skill-auto-continue',\n kind: 'install',\n title: 'Auto-continue skill',\n description: 'Continue multi-step todos while keeping safety gates.',\n },\n {\n id: 'skill-tdd-with-agents',\n kind: 'install',\n title: 'TDD with agents skill',\n description: 'RED, GREEN, REFACTOR test-driven implementation.',\n },\n {\n id: 'skill-code-review-checklist',\n kind: 'install',\n title: 'Code review checklist skill',\n description: 'Systematic code review and quality gates.',\n },\n {\n id: 'skill-prompt-refinery',\n kind: 'install',\n title: 'Prompt refinery skill',\n description: 'Vague requests refined — silent adjust, >> full contract.',\n },\n {\n id: 'gate-idle-todo-enforcer',\n kind: 'runtime',\n title: 'Idle todo enforcer',\n description: 'Continues pending todos when a session goes idle.',\n },\n {\n id: 'gate-context-pruner',\n kind: 'runtime',\n title: 'Context pruner',\n description: 'Prunes repeated tool output before summarization.',\n },\n {\n id: 'gate-j1-risk-gate',\n kind: 'runtime',\n title: 'J1 risk gate',\n description: 'High-risk tool calls demand explicit human approval.',\n },\n])\n\nexport interface OverrideEntry {\n action: 'disable' | 'replace'\n content?: string\n reason?: string\n}\n\nexport type EffectiveOverrides = Record\n\n/** Which behaviors the settings window can write (runtime + install skills). */\nexport const SETTINGS_TOGGLABLE_IDS = new Set(SETTINGS_BEHAVIORS.map((b) => b.id))\n\nexport function isBehaviorDisabled(effective: EffectiveOverrides, id: string): boolean {\n return effective[id]?.action === 'disable'\n}\n\nexport const TOGGLE_REASON = 'toggled in /pantheon-settings'\n\n/**\n * Toggle (a targeted write keeps the toggle semantics: a `replace` entry is\n * never destroyed — disabling keeps its `content`, re-enabling restores the\n * replace; a settings-written disable is removed outright, no toggle noise).\n */\nexport function toggledOverrides(\n effective: EffectiveOverrides,\n id: string,\n reason: string = TOGGLE_REASON,\n): EffectiveOverrides {\n const next: EffectiveOverrides = { ...effective }\n const entry = next[id]\n if (entry?.action === 'disable') {\n if (entry.content !== undefined) {\n next[id] =\n entry.reason === reason\n ? { action: 'replace', content: entry.content }\n : {\n action: 'replace',\n content: entry.content,\n ...(entry.reason !== undefined ? { reason: entry.reason } : {}),\n }\n } else {\n delete next[id]\n }\n } else {\n next[id] =\n entry?.content !== undefined\n ? { action: 'disable', reason, content: entry.content }\n : { action: 'disable', reason }\n }\n return next\n}\n\n/** Set an explicit on/off target (the cycler's save path) via the toggle semantics. */\nexport function setOverrideState(\n effective: EffectiveOverrides,\n id: string,\n target: 'enabled' | 'disabled',\n reason: string = TOGGLE_REASON,\n): EffectiveOverrides {\n const disabled = isBehaviorDisabled(effective, id)\n if ((target === 'disabled') === disabled) return effective\n return toggledOverrides(effective, id, reason)\n}\n\nexport function serializeOverrides(effective: EffectiveOverrides): string {\n const ordered: Record = {}\n for (const id of Object.keys(effective).sort()) ordered[id] = effective[id]\n return `${JSON.stringify(ordered, null, 2)}\\n`\n}\n\n// ── Overrides load (global + project files) ────────────────────────────\n\nexport interface OverridesLoad {\n global: EffectiveOverrides\n project: EffectiveOverrides\n /** The GLOBAL file exists but does not parse — writes are refused. */\n corruptGlobal: boolean\n}\n\n/** Merge for DISPLAY only, mirroring the runtime precedence: project wins per id. */\nexport function mergedOverrides(load: OverridesLoad): EffectiveOverrides {\n return { ...load.global, ...load.project }\n}\n\nexport function canWriteOverrides(load: OverridesLoad): boolean {\n return !load.corruptGlobal\n}\n\n// ── Tab / group / row model (the cycler window) ────────────────────────\n\nexport interface SettingsRow {\n id: string\n name: string\n /** Current effective value (display); the staged draft may differ. */\n value: string\n /** Allowed values for ←/→; presence marks the row as editable. */\n cycle?: readonly string[]\n /** The row's DEFAULT value — what the Defaults action stages. */\n def?: string\n /** Right-column note (writes-where, applies-live, from-where). */\n note?: string\n /** Enter triggers this action instead of cycling (e.g. `update-check`). */\n action?: string\n}\n\nexport interface SettingsGroup {\n /** Bold group header; undefined renders rows without a header. */\n title?: string\n rows: SettingsRow[]\n}\n\nexport interface SettingsTab {\n id: string\n title: string\n groups: SettingsGroup[]\n}\n\n/** Neutral tab for out-of-range indexes (noUncheckedIndexedAccess guard). */\nexport const EMPTY_TAB: SettingsTab = { id: 'empty', title: '', groups: [] }\n\n/** Flat, in-order rows of a tab (the up/down navigation space). */\nexport function tabRows(tab: SettingsTab): SettingsRow[] {\n return tab.groups.flatMap((group) => group.rows)\n}\n\nexport function findRow(tab: SettingsTab, id: string): SettingsRow | undefined {\n return tabRows(tab).find((row) => row.id === id)\n}\n\n// ── The cycler ─────────────────────────────────────────────────────────\n\n/** Step through the cycle with wrap-around; non-cyclable rows return the input. */\nexport function cycleValue(value: string, cycle: readonly string[], direction: 1 | -1): string {\n if (cycle.length === 0) return value\n const index = cycle.indexOf(value)\n if (index === -1) return cycle[0] ?? value\n const next = (index + direction + cycle.length) % cycle.length\n return cycle[next] ?? value\n}\n\n// ── The draft (staged edits; the disk never changes before save) ───────\n\nexport type SettingsDraft = Record\n\nexport function stageValue(\n draft: SettingsDraft,\n row: SettingsRow,\n direction: 1 | -1,\n): SettingsDraft {\n if (row.cycle === undefined) return draft\n const current = draft[row.id] ?? row.value\n const staged = cycleValue(current, row.cycle, direction)\n if (staged === row.value) {\n // staged back onto the disk value — drop the entry (no toggle noise)\n if (draft[row.id] === undefined) return draft\n const next = { ...draft }\n delete next[row.id]\n return next\n }\n return { ...draft, [row.id]: staged }\n}\n\n/** Stage an explicit target value for one row (the Defaults action path). */\nexport function stageRowToValue(\n draft: SettingsDraft,\n row: SettingsRow,\n target: string,\n): SettingsDraft {\n if (!row.cycle?.includes(target)) return draft\n if (target === row.value) {\n if (draft[row.id] === undefined) return draft\n const next = { ...draft }\n delete next[row.id]\n return next\n }\n return { ...draft, [row.id]: target }\n}\n\n/**\n * Stage every cyclable row's DEFAULT value of a tab. Rows already at their\n * default have their staged entry dropped; rows staged elsewhere keep it\n * until the Defaults action targets them.\n */\nexport function stageDefaults(draft: SettingsDraft, tab: SettingsTab): SettingsDraft {\n let next = draft\n for (const row of tabRows(tab)) {\n if (row.cycle === undefined || row.def === undefined) continue\n const candidate = next[row.id] ?? row.value\n if (candidate === row.def) {\n if (next[row.id] !== undefined) {\n const copy = { ...next }\n delete copy[row.id]\n next = copy\n }\n continue\n }\n next = stageRowToValue(next, { ...row, value: candidate }, row.def)\n }\n return next\n}\n\n/** Drop every staged entry of one tab (ctrl+r). */\nexport function resetTab(draft: SettingsDraft, tab: SettingsTab): SettingsDraft {\n const ids = new Set(tabRows(tab).map((row) => row.id))\n const next: SettingsDraft = {}\n for (const [id, value] of Object.entries(draft)) {\n if (!ids.has(id)) next[id] = value\n }\n return next\n}\n\nexport function draftCount(draft: SettingsDraft): number {\n return Object.keys(draft).length\n}\n\nexport function draftDirty(draft: SettingsDraft): boolean {\n return draftCount(draft) > 0\n}\n\nexport function tabDirty(draft: SettingsDraft, tab: SettingsTab): boolean {\n return tabRows(tab).some((row) => draft[row.id] !== undefined)\n}\n\n// ── Applying the draft ─────────────────────────────────────────────────\n\nexport interface DraftWriterResult {\n ok: boolean\n reason?: string\n}\n\n/**\n * One callback that dispatches a staged row to its real writer (gates →\n * overrides file, decision → decision-router.json, preset → active-preset).\n *Injected by the glue so the disk never runs in tests.\n */\nexport type DraftWriter = (id: string, value: string) => DraftWriterResult\n\nexport interface AppliedDraft {\n applied: string[]\n failed: { id: string; reason: string }[]\n}\n\n/** Apply every staged entry; failures are collected, never thrown. */\nexport function applyDraft(draft: SettingsDraft, writer: DraftWriter): AppliedDraft {\n const applied: string[] = []\n const failed: AppliedDraft['failed'] = []\n for (const [id, value] of Object.entries(draft)) {\n const result = writer(id, value)\n if (result.ok) applied.push(id)\n else failed.push({ id, reason: result.reason ?? 'write failed' })\n }\n return { applied, failed }\n}\n\n/** The rows that succeeded and are still in the draft (failed ones stay staged). */\nexport function settledDraft(draft: SettingsDraft, applied: readonly string[]): SettingsDraft {\n const next: SettingsDraft = {}\n for (const [id, value] of Object.entries(draft)) {\n if (!applied.includes(id)) next[id] = value\n }\n return next\n}\n\n// ── Gates / About tabs (behavior-native; the other tabs live in their modules) ──\n\nexport const GATES_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\nexport type OverridesScope = 'global' | 'project'\nexport const OVERRIDES_SCOPE_CYCLE: readonly OverridesScope[] = Object.freeze(['global', 'project'])\n\nexport function buildGatesTab(\n load: OverridesLoad,\n languagePref?: string,\n overridesScope?: OverridesScope,\n): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const merged = mergedOverrides(load)\n const editingProject = overridesScope === 'project'\n const rowFor = (behavior: SettingsBehavior): SettingsRow => {\n const fromProject = load.project[behavior.id] !== undefined\n const effective = editingProject\n ? isBehaviorDisabled({ ...load.global, ...load.project }, behavior.id)\n : isBehaviorDisabled(load.global, behavior.id)\n const writable = editingProject ? true : !fromProject && canWriteOverrides(load)\n return {\n id: `gate.${behavior.id}`,\n name: fromProject ? `${behavior.title} (${isPt ? 'projeto' : 'project'})` : behavior.title,\n value: (editingProject ? effective : isBehaviorDisabled(merged, behavior.id))\n ? 'disabled'\n : 'enabled',\n ...(writable ? { cycle: GATES_ENABLED_CYCLE } : {}),\n note:\n !editingProject && fromProject\n ? isPt\n ? 'arquivo do projeto tem precedência · edite .pantheon/overrides.json'\n : 'project file wins at runtime — edit .pantheon/overrides.json'\n : editingProject\n ? isPt\n ? 'salva em .pantheon/overrides.json (escopo do projeto)'\n : 'saves to .pantheon/overrides.json (project scope)'\n : behavior.description,\n }\n }\n const install = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === 'install')\n const runtime = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === 'runtime')\n const groups: SettingsGroup[] = []\n if (overridesScope !== undefined) {\n groups.push({\n title: isPt ? 'Escopo das regras' : 'Rules Scope',\n rows: [\n {\n id: 'gates.scope',\n name: isPt ? 'Escopo de edição' : 'Edit scope',\n value: overridesScope,\n cycle: OVERRIDES_SCOPE_CYCLE,\n note: isPt\n ? 'alterne entre global (~/.config/opencode) e projeto (.pantheon)'\n : 'switch between global (~/.config/opencode) and project (.pantheon)',\n },\n ],\n })\n }\n groups.push(\n { title: isPt ? 'Skills instaladas' : 'Install skills', rows: install.map(rowFor) },\n { title: isPt ? 'Portões de execução' : 'Runtime gates', rows: runtime.map(rowFor) },\n )\n return {\n id: 'gates',\n title: 'Gates',\n groups,\n }\n}\n\nexport interface AboutTabExtra {\n nodeVersion?: string\n platform?: string\n preset?: string | null\n decisionEnabled?: boolean\n j1Mode?: string\n languagePref?: string\n}\n\nexport function buildAboutTab(version: string, extra?: AboutTabExtra): SettingsTab {\n const isPt = extra?.languagePref === 'pt-BR'\n\n const sysRows: SettingsRow[] = [\n {\n id: 'about.version',\n name: isPt ? 'Versão' : 'Version',\n value: `v${version}`,\n note: isPt\n ? 'OpenCode 2.x nativo — contrato V1 descontinuado'\n : 'OpenCode 2.x only — the V1 contract is removed',\n },\n {\n id: 'about.behaviors',\n name: isPt ? 'Comportamentos' : 'Behaviors',\n value: String(SETTINGS_BEHAVIORS.length),\n note: isPt\n ? 'portões e skills de governança registradas'\n : 'registered governance gates and skills',\n },\n ]\n\n if (extra?.nodeVersion) {\n sysRows.push({\n id: 'about.runtime',\n name: 'Runtime Node.js',\n value: `v${extra.nodeVersion}`,\n note: extra.platform ? `${isPt ? 'plataforma' : 'platform'}: ${extra.platform}` : '',\n })\n }\n\n const govRows: SettingsRow[] = [\n {\n id: 'about.preset',\n name: isPt ? 'Predefinição' : 'Active Preset',\n value: extra?.preset ?? 'none',\n note: isPt ? 'modelo global ativo do Pantheon' : 'global model preset active in Pantheon',\n },\n {\n id: 'about.decision',\n name: isPt ? 'Assistente Jev' : 'Decision Router',\n value: extra?.decisionEnabled\n ? isPt\n ? 'ativado'\n : 'enabled'\n : isPt\n ? 'desativado'\n : 'disabled',\n note: isPt ? 'arbitragem de modelos e candidatos' : 'model and candidate arbitration',\n },\n {\n id: 'about.j1',\n name: isPt ? 'Portão J1' : 'J1 Risk Gate',\n value: extra?.j1Mode ?? 'shadow',\n note: isPt\n ? 'portão de risco de segurança operacional'\n : 'operational safety risk score gate',\n },\n ]\n\n const refRows: SettingsRow[] = [\n {\n id: 'about.license',\n name: isPt ? 'Licença' : 'License',\n value: 'MIT',\n note: 'Open source · Pantheon Project',\n },\n {\n id: 'about.repo',\n name: isPt ? 'Repositório' : 'Repository',\n value: 'ils15/pantheon-opencode',\n note: 'github.com/ils15/pantheon-opencode',\n },\n ]\n\n const groups = [{ title: isPt ? 'Sistema & Plataforma' : 'System & Platform', rows: sysRows }]\n if (extra?.preset !== undefined || extra?.decisionEnabled !== undefined) {\n groups.push({ title: isPt ? 'Governança & Roteamento' : 'Governance & Routing', rows: govRows })\n }\n groups.push({ title: isPt ? 'Projeto & Referências' : 'Project & References', rows: refRows })\n\n return {\n id: 'about',\n title: isPt ? 'Sobre' : 'About',\n groups,\n }\n}\n\nexport interface ChangelogHighlightItem {\n title: string\n detail: string\n group?: string | undefined\n}\n\nexport function buildChangelogTab(\n version: string,\n items: ChangelogHighlightItem[] = [],\n languagePref?: string | undefined,\n): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n\n const rows: SettingsRow[] = []\n if (items.length > 0) {\n items.forEach((item, index) => {\n rows.push({\n id: `changelog.item.${index + 1}`,\n name: item.title.slice(0, 26),\n value: '',\n note: item.detail,\n })\n })\n } else {\n rows.push({\n id: 'changelog.info',\n name: isPt ? 'Versão' : 'Release',\n value: `v${version}`,\n note: isPt\n ? 'veja o histórico completo no CHANGELOG.md ou no GitHub'\n : 'view full history in CHANGELOG.md or GitHub releases',\n })\n }\n\n return {\n id: 'changelog',\n title: isPt ? 'Changelog' : 'Changelog',\n groups: [\n {\n title: isPt ? `Novidades na versão v${version}` : `What's New in v${version}`,\n rows,\n },\n {\n title: isPt ? 'Referências de Versão' : 'Release References',\n rows: [\n {\n id: 'changelog.docs',\n name: isPt ? 'Documentação' : 'Documentation',\n value: 'CHANGELOG.md',\n note: isPt\n ? 'incluído na raiz do plugin e do repositório'\n : 'shipped at plugin root and repository root',\n },\n {\n id: 'changelog.repo',\n name: isPt ? 'Repositório GitHub' : 'GitHub Repository',\n value: 'ils15/pantheon-opencode',\n note: isPt\n ? 'versões, pull requests e discussões'\n : 'releases, pull requests and discussion',\n },\n ],\n },\n ],\n }\n}\n","/**\n * Update notifier core (TUI-local copy — the bundle must stay self-contained,\n * same precedent as cost-data.ts/model-pricing.ts).\n *\n * Pin + notify, never silent auto-update: one notice per newer version,\n * TTL-cached, offline-safe, and a stable install is never advertised a beta\n * (the update guard owns that crossing). docs/design/2.0-settings-and-install.md\n */\n\nexport const UPDATE_CHECK_TTL_MS = 6 * 60 * 60 * 1000\n\nexport interface UpdateCheckState {\n /** Last version a notice was surfaced for (no repeats per version). */\n lastNotifiedVersion?: string\n /** Last version seen on the registry (persisted across TTL restarts). */\n lastKnownLatestVersion?: string\n /** Last time the registry was queried, for the TTL. */\n lastCheckMs?: number\n}\n\nexport interface UpdateNoticeInput {\n currentVersion: string\n latestVersion: string\n state?: UpdateCheckState\n nowMs?: number\n ttlMs?: number\n isPt?: boolean\n}\n\nexport interface UpdateNotice {\n version: string\n message: string\n}\n\nconst isBetaOrRc = (version: string) => /-(?:beta|rc)\\.\\d+$/.test(String(version).trim())\n\n/** True when `latestVersion` is strictly newer and compatible with `currentVersion` channel. */\nexport function isNewerUpdateAvailable(currentVersion: string, latestVersion: string): boolean {\n const current = String(currentVersion).trim()\n const latest = String(latestVersion).trim()\n if (!current || !latest) return false\n // A stable install is never advertised a prerelease: explicit opt-in owns that crossing.\n if (!isBetaOrRc(current) && isBetaOrRc(latest)) return false\n return comparePantheonVersions(latest, current) > 0\n}\n\n/** Package specifier matching the running release line (`@beta` on prereleases). */\nexport function packageSpecForVersion(version: string): string {\n return isBetaOrRc(version) ? 'pantheon-opencode@beta' : 'pantheon-opencode'\n}\n\n/** Format a bilingual toast title + message for a newly discovered update. */\nexport function formatUpdateToast(\n currentVersion: string,\n latestVersion: string,\n isPt = false,\n): { title: string; message: string } {\n const spec = packageSpecForVersion(currentVersion)\n if (isPt) {\n return {\n title: `Pantheon v${latestVersion} disponível`,\n message: `Atualize em /pantheon-settings (Atualizações) ou \\`opencode plugin update ${spec}\\``,\n }\n }\n return {\n title: `Pantheon v${latestVersion} available`,\n message: `Update in /pantheon-settings (Updates) or \\`opencode plugin update ${spec}\\``,\n }\n}\n\n/** Compact persistent badge rendered in Home footer and Sidebar header when an update exists. */\nexport function formatUpdateBadge(\n currentVersion: string,\n latestVersion: string | null | undefined,\n options: { isPt?: boolean; compact?: boolean } = {},\n): string | null {\n if (!latestVersion || !isNewerUpdateAvailable(currentVersion, latestVersion)) return null\n const version = latestVersion.trim().replace(/^v/i, '')\n if (options.compact) return `↑ v${version} (/pantheon-settings)`\n return options.isPt\n ? `↑ v${version} disponível · /pantheon-settings`\n : `↑ v${version} available · /pantheon-settings`\n}\n\n/** Resolve cached newer version from persisted check state (no network call needed). */\nexport function resolveCachedAvailableUpdate(\n currentVersion: string,\n state: UpdateCheckState | undefined,\n): string | null {\n if (!state) return null\n const candidate = state.lastKnownLatestVersion ?? state.lastNotifiedVersion\n if (!candidate) return null\n return isNewerUpdateAvailable(currentVersion, candidate) ? candidate : null\n}\n\n/** Stamp `lastKnownLatestVersion` onto an `UpdateCheckState` without altering TTL/notice fields. */\nexport function withKnownLatest(\n state: UpdateCheckState,\n latestVersion: string | null,\n): UpdateCheckState {\n if (!latestVersion) return state\n return { ...state, lastKnownLatestVersion: latestVersion }\n}\n\nlet availableUpdateState: string | null = null\nconst availableUpdateListeners = new Set<(version: string | null) => void>()\n\nexport function getAvailableUpdateVersion(): string | null {\n return availableUpdateState\n}\n\nexport function setAvailableUpdateVersion(version: string | null): void {\n const normalized = version && version.trim() !== '' ? version.trim() : null\n if (normalized === availableUpdateState) return\n availableUpdateState = normalized\n for (const listener of availableUpdateListeners) {\n try {\n listener(availableUpdateState)\n } catch {}\n }\n}\n\nexport function subscribeAvailableUpdate(listener: (version: string | null) => void): () => void {\n availableUpdateListeners.add(listener)\n return () => {\n availableUpdateListeners.delete(listener)\n }\n}\n\n/** Semver-ish compare for X.Y.Z[-(beta|rc).N]; prereleases sort before their release. */\nexport function comparePantheonVersions(left: string, right: string): number {\n const parse = (version: string) => {\n const match = String(version)\n .trim()\n .match(/^(\\d+)\\.(\\d+)\\.(\\d+)(?:-(beta|rc)\\.(\\d+))?$/)\n if (!match) return null\n const [, major = '', minor = '', patch = '', stage = '', stageNum = ''] = match\n const stageRank = stage === 'beta' ? 1 : stage === 'rc' ? 2 : 3\n return {\n core: [+major, +minor, +patch] as [number, number, number],\n stageRank,\n stageNum: stage !== '' ? +stageNum : Number.POSITIVE_INFINITY,\n }\n }\n const a = parse(left)\n const b = parse(right)\n if (!a || !b) return 0\n const [aMajor, aMinor, aPatch] = a.core\n const [bMajor, bMinor, bPatch] = b.core\n if (aMajor !== bMajor) return aMajor - bMajor\n if (aMinor !== bMinor) return aMinor - bMinor\n if (aPatch !== bPatch) return aPatch - bPatch\n if (a.stageRank !== b.stageRank) return a.stageRank - b.stageRank\n return a.stageNum - b.stageNum\n}\n\nexport function pickUpdateNotice(input: UpdateNoticeInput): UpdateNotice | null {\n const { currentVersion, latestVersion, state = {}, nowMs = Date.now(), isPt = false } = input\n const ttlMs = input.ttlMs ?? UPDATE_CHECK_TTL_MS\n\n const lastCheck = state.lastCheckMs ?? 0\n if (nowMs - lastCheck < ttlMs) return null\n if (state.lastNotifiedVersion === latestVersion) return null\n if (!isNewerUpdateAvailable(currentVersion, latestVersion)) return null\n\n return {\n version: latestVersion,\n message: formatUpdateToast(currentVersion, latestVersion, isPt).message,\n }\n}\n\n/** The state to persist after a check (notified or not) for the TTL. */\nexport function nextCheckState(\n previous: UpdateCheckState,\n notice: UpdateNotice | null,\n nowMs: number,\n): UpdateCheckState {\n const lastNotifiedVersion = notice?.version ?? previous.lastNotifiedVersion\n return {\n lastCheckMs: nowMs,\n ...(lastNotifiedVersion !== undefined ? { lastNotifiedVersion } : {}),\n }\n}\n","/**\n * doctor-state.ts — the Doctor section of the settings window (read-only).\n *\n * TUI-local replica (the bundle must stay self-contained — the installed copy\n * physically lacks the repo tree, so doctor.mjs itself is unreachable). Only\n * the FILE-DERIVABLE checks are mirrored here; everything that spawns\n * processes, reads the network, or writes (MCP smoke, python validators, git,\n * venv pins, --fix quarantines) stays in the CLI and the section says so.\n *\n * The install-state path mirrors doctor's checkInstallVersionDrift\n * (`/opencode/.pantheon/install-state.json`); the Node floor is\n * drift-pinned against scripts/node-engine-policy.mjs by\n * tests/tui-doctor-state.test.mjs.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { readDecisionRouterConfig } from './decision-router-state.ts'\nimport type { OverridesLoad } from './pantheon-settings-state.ts'\nimport {\n SETTINGS_BEHAVIORS,\n type SettingsRow,\n type SettingsTab,\n} from './pantheon-settings-state.ts'\nimport { comparePantheonVersions } from './update-notice.ts'\n\n/** Drift-pinned against scripts/node-engine-policy.mjs MIN_SUPPORTED_NODE_VERSION. */\nexport const MIN_SUPPORTED_NODE_VERSION = '26.4.0'\n\nexport function opencodePantheonDir(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'opencode', '.pantheon')\n}\n\nexport interface InstallVersionHealth {\n status: 'ok' | 'older' | 'newer' | 'unknown'\n installed: string | null\n}\n\n/**\n * H2: the installed package version (install-state) vs the running one.\n * Fail-open: a missing/unreadable state file means \"unknown\", not a failure —\n * pre-2.0 installs may not have one.\n */\nexport function classifyInstallVersion(\n runningVersion: string,\n env: Record = process.env,\n): InstallVersionHealth {\n let installed: string | null = null\n try {\n const path = join(opencodePantheonDir(env), 'install-state.json')\n const raw = JSON.parse(readFileSync(path, 'utf8')) as { pantheon_version?: unknown }\n if (typeof raw?.pantheon_version === 'string' && raw.pantheon_version !== '') {\n installed = raw.pantheon_version\n }\n } catch {\n installed = null\n }\n if (installed === null) return { status: 'unknown', installed: null }\n const compared = comparePantheonVersions(installed, runningVersion)\n if (compared === 0) return { status: 'ok', installed }\n return { status: compared < 0 ? 'older' : 'newer', installed }\n}\n\nexport function isSupportedNodeFloor(version: string): boolean {\n // Same shape as the canonical parser: a prerelease is outside the floor.\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([^+]+))?(?:\\+([\\w.-]+))?$/.exec(String(version))\n const minimum = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(MIN_SUPPORTED_NODE_VERSION)\n if (!match || !minimum) return false\n const [, major = '', minor = '', patch = '', prerelease = ''] = match\n if (prerelease !== '') return false\n const [, minMajor = '0', minMinor = '0', minPatch = '0'] = minimum\n const currentParts = [+major, +minor, +patch]\n const minimumParts = [+minMajor, +minMinor, +minPatch]\n for (let index = 0; index < 3; index += 1) {\n const currentPart = currentParts[index] ?? 0\n const minimumPart = minimumParts[index] ?? 0\n if (currentPart !== minimumPart) return currentPart > minimumPart\n }\n return true\n}\n\nexport interface OverridesHealth {\n status: 'clean' | 'unknown-ids' | 'corrupt'\n unknownIds: string[]\n}\n\n/** K: validate both overrides files against the window's registry. */\nexport function classifyOverridesHealth(load: OverridesLoad): OverridesHealth {\n if (load.corruptGlobal) return { status: 'corrupt', unknownIds: [] }\n const known = new Set(SETTINGS_BEHAVIORS.map((behavior) => behavior.id))\n const unknownIds = Object.keys({ ...load.global, ...load.project }).filter((id) => !known.has(id))\n return { status: unknownIds.length > 0 ? 'unknown-ids' : 'clean', unknownIds }\n}\n\nexport interface DecisionConfigHealth {\n status: 'ok' | 'corrupt' | 'absent'\n}\n\nexport function classifyDecisionConfigHealth(\n env: Record = process.env,\n): DecisionConfigHealth {\n if (\n !existsSync(\n join(\n env.XDG_CONFIG_HOME ?? join(env.HOME ?? '', '.config'),\n 'pantheon',\n 'decision-router.json',\n ),\n )\n ) {\n return { status: 'absent' }\n }\n return readDecisionRouterConfig(env).corrupt ? { status: 'corrupt' } : { status: 'ok' }\n}\n\nexport interface DoctorSectionInput {\n runningVersion: string\n nodeVersion: string\n load: OverridesLoad\n env?: Record\n}\n\nexport function buildDoctorTab(input: DoctorSectionInput): SettingsTab {\n const env = input.env ?? process.env\n const rows: SettingsRow[] = []\n\n const version = classifyInstallVersion(input.runningVersion, env)\n rows.push({\n id: 'doctor.version',\n name: 'Install version',\n value:\n version.status === 'ok'\n ? `v${version.installed} — matches`\n : version.status === 'older'\n ? `v${version.installed} older`\n : version.status === 'newer'\n ? `v${version.installed} newer`\n : 'unknown',\n note:\n version.status === 'older'\n ? 'refresh with `pantheon-opencode update`'\n : 'read from /opencode/.pantheon/install-state.json',\n })\n\n const nodeOk = isSupportedNodeFloor(input.nodeVersion)\n rows.push({\n id: 'doctor.node',\n name: 'Node runtime',\n value: input.nodeVersion.replace(/^v/, ''),\n note: nodeOk\n ? `meets the >= ${MIN_SUPPORTED_NODE_VERSION} floor`\n : `below the >= ${MIN_SUPPORTED_NODE_VERSION} floor — tooling may refuse`,\n })\n\n const overrides = classifyOverridesHealth(input.load)\n rows.push({\n id: 'doctor.overrides',\n name: 'Overrides',\n value:\n overrides.status === 'clean'\n ? 'valid'\n : overrides.status === 'corrupt'\n ? 'unreadable'\n : `${overrides.unknownIds.length} unknown id(s)`,\n note:\n overrides.status === 'unknown-ids'\n ? `${overrides.unknownIds.join(', ')} — harmless; repair with doctor --fix`\n : overrides.status === 'corrupt'\n ? 'writes are refused until repaired (doctor --fix)'\n : 'both files parse against the behavior registry',\n })\n\n const decision = classifyDecisionConfigHealth(env)\n rows.push({\n id: 'doctor.decision',\n name: 'Decision config',\n value:\n decision.status === 'ok' ? 'valid' : decision.status === 'corrupt' ? 'corrupt' : 'absent',\n note:\n decision.status === 'corrupt'\n ? 'runtime fail-closes to disabled · read from /pantheon/decision-router.json'\n : 'read from /pantheon/decision-router.json',\n })\n\n return {\n id: 'doctor',\n title: 'Doctor',\n groups: [\n {\n title: 'Health (file-derived)',\n rows,\n },\n {\n rows: [\n {\n id: 'doctor.cli',\n name: 'Full check',\n value: '`pantheon-opencode doctor`',\n note: 'MCP smoke, venv pins, git stay in the CLI',\n },\n ],\n },\n ],\n }\n}\n","/**\n * settings-i18n.ts — Bilingual (PT-BR / EN) internationalization for TUI settings.\n *\n * Provides localized titles, labels, and explanations for:\n * - Decision Router & Jev model selection\n * - Autonomy & Budgets\n * - Safety & J1 Risk Gate\n *\n * Automatically detects environment locale (LANG / LC_ALL) while allowing\n * manual override in TUI preferences.\n */\n\nexport type SettingsLanguage = 'auto' | 'pt-BR' | 'en'\n\nexport const SETTINGS_LANGUAGES_CYCLE: readonly string[] = Object.freeze(['auto', 'pt-BR', 'en'])\nexport const SUPPORTED_LANGUAGES = SETTINGS_LANGUAGES_CYCLE\n\n/**\n * Resolve effective language: 'pt-BR' or 'en'.\n * Defaults to 'pt-BR' if system locale contains 'pt', if Intl locale is pt,\n * or if system timezone is Brazilian/Portuguese; otherwise 'en'.\n */\nexport function resolveLanguage(\n preference: string = 'auto',\n env: Record = process.env,\n): 'pt-BR' | 'en' {\n if (preference === 'pt-BR') return 'pt-BR'\n if (preference === 'en') return 'en'\n\n // 1. Auto-detection based on environment locale variables\n const lang = (env.LC_ALL ?? env.LC_MESSAGES ?? env.LANG ?? env.LANGUAGE ?? '').toLowerCase()\n if (lang.startsWith('pt')) return 'pt-BR'\n\n // 2. Auto-detection based on Intl locale\n try {\n const intlLocale = Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()\n if (intlLocale.startsWith('pt')) return 'pt-BR'\n } catch {}\n\n // 3. Auto-detection based on timezone (Brazil & Portugal)\n try {\n const tz = (env.TZ ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? '').toLowerCase()\n if (\n tz.includes('sao_paulo') ||\n tz.includes('brazil') ||\n tz.includes('fortaleza') ||\n tz.includes('recife') ||\n tz.includes('manaus') ||\n tz.includes('belem') ||\n tz.includes('cuiaba') ||\n tz.includes('campo_grande') ||\n tz.includes('porto_velho') ||\n tz.includes('rio_branco') ||\n tz.includes('boa_vista') ||\n tz.includes('maceio') ||\n tz.includes('bahia') ||\n tz.includes('noronha') ||\n tz.includes('araguaina') ||\n tz.includes('santarem') ||\n tz.includes('lisbon') ||\n tz.includes('madeira') ||\n tz.includes('azores')\n ) {\n return 'pt-BR'\n }\n } catch {}\n\n return 'en'\n}\n\nexport interface I18nStringPair {\n en: string\n pt: string\n}\n\nexport const I18N = {\n tabs: {\n decision: { en: 'Decision (Jev)', pt: 'Decisão (Jev)' },\n autonomy: { en: 'Autonomy', pt: 'Autonomia' },\n safety: { en: 'Safety (J1)', pt: 'Segurança (J1)' },\n tui: { en: 'TUI', pt: 'TUI' },\n },\n decision: {\n groupRouter: {\n en: 'Decision Router (Jev Assistant)',\n pt: 'Assistente de Decisão (Jev)',\n },\n groupCredentials: {\n en: 'Credentials (status only — values never enter the window)',\n pt: 'Credenciais (apenas status — valores protegidos)',\n },\n routerName: {\n en: 'Router (Decision Assistant)',\n pt: 'Assistente Jev',\n },\n routerNote: {\n en: 'applies live — enables intelligent route arbitration and candidate ranking',\n pt: 'aplica em tempo real — motor de arbitragem inteligente e ranking de rotas',\n },\n modelName: {\n en: 'Decision model',\n pt: 'Modelo de Decisão',\n },\n modelNote: {\n en: 'local routes on-device (free); auto/explicit pick a remote decision model',\n pt: 'local decide no seu PC (grátis); auto/explícito usa modelo nuvem (OpenRouter)',\n },\n selectionModeName: {\n en: 'Selection mode',\n pt: 'Modo de operação',\n },\n selectionModeNote: {\n en: 'local routes on-device; auto/explicit pick a remote decision model',\n pt: 'local decide no dispositivo; auto/explícito usa modelo remoto',\n },\n egressName: {\n en: 'Cloud API access (Egress)',\n pt: 'Acesso à Nuvem (Egress)',\n },\n egressNoteGranted: {\n en: 'granted = remote decision routes may call their gateway (budget-capped)',\n pt: 'permitido = rotas remotas podem consultar a API (com limite de orçamento)',\n },\n egressNoteNotGranted: {\n en: 'not granted = remote routes blocked; local heuristic decisions only',\n pt: 'não permitido = chamadas remotas bloqueadas; apenas heurística local',\n },\n candidatesName: {\n en: 'Active candidates',\n pt: 'Candidatos ativos',\n },\n },\n autonomy: {\n groupGoalLoop: {\n en: 'Goal loop (multi-turn session auto-continuation)',\n pt: 'Execução Contínua (Goal Loop)',\n },\n goalLoopName: {\n en: 'Goal loop',\n pt: 'Loop contínuo',\n },\n goalLoopNote: {\n en: 'auto-continues multi-turn tasks when session goes idle · applies after OpenCode restart',\n pt: 'continua tarefas de múltiplos passos automaticamente · requer reinício',\n },\n maxContinuationsName: {\n en: 'Max continuations',\n pt: 'Limite de turnos',\n },\n maxContinuationsNote: {\n en: '1..200 — safety ceiling to prevent runaway tasks',\n pt: '1..200 — teto de segurança contra tarefas infinitas',\n },\n cooldownName: {\n en: 'Cooldown (ms)',\n pt: 'Intervalo (ms)',\n },\n cooldownNote: {\n en: 'delay between autonomous turns (min 1000ms)',\n pt: 'tempo de espera entre turnos autônomos (mín 1000ms)',\n },\n groupBudgets: {\n en: 'Decision budgets (applies live per gated call)',\n pt: 'Orçamento Jev (teto financeiro de proteção)',\n },\n monthlyCapName: {\n en: 'Monthly cap',\n pt: 'Teto mensal (USD)',\n },\n monthlyCapNote: {\n en: 'monthly USD ceiling for gated arbitrator decisions',\n pt: 'teto mensal em dólares para decisões do assistente Jev',\n },\n perDecisionCapName: {\n en: 'Per-decision cap',\n pt: 'Teto por consulta (USD)',\n },\n perDecisionCapNote: {\n en: 'price cap — gated decisions above this are refused',\n pt: 'teto por decisão — consultas remotas que excederem são recusadas',\n },\n groupGradient: {\n en: 'Decision gradient (reference policy · J1 owns the risk axis)',\n pt: 'Níveis de Decisão & Segurança (Referência)',\n },\n soloName: {\n en: 'Decide solo',\n pt: 'Decisão direta',\n },\n soloNote: {\n en: 'reversible & low-risk edits, routine fixes (no gate)',\n pt: 'edições reversíveis e baixo risco, sem portão de bloqueio',\n },\n jevName: {\n en: 'Jev decides',\n pt: 'Decisão Jev',\n },\n jevNote: {\n en: 'typed ambiguity & candidate ranking (budget-capped)',\n pt: 'ambiguidade e ranking de skills com teto de orçamento',\n },\n humanName: {\n en: 'Human decides',\n pt: 'Aprovação humana',\n },\n humanNote: {\n en: 'high-risk & destructive operations (J1 gate)',\n pt: 'ações de alto risco e destrutivas (portão de segurança J1)',\n },\n },\n safety: {\n groupSafety: {\n en: 'Safety & Risk Level (J1 Gate)',\n pt: 'Nível de Proteção & Portão de Risco (J1)',\n },\n modeName: {\n en: 'Protection mode',\n pt: 'Modo de proteção',\n },\n thresholdName: {\n en: 'Enforce threshold',\n pt: 'Teto para bloqueio',\n },\n thresholdNote: {\n en: 'deny at or above · 0..1 · default 0.8',\n pt: 'bloqueia em ou acima de · 0..1 · padrão 0.8',\n },\n gateName: {\n en: 'Safety gate',\n pt: 'Portão de segurança',\n },\n },\n} as const\n\n/** Helper to get localized text */\nexport function t(entry: I18nStringPair, lang: 'pt-BR' | 'en'): string {\n return lang === 'pt-BR' ? entry.pt : entry.en\n}\n","/**\n * j1-gate-status.ts — the J1 Risk Gate section of the settings window.\n *\n * TUI-local replica of the ladder in src/pantheon/jev-risk-gate.ts (the\n * bundle must stay self-contained); tests/tui-settings-j1.test.mjs pins the\n * env names, the ladder values and the default threshold against that source.\n *\n * STATUS ONLY by design: the ladder has no file surface yet — mode and\n * threshold are env-only and read once at plugin setup — so nothing here\n * writes, and the section says so. A file surface is a runtime-plugin change\n * (beta.3 candidate), not a window change.\n */\nimport type { SettingsTab } from './pantheon-settings-state.ts'\nimport { resolveLanguage } from './settings-i18n.ts'\n\nexport const J1_FLAG_ENV = 'PANTHEON_J1_RISK_SCORE'\nexport const J1_THRESHOLD_ENV = 'PANTHEON_J1_ENFORCE_THRESHOLD'\nexport const J1_THRESHOLD_DEFAULT = 0.8\n\nexport type J1Mode = 'off' | 'shadow' | 'warn' | 'enforce'\n\n/** `1`/`on`/`true` map to `shadow` for back-compatibility with the shipped setup. */\nconst FLAG_ON = new Set(['1', 'on', 'true', 'shadow'])\n\nexport function j1ModeFromEnv(env: Record = process.env): J1Mode {\n const raw = (env[J1_FLAG_ENV] ?? '').trim().toLowerCase()\n if (raw === 'enforce') return 'enforce'\n if (raw === 'warn') return 'warn'\n return FLAG_ON.has(raw) ? 'shadow' : 'off'\n}\n\n/** Invalid or out-of-range values fall back to the default — a typo must not disable the gate. */\nexport function j1ThresholdFromEnv(env: Record = process.env): number {\n const text = (env[J1_THRESHOLD_ENV] ?? '').trim()\n if (text === '') return J1_THRESHOLD_DEFAULT\n const raw = Number(text)\n if (!Number.isFinite(raw) || raw < 0 || raw > 1) return J1_THRESHOLD_DEFAULT\n return raw\n}\n\nconst MODE_DESCRIPTION_EN: Record = {\n off: 'nothing fires (hard zero)',\n shadow: 'observe + record; invisible in the session',\n warn: 'RESERVED — behaves as shadow in this release',\n enforce: 'high-risk scores DENY the tool call (fail-open on gate unavailability)',\n}\n\nconst MODE_DESCRIPTION_PT: Record = {\n off: 'desativado (hard zero)',\n shadow: 'observa + registra telemetria (modo silencioso)',\n warn: 'RESERVADO (RESERVED) — comporta-se como shadow nesta versão',\n enforce: 'alto risco bloqueia a ferramenta (fail-open se indisponível)',\n}\n\nexport function buildJ1Tab(\n env: Record,\n disabledByOverride: boolean,\n languagePref?: string | undefined,\n): SettingsTab {\n const lang = resolveLanguage(languagePref)\n const isPt = lang === 'pt-BR'\n const mode = j1ModeFromEnv(env)\n const threshold = j1ThresholdFromEnv(env)\n const gateState = disabledByOverride\n ? 'disabled via overrides'\n : mode === 'off'\n ? 'off (env unset)'\n : 'active'\n const desc = isPt ? MODE_DESCRIPTION_PT[mode] : MODE_DESCRIPTION_EN[mode]\n\n return {\n id: 'j1',\n title: isPt ? 'Segurança J1' : 'J1 Safety',\n groups: [\n {\n title: isPt ? 'Portão de Segurança (J1)' : 'Safety Risk Gate (J1)',\n rows: [\n {\n id: 'j1.mode',\n name: isPt ? 'Modo de Operação' : 'Operation Mode',\n value: mode,\n note: `${desc} · ${isPt ? 'reinício necessário (restart applies)' : 'restart applies'}`,\n },\n {\n id: 'j1.threshold',\n name: isPt ? 'Limiar de bloqueio' : 'Enforce threshold',\n value: String(threshold),\n note: isPt\n ? 'bloqueia em ou acima · 0..1 · padrão 0.8'\n : 'deny at or above · 0..1 · default 0.8',\n },\n {\n id: 'j1.gate',\n name: isPt ? 'Portão de Segurança' : 'Safety Risk Gate',\n value: gateState,\n note: `${J1_FLAG_ENV} / ${J1_THRESHOLD_ENV} · ${isPt ? 'lido na inicialização' : 'read once at startup'}`,\n },\n ],\n },\n ],\n }\n}\n","/**\n * legacy-audit.ts — Self-contained Legacy & Drift Auditor for the TUI Settings panel.\n *\n * Scans global (~/.config/opencode) and workspace () scopes for:\n * - Dead V1 hooks/files (pantheon-hooks.*, tiers.json, fastembed_cache, .migration-checkpoint)\n * - Unmigrated legacy stores (memory.db, persistence/{global,project}.db, goals.json)\n * - Redundant copied canonical Pantheon assets shadowed by native plugin transforms\n * - Drifted copied TUI plugins (plugins/pantheon-tui version != running plugin version)\n * - Old configuration backup sidecars (opencode.json.bak*, active-preset.json.bak*)\n *\n * Always migrates unmigrated legacy context/memory/goals BEFORE deleting obsolete stores,\n * and NEVER touches user-created custom agents or custom user skills.\n */\n\nimport {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n realpathSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\n\nexport type LegacyScope = 'global' | 'project'\nexport type LegacyCategory =\n | 'legacyStore'\n | 'hooks'\n | 'v1Obsolete'\n | 'backup'\n | 'redundantAsset'\n | 'drift'\n\nexport interface LegacyAuditItem {\n readonly path: string\n readonly scope: LegacyScope\n readonly category: LegacyCategory\n readonly reason: string\n readonly bytes: number\n}\n\nexport interface LegacyAuditSummary {\n readonly total: number\n readonly totalBytes: number\n readonly unmigratedStores: number\n readonly byScope: Record\n readonly byCategory: Record\n}\n\nexport interface LegacyAuditScan {\n readonly items: LegacyAuditItem[]\n readonly summary: LegacyAuditSummary\n}\n\nexport interface LegacyCleanResult {\n readonly removed: string[]\n readonly reclaimedBytes: number\n readonly migratedRecords: number\n readonly errors: Array<{ readonly path: string; readonly reason: string }>\n}\n\nexport interface LegacyAuditOptions {\n readonly workspaceDir?: string\n readonly globalConfigDir?: string\n readonly runningVersion?: string\n readonly includeRedundantCopiedAssets?: boolean\n readonly env?: Record\n}\n\nconst SAFE_SEGMENT_RE = /^[a-zA-Z0-9._:-]{1,128}$/\n\nconst CANONICAL_AGENT_MD_FILES: readonly string[] = Object.freeze([\n 'aphrodite.md',\n 'apollo.md',\n 'artemis.md',\n 'athena.md',\n 'demeter.md',\n 'gaia.md',\n 'hephaestus.md',\n 'hermes.md',\n 'iris.md',\n 'mnemosyne.md',\n 'nyx.md',\n 'prometheus.md',\n 'talos.md',\n 'themis.md',\n 'zeus.md',\n])\n\nconst CANONICAL_COMMAND_MD_FILES: readonly string[] = Object.freeze([\n 'pantheon.md',\n 'pantheon-audit.md',\n 'pantheon-deepwork.md',\n 'pantheon-focus.md',\n 'pantheon-model.md',\n 'pantheon-optimize.md',\n 'pantheon-settings.md',\n 'pantheon-vision.md',\n])\n\nconst CANONICAL_SKILL_IDS: readonly string[] = Object.freeze([\n 'agent-coordination',\n 'agent-forge',\n 'artifact-management',\n 'auto-continue',\n 'clonedeps',\n 'code-review-checklist',\n 'codemap',\n 'context-compression',\n 'fast-path-execution',\n 'git-workflow-and-versioning',\n 'incremental-implementation',\n 'instruction-forge',\n 'loop-engineering',\n 'memory-bank',\n 'prompt-refinery',\n 'reflect',\n 'security-hardening',\n 'session-goal',\n 'simplify',\n 'spec-driven-development',\n 'tdd-with-agents',\n 'test-slicing',\n 'verification-planning',\n 'visual-review-pipeline',\n 'worktrees',\n])\n\nconst LEGACY_INSTRUCTION_FILES: readonly string[] = Object.freeze([\n 'zeus-execution-rules.instructions.md',\n 'zeus-orchestration.instructions.md',\n 'zeus-workflow.instructions.md',\n])\n\nexport function resolveAuditGlobalDir(\n env: Record = process.env,\n): string | undefined {\n if (env.PANTHEON_HOME?.trim()) return resolve(env.PANTHEON_HOME.trim())\n if (env.XDG_CONFIG_HOME?.trim()) return join(resolve(env.XDG_CONFIG_HOME.trim()), 'opencode')\n if (env.NODE_TEST_CONTEXT) return undefined\n const home = env.HOME?.trim()\n return home ? join(resolve(home), '.config', 'opencode') : undefined\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`\n return `${(bytes / (1024 * 1024)).toFixed(2)} MB`\n}\n\nfunction toSafeSegment(raw: unknown, fallback = 'default'): string {\n const str = String(raw ?? '')\n .trim()\n .replace(/[^a-zA-Z0-9._:-]/g, '_')\n .slice(0, 128)\n if (!str || str === '.' || str === '..' || !SAFE_SEGMENT_RE.test(str)) return fallback\n return str\n}\n\nfunction measurePathBytes(targetPath: string, depth = 0): number {\n if (depth > 8) return 0\n try {\n const st = statSync(targetPath)\n if (st.isFile()) return st.size\n if (!st.isDirectory()) return 0\n let total = 0\n for (const entry of readdirSync(targetPath, { withFileTypes: true })) {\n total += measurePathBytes(join(targetPath, entry.name), depth + 1)\n }\n return total\n } catch {\n return 0\n }\n}\n\nfunction samePath(a: string, b: string): boolean {\n if (resolve(a) === resolve(b)) return true\n if (!existsSync(a) || !existsSync(b)) return false\n try {\n return realpathSync(a) === realpathSync(b)\n } catch {\n return false\n }\n}\n\nfunction isConfinedWithin(rootDir: string, targetPath: string): boolean {\n try {\n const realRoot = realpathSync(rootDir)\n const parentReal = realpathSync(dirname(targetPath))\n return parentReal === realRoot || parentReal.startsWith(`${realRoot}/`)\n } catch {\n return false\n }\n}\n\nfunction countTableRows(db: DatabaseSync, tableName: string): number {\n try {\n const row = db\n .prepare(`SELECT count(*) AS cnt FROM \"${tableName.replace(/\"/g, '\"\"')}\"`)\n .get() as { cnt?: number } | undefined\n return Number(row?.cnt ?? 0)\n } catch {\n return 0\n }\n}\n\nfunction tableExists(db: DatabaseSync, name: string): boolean {\n try {\n const row = db\n .prepare(\"SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name = ?\")\n .get(name) as { name?: string } | undefined\n return Boolean(row?.name)\n } catch {\n return false\n }\n}\n\nfunction collectScopeAudit(\n scope: LegacyScope,\n baseRoot: string,\n configRoot: string,\n options: LegacyAuditOptions,\n): { items: LegacyAuditItem[]; unmigratedStores: number } {\n const items: LegacyAuditItem[] = []\n const seen = new Set()\n let unmigratedStores = 0\n\n const addItem = (filePath: string, category: LegacyCategory, reason: string) => {\n const resolved = resolve(filePath)\n if (seen.has(resolved) || !existsSync(resolved)) return\n seen.add(resolved)\n items.push({\n path: resolved,\n scope,\n category,\n reason,\n bytes: measurePathBytes(resolved),\n })\n }\n\n // 1. Dead V1 hooks & obsolete config files\n for (const hookName of ['pantheon-hooks.ts', 'pantheon-hooks.js', 'pantheon-hooks.mjs']) {\n addItem(join(configRoot, 'plugins', hookName), 'hooks', 'Obsolete OpenCode V1 hook plugin')\n }\n addItem(join(configRoot, 'tiers.json'), 'v1Obsolete', 'Obsolete V1 model tiers registry')\n addItem(join(baseRoot, 'tiers.json'), 'v1Obsolete', 'Obsolete V1 model tiers registry')\n\n const pantheonDir = join(baseRoot, '.pantheon')\n addItem(join(pantheonDir, 'fastembed_cache'), 'v1Obsolete', 'Unused legacy fastembed cache')\n addItem(join(pantheonDir, '.fastembed'), 'v1Obsolete', 'Unused legacy fastembed cache')\n addItem(join(baseRoot, 'fastembed_cache'), 'v1Obsolete', 'Unused legacy fastembed cache')\n addItem(\n join(pantheonDir, '.migration-checkpoint'),\n 'v1Obsolete',\n 'Stale migration checkpoint file',\n )\n\n for (const bakDir of [configRoot, pantheonDir]) {\n if (!existsSync(bakDir)) continue\n try {\n for (const name of readdirSync(bakDir)) {\n if (name.startsWith('opencode.json.bak') || name.startsWith('active-preset.json.bak')) {\n addItem(join(bakDir, name), 'backup', 'Old configuration backup sidecar')\n }\n }\n } catch {\n /* ignore */\n }\n }\n\n // 2. Unmigrated legacy stores\n const legacyFlatMemDb = join(pantheonDir, 'memory.db')\n if (existsSync(legacyFlatMemDb)) {\n unmigratedStores += 1\n addItem(legacyFlatMemDb, 'legacyStore', 'Unmigrated flat .pantheon/memory.db')\n }\n\n const canonicalMemDb = join(pantheonDir, 'memory', 'memory.db')\n if (existsSync(canonicalMemDb)) {\n try {\n const db = new DatabaseSync(canonicalMemDb, { readOnly: true })\n const legacyVecTables = [\n 'memories_vec',\n 'vec_memories',\n 'memory_embeddings',\n 'memory_vectors',\n ]\n const hasLegacyVec = legacyVecTables.some((t) => tableExists(db, t))\n db.close()\n if (hasLegacyVec) {\n unmigratedStores += 1\n items.push({\n path: `${canonicalMemDb}#legacy-vec`,\n scope,\n category: 'legacyStore',\n reason: 'Legacy vector tables pending cleanup in memory.db',\n bytes: 0,\n })\n }\n } catch {\n /* ignore */\n }\n }\n\n for (const dbName of ['global.db', 'project.db']) {\n const persDbPath = join(pantheonDir, 'persistence', dbName)\n if (existsSync(persDbPath)) {\n unmigratedStores += 1\n addItem(persDbPath, 'legacyStore', `Unmigrated persistence/${dbName}`)\n }\n }\n\n const legacyGoalsJson = join(pantheonDir, 'goals.json')\n if (existsSync(legacyGoalsJson)) {\n unmigratedStores += 1\n addItem(legacyGoalsJson, 'legacyStore', 'Unmigrated legacy goals.json')\n }\n\n // 3. Redundant copied Pantheon assets shadowed by native plugin transforms\n if (options.includeRedundantCopiedAssets !== false) {\n for (const agentFile of CANONICAL_AGENT_MD_FILES) {\n addItem(\n join(configRoot, 'agents', agentFile),\n 'redundantAsset',\n 'Canonical Pantheon agent copy shadowed by native plugin transform',\n )\n addItem(\n join(configRoot, 'agent', agentFile),\n 'redundantAsset',\n 'Legacy singular agent copy shadowed by native plugin transform',\n )\n addItem(\n join(configRoot, 'prompts', agentFile),\n 'redundantAsset',\n 'Legacy prompt template copy provided in package',\n )\n }\n\n for (const cmdFile of CANONICAL_COMMAND_MD_FILES) {\n addItem(\n join(configRoot, 'commands', cmdFile),\n 'redundantAsset',\n 'Canonical Pantheon command copy shadowed by native plugin transform',\n )\n addItem(\n join(configRoot, 'command', cmdFile),\n 'redundantAsset',\n 'Legacy singular command directory copy',\n )\n }\n\n for (const instr of LEGACY_INSTRUCTION_FILES) {\n addItem(\n join(configRoot, 'instructions', instr),\n 'redundantAsset',\n 'Legacy instruction file superseded by AGENTS.global.md',\n )\n }\n\n for (const skillId of CANONICAL_SKILL_IDS) {\n addItem(\n join(configRoot, 'skills', skillId),\n 'redundantAsset',\n 'Bundled Pantheon skill directory provided natively by plugin',\n )\n }\n\n const tuiCopyDir = join(configRoot, 'plugins', 'pantheon-tui')\n if (existsSync(tuiCopyDir)) {\n let copiedVersion = ''\n try {\n copiedVersion = String(\n JSON.parse(readFileSync(join(tuiCopyDir, 'package.json'), 'utf8')).version ?? '',\n )\n } catch {\n copiedVersion = ''\n }\n const runningVersion = options.runningVersion ? String(options.runningVersion) : ''\n const drifted = Boolean(runningVersion && copiedVersion && copiedVersion !== runningVersion)\n addItem(\n tuiCopyDir,\n drifted ? 'drift' : 'redundantAsset',\n drifted\n ? `Copied TUI plugin v${copiedVersion} drifts from v${runningVersion}`\n : 'Copied TUI directory superseded by npm package export',\n )\n }\n }\n\n return { items, unmigratedStores }\n}\n\nfunction ensureCanonicalMemoryDb(dbPath: string): DatabaseSync {\n mkdirSync(dirname(dbPath), { recursive: true })\n const db = new DatabaseSync(dbPath)\n db.exec(`\n PRAGMA busy_timeout = 3000;\n PRAGMA journal_mode = WAL;\n CREATE TABLE IF NOT EXISTS memories (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n namespace TEXT NOT NULL DEFAULT 'default',\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n importance REAL NOT NULL DEFAULT 0.5,\n created_at TEXT NOT NULL,\n expires_at TEXT,\n UNIQUE(namespace, key)\n );\n CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(\n key, value, namespace,\n content='memories',\n content_rowid='id'\n );\n CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN\n INSERT INTO memories_fts(rowid, key, value, namespace) VALUES (new.id, new.key, new.value, new.namespace);\n END;\n CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN\n INSERT INTO memories_fts(memories_fts, rowid, key, value, namespace) VALUES('delete', old.id, old.key, old.value, old.namespace);\n END;\n CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN\n INSERT INTO memories_fts(memories_fts, rowid, key, value, namespace) VALUES('delete', old.id, old.key, old.value, old.namespace);\n INSERT INTO memories_fts(rowid, key, value, namespace) VALUES (new.id, new.key, new.value, new.namespace);\n END;\n `)\n return db\n}\n\nfunction migrateScopeBeforeDelete(baseRoot: string): number {\n const pantheonDir = join(baseRoot, '.pantheon')\n if (!existsSync(pantheonDir)) return 0\n let migrated = 0\n const nowIso = new Date().toISOString()\n\n // 1. Migrate flat .pantheon/memory.db -> .pantheon/memory/memory.db + drop legacy vector tables\n const flatMemDbPath = join(pantheonDir, 'memory.db')\n const canonicalMemPath = join(pantheonDir, 'memory', 'memory.db')\n if (existsSync(flatMemDbPath)) {\n try {\n const src = new DatabaseSync(flatMemDbPath, { readOnly: true })\n const dst = ensureCanonicalMemoryDb(canonicalMemPath)\n if (tableExists(src, 'memories')) {\n const rows = src\n .prepare('SELECT namespace, key, value, created_at FROM memories')\n .all() as Array<{\n namespace?: string\n key?: string\n value?: string\n created_at?: string\n }>\n const insert = dst.prepare(\n 'INSERT OR IGNORE INTO memories (namespace, key, value, importance, created_at) VALUES (?, ?, ?, ?, ?)',\n )\n dst.exec('BEGIN IMMEDIATE')\n try {\n for (const r of rows) {\n insert.run(\n String(r.namespace ?? 'default'),\n String(r.key ?? ''),\n String(r.value ?? ''),\n 0.5,\n String(r.created_at ?? nowIso),\n )\n migrated += 1\n }\n dst.exec('COMMIT')\n } catch (txErr) {\n try {\n dst.exec('ROLLBACK')\n } catch {\n /* ignore */\n }\n throw txErr\n }\n }\n src.close()\n dst.close()\n } catch {\n /* fail-open */\n }\n }\n\n if (existsSync(canonicalMemPath)) {\n try {\n const db = ensureCanonicalMemoryDb(canonicalMemPath)\n for (const trig of ['memories_vec_ai', 'memories_vec_ad', 'memories_vec_au']) {\n db.exec(`DROP TRIGGER IF EXISTS ${trig}`)\n }\n for (const tbl of ['memories_vec', 'vec_memories', 'memory_embeddings', 'memory_vectors']) {\n if (tableExists(db, tbl)) {\n db.exec(`DROP TABLE IF EXISTS ${tbl}`)\n migrated += 1\n }\n }\n db.close()\n } catch {\n /* fail-open */\n }\n }\n\n // 2. Migrate persistence/{global,project}.db -> persistence//.json\n const persDir = join(pantheonDir, 'persistence')\n for (const dbName of ['global.db', 'project.db']) {\n const dbPath = join(persDir, dbName)\n if (!existsSync(dbPath)) continue\n try {\n const db = new DatabaseSync(dbPath, { readOnly: true })\n for (const tbl of ['kv', 'kv_store', 'context', 'checkpoints', 'sessions']) {\n if (!tableExists(db, tbl) || countTableRows(db, tbl) === 0) continue\n const cols = db.prepare(`PRAGMA table_info(${tbl})`).all() as Array<{ name: string }>\n const colNames = new Set(cols.map((c) => c.name))\n const keyCol = colNames.has('key')\n ? 'key'\n : colNames.has('id')\n ? 'id'\n : colNames.has('session_id')\n ? 'session_id'\n : null\n const valCol = colNames.has('value')\n ? 'value'\n : colNames.has('data')\n ? 'data'\n : colNames.has('content')\n ? 'content'\n : null\n if (!keyCol || !valCol) continue\n const nsSelect = colNames.has('namespace')\n ? 'namespace'\n : `'${tbl === 'checkpoints' || tbl === 'sessions' ? 'checkpoints' : 'default'}' AS namespace`\n const rows = db\n .prepare(`SELECT ${nsSelect}, ${keyCol} AS k, ${valCol} AS v FROM ${tbl}`)\n .all() as Array<{\n namespace?: string\n k?: string\n v?: unknown\n }>\n for (const r of rows) {\n const ns = toSafeSegment(r.namespace, 'default')\n const key = toSafeSegment(r.k, '')\n if (!key) continue\n const targetDir = join(persDir, ns)\n const targetFile = join(targetDir, `${key}.json`)\n if (!existsSync(targetFile)) {\n mkdirSync(targetDir, { recursive: true })\n writeFileSync(\n targetFile,\n JSON.stringify(\n { key, namespace: ns, value: String(r.v ?? ''), updated_at: nowIso },\n null,\n 2,\n ),\n 'utf8',\n )\n migrated += 1\n }\n }\n }\n db.close()\n } catch {\n /* fail-open */\n }\n }\n\n // 3. Migrate legacy goals.json -> .pantheon/goals/.json\n const legacyGoalsPath = join(pantheonDir, 'goals.json')\n if (existsSync(legacyGoalsPath)) {\n try {\n const parsed = JSON.parse(readFileSync(legacyGoalsPath, 'utf8')) as unknown\n const list = Array.isArray(parsed)\n ? parsed\n : parsed &&\n typeof parsed === 'object' &&\n Array.isArray((parsed as { goals?: unknown }).goals)\n ? ((parsed as { goals: unknown[] }).goals ?? [])\n : []\n const goalsDir = join(pantheonDir, 'goals')\n for (const item of list) {\n if (!item || typeof item !== 'object') continue\n const rec = item as Record\n const safeId = toSafeSegment(rec.id ?? rec.goal_id, '')\n if (!safeId) continue\n const target = join(goalsDir, `${safeId}.json`)\n if (!existsSync(target)) {\n mkdirSync(goalsDir, { recursive: true })\n writeFileSync(\n target,\n JSON.stringify(\n {\n id: safeId,\n title: String(rec.title ?? rec.description ?? ''),\n criteria: Array.isArray(rec.criteria) ? rec.criteria.map(String) : [],\n status: String(rec.status ?? 'active'),\n created_at: typeof rec.created_at === 'string' ? rec.created_at : nowIso,\n updated_at: typeof rec.updated_at === 'string' ? rec.updated_at : nowIso,\n },\n null,\n 2,\n ),\n 'utf8',\n )\n migrated += 1\n }\n }\n } catch {\n /* fail-open */\n }\n }\n\n return migrated\n}\n\nexport function scanLegacyArtifacts(options: LegacyAuditOptions = {}): LegacyAuditScan {\n const workspaceDir = options.workspaceDir ? resolve(options.workspaceDir) : undefined\n const globalConfigDir = options.globalConfigDir\n ? resolve(options.globalConfigDir)\n : resolveAuditGlobalDir(options.env)\n\n const items: LegacyAuditItem[] = []\n let unmigratedStores = 0\n\n if (globalConfigDir && existsSync(globalConfigDir) && globalConfigDir !== '/') {\n const res = collectScopeAudit('global', globalConfigDir, globalConfigDir, options)\n items.push(...res.items)\n unmigratedStores += res.unmigratedStores\n }\n\n if (\n workspaceDir &&\n existsSync(workspaceDir) &&\n workspaceDir !== '/' &&\n (!globalConfigDir || !samePath(workspaceDir, globalConfigDir))\n ) {\n const res = collectScopeAudit('project', workspaceDir, join(workspaceDir, '.opencode'), options)\n items.push(...res.items)\n unmigratedStores += res.unmigratedStores\n }\n\n const byScope: Record = { global: 0, project: 0 }\n const byCategory: Record = {}\n let totalBytes = 0\n for (const item of items) {\n byScope[item.scope] = (byScope[item.scope] ?? 0) + 1\n byCategory[item.category] = (byCategory[item.category] ?? 0) + 1\n totalBytes += item.bytes\n }\n\n return {\n items,\n summary: {\n total: items.length,\n totalBytes,\n unmigratedStores,\n byScope,\n byCategory,\n },\n }\n}\n\nexport function cleanLegacyArtifacts(\n options: LegacyAuditOptions & { readonly scope?: 'all' | LegacyScope } = {},\n): LegacyCleanResult {\n const workspaceDir = options.workspaceDir ? resolve(options.workspaceDir) : undefined\n const globalConfigDir = options.globalConfigDir\n ? resolve(options.globalConfigDir)\n : resolveAuditGlobalDir(options.env)\n const scopeFilter = options.scope && options.scope !== 'all' ? options.scope : null\n\n const scan = scanLegacyArtifacts(options)\n let migratedRecords = 0\n\n if (\n scopeFilter !== 'project' &&\n globalConfigDir &&\n existsSync(globalConfigDir) &&\n globalConfigDir !== '/'\n ) {\n migratedRecords += migrateScopeBeforeDelete(globalConfigDir)\n }\n if (\n scopeFilter !== 'global' &&\n workspaceDir &&\n existsSync(workspaceDir) &&\n workspaceDir !== '/' &&\n (!globalConfigDir || !samePath(workspaceDir, globalConfigDir))\n ) {\n migratedRecords += migrateScopeBeforeDelete(workspaceDir)\n }\n\n const removed: string[] = []\n const errors: Array<{ readonly path: string; readonly reason: string }> = []\n let reclaimedBytes = 0\n\n for (const item of scan.items) {\n if (scopeFilter && item.scope !== scopeFilter) continue\n if (item.path.endsWith('#legacy-vec')) {\n removed.push(item.path)\n continue\n }\n const scopeRoot = item.scope === 'global' ? globalConfigDir : workspaceDir\n if (!scopeRoot || !isConfinedWithin(scopeRoot, item.path)) {\n errors.push({ path: item.path, reason: 'Path escapes target scope root' })\n continue\n }\n try {\n if (existsSync(item.path)) {\n rmSync(item.path, { recursive: true, force: true })\n removed.push(item.path)\n reclaimedBytes += item.bytes\n }\n if (item.path.endsWith('.db')) {\n for (const suffix of ['-wal', '-shm', '-journal']) {\n const sidecar = `${item.path}${suffix}`\n if (existsSync(sidecar) && isConfinedWithin(scopeRoot, sidecar)) {\n const sidecarBytes = measurePathBytes(sidecar)\n rmSync(sidecar, { force: true })\n removed.push(sidecar)\n reclaimedBytes += sidecarBytes\n }\n }\n }\n } catch (err) {\n errors.push({\n path: item.path,\n reason: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n return {\n removed,\n reclaimedBytes,\n migratedRecords,\n errors,\n }\n}\n","/**\n * preset-state.ts — the Model Preset section of the settings window.\n *\n * TUI-local replica (the bundle must stay self-contained). The preset NAMES\n * mirror routing.yml's `presets:` and are drift-pinned by\n * tests/tui-preset-state.test.mjs against `loadPresetDefs()`. The marker file\n * shape mirrors scripts/install/model-picker.mjs's `buildActivePresetFile`\n * (version 1), and the readers (`resolveActivePreset`, vision.ts candidates)\n * only consult `.preset`, so the window writes `source: 'tui-settings'`.\n *\n * Scope note: the window writes the GLOBAL marker only\n * (`/opencode/.pantheon/active-preset.json`). A project marker\n * wins (it precedes the global path in every runtime candidate list), so it\n * is displayed read-only. `none` DELETES the marker with a .bak backup — the\n * same contract as the CLI's `set-tier none`.\n */\nimport {\n copyFileSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\n\n/** Mirrors routing.yml `presets:` — drift-pinned against loadPresetDefs(). */\nexport const PRESET_NAMES: readonly string[] = Object.freeze([\n 'go-free',\n 'go-fast',\n 'go-premium',\n 'go-hybrid',\n 'anthropic',\n 'openai',\n])\n\nexport interface ActivePresetMarker {\n version: number\n preset: string\n source: string\n updated_at: string\n}\n\nexport function globalActivePresetPath(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'opencode', '.pantheon', 'active-preset.json')\n}\n\nexport function projectActivePresetPath() {\n return join(process.cwd(), '.pantheon', 'active-preset.json')\n}\n\n/** Fail-open read: missing/corrupt marker = no active preset. */\nexport function readActivePresetMarker(path: string): { name: string; updatedAt: string } | null {\n try {\n const raw = JSON.parse(readFileSync(path, 'utf8')) as { preset?: unknown; updated_at?: unknown }\n if (typeof raw?.preset !== 'string' || raw.preset === '' || raw.preset === 'none') return null\n return {\n name: raw.preset,\n updatedAt: typeof raw.updated_at === 'string' ? raw.updated_at : '',\n }\n } catch {\n return null\n }\n}\n\nfunction writeMarkerAtomically(path: string, content: string): void {\n mkdirSync(dirname(path), { recursive: true })\n const temp = `${path}.tui.tmp`\n writeFileSync(temp, content)\n renameSync(temp, path)\n}\n\n/** Select a preset globally: .bak backup, atomic write, version-1 marker. */\nexport function writeActivePreset(\n path: string,\n name: string,\n nowIso = new Date().toISOString(),\n): void {\n if (!PRESET_NAMES.includes(name)) {\n throw new TypeError(`Refusing to persist unknown preset \"${name}\"`)\n }\n backupMarker(path)\n const marker: ActivePresetMarker = {\n version: 1,\n preset: name,\n source: 'tui-settings',\n updated_at: nowIso,\n }\n writeMarkerAtomically(path, `${JSON.stringify(marker, null, 2)}\\n`)\n}\n\n/** Clear the global marker (the `none` contract): .bak backup, then remove. */\nexport function clearActivePreset(path: string): void {\n backupMarker(path)\n rmSync(path, { force: true })\n}\n\nfunction backupMarker(path: string): void {\n if (!existsSync(path)) return\n mkdirSync(dirname(path), { recursive: true })\n copyFileSync(path, `${path}.bak`)\n}\n\nexport const VISION_MODEL_OPTIONS: readonly string[] = Object.freeze([\n 'auto',\n 'opencode-go/mimo-v2.6-flash',\n 'google/gemini-2.5-flash',\n 'openai/gpt-5-mini',\n 'anthropic/claude-3-5-haiku',\n 'opencode-go/mimo-v2.5',\n])\n\nexport function visionConfigPaths(\n cwd = process.cwd(),\n env: Record = process.env,\n): string[] {\n const home = env.HOME ?? ''\n const xdg = env.XDG_CONFIG_HOME ?? join(home, '.config')\n return [\n join(cwd, '.opencode', 'opencode-vision.json'),\n join(xdg, 'opencode', 'opencode-vision.json'),\n ]\n}\n\nexport function readConfiguredVisionModel(\n cwd = process.cwd(),\n env: Record = process.env,\n): string {\n for (const path of visionConfigPaths(cwd, env)) {\n try {\n if (existsSync(path)) {\n const parsed = JSON.parse(readFileSync(path, 'utf8')) as { visionModel?: unknown }\n if (typeof parsed?.visionModel === 'string' && parsed.visionModel.trim()) {\n return parsed.visionModel.trim()\n }\n }\n } catch {\n // ignore corrupt/missing\n }\n }\n return 'auto'\n}\n\nexport function writeConfiguredVisionModel(\n model: string,\n cwd = process.cwd(),\n env: Record = process.env,\n): void {\n const home = env.HOME ?? ''\n const xdg = env.XDG_CONFIG_HOME ?? join(home, '.config')\n const projectDir = join(cwd, '.opencode')\n const targetPath = existsSync(projectDir)\n ? join(projectDir, 'opencode-vision.json')\n : join(xdg, 'opencode', 'opencode-vision.json')\n\n let current: Record = {}\n try {\n if (existsSync(targetPath)) {\n current = JSON.parse(readFileSync(targetPath, 'utf8')) as Record\n }\n } catch {\n current = {}\n }\n\n if (model === 'auto' || !model.trim()) {\n delete current.visionModel\n } else {\n current.visionModel = model.trim()\n }\n\n mkdirSync(dirname(targetPath), { recursive: true })\n const temp = `${targetPath}.tui.tmp`\n writeFileSync(temp, `${JSON.stringify(current, null, 2)}\\n`, 'utf8')\n renameSync(temp, targetPath)\n}\n\nexport interface PresetSectionInput {\n globalName: string | null\n projectName: string | null\n visionModel?: string\n}\n\n/** The staged value 'none' means: delete the global marker (the CLI contract). */\nexport const PRESET_NONE = 'none'\n\nexport const PRESET_CYCLE: readonly string[] = Object.freeze([PRESET_NONE, ...PRESET_NAMES])\n\nexport function buildPresetTab(input: PresetSectionInput, languagePref?: string): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const rows: SettingsRow[] = [\n {\n id: 'preset',\n name: isPt ? 'Predefinição' : 'Preset',\n value: input.globalName ?? PRESET_NONE,\n cycle: PRESET_CYCLE,\n note: isPt\n ? 'marcador global · gravação atômica, backup .bak · none = padrão OpenCode'\n : 'global marker · atomic write, .bak backup · none = opencode defaults',\n },\n ]\n if (input.projectName !== null) {\n rows.push({\n id: 'preset.project',\n name: isPt ? 'Projeto' : 'Project',\n value: input.projectName,\n note: isPt\n ? `${projectActivePresetPath()} tem precedência sobre o global — somente leitura aqui`\n : `${projectActivePresetPath()} wins over the global marker — read-only here`,\n })\n }\n if (input.visionModel !== undefined) {\n rows.push({\n id: 'preset.vision_model',\n name: isPt ? 'Modelo de Visão' : 'Vision Model',\n value: input.visionModel || 'auto',\n cycle: VISION_MODEL_OPTIONS,\n note: isPt\n ? 'modelo para inspeção de imagens (vision_describe) · salvo em opencode-vision.json'\n : 'model for image inspection (vision_describe) · saved in opencode-vision.json',\n })\n }\n return {\n id: 'preset',\n title: 'Preset',\n groups: [{ title: isPt ? 'Predefinição de modelo' : 'Model preset', rows }],\n }\n}\n","/**\n * quota-state.ts — the Quotas & Spend tab (inspired by opencode-quota).\n *\n * Exposes live model token spending, daily budgets, rate-limits per provider,\n * and context token telemetry in a dedicated tab in the Pantheon Settings window.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport type { SettingsTab } from './pantheon-settings-state.ts'\nimport { resolveLanguage } from './settings-i18n.ts'\n\nexport interface QuotaSnapshot {\n todaySpend?: string\n monthSpend?: string\n sessionSpend?: string\n sessionTokens?: string\n cacheHit?: string\n speed?: string\n}\n\nexport interface QuotaPrefs {\n sessionCap: string\n alertThreshold: 'enabled' | 'disabled'\n autoCompact: 'enabled' | 'disabled'\n}\n\nexport const DEFAULT_QUOTA_PREFS: QuotaPrefs = {\n sessionCap: '$5.00',\n alertThreshold: 'enabled',\n autoCompact: 'enabled',\n}\n\nexport function resolveQuotaPrefsPath(): string {\n const xdg = process.env.XDG_CONFIG_HOME\n const base = xdg?.startsWith('/') ? xdg : join(homedir(), '.config')\n return join(base, 'opencode', 'pantheon-quota.json')\n}\n\nexport function readQuotaPrefs(filePath = resolveQuotaPrefsPath()): QuotaPrefs {\n try {\n if (!existsSync(filePath)) return { ...DEFAULT_QUOTA_PREFS }\n const raw = JSON.parse(readFileSync(filePath, 'utf8')) as Partial\n return {\n sessionCap:\n typeof raw.sessionCap === 'string' &&\n ['$1.00', '$2.00', '$5.00', '$10.00', 'unlimited'].includes(raw.sessionCap)\n ? raw.sessionCap\n : DEFAULT_QUOTA_PREFS.sessionCap,\n alertThreshold: raw.alertThreshold === 'disabled' ? 'disabled' : 'enabled',\n autoCompact: raw.autoCompact === 'disabled' ? 'disabled' : 'enabled',\n }\n } catch {\n return { ...DEFAULT_QUOTA_PREFS }\n }\n}\n\nexport function writeQuotaPrefs(prefs: QuotaPrefs, filePath = resolveQuotaPrefsPath()): void {\n mkdirSync(dirname(filePath), { recursive: true })\n writeFileSync(filePath, `${JSON.stringify(prefs, null, 2)}\\n`, 'utf8')\n}\n\nexport function applyQuotaRow(prefs: QuotaPrefs, id: string, value: string): QuotaPrefs {\n const next = { ...prefs }\n if (id === 'quota.budget.sessionCap') {\n if (['$1.00', '$2.00', '$5.00', '$10.00', 'unlimited'].includes(value)) {\n next.sessionCap = value\n }\n } else if (id === 'quota.budget.alertThreshold') {\n next.alertThreshold = value === 'disabled' ? 'disabled' : 'enabled'\n } else if (id === 'quota.compaction.auto') {\n next.autoCompact = value === 'disabled' ? 'disabled' : 'enabled'\n }\n return next\n}\n\nexport function buildQuotaTab(\n snapshot?: QuotaSnapshot,\n languagePref?: string,\n prefs: QuotaPrefs = readQuotaPrefs(),\n): SettingsTab {\n const isPt = resolveLanguage(languagePref) === 'pt-BR'\n\n return {\n id: 'quota',\n title: isPt ? 'Cotas & Gastos' : 'Quotas & Spend',\n groups: [\n {\n title: isPt ? 'Consumo & Gastos de Sessão' : 'Session Spend & Tokens',\n rows: [\n {\n id: 'quota.spend.today',\n name: isPt ? 'Gasto hoje (00h-agora)' : 'Spend today (00h-now)',\n value: snapshot?.todaySpend ?? '—',\n note: isPt ? 'Calculado a partir de opencode.db' : 'Derived from opencode.db ledger',\n },\n {\n id: 'quota.spend.month',\n name: isPt ? 'Gasto acumulado (30d)' : 'Spend last 30 days',\n value: snapshot?.monthSpend ?? '—',\n note: isPt ? 'Janela móvel de 30 dias' : 'Rolling 30-day window',\n },\n {\n id: 'quota.spend.session',\n name: isPt ? 'Gasto na sessão ativa' : 'Active session spend',\n value: snapshot?.sessionSpend ?? '—',\n note: isPt ? 'Custo de todas as mensagens do turno' : 'Sum of turn assistant messages',\n },\n {\n id: 'quota.tokens.context',\n name: isPt ? 'Tokens de contexto' : 'Context tokens',\n value: snapshot?.sessionTokens ?? '—',\n note: isPt\n ? 'Tokens consumidos vs janela do modelo'\n : 'Tokens used vs model context limit',\n },\n {\n id: 'quota.tokens.cache',\n name: isPt ? 'Eficiência de cache' : 'Prompt cache hit',\n value: snapshot?.cacheHit ?? '—',\n note: isPt ? 'Desconto de leitura em cache aplicado' : 'Cache read discount applied',\n },\n ],\n },\n {\n title: isPt ? 'Limites & Teto de Orçamento' : 'Rate Limits & Budget Caps',\n rows: [\n {\n id: 'quota.budget.sessionCap',\n name: isPt ? 'Teto por sessão' : 'Session budget cap',\n value: prefs.sessionCap,\n cycle: ['$1.00', '$2.00', '$5.00', '$10.00', 'unlimited'],\n note: isPt\n ? 'Avisa ou pausa ao atingir o teto'\n : 'Warns or pauses when session spend reaches cap',\n },\n {\n id: 'quota.budget.alertThreshold',\n name: isPt ? 'Alerta em 80% do teto' : 'Alert at 80% of cap',\n value: prefs.alertThreshold,\n cycle: ['enabled', 'disabled'],\n note: isPt\n ? 'Emite aviso visual no footer da TUI'\n : 'Shows visual notice in TUI footer',\n },\n {\n id: 'quota.compaction.auto',\n name: isPt ? 'Auto-compactar em 80% do contexto' : 'Auto-compact at 80% context',\n value: prefs.autoCompact,\n cycle: ['enabled', 'disabled'],\n note: isPt\n ? 'Aciona compressão automática de histórico'\n : 'Triggers automatic context compaction',\n },\n ],\n },\n {\n title: isPt\n ? 'Provedores & Janelas de Cota (Referência)'\n : 'Providers & Quota Windows (Reference)',\n rows: [\n {\n id: 'quota.ref.anthropic',\n name: 'Anthropic (Claude 3.7)',\n value: 'Tier 4',\n note: isPt\n ? '400k TPM · Reset diário às 00:00 UTC'\n : '400k TPM · Daily reset at 00:00 UTC',\n },\n {\n id: 'quota.ref.openai',\n name: 'OpenAI (GPT-4o)',\n value: 'Tier 4',\n note: isPt\n ? '800k TPM · Reset por janela móvel de 1 min'\n : '800k TPM · 1-minute rolling window',\n },\n {\n id: 'quota.ref.google',\n name: 'Google (Gemini 2.5)',\n value: 'Pay-as-you-go',\n note: isPt\n ? '4M TPM · Alta capacidade com cota flexível'\n : '4M TPM · High capacity with flexible quota',\n },\n ],\n },\n ],\n }\n}\n","// biome-ignore-all lint/suspicious/noExplicitAny: stored prefs are host JSON of a known shape.\n/**\n * tui-prefs.ts — the TUI personalization core (the settings window's TUI tab).\n *\n * TUI-local copy doctrine (same as cost-data.ts): the bundle must stay\n * self-contained. Persistence is the HOST's durable plugin storage\n * (`context.storage.store('tui-prefs', { initial })` — reactive solid store,\n * live-synced across TUI instances); this module owns the SHAPE and the pure\n * operations, never the store handle.\n *\n * v1 surfaces: sidebar fixed headers, sidebar blocks, the Context block's\n * sub-lines and gauge style, and the two Pantheon footer lines. Everything\n * defaults to on — the window exists to turn things OFF.\n */\n\nimport type { Context } from '@opencode/plugin/tui/context'\nimport type { Accessor, Setter } from 'solid-js'\nimport { createSignal } from 'solid-js'\nimport type { SettingsDraft, SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\nimport { resolveLanguage } from './settings-i18n.ts'\n\n// ── The durable store handle (host storage, one per plugin) ────────────\n// Created once at setup and stashed under a globalThis symbol so\n// hot-reload generations keep sharing the same live store (the same\n// singleton doctrine as the plugin's SINGLETON guard).\n\nconst PREFS_SYMBOL = Symbol.for('pantheon.tui.prefs.v1')\nconst DRAFT_PREVIEW_SYMBOL = Symbol.for('pantheon.tui.draft_preview.v1')\ntype PrefsStore = readonly [TuiPrefs, (mutation: (draft: TuiPrefs) => void) => Promise]\ntype DraftSignal = [Accessor, Setter]\n\nfunction stash(): PrefsStore | undefined {\n return (globalThis as Record)[PREFS_SYMBOL] as PrefsStore | undefined\n}\n\nfunction getDraftPreviewSignal(): DraftSignal {\n const g = globalThis as Record\n if (!g[DRAFT_PREVIEW_SYMBOL]) {\n g[DRAFT_PREVIEW_SYMBOL] = createSignal(undefined)\n }\n return g[DRAFT_PREVIEW_SYMBOL] as DraftSignal\n}\n\n/** Set the active draft preview overlay (used by settings window to provide live preview). */\nexport function setTuiDraftPreview(draft: SettingsDraft | undefined): void {\n const [, setDraft] = getDraftPreviewSignal()\n setDraft(draft && Object.keys(draft).length > 0 ? { ...draft } : undefined)\n}\n\n/** Clear the active draft preview overlay. */\nexport function clearTuiDraftPreview(): void {\n const [, setDraft] = getDraftPreviewSignal()\n setDraft(undefined)\n}\n\n/** The active draft preview accessor. */\nexport function tuiDraftPreview(): SettingsDraft | undefined {\n const [draft] = getDraftPreviewSignal()\n return draft()\n}\n\n/** Create (or reuse) the durable prefs store. Fail-open: without host\n * storage the consumers fall back to DEFAULT_TUI_PREFS (read-only). */\nexport function initTuiPrefs(context: Context): void {\n if (stash() !== undefined) return\n try {\n const handle = context.storage?.store?.('tui-prefs', { initial: DEFAULT_TUI_PREFS }) as\n | PrefsStore\n | undefined\n if (handle !== undefined) {\n ;(globalThis as unknown as Record)[PREFS_SYMBOL] = handle\n // Self-heal: if store was persisted before layout existed or lacks new fields, backfill defaults\n if (\n !handle[0]?.layout ||\n typeof handle[0]?.sidebar?.context?.turnCost !== 'boolean' ||\n typeof handle[0]?.sidebar?.context?.tokenAnatomy !== 'boolean'\n ) {\n handle[1]((draft: any) => {\n if (!draft.layout) {\n draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n }\n if (draft.sidebar?.context) {\n if (typeof draft.sidebar.context.turnCost !== 'boolean') {\n draft.sidebar.context.turnCost = true\n }\n if (typeof draft.sidebar.context.tokenAnatomy !== 'boolean') {\n draft.sidebar.context.tokenAnatomy = true\n }\n }\n }).catch(() => {})\n }\n }\n } catch {\n /* no host storage — defaults stay read-only */\n }\n}\n\n/** Deep clone and overlay staged settings draft onto base TuiPrefs. */\nexport function previewTuiPrefs(base: TuiPrefs, draft?: SettingsDraft): TuiPrefs {\n if (!draft || Object.keys(draft).length === 0) return base\n let hasTui = false\n for (const k of Object.keys(draft)) {\n if (k.startsWith('tui.')) {\n hasTui = true\n break\n }\n }\n if (!hasTui) return base\n\n const normalized = normalizeTuiPrefs(base)\n const effective: TuiPrefs = {\n version: 1,\n layout: { ...normalized.layout },\n ...(normalized.theme ? { theme: { ...normalized.theme } } : {}),\n sidebar: {\n header: { ...normalized.sidebar.header },\n ...(normalized.sidebar.pinnedSessions\n ? { pinnedSessions: [...normalized.sidebar.pinnedSessions] }\n : {}),\n blocks: { ...normalized.sidebar.blocks },\n context: { ...normalized.sidebar.context },\n },\n footer: { ...normalized.footer },\n }\n\n for (const [id, value] of Object.entries(draft)) {\n if (id.startsWith('tui.')) {\n applyTuiRow(effective, id, value)\n }\n }\n return effective\n}\n\n/** The raw persisted prefs from host storage (no draft overlay). */\nexport function savedTuiPrefs(): TuiPrefs {\n const s = stash()?.[0]\n if (!s) return DEFAULT_TUI_PREFS\n return normalizeTuiPrefs(s)\n}\n\n/** The live reactive prefs (read properties inside memos/JSX — tracked).\n * When a settings window has an active draft, preview overlays on top\n * of durable storage in real time. */\nexport function tuiPrefs(): TuiPrefs {\n const base = savedTuiPrefs()\n const preview = tuiDraftPreview()\n if (!preview) return base\n return previewTuiPrefs(base, preview)\n}\n\n/** Stage a mutation against the durable store; resolves when persisted. */\nexport function mutateTuiPrefs(mutation: (draft: TuiPrefs) => void): Promise {\n const handle = stash()\n if (handle === undefined) return Promise.resolve()\n return handle[1](mutation)\n}\n\nexport const GAUGE_STYLES: readonly string[] = Object.freeze(['both', 'bar', 'percent', 'off'])\nexport const ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const BAR_SHAPES_CYCLE: readonly string[] = Object.freeze([\n 'smooth',\n 'line',\n 'block',\n 'ascii',\n 'dots',\n 'braille',\n])\nexport const BAR_WIDTHS_CYCLE: readonly string[] = Object.freeze([\n 'standard',\n 'compact',\n 'wide',\n 'full',\n])\nexport const LAYOUT_PRESETS_CYCLE: readonly string[] = Object.freeze(['comfortable', 'compact'])\nexport const SEPARATOR_STYLES_CYCLE: readonly string[] = Object.freeze([\n 'spaces',\n 'pipes',\n 'dots',\n 'slashes',\n])\nexport const SETTINGS_VIEW_MODES: readonly string[] = Object.freeze([\n 'docked',\n 'fullscreen',\n 'dialog',\n])\n\nexport type GaugeStyle = 'both' | 'bar' | 'percent' | 'off'\nexport type BarShapePref = 'line' | 'block' | 'smooth' | 'ascii' | 'dots' | 'braille'\nexport type BarWidthPref = 'standard' | 'compact' | 'wide' | 'full'\nexport type LayoutPresetPref = 'comfortable' | 'compact'\nexport type SeparatorStylePref = 'spaces' | 'pipes' | 'dots' | 'slashes'\nexport type SettingsViewModePref = 'docked' | 'fullscreen' | 'dialog'\nexport type LanguagePref = 'auto' | 'pt-BR' | 'en'\n\nexport const LANGUAGE_CYCLE: readonly string[] = Object.freeze(['auto', 'pt-BR', 'en'])\n\nexport type ThemeModePref = 'auto' | 'dark' | 'light'\nexport const THEME_MODES_CYCLE: readonly string[] = Object.freeze(['auto', 'dark', 'light'])\n\nexport type AccentColorPref = 'host' | 'pantheon' | 'emerald' | 'cyan' | 'amber' | 'purple' | 'rose'\nexport const ACCENT_COLORS_CYCLE: readonly string[] = Object.freeze([\n 'host',\n 'pantheon',\n 'emerald',\n 'cyan',\n 'amber',\n 'purple',\n 'rose',\n])\n\nexport const ACCENT_PALETTE: Record<\n AccentColorPref,\n { primary: string; hover: string; muted: string }\n> = {\n host: { primary: '#fba970', hover: '#fdba74', muted: '#a1a1aa' },\n pantheon: { primary: '#fba970', hover: '#fdba74', muted: '#a1a1aa' },\n emerald: { primary: '#10b981', hover: '#34d399', muted: '#059669' },\n cyan: { primary: '#06b6d4', hover: '#22d3ee', muted: '#0891b2' },\n amber: { primary: '#f59e0b', hover: '#fbbf24', muted: '#d97706' },\n purple: { primary: '#a855f7', hover: '#c084fc', muted: '#9333ea' },\n rose: { primary: '#f43f5e', hover: '#fb7185', muted: '#e11d48' },\n}\n\nexport function resolveAccentColor(accent: AccentColorPref | undefined, contextTheme: any): string {\n if (!accent || accent === 'host') {\n return contextTheme?.text?.feedback?.warning?.base ?? contextTheme?.text?.base ?? '#fba970'\n }\n return ACCENT_PALETTE[accent]?.primary ?? '#fba970'\n}\n\nexport interface TuiPrefs {\n version: 1\n layout: {\n preset: LayoutPresetPref\n separator: SeparatorStylePref\n settingsView?: SettingsViewModePref\n language?: LanguagePref\n }\n theme?: {\n mode?: ThemeModePref\n accent?: AccentColorPref\n }\n sidebar: {\n header: { version: boolean; preset: boolean; session: boolean }\n pinnedSessions?: string[]\n blocks: { context: boolean; git: boolean; todo?: boolean; dispatch: boolean }\n context: {\n gauge: GaugeStyle\n barShape: BarShapePref\n barWidth: BarWidthPref\n evenMark: boolean\n tokens: boolean\n spent: boolean\n modelUsage: boolean\n performance: boolean\n localSpend: boolean\n turnCost: boolean\n tokenAnatomy: boolean\n }\n }\n footer: { prompt: boolean; home: boolean }\n}\n\nexport const DEFAULT_TUI_PREFS: TuiPrefs = {\n version: 1,\n layout: {\n preset: 'comfortable',\n separator: 'spaces',\n settingsView: 'docked',\n language: 'auto',\n },\n theme: {\n mode: 'auto',\n accent: 'host',\n },\n sidebar: {\n header: { version: true, preset: true, session: true },\n pinnedSessions: [],\n blocks: { context: true, git: true, todo: false, dispatch: true },\n context: {\n gauge: 'both',\n barShape: 'smooth',\n barWidth: 'standard',\n evenMark: false,\n tokens: true,\n spent: true,\n modelUsage: true,\n performance: true,\n localSpend: true,\n turnCost: true,\n tokenAnatomy: true,\n },\n },\n footer: { prompt: true, home: true },\n}\n\nfunction asBool(value: unknown, fallback: boolean): boolean {\n return typeof value === 'boolean' ? value : fallback\n}\n\n/** Deep-merge stored JSON over the defaults; unknown keys and junk are ignored. */\nexport function normalizeTuiPrefs(raw: unknown): TuiPrefs {\n const stored = (typeof raw === 'object' && raw !== null ? raw : {}) as Record\n const layout = (\n typeof stored.layout === 'object' && stored.layout !== null ? stored.layout : {}\n ) as Record\n const sidebar = (\n typeof stored.sidebar === 'object' && stored.sidebar !== null ? stored.sidebar : {}\n ) as Record\n const header = (\n typeof sidebar.header === 'object' && sidebar.header !== null ? sidebar.header : {}\n ) as Record\n const blocks = (\n typeof sidebar.blocks === 'object' && sidebar.blocks !== null ? sidebar.blocks : {}\n ) as Record\n const context = (\n typeof sidebar.context === 'object' && sidebar.context !== null ? sidebar.context : {}\n ) as Record\n const footer = (\n typeof stored.footer === 'object' && stored.footer !== null ? stored.footer : {}\n ) as Record\n const rawTheme = (\n typeof stored.theme === 'object' && stored.theme !== null ? stored.theme : {}\n ) as Record\n const themeMode = THEME_MODES_CYCLE.includes(rawTheme.mode as string)\n ? (rawTheme.mode as ThemeModePref)\n : (DEFAULT_TUI_PREFS.theme?.mode ?? 'auto')\n const themeAccent = ACCENT_COLORS_CYCLE.includes(rawTheme.accent as string)\n ? (rawTheme.accent as AccentColorPref)\n : (DEFAULT_TUI_PREFS.theme?.accent ?? 'host')\n const preset = LAYOUT_PRESETS_CYCLE.includes(layout.preset as string)\n ? (layout.preset as LayoutPresetPref)\n : DEFAULT_TUI_PREFS.layout.preset\n const separator = SEPARATOR_STYLES_CYCLE.includes(layout.separator as string)\n ? (layout.separator as SeparatorStylePref)\n : DEFAULT_TUI_PREFS.layout.separator\n const settingsView = (\n SETTINGS_VIEW_MODES.includes(layout.settingsView as string)\n ? layout.settingsView\n : DEFAULT_TUI_PREFS.layout.settingsView\n ) as SettingsViewModePref\n const language = (\n LANGUAGE_CYCLE.includes(layout.language as string)\n ? layout.language\n : DEFAULT_TUI_PREFS.layout.language\n ) as LanguagePref\n const gauge = GAUGE_STYLES.includes(context.gauge as string)\n ? (context.gauge as GaugeStyle)\n : DEFAULT_TUI_PREFS.sidebar.context.gauge\n const barShape = BAR_SHAPES_CYCLE.includes(context.barShape as string)\n ? (context.barShape as BarShapePref)\n : DEFAULT_TUI_PREFS.sidebar.context.barShape\n const barWidth = BAR_WIDTHS_CYCLE.includes(context.barWidth as string)\n ? (context.barWidth as BarWidthPref)\n : DEFAULT_TUI_PREFS.sidebar.context.barWidth\n const evenMark = asBool(context.evenMark, DEFAULT_TUI_PREFS.sidebar.context.evenMark)\n\n return {\n version: 1,\n layout: {\n preset,\n separator,\n settingsView,\n language,\n },\n theme: {\n mode: themeMode,\n accent: themeAccent,\n },\n sidebar: {\n header: {\n version: asBool(header.version, true),\n preset: asBool(header.preset, true),\n session: asBool(header.session, true),\n },\n pinnedSessions: Array.isArray(sidebar.pinnedSessions)\n ? sidebar.pinnedSessions.filter((s: unknown) => typeof s === 'string')\n : [],\n blocks: {\n context: asBool(blocks.context, true),\n git: asBool(blocks.git, true),\n todo: asBool(blocks.todo, false),\n dispatch: asBool(blocks.dispatch, true),\n },\n context: {\n gauge,\n barShape,\n barWidth,\n evenMark,\n tokens: asBool(context.tokens, true),\n spent: asBool(context.spent, true),\n modelUsage: asBool(context.modelUsage, true),\n performance: asBool(context.performance, true),\n localSpend: asBool(context.localSpend, true),\n turnCost: asBool(context.turnCost, true),\n tokenAnatomy: asBool(context.tokenAnatomy, true),\n },\n },\n footer: {\n prompt: asBool(footer.prompt, true),\n home: asBool(footer.home, true),\n },\n }\n}\n\n// ── The TUI tab (cycler rows over the dotted pref paths) ───────────────\n\nconst onOff = ENABLED_CYCLE\nconst row = (id: string, name: string, value: boolean, note: string): SettingsRow => ({\n id,\n name,\n value: value ? 'enabled' : 'disabled',\n cycle: onOff,\n note,\n})\n\nexport function buildTuiTab(prefs: TuiPrefs, languagePref?: string): SettingsTab {\n const isPt = resolveLanguage(languagePref ?? prefs.layout?.language) === 'pt-BR'\n return {\n id: 'tui',\n title: 'TUI',\n groups: [\n {\n title: isPt ? 'Predefinição & Layout' : 'Preset & Layout',\n rows: [\n {\n id: 'tui.layout.preset',\n name: isPt ? 'Predefinição de layout' : 'Layout preset',\n value: prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset,\n cycle: LAYOUT_PRESETS_CYCLE,\n note: isPt\n ? 'comfortable | compact — define espaçamento e bordas'\n : 'comfortable | compact — sets spacing & borders',\n },\n {\n id: 'tui.layout.separator',\n name: isPt ? 'Separador' : 'Separator',\n value: prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator,\n cycle: SEPARATOR_STYLES_CYCLE,\n note: isPt\n ? 'spaces | pipes | dots | slashes — glifos na linha de status'\n : 'spaces | pipes | dots | slashes — status line glyphs',\n },\n {\n id: 'tui.layout.settingsView',\n name: isPt ? 'Superfície de configurações' : 'Settings surface',\n value: tuiRowValue(prefs, 'tui.layout.settingsView') ?? 'docked',\n cycle: SETTINGS_VIEW_MODES,\n note: isPt\n ? 'docked (acima do prompt) | fullscreen | dialog'\n : 'docked (above prompt) | fullscreen router page | dialog overlay',\n },\n {\n id: 'tui.layout.language',\n name: isPt ? 'Idioma / Language' : 'Language / Idioma',\n value: tuiRowValue(prefs, 'tui.layout.language') ?? 'auto',\n cycle: LANGUAGE_CYCLE,\n note: isPt\n ? 'auto (detecta via fuso/locale) | pt-BR (Português) | en (English)'\n : 'auto (detect via timezone/locale) | pt-BR (Português) | en (English)',\n },\n ],\n },\n {\n title: isPt ? 'Cores & Tema' : 'Colors & Theme',\n rows: [\n {\n id: 'tui.theme.mode',\n name: isPt ? 'Modo do tema' : 'Theme mode',\n value: tuiRowValue(prefs, 'tui.theme.mode') ?? 'auto',\n cycle: THEME_MODES_CYCLE,\n note: isPt\n ? 'auto (segue o OpenCode) | dark | light'\n : 'auto (follow OpenCode theme) | dark | light',\n },\n {\n id: 'tui.theme.accent',\n name: isPt ? 'Cor de destaque' : 'Accent color',\n value: tuiRowValue(prefs, 'tui.theme.accent') ?? 'host',\n cycle: ACCENT_COLORS_CYCLE,\n note: isPt\n ? 'host (segue tema) | pantheon | emerald | cyan | amber | purple | rose'\n : 'host (follow theme) | pantheon | emerald | cyan | amber | purple | rose',\n },\n ],\n },\n {\n title: isPt ? 'Barras & Medidores' : 'Bars & Gauges',\n rows: [\n {\n id: 'tui.sidebar.context.barShape',\n name: isPt ? 'Formato da barra' : 'Bar shape',\n value: prefs.sidebar.context.barShape,\n cycle: BAR_SHAPES_CYCLE,\n note: 'line (━─) | block (▰▱) | smooth (█░) | ascii (=) | dots (●○) | braille',\n },\n {\n id: 'tui.sidebar.context.barWidth',\n name: isPt ? 'Largura da barra' : 'Bar width',\n value: prefs.sidebar.context.barWidth,\n cycle: BAR_WIDTHS_CYCLE,\n note: isPt\n ? 'standard (12) | compact (8) | wide (16) | full (20 células)'\n : 'standard (12) | compact (8) | wide (16) | full (20 cells)',\n },\n row(\n 'tui.sidebar.context.evenMark',\n isPt ? 'Marca central (50%)' : 'Even-use mark',\n prefs.sidebar.context.evenMark,\n isPt\n ? '| indicador aos 50% nas barras de medição'\n : '| indicator at 50% midpoint in gauge bars',\n ),\n {\n id: 'tui.sidebar.context.gauge',\n name: isPt ? 'Estilo do medidor' : 'Gauge style',\n value: prefs.sidebar.context.gauge,\n cycle: GAUGE_STYLES,\n note: 'both | bar | percent | off — `▰▱ 42% of 200k`',\n },\n ],\n },\n {\n title: isPt ? 'Cabeçalho da barra lateral' : 'Sidebar header',\n rows: [\n row(\n 'tui.sidebar.header.version',\n isPt ? 'Linha de versão' : 'Version line',\n prefs.sidebar.header.version,\n isPt ? 'linha `Pantheon v…`' : 'the `Pantheon v…` line',\n ),\n row(\n 'tui.sidebar.header.preset',\n isPt ? 'Linha de preset' : 'Preset line',\n prefs.sidebar.header.preset,\n isPt ? 'linha `▸ preset · provider`' : 'the `▸ preset · provider` line',\n ),\n row(\n 'tui.sidebar.header.session',\n isPt ? 'Linha de sessão' : 'Session line',\n prefs.sidebar.header.session,\n isPt ? 'título da sessão ativa' : 'the active session title',\n ),\n ],\n },\n {\n title: isPt ? 'Blocos da barra lateral' : 'Sidebar blocks',\n rows: [\n row(\n 'tui.sidebar.block.context',\n isPt ? 'Bloco de contexto' : 'Context block',\n prefs.sidebar.blocks.context,\n isPt ? 'tokens, medidor, custo, uso de modelos' : 'tokens, gauge, spend, model usage',\n ),\n row(\n 'tui.sidebar.block.git',\n isPt ? 'Bloco do Git' : 'Git block',\n prefs.sidebar.blocks.git,\n isPt ? 'branch + contagem de alterações' : 'branch + working-tree counts',\n ),\n row(\n 'tui.sidebar.block.dispatch',\n isPt ? 'Bloco Dispatch' : 'Dispatch block',\n prefs.sidebar.blocks.dispatch,\n isPt ? 'delegações em tempo real' : 'live delegations + rollup',\n ),\n ],\n },\n {\n title: isPt ? 'Detalhe do bloco de contexto' : 'Context block detail',\n rows: [\n row(\n 'tui.sidebar.context.tokens',\n isPt ? 'Linha de tokens' : 'Tokens row',\n prefs.sidebar.context.tokens,\n isPt ? 'contagem bruta de tokens' : 'the raw token count line',\n ),\n row(\n 'tui.sidebar.context.spent',\n isPt ? 'Linha de custo' : 'Spent row',\n prefs.sidebar.context.spent,\n isPt ? 'linha `$… gastos na sessão`' : 'the `$… spent in session` line',\n ),\n row(\n 'tui.sidebar.context.modelUsage',\n isPt ? 'Tabela de uso de modelos' : 'Model usage table',\n prefs.sidebar.context.modelUsage,\n isPt ? 'resumo de chamadas por modelo' : 'per-model tokens/USD',\n ),\n row(\n 'tui.sidebar.context.performance',\n isPt ? 'Linha de desempenho' : 'Performance row',\n prefs.sidebar.context.performance,\n isPt ? 'tokens/segundo e latência' : 'cache % + tok/s',\n ),\n row(\n 'tui.sidebar.context.turnCost',\n isPt ? 'Custo do turno' : 'Turn cost',\n prefs.sidebar.context.turnCost,\n isPt ? 'linha `Turn: $… (prev: $…)`' : 'the `Turn: $… (prev: $…)` line',\n ),\n row(\n 'tui.sidebar.context.tokenAnatomy',\n isPt ? 'Anatomia de tokens' : 'Token anatomy',\n prefs.sidebar.context.tokenAnatomy,\n isPt ? 'linha `↑in ↓out ✦think`' : 'the `↑in ↓out ✦think` line',\n ),\n row(\n 'tui.sidebar.context.localSpend',\n isPt ? 'Linha de custo local' : 'Local spend row',\n prefs.sidebar.context.localSpend,\n isPt ? 'totais de hoje / 30 dias' : 'hoje / 30d totals',\n ),\n ],\n },\n {\n title: isPt ? 'Rodapés' : 'Footers',\n rows: [\n row(\n 'tui.footer.prompt',\n isPt ? 'Prompt inferior' : 'Prompt footer',\n prefs.footer.prompt,\n isPt\n ? 'linha `▸preset · ✦n ativos` durante delegações'\n : 'the `▸preset · ✦n ativos` line while delegations run',\n ),\n row(\n 'tui.footer.home',\n isPt ? 'Status inicial' : 'Home status',\n prefs.footer.home,\n isPt\n ? 'linha `Pantheon v…` sob o prompt inicial'\n : 'the `Pantheon v…` line under the home prompt',\n ),\n ],\n },\n ],\n }\n}\n\n/**\n * Apply one staged row INTO a prefs draft (in place — the storage mutate\n * callback hands an immer-style draft). Unknown ids or junk values are no-ops.\n */\nexport function applyTuiRow(draft: TuiPrefs, id: string, value: string): void {\n const enabled = value === 'enabled'\n switch (id) {\n case 'tui.layout.preset':\n if (LAYOUT_PRESETS_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.preset = value as LayoutPresetPref\n }\n return\n case 'tui.layout.separator':\n if (SEPARATOR_STYLES_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.separator = value as SeparatorStylePref\n }\n return\n case 'tui.layout.settingsView':\n if (SETTINGS_VIEW_MODES.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.settingsView = value as SettingsViewModePref\n }\n return\n case 'tui.layout.language':\n if (LANGUAGE_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.language = value as LanguagePref\n }\n return\n case 'tui.theme.mode':\n if (THEME_MODES_CYCLE.includes(value)) {\n if (!draft.theme) draft.theme = { ...DEFAULT_TUI_PREFS.theme }\n draft.theme.mode = value as ThemeModePref\n }\n return\n case 'tui.theme.accent':\n if (ACCENT_COLORS_CYCLE.includes(value)) {\n if (!draft.theme) draft.theme = { ...DEFAULT_TUI_PREFS.theme }\n draft.theme.accent = value as AccentColorPref\n }\n return\n case 'tui.sidebar.context.barShape':\n if (BAR_SHAPES_CYCLE.includes(value)) draft.sidebar.context.barShape = value as BarShapePref\n return\n case 'tui.sidebar.context.barWidth':\n if (BAR_WIDTHS_CYCLE.includes(value)) draft.sidebar.context.barWidth = value as BarWidthPref\n return\n case 'tui.sidebar.context.evenMark':\n draft.sidebar.context.evenMark = enabled\n return\n case 'tui.sidebar.header.version':\n draft.sidebar.header.version = enabled\n return\n case 'tui.sidebar.header.preset':\n draft.sidebar.header.preset = enabled\n return\n case 'tui.sidebar.header.session':\n draft.sidebar.header.session = enabled\n return\n case 'tui.sidebar.block.context':\n draft.sidebar.blocks.context = enabled\n return\n case 'tui.sidebar.block.git':\n draft.sidebar.blocks.git = enabled\n return\n case 'tui.sidebar.block.todo':\n draft.sidebar.blocks.todo = enabled\n return\n case 'tui.sidebar.block.dispatch':\n draft.sidebar.blocks.dispatch = enabled\n return\n case 'tui.sidebar.context.gauge':\n if (GAUGE_STYLES.includes(value)) draft.sidebar.context.gauge = value as GaugeStyle\n return\n case 'tui.sidebar.context.tokens':\n draft.sidebar.context.tokens = enabled\n return\n case 'tui.sidebar.context.spent':\n draft.sidebar.context.spent = enabled\n return\n case 'tui.sidebar.context.modelUsage':\n draft.sidebar.context.modelUsage = enabled\n return\n case 'tui.sidebar.context.performance':\n draft.sidebar.context.performance = enabled\n return\n case 'tui.sidebar.context.localSpend':\n draft.sidebar.context.localSpend = enabled\n return\n case 'tui.sidebar.context.turnCost':\n draft.sidebar.context.turnCost = enabled\n return\n case 'tui.sidebar.context.tokenAnatomy':\n draft.sidebar.context.tokenAnatomy = enabled\n return\n case 'tui.footer.prompt':\n draft.footer.prompt = enabled\n return\n case 'tui.footer.home':\n draft.footer.home = enabled\n return\n default:\n return\n }\n}\n\n/** Read the current pref value for a row id ('enabled'/'disabled'/gauge/custom). */\nexport function tuiRowValue(prefs: TuiPrefs, id: string): string | undefined {\n if (id === 'tui.layout.preset') return prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset\n if (id === 'tui.layout.separator')\n return prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator\n if (id === 'tui.layout.settingsView')\n return prefs.layout?.settingsView ?? DEFAULT_TUI_PREFS.layout.settingsView ?? 'docked'\n if (id === 'tui.layout.language') return prefs.layout?.language ?? 'auto'\n if (id === 'tui.theme.mode') return prefs.theme?.mode ?? DEFAULT_TUI_PREFS.theme?.mode ?? 'auto'\n if (id === 'tui.theme.accent')\n return prefs.theme?.accent ?? DEFAULT_TUI_PREFS.theme?.accent ?? 'host'\n if (id === 'tui.sidebar.context.barShape') return prefs.sidebar.context.barShape\n if (id === 'tui.sidebar.context.barWidth') return prefs.sidebar.context.barWidth\n if (id === 'tui.sidebar.context.gauge') return prefs.sidebar.context.gauge\n if (id === 'tui.sidebar.context.evenMark')\n return prefs.sidebar.context.evenMark ? 'enabled' : 'disabled'\n const enabled = (() => {\n switch (id) {\n case 'tui.sidebar.header.version':\n return prefs.sidebar.header.version\n case 'tui.sidebar.header.preset':\n return prefs.sidebar.header.preset\n case 'tui.sidebar.header.session':\n return prefs.sidebar.header.session\n case 'tui.sidebar.block.context':\n return prefs.sidebar.blocks.context\n case 'tui.sidebar.block.git':\n return prefs.sidebar.blocks.git\n case 'tui.sidebar.block.todo':\n return prefs.sidebar.blocks.todo\n case 'tui.sidebar.block.dispatch':\n return prefs.sidebar.blocks.dispatch\n case 'tui.sidebar.context.tokens':\n return prefs.sidebar.context.tokens\n case 'tui.sidebar.context.spent':\n return prefs.sidebar.context.spent\n case 'tui.sidebar.context.modelUsage':\n return prefs.sidebar.context.modelUsage\n case 'tui.sidebar.context.performance':\n return prefs.sidebar.context.performance\n case 'tui.sidebar.context.localSpend':\n return prefs.sidebar.context.localSpend\n case 'tui.sidebar.context.turnCost':\n return prefs.sidebar.context.turnCost\n case 'tui.sidebar.context.tokenAnatomy':\n return prefs.sidebar.context.tokenAnatomy\n case 'tui.footer.prompt':\n return prefs.footer.prompt\n case 'tui.footer.home':\n return prefs.footer.home\n default:\n return undefined\n }\n })()\n return enabled === undefined ? undefined : enabled ? 'enabled' : 'disabled'\n}\n\nexport function isSessionPinned(sessionID: string | undefined): boolean {\n if (!sessionID) return false\n const list = tuiPrefs().sidebar.pinnedSessions\n return Array.isArray(list) && list.includes(sessionID)\n}\n\nexport function togglePinSession(sessionID: string | undefined): Promise {\n if (!sessionID) return Promise.resolve()\n return mutateTuiPrefs((draft) => {\n if (!Array.isArray(draft.sidebar.pinnedSessions)) {\n draft.sidebar.pinnedSessions = []\n }\n const idx = draft.sidebar.pinnedSessions.indexOf(sessionID)\n if (idx >= 0) {\n draft.sidebar.pinnedSessions.splice(idx, 1)\n } else {\n draft.sidebar.pinnedSessions.push(sessionID)\n }\n })\n}\n","/**\n * update-status.ts — the Updates section of the settings window.\n *\n * TUI-local; derives rows from the update-notice.ts primitives. The registry\n * fetch and state persistence stay in the .tsx glue (host side) — this module\n * only classifies the channel and builds rows from injected state, so the\n * whole thing is testable without network.\n */\n\nimport { formatBytes, type LegacyAuditSummary } from './legacy-audit.ts'\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\nimport { comparePantheonVersions, type UpdateCheckState } from './update-notice.ts'\n\nexport type UpdateChannel = 'stable' | 'beta'\n\n/** The running version's channel: a `-beta.N` suffix rides the beta dist-tag. */\nexport function updateChannelFor(version: string): UpdateChannel {\n return /-beta\\.\\d+$/.test(version) ? 'beta' : 'stable'\n}\n\n/** The npm dist-tag the registry check should query for the channel. */\nexport function registryTagForChannel(channel: UpdateChannel): string {\n return channel === 'beta' ? 'beta' : 'latest'\n}\n\nexport function registryUrlForChannel(channel: UpdateChannel): string {\n return `https://registry.npmjs.org/pantheon-opencode/${registryTagForChannel(channel)}`\n}\n\nfunction formatAgo(ms: number, isPt = false): string {\n if (ms < 60_000) return isPt ? 'agora mesmo' : 'just now'\n if (ms < 3_600_000)\n return isPt ? `há ${Math.floor(ms / 60_000)}m` : `${Math.floor(ms / 60_000)}m ago`\n if (ms < 86_400_000)\n return isPt ? `há ${Math.floor(ms / 3_600_000)}h` : `${Math.floor(ms / 3_600_000)}h ago`\n return isPt ? `há ${Math.floor(ms / 86_400_000)}d` : `${Math.floor(ms / 86_400_000)}d ago`\n}\n\nexport interface UpdatesSectionInput {\n currentVersion: string\n state: UpdateCheckState\n /** Selected channel (defaults to updateChannelFor(currentVersion)). */\n selectedChannel?: UpdateChannel\n /** Latest version seen this session (a check-now inside this window). */\n lastCheckedVersion?: string\n /** A check-now is in flight (this window). */\n checking?: boolean\n /** An update run is in flight (this window). */\n updating?: boolean\n /** Latest scan summary from legacy-audit.ts (global + project). */\n legacyAudit?: LegacyAuditSummary | null\n /** Whether a legacy scan is currently running. */\n legacyScanning?: boolean\n /** Whether a legacy cleanup is currently running. */\n legacyCleaning?: boolean\n /** Outcome notice from the last scan/clean action. */\n legacyNotice?: string\n nowMs?: number\n languagePref?: string\n}\n\nexport function buildUpdatesTab(input: UpdatesSectionInput): SettingsTab {\n const isPt = input.languagePref === 'pt-BR'\n const nowMs = input.nowMs ?? Date.now()\n const channel = input.selectedChannel ?? updateChannelFor(input.currentVersion)\n const lastCheckMs = input.state.lastCheckMs\n const latest = input.lastCheckedVersion ?? input.state.lastNotifiedVersion\n\n const stable = (version: string) => !/-beta\\.\\d+$/.test(version)\n const newer =\n latest !== undefined &&\n comparePantheonVersions(latest, input.currentVersion) > 0 &&\n !(stable(input.currentVersion) && !stable(latest))\n\n const rows: SettingsRow[] = [\n {\n id: 'update.channel',\n name: isPt ? 'Canal' : 'Channel',\n value: channel,\n cycle: ['stable', 'beta'] as const,\n note: isPt\n ? 'stable segue npm `latest`; beta segue npm `beta`'\n : 'stable tracks npm `latest`; beta tracks npm `beta`',\n },\n {\n id: 'update.check',\n name: isPt ? 'Verificar agora' : 'Check now',\n value: input.checking\n ? isPt\n ? 'verificando…'\n : 'checking…'\n : lastCheckMs\n ? isPt\n ? `última verificação ${formatAgo(nowMs - lastCheckMs, true)}`\n : `last check ${formatAgo(nowMs - lastCheckMs, false)}`\n : isPt\n ? 'nunca verificado'\n : 'never checked',\n action: 'update-check',\n note: isPt\n ? 'enter consulta o registro npm para o canal ativo'\n : 'enter probes the registry for the running channel',\n },\n ]\n\n const pluginCommand =\n channel === 'beta'\n ? 'opencode plugin add pantheon-opencode@beta'\n : 'opencode plugin add pantheon-opencode'\n\n if (latest) {\n rows.push({\n id: 'update.latest',\n name: isPt ? 'Registro (npm)' : 'Registry',\n value: newer\n ? `v${latest} ${isPt ? 'disponível' : 'available'}`\n : isPt\n ? 'atualizado'\n : 'up to date',\n note: newer\n ? isPt\n ? `atualize via \\`${pluginCommand}\\``\n : `update via \\`${pluginCommand}\\``\n : isPt\n ? 'nenhuma versão mais recente compatível'\n : 'no newer compatible version',\n })\n rows.push({\n id: 'update.run',\n name: isPt ? 'Atualizar plugin' : 'Update plugin',\n value: input.updating\n ? isPt\n ? 'atualizando…'\n : 'updating…'\n : newer\n ? `${isPt ? 'instalar' : 'install'} v${latest}`\n : isPt\n ? 'reinstalar / atualizar'\n : 'reinstall / refresh',\n action: 'update-run',\n note: newer\n ? isPt\n ? `enter executa \\`${pluginCommand}\\``\n : `enter runs \\`${pluginCommand}\\``\n : isPt\n ? 'enter atualiza o plugin instalado'\n : 'enter refreshes the installed plugin',\n })\n }\n\n rows.push({\n id: 'update.command',\n name: isPt ? 'Comando Nativo' : 'Plugin Command',\n value: pluginCommand,\n note: isPt\n ? 'instalação nativa sem npx · funciona global ou no projeto'\n : 'native plugin install (no npx) · works global or per-project',\n })\n\n const audit = input.legacyAudit\n const legacyRows: SettingsRow[] = [\n {\n id: 'legacy.status',\n name: isPt ? 'Auditoria legada' : 'Legacy & Drift',\n value: input.legacyScanning\n ? isPt\n ? 'escaneando…'\n : 'scanning…'\n : audit === undefined || audit === null\n ? isPt\n ? 'não escaneado'\n : 'not scanned'\n : audit.total === 0\n ? isPt\n ? 'limpo (0 obsoletos)'\n : 'clean (0 obsolete)'\n : isPt\n ? `${audit.total} arquivo(s) (${formatBytes(audit.totalBytes)})`\n : `${audit.total} file(s) (${formatBytes(audit.totalBytes)})`,\n note: input.legacyNotice\n ? input.legacyNotice\n : audit && audit.total > 0\n ? isPt\n ? `global: ${audit.byScope.global} · projeto: ${audit.byScope.project}${audit.unmigratedStores > 0 ? ` · ${audit.unmigratedStores} store(s) p/ migrar` : ''}`\n : `global: ${audit.byScope.global} · project: ${audit.byScope.project}${audit.unmigratedStores > 0 ? ` · ${audit.unmigratedStores} store(s) to migrate` : ''}`\n : isPt\n ? 'verifica hooks V1, bancos não migrados e cópias redundantes'\n : 'checks V1 hooks, unmigrated stores & redundant plugin copies',\n },\n {\n id: 'legacy.scan',\n name: isPt ? 'Escanear obsoletos' : 'Scan legacy & drift',\n value: input.legacyScanning\n ? isPt\n ? 'escaneando…'\n : 'scanning…'\n : isPt\n ? 'verificar global + projeto'\n : 'check global + project',\n action: 'legacy-scan',\n note: isPt\n ? 'enter escaneia sem modificar ou apagar nenhum arquivo'\n : 'enter scans read-only without deleting anything',\n },\n {\n id: 'legacy.clean',\n name: isPt ? 'Migrar & limpar' : 'Migrate & clean obsolete',\n value: input.legacyCleaning\n ? isPt\n ? 'limpando…'\n : 'cleaning…'\n : audit && audit.total > 0\n ? isPt\n ? `remover ${audit.total} (${formatBytes(audit.totalBytes)})`\n : `remove ${audit.total} (${formatBytes(audit.totalBytes)})`\n : isPt\n ? 'nada para remover'\n : 'nothing to remove',\n action: 'legacy-clean',\n note: isPt\n ? 'migra memória/contexto/goals antes e preserva agentes/skills custom'\n : 'migrates memory/context/goals first · preserves custom agents/skills',\n },\n ]\n\n return {\n id: 'updates',\n title: isPt ? 'Atualizações' : 'Updates',\n groups: [\n { title: isPt ? 'Atualizações do Plugin' : 'Plugin Updates', rows },\n { title: isPt ? 'Legados, Drift & Limpeza' : 'Legacy, Drift & Cleanup', rows: legacyRows },\n ],\n }\n}\n","/**\n * whats-new-highlights.ts — release highlights for the one-time \"What's new\"\n * window, extracted from the CHANGELOG.md shipped with the plugin copy.\n *\n * The section-finding logic is an inline replica of scripts/changelog-extract.mjs\n * `extractSection` (pinned by a parity test in tests/tui-whats-new.test.mjs):\n * the copied plugin ships only dist/ + package.json (+ CHANGELOG.md, copied by\n * both installers), so it cannot reach scripts/ at runtime — the same reason\n * the preset resolver is mirrored in index.tsx/index-v2.tsx rather than\n * imported. The script's CLI main is NOT replicated; the plugin only needs the\n * pure extraction.\n *\n * Everything is reduced to bounded plain text: no markdown syntax artifacts,\n * at most WHATS_NEW_MAX_ITEMS bullets. Missing CHANGELOG.md, an unknown\n * version or an empty section all resolve to an empty highlight set — the\n * window simply does not show (fail-open, like the rest of the plugin).\n */\nimport { readFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\n/** Hard cap on bullets shown in the window (the remainder is counted). */\nexport const WHATS_NEW_MAX_ITEMS = 12\n\n/**\n * Cap for the curated `🆕 What's New` summary block — the window shows the\n * summary, never the full Added/Changed/Fixed walls.\n */\nexport const WHATS_NEW_SUMMARY_MAX_ITEMS = 6\n\n/** Bullets longer than this are truncated with an ellipsis (one-line rule). */\nexport const WHATS_NEW_ITEM_MAX_CHARS = 140\n\n/** Prefix of the \"+N more\" line appended when the bullet budget is exceeded. */\nexport const WHATS_NEW_MORE_PREFIX = '… +'\n\n/** H3 subsection headings are kept as plain-text group labels. */\nexport interface WhatsNewGroup {\n heading: string | null\n items: string[]\n}\n\nexport interface WhatsNewHighlights {\n /** Normalized version the highlights belong to (null when not found). */\n version: string | null\n found: boolean\n groups: WhatsNewGroup[]\n /** Total bullets in the section, before the WHATS_NEW_MAX_ITEMS cut. */\n totalItems: number\n /** True when totalItems exceeded WHATS_NEW_MAX_ITEMS. */\n truncated: boolean\n}\n\nexport const EMPTY_HIGHLIGHTS: WhatsNewHighlights = {\n version: null,\n found: false,\n groups: [],\n totalItems: 0,\n truncated: false,\n}\n\n/** Escape regex metacharacters so a version like 1.0.0 matches literally. */\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Extract the body of a version section from changelog text — inline replica\n * of scripts/changelog-extract.mjs `extractSection` (see that file for the\n * full contract: `## [] - YYYY-MM-DD`, leading `v` and the date\n * optional, `## [Unreleased]` never matched).\n */\nexport function extractSection(\n changelogText: string,\n version: string,\n): { found: boolean; body: string | null } {\n const normalized = String(version).trim().replace(/^v/i, '')\n if (!normalized || /^unreleased$/i.test(normalized)) return { found: false, body: null }\n\n const escaped = escapeRegExp(normalized)\n // Single-line heading: `## [v?1.2.1]` optionally followed by ` - YYYY-MM-DD`.\n // [ \\t] (not \\s) keeps the match from crossing newlines; the lookahead\n // requires end-of-line or whitespace so `[1.0.0-beta]` can never match `1.0.0`.\n const headingRe = new RegExp(\n `^##[ \\\\t]+\\\\[v?${escaped}\\\\](?:[ \\\\t]*-[ \\\\t]*\\\\d{4}-\\\\d{2}-\\\\d{2})?(?=[ \\\\t]|$)`,\n 'm',\n )\n const match = headingRe.exec(changelogText)\n if (!match) return { found: false, body: null }\n\n // Advance past the heading line (match.index may point mid-line).\n const newline = changelogText.indexOf('\\n', match.index)\n const start = newline === -1 ? changelogText.length : newline + 1\n\n // Body ends at the next `## [` heading or end of text.\n const nextHeading = /^##[ \\t]+\\[/m.exec(changelogText.slice(start))\n const end = nextHeading ? start + nextHeading.index : changelogText.length\n\n return { found: true, body: changelogText.slice(start, end).trim() }\n}\n\n/**\n * Reduce one markdown line to plain text: links keep their label, emphasis\n * and inline-code markers are dropped, HTML comment fragments are removed,\n * and whitespace collapses. Deliberately simple — the input is our own\n * CHANGELOG (lint-capped at 200 chars per bullet), not hostile input.\n */\nexport function stripMarkdown(text: string): string {\n return text\n .replace(//g, ' ')\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1')\n .replace(/(\\*\\*|__)/g, '')\n .replace(/`/g, '')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** Strip the leading H3 marker (`### Added` → `Added`). */\nfunction stripHeading(text: string): string {\n return text.replace(/^#{1,6}[ \\t]+/, '').trim()\n}\n\n/**\n * Extract the curated summary block (`### 🆕 What's New` or `## 🆕 What's New`)\n * from a section body: its bullets only, each truncated to\n * WHATS_NEW_ITEM_MAX_CHARS, capped to WHATS_NEW_SUMMARY_MAX_ITEMS. Null when\n * the section carries no summary block (the full-section fallback applies).\n */\nexport function extractWhatsNewSummary(body: string): string[] | null {\n const lines = body.split('\\n')\n const start = lines.findIndex((line) => /^#{2,3}[ \\t]+.*What'?s New/i.test(line.trim()))\n if (start === -1) return null\n const items: string[] = []\n for (const rawLine of lines.slice(start + 1)) {\n const line = rawLine.trim()\n if (line === '' || line.startsWith('/g, ' ')\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1')\n .replace(/(\\*\\*|__)/g, '')\n .replace(/`/g, '')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** Strip the leading H3 marker (`### Added` → `Added`). */\nfunction stripHeading(text: string): string {\n return text.replace(/^#{1,6}[ \\t]+/, '').trim()\n}\n\n/**\n * Extract the curated summary block (`### 🆕 What's New` or `## 🆕 What's New`)\n * from a section body: its bullets only, each truncated to\n * WHATS_NEW_ITEM_MAX_CHARS, capped to WHATS_NEW_SUMMARY_MAX_ITEMS. Null when\n * the section carries no summary block (the full-section fallback applies).\n */\nexport function extractWhatsNewSummary(body: string): string[] | null {\n const lines = body.split('\\n')\n const start = lines.findIndex((line) => /^#{2,3}[ \\t]+.*What'?s New/i.test(line.trim()))\n if (start === -1) return null\n const items: string[] = []\n for (const rawLine of lines.slice(start + 1)) {\n const line = rawLine.trim()\n if (line === '' || line.startsWith('