pantheon-opencode 2.0.0-beta.1 → 2.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"tui.js","names":["numberOrNull"],"sources":["../src/context-gauge.ts","../src/model-usage-limits.ts","../src/pantheon-settings-state.ts","../src/sidebar-width.ts","../src/update-notice.ts","../src/whats-new-highlights.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\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 cells = 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(1, Math.floor(cells))\n const filled = contextBarFilled(value, total)\n return {\n filled: CONTEXT_BAR_FILLED_CELL.repeat(filled),\n empty: CONTEXT_BAR_EMPTY_CELL.repeat(total - filled),\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 * 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/settings-registry.test.mjs); the Overrides tab reads\n * and writes the GLOBAL overrides file — the same one\n * `pantheon-opencode`'s installer and doctor consume\n * (`<config-dir>/pantheon-overrides.json`).\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<string, OverrideEntry>\n\n/** Which behaviors the settings window can toggle (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\n/** Toggle: disabled -> enabled (entry removed); enabled -> disabled (entry written). */\nexport function toggledOverrides(\n effective: EffectiveOverrides,\n id: string,\n reason = 'toggled in /pantheon-settings',\n): EffectiveOverrides {\n const next: EffectiveOverrides = { ...effective }\n if (next[id]?.action === 'disable') delete next[id]\n else next[id] = { action: 'disable', reason }\n return next\n}\n\nexport function serializeOverrides(effective: EffectiveOverrides): string {\n const ordered: Record<string, unknown> = {}\n for (const id of Object.keys(effective).sort()) ordered[id] = effective[id]\n return `${JSON.stringify(ordered, null, 2)}\\n`\n}\n\nexport interface AboutData {\n version: string\n skillCount: number\n agentCount: number\n}\n\nexport function aboutRows(data: AboutData): string[] {\n return [\n `Pantheon v${data.version}`,\n `${data.skillCount} skills · 14 agents · 5 MCP servers`,\n 'OpenCode 2.x only — the V1 contract is removed.',\n 'Docs: docs/design/2.0-settings-and-install.md',\n ]\n}\n","/** Conservative content budget; the host sidebar slot does not report its runtime width. */\nexport const SIDEBAR_CONTENT_WIDTH = 34\n\nexport const GRAPHEMES = new Intl.Segmenter(undefined, { granularity: 'grapheme' })\n\n/** A grapheme the host draws two cells wide: emoji presentation, an extended\n * pictograph (a bare `❤` counts too, exactly as the host's `emoji-regex`\n * does) and a regional-indicator pair (a flag). */\nconst EMOJI_GLYPH = /\\p{Emoji_Presentation}|\\p{Extended_Pictographic}|\\p{Regional_Indicator}/u\n/** VS16 asks for emoji presentation; without it `1` is one cell, with it the\n * keycap sequence is drawn as one two-cell glyph. */\nconst EMOJI_PRESENTATION_SELECTOR = '\\uFE0F'\n/** Unicode default-ignorable code points carry no width of their own. */\nconst IGNORABLE_GLYPH = /^\\p{Default_Ignorable_Code_Point}$/u\n/** East Asian Wide/Fullwidth ranges — two cells, never the ambiguous width\n * (the host measures ambiguous as narrow, so `▸`/`✓`/`—` stay one cell).\n * Generated from the host's own measurement (`string-width` over every code\n * point, emoji excluded), so this table can be regenerated verbatim when the\n * host upgrades its Unicode data instead of being hand-edited. */\nconst CELL_WIDE_RANGES: readonly (readonly [number, number])[] = [\n [0x1100, 0x115e],\n [0x2329, 0x232a],\n [0x2630, 0x2637],\n [0x268a, 0x268f],\n [0x2e80, 0x2e99],\n [0x2e9b, 0x2ef3],\n [0x2f00, 0x2fd5],\n [0x2ff0, 0x302f],\n [0x3031, 0x303c],\n [0x303e, 0x303e],\n [0x3041, 0x3096],\n [0x3099, 0x30ff],\n [0x3105, 0x312f],\n [0x3131, 0x3163],\n [0x3165, 0x318e],\n [0x3190, 0x31e5],\n [0x31ef, 0x321e],\n [0x3220, 0x3247],\n [0x3250, 0x3296],\n [0x3298, 0x3298],\n [0x329a, 0xa48c],\n [0xa490, 0xa4c6],\n [0xa960, 0xa97c],\n [0xac00, 0xd7a3],\n [0xf900, 0xfaff],\n [0xfe10, 0xfe19],\n [0xfe30, 0xfe52],\n [0xfe54, 0xfe66],\n [0xfe68, 0xfe6b],\n [0xff01, 0xff60],\n [0xffe0, 0xffe6],\n [0x16fe0, 0x16fe4],\n [0x16ff0, 0x16ff6],\n [0x17000, 0x18cda],\n [0x18cff, 0x18d20],\n [0x18d80, 0x18df2],\n [0x18e00, 0x19191],\n [0x191a0, 0x191d2],\n [0x1aff0, 0x1aff3],\n [0x1aff5, 0x1affb],\n [0x1affd, 0x1affe],\n [0x1b000, 0x1b128],\n [0x1b132, 0x1b132],\n [0x1b150, 0x1b152],\n [0x1b155, 0x1b155],\n [0x1b164, 0x1b168],\n [0x1b170, 0x1b2fb],\n [0x1d300, 0x1d356],\n [0x1d360, 0x1d376],\n [0x1f200, 0x1f200],\n [0x1f210, 0x1f219],\n [0x1f21b, 0x1f22e],\n [0x1f230, 0x1f231],\n [0x1f23b, 0x1f23b],\n [0x1f240, 0x1f248],\n [0x1f260, 0x1f265],\n [0x20000, 0x2fffd],\n [0x30000, 0x3fffd],\n]\n\n/** One code point the terminal draws no cell for: control characters, the\n * zero-width joiners/marks, combining marks and variation selectors. */\nfunction isZeroWidthCodePoint(code: number, glyph: string): boolean {\n if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) return true\n if (code >= 0x200b && code <= 0x200f) return true\n if (code === 0xfeff) return true\n if (code >= 0x300 && code <= 0x36f) return true\n if (code >= 0x1ab0 && code <= 0x1aff) return true\n if (code >= 0x1dc0 && code <= 0x1dff) return true\n if (code >= 0x20d0 && code <= 0x20ff) return true\n if (code >= 0xfe00 && code <= 0xfe0f) return true\n if (code >= 0xfe20 && code <= 0xfe2f) return true\n if (code >= 0xe0100 && code <= 0xe01ef) return true\n if (code >= 0xd800 && code <= 0xdfff) return true // a lone surrogate\n return IGNORABLE_GLYPH.test(glyph)\n}\n\nfunction isWideCodePoint(code: number): boolean {\n for (const [low, high] of CELL_WIDE_RANGES) {\n if (code < low) return false\n if (code <= high) return true\n }\n return false\n}\n\n/** Cells one grapheme occupies. */\nfunction graphemeWidth(segment: string): number {\n if (EMOJI_GLYPH.test(segment)) return 2\n // A lone VS16 carries no width; after a base it asks for emoji presentation.\n if (segment.length > 1 && segment.includes(EMOJI_PRESENTATION_SELECTOR)) return 2\n let width = 0\n for (const glyph of segment) {\n const code = glyph.codePointAt(0) ?? 0\n if (isZeroWidthCodePoint(code, glyph)) continue\n width += isWideCodePoint(code) ? 2 : 1\n }\n return width\n}\n\n/** Terminal cells `value` occupies — the unit every column in this plugin is\n * measured in. Mirrors the host (that is how `@opentui/core` sizes a text\n * run): emoji count as two cells, East Asian Wide/Fullwidth as two, East\n * Asian Ambiguous as one, combining marks and variation selectors as none.\n * Pure. */\nexport function cellWidth(value: string): number {\n let width = 0\n for (const { segment } of GRAPHEMES.segment(value)) width += graphemeWidth(segment)\n return width\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 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}\n\nexport interface UpdateNotice {\n version: string\n message: string\n}\n\n/** Semver-ish compare for X.Y.Z[-beta.N]; betas 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\\.(\\d+))?$/)\n if (!match) return null\n return {\n core: [+match[1], +match[2], +match[3]],\n beta: match[4] === undefined ? Number.POSITIVE_INFINITY : +match[4],\n }\n }\n const a = parse(left)\n const b = parse(right)\n if (!a || !b) return 0\n for (let index = 0; index < 3; index += 1) {\n if (a.core[index] !== b.core[index]) return a.core[index] - b.core[index]\n }\n return a.beta - b.beta\n}\n\nexport function pickUpdateNotice(input: UpdateNoticeInput): UpdateNotice | null {\n const { currentVersion, latestVersion, state = {}, nowMs = Date.now() } = 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\n const stable = (version: string) => !/-beta\\.\\d+$/.test(version)\n // A stable install is never advertised a beta: the update guard owns that\n // crossing and requires explicit opt-in there.\n if (stable(currentVersion) && !stable(latestVersion)) return null\n\n if (comparePantheonVersions(latestVersion, currentVersion) <= 0) return null\n\n return {\n version: latestVersion,\n message:\n `pantheon-opencode ${latestVersion} available — ` +\n 'changelog in /pantheon-settings, adopt with `pantheon-opencode update`',\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 return {\n lastCheckMs: nowMs,\n lastNotifiedVersion: notice?.version ?? previous.lastNotifiedVersion,\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: `## [<version>] - 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(/<!--[\\s\\S]*?-->/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('<!--')) continue\n if (/^#{1,6}[ \\t]/.test(line)) break // next subsection — summary ended\n if (!/^[-*][ \\t]/.test(line)) continue\n if (items.length >= WHATS_NEW_SUMMARY_MAX_ITEMS) break\n const content = stripMarkdown(line.replace(/^[-*][ \\t]+/, ''))\n if (content === '') continue\n items.push(\n content.length > WHATS_NEW_ITEM_MAX_CHARS\n ? `${content.slice(0, WHATS_NEW_ITEM_MAX_CHARS - 1)}…`\n : content,\n )\n }\n return items.length > 0 ? items : null\n}\n\n/**\n * Extract the release highlights for `version`. When the section carries a\n * curated `🆕 What's New` summary block, THE WINDOW SHOWS ONLY THAT (the\n * full Added/Changed/Fixed walls are for the CHANGELOG readers, not the\n * dialog); otherwise it falls back to the H3-group extraction bounded to\n * WHATS_NEW_MAX_ITEMS bullets. A missing section, a bullet-less section or a\n * blank changelog all return EMPTY_HIGHLIGHTS (no window).\n */\nexport function extractHighlights(changelogText: string, version: string): WhatsNewHighlights {\n const { found, body } = extractSection(changelogText ?? '', version ?? '')\n if (!found || !body) return { ...EMPTY_HIGHLIGHTS }\n\n const summary = extractWhatsNewSummary(body)\n if (summary !== null) {\n return {\n version: String(version).trim().replace(/^v/i, ''),\n found: true,\n groups: [{ heading: null, items: summary }],\n totalItems: summary.length,\n truncated: false,\n }\n }\n\n const groups: WhatsNewGroup[] = []\n let totalItems = 0\n let truncated = false\n\n for (const rawLine of body.split('\\n')) {\n const line = rawLine.trim()\n if (line === '' || line.startsWith('<!--')) continue\n\n if (/^#{1,6}[ \\t]/.test(line)) {\n const heading = stripMarkdown(stripHeading(line))\n if (heading === '') continue\n if (groups.at(-1)?.items.length === 0) groups.pop() // empty group boundary\n groups.push({ heading, items: [] })\n continue\n }\n\n if (totalItems >= WHATS_NEW_MAX_ITEMS) {\n // Keep scanning only to count the remainder for the \"+N more\" line.\n if (/^[-*][ \\t]/.test(line)) totalItems += 1\n continue\n }\n\n const isBullet = /^[-*][ \\t]/.test(line)\n const continuation = (groups.at(-1)?.items.length ?? 0) > 0\n if (!isBullet && !continuation) continue // prose between groups — not a highlight\n\n const content = stripMarkdown(isBullet ? line.replace(/^[-*][ \\t]+/, '') : line)\n if (content === '') continue\n const bounded =\n content.length > WHATS_NEW_ITEM_MAX_CHARS\n ? `${content.slice(0, WHATS_NEW_ITEM_MAX_CHARS - 1)}…`\n : content\n const group = groups.at(-1)\n if (group === undefined) {\n groups.push({ heading: null, items: [bounded] })\n } else if (isBullet || group.items.length === 0) {\n group.items.push(bounded)\n } else {\n group.items[group.items.length - 1] = `${group.items.at(-1)} ${bounded}`.trim()\n }\n if (isBullet) totalItems += 1\n }\n\n const kept = groups.filter((group) => group.items.length > 0)\n truncated = totalItems > WHATS_NEW_MAX_ITEMS\n return {\n version: found ? String(version).trim().replace(/^v/i, '') : null,\n found,\n groups: kept,\n totalItems,\n truncated,\n }\n}\n\n/** Window title — mirrors the sidebar's `Pantheon v<version>` convention. */\nexport function whatsNewTitle(version: string): string {\n return `O que há de novo — Pantheon v${String(version).trim().replace(/^v/i, '')}`\n}\n\n/** Flat display lines for the window: group headings, `• ` bullets, `+N more`. */\nexport function whatsNewLines(highlights: WhatsNewHighlights): string[] {\n const lines: string[] = []\n for (const group of highlights.groups) {\n if (group.heading !== null) lines.push(group.heading)\n for (const item of group.items) lines.push(`• ${item}`)\n }\n if (highlights.truncated) {\n const hidden = Math.max(0, highlights.totalItems - WHATS_NEW_MAX_ITEMS)\n if (hidden > 0) lines.push(`${WHATS_NEW_MORE_PREFIX}${hidden} mais`)\n }\n return lines\n}\n\n/**\n * Candidate CHANGELOG.md locations for a bundle, first readable wins:\n * 1. the plugin copy root (`<configDir>/plugins/pantheon-tui/CHANGELOG.md`,\n * shipped by both installers next to package.json);\n * 2. the package root (dev checkout; also an npm-package install when the\n * bundle runs from `<pkg>/src/plugins/tui/dist/`).\n */\nexport function changelogCandidates(bundlePath: string): string[] {\n const dist = dirname(bundlePath)\n const copyRoot = dirname(dist)\n // The second leg targets the package root: src/plugins/tui → plugins → src\n // → package root (dev checkout / npm-package install). On an installed copy\n // the same three levels land on the XDG base, where no CHANGELOG lives —\n // harmless, the copy-root candidate is the one the installers ship.\n const packageRoot = dirname(dirname(dirname(copyRoot)))\n return [join(copyRoot, 'CHANGELOG.md'), join(packageRoot, 'CHANGELOG.md')]\n}\n\n/** Read the first existing candidate; null when none is readable (no window). */\nexport async function readChangelogForBundle(bundleUrl: string): Promise<string | null> {\n try {\n const bundlePath = fileURLToPath(bundleUrl)\n for (const candidate of changelogCandidates(bundlePath)) {\n try {\n return await readFile(candidate, 'utf8')\n } catch {}\n }\n return null\n } catch {\n return null\n }\n}\n\n/** Build-time embedded version (tsdown `define` in tsdown.config.ts). */\ndeclare const __PANTHEON_VERSION__: string | undefined\n\n/** The ambient build-time version, or null outside a tsdown build. */\nexport function embeddedVersion(): string | null {\n return typeof __PANTHEON_VERSION__ !== 'undefined' && __PANTHEON_VERSION__\n ? __PANTHEON_VERSION__\n : null\n}\n\n/**\n * Resolve the running Pantheon version for the what's-new window: the plugin\n * copy's own package.json first (the copy root two levels above the bundle,\n * then the package root four levels above — the same legs as the V1 sidebar's\n * detectVersion try 0a/0b), falling back to the tsdown build embed. Null when\n * nothing resolves → no window (fail-open).\n */\nexport async function resolveRunningVersion(\n bundleUrl: string,\n embedded: string | null = embeddedVersion(),\n): Promise<string | null> {\n try {\n const bundlePath = fileURLToPath(bundleUrl)\n const dist = dirname(bundlePath)\n for (const root of [dirname(dist), dirname(dirname(dirname(dist)))]) {\n try {\n const raw = await readFile(join(root, 'package.json'), 'utf8')\n const parsed = JSON.parse(raw) as { version?: unknown }\n if (typeof parsed.version === 'string' && parsed.version.trim() !== '') {\n return parsed.version\n }\n } catch {}\n }\n } catch {\n /* fall through to the embed */\n }\n return embedded\n}\n","/**\n * whats-new-state.ts — last-seen version for the one-time \"What's new\" window.\n *\n * The TUI shows a dismissable release-highlights dialog once per Pantheon\n * version. Whether a version was already seen is persisted next to the other\n * opencode-level Pantheon state: `<configDir>/.pantheon/whats-new.json`, the\n * same directory that already holds `install-state.json` (scripts/install/\n * state.mjs) and the active-preset file the sidebar reads. There is no\n * established persistent TUI KV store (the host `api.kv` is per-process), so\n * the plugin owns one small JSON file with the atomic-write discipline used\n * across the repo (unique tmp + rename, mirrors scripts/install/verify.mjs).\n *\n * Fail-open everywhere: a missing or corrupt file reads as \"never seen\" (the\n * window may show), a failed write is silent (the window may show again) —\n * neither can ever block TUI startup.\n */\nimport { mkdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\n\n/** State file name, kept next to `install-state.json` in `<configDir>/.pantheon/`. */\nexport const WHATS_NEW_STATE_FILENAME = 'whats-new.json'\n\n/** Shape of the persisted file — the plugin owns this file outright. */\nexport interface WhatsNewStateFile {\n seenVersion: string | null\n updatedAt: string\n}\n\ntype Env = Record<string, string | undefined>\n\n/** Parse a state file body; null when unreadable as the expected shape. */\nexport function parseWhatsNewState(raw: string): WhatsNewStateFile | null {\n try {\n const parsed: unknown = JSON.parse(raw)\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null\n const record = parsed as Record<string, unknown>\n const seen = record.seenVersion\n if (typeof seen !== 'string' && seen !== null) return null\n return { seenVersion: seen, updatedAt: String(record.updatedAt ?? '') }\n } catch {\n return null\n }\n}\n\n/** Read the persisted state; null when missing or corrupt (never throws). */\nexport async function readWhatsNewState(statePath: string): Promise<WhatsNewStateFile | null> {\n try {\n return parseWhatsNewState(await readFile(statePath, 'utf8'))\n } catch {\n return null\n }\n}\n\n/**\n * Whether the one-time window should show for `version`: any version change\n * since the last dismissal (including downgrades). A falsy version — the\n * resolver failed — never shows.\n */\nexport async function shouldShowWhatsNew(\n version: string | null | undefined,\n statePath: string,\n): Promise<boolean> {\n if (typeof version !== 'string' || version.trim() === '') return false\n const state = await readWhatsNewState(statePath)\n return state?.seenVersion !== version\n}\n\n/**\n * Persist `version` as seen (atomic tmp + rename, 0o600). Never throws: a\n * failed write leaves the state untouched and the window may show again —\n * the same fail-open contract as the rest of the plugin.\n */\nexport async function markSeenWhatsNew(version: string, statePath: string): Promise<boolean> {\n if (typeof version !== 'string' || version.trim() === '') return false\n const previous = await readWhatsNewState(statePath)\n const next: WhatsNewStateFile = {\n seenVersion: version,\n updatedAt: new Date().toISOString(),\n }\n const tmpPath = `${statePath}.tmp-${process.pid}`\n try {\n await mkdir(dirname(statePath), { recursive: true })\n await writeFile(tmpPath, `${JSON.stringify({ ...previous, ...next }, null, 2)}\\n`, {\n encoding: 'utf8',\n mode: 0o600,\n })\n await rename(tmpPath, statePath)\n return true\n } catch {\n try {\n await unlink(tmpPath)\n } catch {\n /* nothing to clean up */\n }\n return false\n }\n}\n\n/** `stat`-based existence probe (async I/O discipline). */\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path)\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Default state path: `<configDir>/.pantheon/whats-new.json`, resolving the\n * OpenCode config directory exactly like src/pantheon/tui-version-check.ts\n * (`$XDG_CONFIG_HOME/opencode` → `~/.opencode`), defaulting to the XDG\n * location `init` creates when neither exists yet.\n */\nexport async function defaultWhatsNewStatePath(\n env: Env = process.env,\n home: string = homedir(),\n): Promise<string> {\n const xdgConfig = env.XDG_CONFIG_HOME || join(home, '.config')\n const primary = join(xdgConfig, 'opencode')\n if (await pathExists(primary)) return join(primary, '.pantheon', WHATS_NEW_STATE_FILENAME)\n\n const legacy = join(home, '.opencode')\n if (await pathExists(legacy)) return join(legacy, '.pantheon', WHATS_NEW_STATE_FILENAME)\n\n return join(primary, '.pantheon', WHATS_NEW_STATE_FILENAME)\n}\n","/**\n * whats-new-open.ts — the show-once decision for the \"What's new\" window.\n *\n * Plain data in, plain data out: the entrypoints (index.tsx / index-v2.tsx)\n * resolve the running version and the shipped CHANGELOG.md, then hand this\n * module a `show` callback that renders the view data through the host's\n * dialog API. Keeping the decision JSX-free makes the whole one-time flow\n * testable offline (node strips the types natively) — the Solid glue lives in\n * whats-new.tsx.\n *\n * Contract (pinned by tests/tui-whats-new.test.mjs):\n * - shows at most once per version: dismissal marks the version seen;\n * - nothing to show (no version, missing CHANGELOG, empty section) → no\n * window AND no pin — the next start may still show it;\n * - never throws on its own inputs; I/O failures inside the state module\n * are fail-open there.\n */\nimport {\n EMPTY_HIGHLIGHTS,\n extractHighlights,\n type WhatsNewHighlights,\n whatsNewLines,\n whatsNewTitle,\n} from './whats-new-highlights.ts'\nimport { markSeenWhatsNew, shouldShowWhatsNew } from './whats-new-state.ts'\n\n/** Muted footer hint teaching the dismiss bind (Portuguese, like the sidebar). */\nexport const WHATS_NEW_CLOSE_HINT = 'esc/q fechar'\n\n/** Hint variant when the highlights span more than one page. */\nexport const WHATS_NEW_PAGES_HINT = 'esc/q fechar · n próxima · p volta'\n\n/** The CHANGELOG pointer shown under the highlights (the window summarizes; the file is complete). */\nexport const WHATS_NEW_MORE_HINT = 'CHANGELOG completo: CHANGELOG.md no pacote'\n\n/** Rows per page — bounded so no changelog can overflow the terminal. */\nexport const WHATS_NEW_PAGE_SIZE = 14\n\n/** Hard-wrap one display line into rows of at most `width` columns (>= 10). */\nexport function wrapWhatsNewLine(line: string, width: number): string[] {\n const bounded = Number.isInteger(width) && width > 10 ? width : 76\n const text = String(line)\n if (text.length <= bounded) return [text]\n const rows: string[] = []\n let rest = text\n while (rest.length > bounded) {\n rows.push(rest.slice(0, bounded))\n rest = rest.slice(bounded)\n }\n if (rest.length > 0) rows.push(rest)\n return rows\n}\n\n/** Slice display lines into fixed-size pages (>= 1 page, empty-safe). */\nexport function paginateWhatsNewLines(\n lines: string[],\n pageSize: number = WHATS_NEW_PAGE_SIZE,\n): string[][] {\n const size = Number.isInteger(pageSize) && pageSize > 0 ? pageSize : WHATS_NEW_PAGE_SIZE\n if (lines.length === 0) return [[]]\n const pages: string[][] = []\n for (let i = 0; i < lines.length; i += size) pages.push(lines.slice(i, i + size))\n return pages\n}\n\n/** Everything the window needs to render — no host types, no JSX. */\nexport interface WhatsNewViewData {\n version: string\n title: string\n lines: string[]\n /** Fixed-size pages of `lines` (single page when the highlights are short). */\n pages: string[][]\n hint: string\n}\n\nexport type WhatsNewShowFn = (render: () => WhatsNewViewData, onClose: () => void) => void\n\nexport interface WhatsNewOpenInput {\n /** Running Pantheon version (null when unresolvable → no window). */\n version: string | null\n /** Path of the seen-version state file (see whats-new-state.ts). */\n statePath: string\n /** Shipped CHANGELOG.md content, or null when unreadable. */\n changelogText: string | null\n /** Host dialog opener; `onClose` fires on host dismissal (ESC / chrome). */\n show: WhatsNewShowFn\n}\n\n/**\n * Open the one-time window when the version changed and highlights exist.\n * Returns true when the window was shown; the caller's `onClose` callback\n * (both host-initiated and local close binds) must funnel into marking seen.\n */\nexport async function openWhatsNew(input: WhatsNewOpenInput): Promise<boolean> {\n const { version, statePath, changelogText, show } = input\n if (typeof version !== 'string' || version.trim() === '') return false\n if (!(await shouldShowWhatsNew(version, statePath))) return false\n\n const highlights: WhatsNewHighlights = changelogText\n ? extractHighlights(changelogText, version)\n : { ...EMPTY_HIGHLIGHTS }\n const lines = whatsNewLines(highlights)\n if (lines.length === 0) return false\n\n const pages = paginateWhatsNewLines(lines)\n const data: WhatsNewViewData = {\n version,\n title: whatsNewTitle(version),\n lines,\n pages,\n hint: pages.length > 1 ? WHATS_NEW_PAGES_HINT : WHATS_NEW_CLOSE_HINT,\n }\n show(\n () => data,\n () => {\n void markSeenWhatsNew(version, statePath)\n },\n )\n return true\n}\n"],"mappings":";;;;;;;;;;AAIA,MAAa,oBAAoB;AACjC,MAAa,0BAA0B;AACvC,MAAa,yBAAyB;AAEtC,SAASA,eAAa,OAA+B;CACnD,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAgB,iBAAiB,SAAsC;CACrE,IAAI,UAAU,IAAI,OAAO;CACzB,IAAI,UAAU,IAAI,OAAO;CACzB,IAAI,UAAU,IAAI,OAAO;CACzB,OAAO;AACT;AAEA,SAAgB,iBAAiB,QAAkD;CACjF,MAAM,QAAQA,eAAa,MAAM;CACjC,IAAI,UAAU,QAAQ,QAAQ,GAAG,OAAO;CACxC,OAAO,KAAK,MAAM,KAAK,CAAC,CAAC,eAAe,OAAO;AACjD;AAEA,SAAgB,oBAAoB,OAAiD;CACnF,MAAM,QAAQA,eAAa,KAAK;CAChC,IAAI,UAAU,QAAQ,SAAS,GAAG,OAAO;CACzC,IAAI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K,WAAW,IAAI,WAAA;CAC1D,IAAI,MAAM,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC;CAClC,MAAM,QAAoB,CAAC;CAC3B,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MAAM,MAAM,KAAK,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC;CAChF,OAAO;AACT;;;;;;AA8BA,eAAsB,aAAa,OAA4C;CAC7E,MAAM,EAAE,SAAS,WAAW,eAAe,SAAS;CACpD,IAAI,OAAO,YAAY,YAAY,QAAQ,KAAK,MAAM,IAAI,OAAO;CACjE,IAAI,CAAE,MAAM,mBAAmB,SAAS,SAAS,GAAI,OAAO;CAK5D,MAAM,QAAQ,cAHyB,gBACnC,kBAAkB,eAAe,OAAO,IACxC,EAAE,GAAG,iBAAiB,CACY;CACtC,IAAI,MAAM,WAAW,GAAG,OAAO;CAE/B,MAAM,QAAQ,sBAAsB,KAAK;CACzC,MAAM,OAAyB;EAC7B;EACA,OAAO,cAAc,OAAO;EAC5B;EACA;EACA,MAAM,MAAM,SAAS,IAAI,uBAAuB;CAClD;CACA,WACQ,YACA;EACJ,iBAAsB,SAAS,SAAS;CAC1C,CACF;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"tui.js","names":["numberOrNull"],"sources":["../src/context-gauge.ts","../src/model-usage-limits.ts","../src/decision-router-state.ts","../src/pantheon-settings-state.ts","../src/update-notice.ts","../src/doctor-state.ts","../src/j1-gate-status.ts","../src/preset-state.ts","../src/update-status.ts","../src/sidebar-width.ts","../src/whats-new-highlights.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\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 cells = 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(1, Math.floor(cells))\n const filled = contextBarFilled(value, total)\n return {\n filled: CONTEXT_BAR_FILLED_CELL.repeat(filled),\n empty: CONTEXT_BAR_EMPTY_CELL.repeat(total - filled),\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 * 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, SettingsSection } from './pantheon-settings-state.ts'\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 function decisionRouterConfigPath(env: Record<string, string | undefined> = 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<string, string | undefined> = 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<string, unknown>\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<string, unknown>\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<string, unknown>\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: 'remote candidates need egress consent — grant via `decision-router setup-model`',\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<string, string | undefined> = 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 function buildDecisionSection(read: DecisionConfigRead): SettingsSection {\n const { config, corrupt } = read\n const rows: SettingsRow[] = [\n {\n id: 'decision.enabled',\n title: `Decision router: ${config.enabled ? 'enabled' : 'disabled'}`,\n description: corrupt\n ? 'config file unreadable/invalid — the runtime fail-closes to disabled'\n : 'the runtime re-reads this file on every gated call — applies live',\n disabled: !config.enabled,\n },\n {\n id: 'decision.selection',\n title: `Selection: ${config.selection.mode}${config.selection.provider ? ` · ${config.selection.provider}` : ''}`,\n description: 'local routes on-device; auto/explicit pick a remote decision model',\n selectable: false,\n },\n ]\n if (config.enabled_candidates.length > 0) {\n rows.push({\n id: 'decision.candidates',\n title: `Candidates: ${config.enabled_candidates.map((candidate) => `${candidate.provider}/${candidate.model}`).join(', ')}`,\n description: config.egress_consent\n ? 'egress consent granted'\n : 'egress consent NOT granted — remote routes fail closed',\n selectable: false,\n })\n }\n return {\n id: 'decision',\n title: 'Decision Model',\n rows,\n hint: corrupt\n ? 'repair via `decision-router setup-model` — writes refused on an invalid file'\n : 'enter: enable/disable · consent and candidates via `decision-router setup-model`',\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); the Gates section\n * reads and writes the GLOBAL overrides file — the same one\n * `pantheon-opencode`'s installer and doctor consume\n * (`<config-dir>/pantheon-overrides.json`).\n *\n * Sections: the window renders one section per page. This module owns the\n * section/row model and the Gates section; other sections live in sibling\n * TUI-local modules (j1-gate-status.ts, update-status.ts, …) and follow the\n * same shape.\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<string, OverrideEntry>\n\n/** Which behaviors the settings window can toggle (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\n// ── Section / row model ────────────────────────────────────────────────\n\nexport interface SettingsRow {\n /** Namespaced action key (`gate.<behavior-id>`, `update.check`, …). */\n id: string\n title: string\n description: string\n /** Gates rows: the override disables the behavior (`[x]` marker). */\n disabled?: boolean\n /** Overrides the `[x]`/`[ ]` marker (`→` action, `✓`/`!` status). */\n marker?: string\n /** false → skipped by up/down and never dispatched by enter (info lines). */\n selectable?: boolean\n /** The effective entry comes from the PROJECT overrides file (read-only). */\n source?: 'global' | 'project'\n}\n\nexport interface SettingsSection {\n id: string\n title: string\n /** One muted hint line under the rows. */\n hint?: string\n rows: SettingsRow[]\n}\n\n/** The rows up/down can reach and enter can dispatch on, in order. */\nexport function selectableRows(section: SettingsSection): SettingsRow[] {\n return section.rows.filter((row) => row.selectable !== false)\n}\n\n/** Flat selection order across every section of the window. */\nexport function flatSelectableRows(sections: readonly SettingsSection[]): SettingsRow[] {\n return sections.flatMap((section) => selectableRows(section))\n}\n\nexport function firstSelectableId(sections: readonly SettingsSection[]): string | undefined {\n return flatSelectableRows(sections)[0]?.id\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/**\n * Merge for DISPLAY only, mirroring the runtime precedence: the project file\n * wins per id (whole entry). The window still writes only the global file.\n */\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// ── Toggle semantics ───────────────────────────────────────────────────\n\nexport const TOGGLE_REASON = 'toggled in /pantheon-settings'\n\n/**\n * Toggle: disabled -> enabled; enabled -> disabled.\n *\n * A `replace` entry is never destroyed by a toggle (\"never trap user state\"):\n * disabling keeps its `content` under the disable entry, and re-enabling\n * restores the replace. A settings-written disable (no content) is removed\n * outright so the overrides file does not accumulate 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 // A settings-written disable restores a clean replace; a hand-authored\n // disable+content keeps its own provenance reason.\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\nexport function serializeOverrides(effective: EffectiveOverrides): string {\n const ordered: Record<string, unknown> = {}\n for (const id of Object.keys(effective).sort()) ordered[id] = effective[id]\n return `${JSON.stringify(ordered, null, 2)}\\n`\n}\n\n// ── Gates section ──────────────────────────────────────────────────────\n\n/**\n * The Gates & Overrides page: behavior state from BOTH overrides files.\n * A project-owned entry wins the runtime merge and the window only writes\n * the global file, so project rows are marked and not togglable here.\n */\nexport function buildGatesSection(load: OverridesLoad): SettingsSection {\n const merged = mergedOverrides(load)\n const rows: SettingsRow[] = SETTINGS_BEHAVIORS.map((behavior) => {\n const fromProject = load.project[behavior.id] !== undefined\n return {\n id: `gate.${behavior.id}`,\n title: fromProject ? `${behavior.title} (project)` : behavior.title,\n description: behavior.description,\n disabled: isBehaviorDisabled(merged, behavior.id),\n selectable: !fromProject,\n source: fromProject ? 'project' : 'global',\n }\n })\n return {\n id: 'gates',\n title: 'Gates & Overrides',\n hint: canWriteOverrides(load)\n ? 'enter: disable/enable · writes pantheon-overrides.json (global)'\n : 'overrides file unreadable — writes refused; repair with `pantheon-opencode doctor --fix`',\n rows,\n }\n}\n\n// ── About section ──────────────────────────────────────────────────────\n\nexport function buildAboutSection(version: string): SettingsSection {\n return {\n id: 'about',\n title: 'About',\n rows: [\n {\n id: 'about.version',\n title: `Pantheon v${version}`,\n description: 'OpenCode 2.x only — the V1 contract is removed.',\n selectable: false,\n },\n {\n id: 'about.behaviors',\n title: `${SETTINGS_BEHAVIORS.length} togglable behaviors`,\n description: 'Docs: docs/design/2.0-settings-and-install.md',\n selectable: false,\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 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}\n\nexport interface UpdateNotice {\n version: string\n message: string\n}\n\n/** Semver-ish compare for X.Y.Z[-beta.N]; betas 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\\.(\\d+))?$/)\n if (!match) return null\n const [, major = '', minor = '', patch = '', beta = ''] = match\n return {\n core: [+major, +minor, +patch] as [number, number, number],\n beta: beta === '' ? Number.POSITIVE_INFINITY : +beta,\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 return a.beta - b.beta\n}\n\nexport function pickUpdateNotice(input: UpdateNoticeInput): UpdateNotice | null {\n const { currentVersion, latestVersion, state = {}, nowMs = Date.now() } = 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\n const stable = (version: string) => !/-beta\\.\\d+$/.test(version)\n // A stable install is never advertised a beta: the update guard owns that\n // crossing and requires explicit opt-in there.\n if (stable(currentVersion) && !stable(latestVersion)) return null\n\n if (comparePantheonVersions(latestVersion, currentVersion) <= 0) return null\n\n return {\n version: latestVersion,\n message:\n `pantheon-opencode ${latestVersion} available — ` +\n 'changelog in /pantheon-settings, adopt with `pantheon-opencode update`',\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 * (`<config>/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 SettingsSection,\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<string, string | undefined> = 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<string, string | undefined> = 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<string, string | undefined> = 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<string, string | undefined>\n}\n\nexport function buildDoctorSection(input: DoctorSectionInput): SettingsSection {\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 title:\n version.status === 'ok'\n ? `Installed version: v${version.installed} — matches`\n : version.status === 'older'\n ? `Installed v${version.installed} is older than the runtime v${input.runningVersion}`\n : version.status === 'newer'\n ? `Installed v${version.installed} is newer than the runtime v${input.runningVersion}`\n : 'Installed version: unknown (no install-state)',\n description:\n version.status === 'older'\n ? 'refresh with `pantheon-opencode update`'\n : 'read from <config>/opencode/.pantheon/install-state.json',\n marker: version.status === 'ok' ? '[✓]' : version.status === 'older' ? '[!]' : '[i]',\n selectable: false,\n })\n\n const nodeOk = isSupportedNodeFloor(input.nodeVersion)\n rows.push({\n id: 'doctor.node',\n title: `Node runtime: ${input.nodeVersion.replace(/^v/, '')}`,\n description: nodeOk\n ? `meets the >= ${MIN_SUPPORTED_NODE_VERSION} floor`\n : `below the >= ${MIN_SUPPORTED_NODE_VERSION} floor — tooling may refuse`,\n marker: nodeOk ? '[✓]' : '[!]',\n selectable: false,\n })\n\n const overrides = classifyOverridesHealth(input.load)\n rows.push({\n id: 'doctor.overrides',\n title:\n overrides.status === 'clean'\n ? 'Overrides: valid'\n : overrides.status === 'corrupt'\n ? 'Overrides: global file unreadable'\n : `Overrides: ${overrides.unknownIds.length} unknown id(s)`,\n description:\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 marker: overrides.status === 'clean' ? '[✓]' : overrides.status === 'corrupt' ? '[✗]' : '[!]',\n selectable: false,\n })\n\n const decision = classifyDecisionConfigHealth(env)\n rows.push({\n id: 'doctor.decision',\n title:\n decision.status === 'ok'\n ? 'Decision config: valid'\n : decision.status === 'corrupt'\n ? 'Decision config: unreadable — runtime fail-closes'\n : 'Decision config: absent (local defaults)',\n description: 'read from <config>/pantheon/decision-router.json',\n marker: decision.status === 'corrupt' ? '[✗]' : '[✓]',\n selectable: false,\n })\n\n return {\n id: 'doctor',\n title: 'Doctor',\n rows,\n hint: 'file checks only — the full doctor (MCP smoke, venv, git) is `pantheon-opencode doctor`',\n }\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 { SettingsRow, SettingsSection } from './pantheon-settings-state.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<string, string | undefined> = 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<string, string | undefined> = 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: Record<J1Mode, string> = {\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\nexport function buildJ1Section(\n env: Record<string, string | undefined>,\n disabledByOverride: boolean,\n): SettingsSection {\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 rows: SettingsRow[] = [\n {\n id: 'j1.mode',\n title: `Mode: ${mode}`,\n description: MODE_DESCRIPTION[mode],\n ...(disabledByOverride ? { marker: '[!]' } : {}),\n selectable: false,\n },\n {\n id: 'j1.threshold',\n title: `Enforce threshold: ${threshold}`,\n description: 'deny at or above; 0..1, default 0.8',\n selectable: false,\n },\n {\n id: 'j1.gate',\n title: `Gate: ${gateState}`,\n description: 'the runtime plugin reads this once at startup',\n selectable: false,\n },\n ]\n return {\n id: 'j1',\n title: 'J1 Risk Gate',\n hint: `set ${J1_FLAG_ENV} / ${J1_THRESHOLD_ENV} — restart applies`,\n rows,\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 * (`<config-dir>/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, SettingsSection } 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<string, string | undefined> = 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 interface PresetSectionInput {\n globalName: string | null\n projectName: string | null\n}\n\nexport function buildPresetSection(input: PresetSectionInput): SettingsSection {\n const rows: SettingsRow[] = PRESET_NAMES.map((name) => ({\n id: `preset.${name}`,\n title: name,\n description: input.globalName === name ? 'active (global)' : 'enter: activate globally',\n disabled: input.globalName === name,\n }))\n rows.push({\n id: 'preset.none',\n title: 'none',\n description: 'clear the global marker — opencode defaults',\n disabled: input.globalName === null,\n marker: input.globalName === null ? '[x]' : '[ ]',\n })\n if (input.projectName !== null) {\n rows.push({\n id: 'preset.project',\n title: `${input.projectName} (project)`,\n description: `${projectActivePresetPath()} wins over the global marker`,\n marker: '[!]',\n selectable: false,\n })\n }\n return {\n id: 'preset',\n title: 'Model Preset',\n rows,\n hint: 'enter: activate globally · writes <config>/opencode/.pantheon/active-preset.json',\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 type { SettingsRow, SettingsSection } from './pantheon-settings-state.ts'\nimport {\n comparePantheonVersions,\n UPDATE_CHECK_TTL_MS,\n type UpdateCheckState,\n} 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): string {\n if (ms < 60_000) return 'just now'\n if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m ago`\n if (ms < 86_400_000) return `${Math.floor(ms / 3_600_000)}h ago`\n return `${Math.floor(ms / 86_400_000)}d ago`\n}\n\nexport interface UpdatesSectionInput {\n currentVersion: string\n state: UpdateCheckState\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 nowMs?: number\n}\n\nexport function buildUpdatesSection(input: UpdatesSectionInput): SettingsSection {\n const nowMs = input.nowMs ?? Date.now()\n const channel = updateChannelFor(input.currentVersion)\n const lastCheckMs = input.state.lastCheckMs\n const latest = input.lastCheckedVersion ?? input.state.lastNotifiedVersion\n\n const rows: SettingsRow[] = [\n {\n id: 'update.channel',\n title: `Channel: ${channel}`,\n description: 'stable tracks npm `latest`; beta tracks npm `beta`',\n selectable: false,\n },\n {\n id: 'update.check',\n title: 'Check now',\n description: input.checking\n ? 'checking…'\n : lastCheckMs\n ? `last check ${formatAgo(nowMs - lastCheckMs)}`\n : 'never checked',\n marker: ' → ',\n selectable: true,\n },\n ]\n\n if (latest) {\n // Same guard as pickUpdateNotice: a stable install is never advertised a\n // beta — the update CLI owns that crossing (explicit opt-in).\n const stable = (version: string) => !/-beta\\.\\d+$/.test(version)\n const newer =\n comparePantheonVersions(latest, input.currentVersion) > 0 &&\n !(stable(input.currentVersion) && !stable(latest))\n rows.push({\n id: 'update.latest',\n title: newer ? `Update available: v${latest}` : `Up to date (latest seen v${latest})`,\n description: newer ? 'adopt with `pantheon-opencode update`' : 'checked against the registry',\n marker: newer ? '[!]' : '[✓]',\n selectable: false,\n })\n }\n\n return {\n id: 'updates',\n title: 'Updates',\n hint: `refresh = \\`pantheon-opencode update\\` · notice TTL ${UPDATE_CHECK_TTL_MS / 3_600_000}h`,\n rows,\n }\n}\n","/** Conservative content budget; the host sidebar slot does not report its runtime width. */\nexport const SIDEBAR_CONTENT_WIDTH = 34\n\nexport const GRAPHEMES = new Intl.Segmenter(undefined, { granularity: 'grapheme' })\n\n/** A grapheme the host draws two cells wide: emoji presentation, an extended\n * pictograph (a bare `❤` counts too, exactly as the host's `emoji-regex`\n * does) and a regional-indicator pair (a flag). */\nconst EMOJI_GLYPH = /\\p{Emoji_Presentation}|\\p{Extended_Pictographic}|\\p{Regional_Indicator}/u\n/** VS16 asks for emoji presentation; without it `1` is one cell, with it the\n * keycap sequence is drawn as one two-cell glyph. */\nconst EMOJI_PRESENTATION_SELECTOR = '\\uFE0F'\n/** Unicode default-ignorable code points carry no width of their own. */\nconst IGNORABLE_GLYPH = /^\\p{Default_Ignorable_Code_Point}$/u\n/** East Asian Wide/Fullwidth ranges — two cells, never the ambiguous width\n * (the host measures ambiguous as narrow, so `▸`/`✓`/`—` stay one cell).\n * Generated from the host's own measurement (`string-width` over every code\n * point, emoji excluded), so this table can be regenerated verbatim when the\n * host upgrades its Unicode data instead of being hand-edited. */\nconst CELL_WIDE_RANGES: readonly (readonly [number, number])[] = [\n [0x1100, 0x115e],\n [0x2329, 0x232a],\n [0x2630, 0x2637],\n [0x268a, 0x268f],\n [0x2e80, 0x2e99],\n [0x2e9b, 0x2ef3],\n [0x2f00, 0x2fd5],\n [0x2ff0, 0x302f],\n [0x3031, 0x303c],\n [0x303e, 0x303e],\n [0x3041, 0x3096],\n [0x3099, 0x30ff],\n [0x3105, 0x312f],\n [0x3131, 0x3163],\n [0x3165, 0x318e],\n [0x3190, 0x31e5],\n [0x31ef, 0x321e],\n [0x3220, 0x3247],\n [0x3250, 0x3296],\n [0x3298, 0x3298],\n [0x329a, 0xa48c],\n [0xa490, 0xa4c6],\n [0xa960, 0xa97c],\n [0xac00, 0xd7a3],\n [0xf900, 0xfaff],\n [0xfe10, 0xfe19],\n [0xfe30, 0xfe52],\n [0xfe54, 0xfe66],\n [0xfe68, 0xfe6b],\n [0xff01, 0xff60],\n [0xffe0, 0xffe6],\n [0x16fe0, 0x16fe4],\n [0x16ff0, 0x16ff6],\n [0x17000, 0x18cda],\n [0x18cff, 0x18d20],\n [0x18d80, 0x18df2],\n [0x18e00, 0x19191],\n [0x191a0, 0x191d2],\n [0x1aff0, 0x1aff3],\n [0x1aff5, 0x1affb],\n [0x1affd, 0x1affe],\n [0x1b000, 0x1b128],\n [0x1b132, 0x1b132],\n [0x1b150, 0x1b152],\n [0x1b155, 0x1b155],\n [0x1b164, 0x1b168],\n [0x1b170, 0x1b2fb],\n [0x1d300, 0x1d356],\n [0x1d360, 0x1d376],\n [0x1f200, 0x1f200],\n [0x1f210, 0x1f219],\n [0x1f21b, 0x1f22e],\n [0x1f230, 0x1f231],\n [0x1f23b, 0x1f23b],\n [0x1f240, 0x1f248],\n [0x1f260, 0x1f265],\n [0x20000, 0x2fffd],\n [0x30000, 0x3fffd],\n]\n\n/** One code point the terminal draws no cell for: control characters, the\n * zero-width joiners/marks, combining marks and variation selectors. */\nfunction isZeroWidthCodePoint(code: number, glyph: string): boolean {\n if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) return true\n if (code >= 0x200b && code <= 0x200f) return true\n if (code === 0xfeff) return true\n if (code >= 0x300 && code <= 0x36f) return true\n if (code >= 0x1ab0 && code <= 0x1aff) return true\n if (code >= 0x1dc0 && code <= 0x1dff) return true\n if (code >= 0x20d0 && code <= 0x20ff) return true\n if (code >= 0xfe00 && code <= 0xfe0f) return true\n if (code >= 0xfe20 && code <= 0xfe2f) return true\n if (code >= 0xe0100 && code <= 0xe01ef) return true\n if (code >= 0xd800 && code <= 0xdfff) return true // a lone surrogate\n return IGNORABLE_GLYPH.test(glyph)\n}\n\nfunction isWideCodePoint(code: number): boolean {\n for (const [low, high] of CELL_WIDE_RANGES) {\n if (code < low) return false\n if (code <= high) return true\n }\n return false\n}\n\n/** Cells one grapheme occupies. */\nfunction graphemeWidth(segment: string): number {\n if (EMOJI_GLYPH.test(segment)) return 2\n // A lone VS16 carries no width; after a base it asks for emoji presentation.\n if (segment.length > 1 && segment.includes(EMOJI_PRESENTATION_SELECTOR)) return 2\n let width = 0\n for (const glyph of segment) {\n const code = glyph.codePointAt(0) ?? 0\n if (isZeroWidthCodePoint(code, glyph)) continue\n width += isWideCodePoint(code) ? 2 : 1\n }\n return width\n}\n\n/** Terminal cells `value` occupies — the unit every column in this plugin is\n * measured in. Mirrors the host (that is how `@opentui/core` sizes a text\n * run): emoji count as two cells, East Asian Wide/Fullwidth as two, East\n * Asian Ambiguous as one, combining marks and variation selectors as none.\n * Pure. */\nexport function cellWidth(value: string): number {\n let width = 0\n for (const { segment } of GRAPHEMES.segment(value)) width += graphemeWidth(segment)\n return width\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: `## [<version>] - 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(/<!--[\\s\\S]*?-->/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('<!--')) continue\n if (/^#{1,6}[ \\t]/.test(line)) break // next subsection — summary ended\n if (!/^[-*][ \\t]/.test(line)) continue\n if (items.length >= WHATS_NEW_SUMMARY_MAX_ITEMS) break\n const content = stripMarkdown(line.replace(/^[-*][ \\t]+/, ''))\n if (content === '') continue\n items.push(\n content.length > WHATS_NEW_ITEM_MAX_CHARS\n ? `${content.slice(0, WHATS_NEW_ITEM_MAX_CHARS - 1)}…`\n : content,\n )\n }\n return items.length > 0 ? items : null\n}\n\n/**\n * Extract the release highlights for `version`. When the section carries a\n * curated `🆕 What's New` summary block, THE WINDOW SHOWS ONLY THAT (the\n * full Added/Changed/Fixed walls are for the CHANGELOG readers, not the\n * dialog); otherwise it falls back to the H3-group extraction bounded to\n * WHATS_NEW_MAX_ITEMS bullets. A missing section, a bullet-less section or a\n * blank changelog all return EMPTY_HIGHLIGHTS (no window).\n */\nexport function extractHighlights(changelogText: string, version: string): WhatsNewHighlights {\n const { found, body } = extractSection(changelogText ?? '', version ?? '')\n if (!found || !body) return { ...EMPTY_HIGHLIGHTS }\n\n const summary = extractWhatsNewSummary(body)\n if (summary !== null) {\n return {\n version: String(version).trim().replace(/^v/i, ''),\n found: true,\n groups: [{ heading: null, items: summary }],\n totalItems: summary.length,\n truncated: false,\n }\n }\n\n const groups: WhatsNewGroup[] = []\n let totalItems = 0\n let truncated = false\n\n for (const rawLine of body.split('\\n')) {\n const line = rawLine.trim()\n if (line === '' || line.startsWith('<!--')) continue\n\n if (/^#{1,6}[ \\t]/.test(line)) {\n const heading = stripMarkdown(stripHeading(line))\n if (heading === '') continue\n if (groups.at(-1)?.items.length === 0) groups.pop() // empty group boundary\n groups.push({ heading, items: [] })\n continue\n }\n\n if (totalItems >= WHATS_NEW_MAX_ITEMS) {\n // Keep scanning only to count the remainder for the \"+N more\" line.\n if (/^[-*][ \\t]/.test(line)) totalItems += 1\n continue\n }\n\n const isBullet = /^[-*][ \\t]/.test(line)\n const continuation = (groups.at(-1)?.items.length ?? 0) > 0\n if (!isBullet && !continuation) continue // prose between groups — not a highlight\n\n const content = stripMarkdown(isBullet ? line.replace(/^[-*][ \\t]+/, '') : line)\n if (content === '') continue\n const bounded =\n content.length > WHATS_NEW_ITEM_MAX_CHARS\n ? `${content.slice(0, WHATS_NEW_ITEM_MAX_CHARS - 1)}…`\n : content\n const group = groups.at(-1)\n if (group === undefined) {\n groups.push({ heading: null, items: [bounded] })\n } else if (isBullet || group.items.length === 0) {\n group.items.push(bounded)\n } else {\n group.items[group.items.length - 1] = `${group.items.at(-1)} ${bounded}`.trim()\n }\n if (isBullet) totalItems += 1\n }\n\n const kept = groups.filter((group) => group.items.length > 0)\n truncated = totalItems > WHATS_NEW_MAX_ITEMS\n return {\n version: found ? String(version).trim().replace(/^v/i, '') : null,\n found,\n groups: kept,\n totalItems,\n truncated,\n }\n}\n\n/** Window title — mirrors the sidebar's `Pantheon v<version>` convention. */\nexport function whatsNewTitle(version: string): string {\n return `O que há de novo — Pantheon v${String(version).trim().replace(/^v/i, '')}`\n}\n\n/** Flat display lines for the window: group headings, `• ` bullets, `+N more`. */\nexport function whatsNewLines(highlights: WhatsNewHighlights): string[] {\n const lines: string[] = []\n for (const group of highlights.groups) {\n if (group.heading !== null) lines.push(group.heading)\n for (const item of group.items) lines.push(`• ${item}`)\n }\n if (highlights.truncated) {\n const hidden = Math.max(0, highlights.totalItems - WHATS_NEW_MAX_ITEMS)\n if (hidden > 0) lines.push(`${WHATS_NEW_MORE_PREFIX}${hidden} mais`)\n }\n return lines\n}\n\n/**\n * Candidate CHANGELOG.md locations for a bundle, first readable wins:\n * 1. the plugin copy root (`<configDir>/plugins/pantheon-tui/CHANGELOG.md`,\n * shipped by both installers next to package.json);\n * 2. the package root (dev checkout; also an npm-package install when the\n * bundle runs from `<pkg>/src/plugins/tui/dist/`).\n */\nexport function changelogCandidates(bundlePath: string): string[] {\n const dist = dirname(bundlePath)\n const copyRoot = dirname(dist)\n // The second leg targets the package root: src/plugins/tui → plugins → src\n // → package root (dev checkout / npm-package install). On an installed copy\n // the same three levels land on the XDG base, where no CHANGELOG lives —\n // harmless, the copy-root candidate is the one the installers ship.\n const packageRoot = dirname(dirname(dirname(copyRoot)))\n return [join(copyRoot, 'CHANGELOG.md'), join(packageRoot, 'CHANGELOG.md')]\n}\n\n/** Read the first existing candidate; null when none is readable (no window). */\nexport async function readChangelogForBundle(bundleUrl: string): Promise<string | null> {\n try {\n const bundlePath = fileURLToPath(bundleUrl)\n for (const candidate of changelogCandidates(bundlePath)) {\n try {\n return await readFile(candidate, 'utf8')\n } catch {}\n }\n return null\n } catch {\n return null\n }\n}\n\n/** Build-time embedded version (tsdown `define` in tsdown.config.ts). */\ndeclare const __PANTHEON_VERSION__: string | undefined\n\n/** The ambient build-time version, or null outside a tsdown build. */\nexport function embeddedVersion(): string | null {\n return typeof __PANTHEON_VERSION__ !== 'undefined' && __PANTHEON_VERSION__\n ? __PANTHEON_VERSION__\n : null\n}\n\n/**\n * Resolve the running Pantheon version for the what's-new window: the plugin\n * copy's own package.json first (the copy root two levels above the bundle,\n * then the package root four levels above — the same legs as the V1 sidebar's\n * detectVersion try 0a/0b), falling back to the tsdown build embed. Null when\n * nothing resolves → no window (fail-open).\n */\nexport async function resolveRunningVersion(\n bundleUrl: string,\n embedded: string | null = embeddedVersion(),\n): Promise<string | null> {\n try {\n const bundlePath = fileURLToPath(bundleUrl)\n const dist = dirname(bundlePath)\n for (const root of [dirname(dist), dirname(dirname(dirname(dist)))]) {\n try {\n const raw = await readFile(join(root, 'package.json'), 'utf8')\n const parsed = JSON.parse(raw) as { version?: unknown }\n if (typeof parsed.version === 'string' && parsed.version.trim() !== '') {\n return parsed.version\n }\n } catch {}\n }\n } catch {\n /* fall through to the embed */\n }\n return embedded\n}\n","/**\n * whats-new-state.ts — last-seen version for the one-time \"What's new\" window.\n *\n * The TUI shows a dismissable release-highlights dialog once per Pantheon\n * version. Whether a version was already seen is persisted next to the other\n * opencode-level Pantheon state: `<configDir>/.pantheon/whats-new.json`, the\n * same directory that already holds `install-state.json` (scripts/install/\n * state.mjs) and the active-preset file the sidebar reads. There is no\n * established persistent TUI KV store (the host `api.kv` is per-process), so\n * the plugin owns one small JSON file with the atomic-write discipline used\n * across the repo (unique tmp + rename, mirrors scripts/install/verify.mjs).\n *\n * Fail-open everywhere: a missing or corrupt file reads as \"never seen\" (the\n * window may show), a failed write is silent (the window may show again) —\n * neither can ever block TUI startup.\n */\nimport { mkdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\n\n/** State file name, kept next to `install-state.json` in `<configDir>/.pantheon/`. */\nexport const WHATS_NEW_STATE_FILENAME = 'whats-new.json'\n\n/** Shape of the persisted file — the plugin owns this file outright. */\nexport interface WhatsNewStateFile {\n seenVersion: string | null\n updatedAt: string\n}\n\ntype Env = Record<string, string | undefined>\n\n/** Parse a state file body; null when unreadable as the expected shape. */\nexport function parseWhatsNewState(raw: string): WhatsNewStateFile | null {\n try {\n const parsed: unknown = JSON.parse(raw)\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null\n const record = parsed as Record<string, unknown>\n const seen = record.seenVersion\n if (typeof seen !== 'string' && seen !== null) return null\n return { seenVersion: seen, updatedAt: String(record.updatedAt ?? '') }\n } catch {\n return null\n }\n}\n\n/** Read the persisted state; null when missing or corrupt (never throws). */\nexport async function readWhatsNewState(statePath: string): Promise<WhatsNewStateFile | null> {\n try {\n return parseWhatsNewState(await readFile(statePath, 'utf8'))\n } catch {\n return null\n }\n}\n\n/**\n * Whether the one-time window should show for `version`: any version change\n * since the last dismissal (including downgrades). A falsy version — the\n * resolver failed — never shows.\n */\nexport async function shouldShowWhatsNew(\n version: string | null | undefined,\n statePath: string,\n): Promise<boolean> {\n if (typeof version !== 'string' || version.trim() === '') return false\n const state = await readWhatsNewState(statePath)\n return state?.seenVersion !== version\n}\n\n/**\n * Persist `version` as seen (atomic tmp + rename, 0o600). Never throws: a\n * failed write leaves the state untouched and the window may show again —\n * the same fail-open contract as the rest of the plugin.\n */\nexport async function markSeenWhatsNew(version: string, statePath: string): Promise<boolean> {\n if (typeof version !== 'string' || version.trim() === '') return false\n const previous = await readWhatsNewState(statePath)\n const next: WhatsNewStateFile = {\n seenVersion: version,\n updatedAt: new Date().toISOString(),\n }\n const tmpPath = `${statePath}.tmp-${process.pid}`\n try {\n await mkdir(dirname(statePath), { recursive: true })\n await writeFile(tmpPath, `${JSON.stringify({ ...previous, ...next }, null, 2)}\\n`, {\n encoding: 'utf8',\n mode: 0o600,\n })\n await rename(tmpPath, statePath)\n return true\n } catch {\n try {\n await unlink(tmpPath)\n } catch {\n /* nothing to clean up */\n }\n return false\n }\n}\n\n/** `stat`-based existence probe (async I/O discipline). */\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path)\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Default state path: `<configDir>/.pantheon/whats-new.json`, resolving the\n * OpenCode config directory exactly like src/pantheon/tui-version-check.ts\n * (`$XDG_CONFIG_HOME/opencode` → `~/.opencode`), defaulting to the XDG\n * location `init` creates when neither exists yet.\n */\nexport async function defaultWhatsNewStatePath(\n env: Env = process.env,\n home: string = homedir(),\n): Promise<string> {\n const xdgConfig = env.XDG_CONFIG_HOME || join(home, '.config')\n const primary = join(xdgConfig, 'opencode')\n if (await pathExists(primary)) return join(primary, '.pantheon', WHATS_NEW_STATE_FILENAME)\n\n const legacy = join(home, '.opencode')\n if (await pathExists(legacy)) return join(legacy, '.pantheon', WHATS_NEW_STATE_FILENAME)\n\n return join(primary, '.pantheon', WHATS_NEW_STATE_FILENAME)\n}\n","/**\n * whats-new-open.ts — the show-once decision for the \"What's new\" window.\n *\n * Plain data in, plain data out: the entrypoints (index.tsx / index-v2.tsx)\n * resolve the running version and the shipped CHANGELOG.md, then hand this\n * module a `show` callback that renders the view data through the host's\n * dialog API. Keeping the decision JSX-free makes the whole one-time flow\n * testable offline (node strips the types natively) — the Solid glue lives in\n * whats-new.tsx.\n *\n * Contract (pinned by tests/tui-whats-new.test.mjs):\n * - shows at most once per version: dismissal marks the version seen;\n * - nothing to show (no version, missing CHANGELOG, empty section) → no\n * window AND no pin — the next start may still show it;\n * - never throws on its own inputs; I/O failures inside the state module\n * are fail-open there.\n */\nimport {\n EMPTY_HIGHLIGHTS,\n extractHighlights,\n type WhatsNewHighlights,\n whatsNewLines,\n whatsNewTitle,\n} from './whats-new-highlights.ts'\nimport { markSeenWhatsNew, shouldShowWhatsNew } from './whats-new-state.ts'\n\n/** Muted footer hint teaching the dismiss bind (Portuguese, like the sidebar). */\nexport const WHATS_NEW_CLOSE_HINT = 'esc/q fechar'\n\n/** Hint variant when the highlights span more than one page. */\nexport const WHATS_NEW_PAGES_HINT = 'esc/q fechar · n próxima · p volta'\n\n/** The CHANGELOG pointer shown under the highlights (the window summarizes; the file is complete). */\nexport const WHATS_NEW_MORE_HINT = 'CHANGELOG completo: CHANGELOG.md no pacote'\n\n/** Rows per page — bounded so no changelog can overflow the terminal. */\nexport const WHATS_NEW_PAGE_SIZE = 14\n\n/** Hard-wrap one display line into rows of at most `width` columns (>= 10). */\nexport function wrapWhatsNewLine(line: string, width: number): string[] {\n const bounded = Number.isInteger(width) && width > 10 ? width : 76\n const text = String(line)\n if (text.length <= bounded) return [text]\n const rows: string[] = []\n let rest = text\n while (rest.length > bounded) {\n rows.push(rest.slice(0, bounded))\n rest = rest.slice(bounded)\n }\n if (rest.length > 0) rows.push(rest)\n return rows\n}\n\n/** Slice display lines into fixed-size pages (>= 1 page, empty-safe). */\nexport function paginateWhatsNewLines(\n lines: string[],\n pageSize: number = WHATS_NEW_PAGE_SIZE,\n): string[][] {\n const size = Number.isInteger(pageSize) && pageSize > 0 ? pageSize : WHATS_NEW_PAGE_SIZE\n if (lines.length === 0) return [[]]\n const pages: string[][] = []\n for (let i = 0; i < lines.length; i += size) pages.push(lines.slice(i, i + size))\n return pages\n}\n\n/** Everything the window needs to render — no host types, no JSX. */\nexport interface WhatsNewViewData {\n version: string\n title: string\n lines: string[]\n /** Fixed-size pages of `lines` (single page when the highlights are short). */\n pages: string[][]\n hint: string\n}\n\nexport type WhatsNewShowFn = (render: () => WhatsNewViewData, onClose: () => void) => void\n\nexport interface WhatsNewOpenInput {\n /** Running Pantheon version (null when unresolvable → no window). */\n version: string | null\n /** Path of the seen-version state file (see whats-new-state.ts). */\n statePath: string\n /** Shipped CHANGELOG.md content, or null when unreadable. */\n changelogText: string | null\n /** Host dialog opener; `onClose` fires on host dismissal (ESC / chrome). */\n show: WhatsNewShowFn\n}\n\n/**\n * Open the one-time window when the version changed and highlights exist.\n * Returns true when the window was shown; the caller's `onClose` callback\n * (both host-initiated and local close binds) must funnel into marking seen.\n */\nexport async function openWhatsNew(input: WhatsNewOpenInput): Promise<boolean> {\n const { version, statePath, changelogText, show } = input\n if (typeof version !== 'string' || version.trim() === '') return false\n if (!(await shouldShowWhatsNew(version, statePath))) return false\n\n const highlights: WhatsNewHighlights = changelogText\n ? extractHighlights(changelogText, version)\n : { ...EMPTY_HIGHLIGHTS }\n const lines = whatsNewLines(highlights)\n if (lines.length === 0) return false\n\n const pages = paginateWhatsNewLines(lines)\n const data: WhatsNewViewData = {\n version,\n title: whatsNewTitle(version),\n lines,\n pages,\n hint: pages.length > 1 ? WHATS_NEW_PAGES_HINT : WHATS_NEW_CLOSE_HINT,\n }\n show(\n () => data,\n () => {\n void markSeenWhatsNew(version, statePath)\n },\n )\n return true\n}\n"],"mappings":";;;;;;;;;;AAIA,MAAa,oBAAoB;AACjC,MAAa,0BAA0B;AACvC,MAAa,yBAAyB;AAEtC,SAASA,eAAa,OAA+B;CACnD,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAgB,iBAAiB,SAAsC;CACrE,IAAI,UAAU,IAA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AAO,KAAK,SAAS,SAAS;EAC5B,KAAK,KAAK,KAAK,MAAM,GAAG,OAAO,CAAC;EAChC,OAAO,KAAK,MAAM,OAAO;CAC3B;CACA,IAAI,KAAK,SAAS,GAAG,KAAK,KAAK,IAAI;CACnC,OAAO;AACT;;AAGA,SAAgB,sBACd,OACA,WAAA,IACY;CACZ,MAAM,OAAO,OAAO,UAAU,QAAQ,KAAK,WAAW,IAAI,WAAA;CAC1D,IAAI,MAAM,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC;CAClC,MAAM,QAAoB,CAAC;CAC3B,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MAAM,MAAM,KAAK,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC;CAChF,OAAO;AACT;;;;;;AA8BA,eAAsB,aAAa,OAA4C;CAC7E,MAAM,EAAE,SAAS,WAAW,eAAe,SAAS;CACpD,IAAI,OAAO,YAAY,YAAY,QAAQ,KAAK,MAAM,IAAI,OAAO;CACjE,IAAI,CAAE,MAAM,mBAAmB,SAAS,SAAS,GAAI,OAAO;CAK5D,MAAM,QAAQ,cAHyB,gBACnC,kBAAkB,eAAe,OAAO,IACxC,EAAE,GAAG,iBAAiB,CACY;CACtC,IAAI,MAAM,WAAW,GAAG,OAAO;CAE/B,MAAM,QAAQ,sBAAsB,KAAK;CACzC,MAAM,OAAyB;EAC7B;EACA,OAAO,cAAc,OAAO;EAC5B;EACA;EACA,MAAM,MAAM,SAAS,IAAI,uBAAuB;CAClD;CACA,WACQ,YACA;EACJ,iBAAsB,SAAS,SAAS;CAC1C,CACF;CACA,OAAO;AACT"}
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pantheon-tui",
3
- "version": "2.0.0-beta.1",
3
+ "version": "2.0.0-beta.2",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pantheon-tui",
9
- "version": "2.0.0-beta.1",
9
+ "version": "2.0.0-beta.2",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@opencode/plugin": "2.0.26",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pantheon-tui",
3
3
  "type": "module",
4
- "version": "2.0.0-beta.1",
4
+ "version": "2.0.0-beta.2",
5
5
  "description": "Pantheon TUI plugin \u2014 V1 rich sidebar and usage gauges; native V2 status, session and delegation sidebar",
6
6
  "license": "MIT",
7
7
  "engines": {
@@ -0,0 +1,242 @@
1
+ /**
2
+ * decision-router-state.ts — the Decision Model section of the settings window.
3
+ *
4
+ * TUI-local replica of the user-level decision-router config
5
+ * (scripts/install/decision-router-config.mjs — the bundle must stay
6
+ * self-contained); tests/tui-decision-router-state.test.mjs pins the schema
7
+ * version, the exact key set and the provider matrix against that source.
8
+ *
9
+ * The runtime re-reads this file on EVERY gated call (jev-decision-tool.ts),
10
+ * so a write here applies live — no restart. The strict exact-key schema is
11
+ * load-bearing: any unknown key fail-closes the runtime to disabled/local,
12
+ * so the writer validates before persisting.
13
+ *
14
+ * Egress consent is CLI-owned: the window never writes `egress_consent`, and
15
+ * refuses to enable the router while remote candidates exist without it.
16
+ */
17
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
18
+ import { dirname, join } from 'node:path'
19
+ import type { SettingsRow, SettingsSection } from './pantheon-settings-state.ts'
20
+
21
+ export const DECISION_CONFIG_SCHEMA_VERSION = 2
22
+
23
+ /** Exact top-level key set — anything else fail-closes the runtime. */
24
+ export const DECISION_CONFIG_KEYS: readonly string[] = Object.freeze([
25
+ 'egress_consent',
26
+ 'enabled',
27
+ 'enabled_candidates',
28
+ 'schema_version',
29
+ 'selection',
30
+ ])
31
+
32
+ export type DecisionSelectionMode = 'local' | 'auto' | 'explicit'
33
+
34
+ export interface DecisionSelection {
35
+ mode: DecisionSelectionMode
36
+ provider?: string
37
+ model?: string
38
+ }
39
+
40
+ export interface DecisionCandidate {
41
+ provider: string
42
+ model: string
43
+ }
44
+
45
+ export interface DecisionRouterConfig {
46
+ schema_version: number
47
+ enabled: boolean
48
+ selection: DecisionSelection
49
+ egress_consent: boolean
50
+ enabled_candidates: readonly DecisionCandidate[]
51
+ }
52
+
53
+ export const DEFAULT_DECISION_CONFIG: DecisionRouterConfig = Object.freeze({
54
+ schema_version: DECISION_CONFIG_SCHEMA_VERSION,
55
+ enabled: false,
56
+ selection: Object.freeze({ mode: 'local' as const }),
57
+ egress_consent: false,
58
+ enabled_candidates: Object.freeze([]),
59
+ })
60
+
61
+ /** The runtime's provider→model matrix (drift-pinned against the installer source). */
62
+ export const DECISION_KNOWN_PROVIDERS: readonly string[] = Object.freeze([
63
+ 'openai-decisions',
64
+ 'typesafe-jev',
65
+ 'opencode-console-jev',
66
+ 'openrouter-jev',
67
+ 'vercel-gateway-jev',
68
+ 'cloudflare-workers-jev',
69
+ ])
70
+
71
+ export function decisionRouterConfigPath(env: Record<string, string | undefined> = process.env) {
72
+ const xdg = env.XDG_CONFIG_HOME
73
+ const home = env.HOME ?? ''
74
+ const root = xdg ?? join(home, '.config')
75
+ return join(root, 'pantheon', 'decision-router.json')
76
+ }
77
+
78
+ export interface DecisionConfigRead {
79
+ config: DecisionRouterConfig
80
+ /** The file exists but is not a valid v2 config — the runtime fail-closes. */
81
+ corrupt: boolean
82
+ }
83
+
84
+ /** Fail-open read: a missing file is the default; an invalid one is reported, not guessed. */
85
+ export function readDecisionRouterConfig(
86
+ env: Record<string, string | undefined> = process.env,
87
+ ): DecisionConfigRead {
88
+ let raw: unknown
89
+ try {
90
+ raw = JSON.parse(readFileSync(decisionRouterConfigPath(env), 'utf8'))
91
+ } catch (error) {
92
+ if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') {
93
+ return { config: cloneDefault(), corrupt: false }
94
+ }
95
+ return { config: cloneDefault(), corrupt: true }
96
+ }
97
+ if (isValidDecisionConfig(raw)) return { config: raw, corrupt: false }
98
+ return { config: cloneDefault(), corrupt: true }
99
+ }
100
+
101
+ function cloneDefault(): DecisionRouterConfig {
102
+ return {
103
+ schema_version: DEFAULT_DECISION_CONFIG.schema_version,
104
+ enabled: DEFAULT_DECISION_CONFIG.enabled,
105
+ selection: { ...DEFAULT_DECISION_CONFIG.selection },
106
+ egress_consent: DEFAULT_DECISION_CONFIG.egress_consent,
107
+ enabled_candidates: [...DEFAULT_DECISION_CONFIG.enabled_candidates],
108
+ }
109
+ }
110
+
111
+ /** The exact-key, exact-shape validation the runtime applies (fail-closed otherwise). */
112
+ export function isValidDecisionConfig(value: unknown): value is DecisionRouterConfig {
113
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
114
+ const record = value as Record<string, unknown>
115
+ const keys = Object.keys(record).sort()
116
+ if (keys.length !== DECISION_CONFIG_KEYS.length) return false
117
+ for (const key of DECISION_CONFIG_KEYS) {
118
+ if (!keys.includes(key)) return false
119
+ }
120
+ if (record.schema_version !== DECISION_CONFIG_SCHEMA_VERSION) return false
121
+ if (typeof record.enabled !== 'boolean') return false
122
+ if (typeof record.egress_consent !== 'boolean') return false
123
+ if (!isValidSelection(record.selection)) return false
124
+ if (!Array.isArray(record.enabled_candidates)) return false
125
+ for (const candidate of record.enabled_candidates) {
126
+ if (typeof candidate !== 'object' || candidate === null) return false
127
+ const entry = candidate as Record<string, unknown>
128
+ if (typeof entry.provider !== 'string' || typeof entry.model !== 'string') return false
129
+ if (Object.keys(entry).length !== 2) return false
130
+ }
131
+ return true
132
+ }
133
+
134
+ function isValidSelection(value: unknown): value is DecisionSelection {
135
+ if (typeof value !== 'object' || value === null) return false
136
+ const selection = value as Record<string, unknown>
137
+ if (selection.mode !== 'local' && selection.mode !== 'auto' && selection.mode !== 'explicit') {
138
+ return false
139
+ }
140
+ const keys = Object.keys(selection).sort()
141
+ for (const key of keys) {
142
+ if (key !== 'mode' && key !== 'provider' && key !== 'model') return false
143
+ }
144
+ if (selection.provider !== undefined && typeof selection.provider !== 'string') return false
145
+ if (selection.model !== undefined && typeof selection.model !== 'string') return false
146
+ return true
147
+ }
148
+
149
+ /** Stable serializer: exact keys in sorted order, 2-space, trailing newline. */
150
+ export function serializeDecisionConfig(config: DecisionRouterConfig): string {
151
+ const ordered = {
152
+ egress_consent: config.egress_consent,
153
+ enabled: config.enabled,
154
+ enabled_candidates: config.enabled_candidates.map((candidate) => ({
155
+ model: candidate.model,
156
+ provider: candidate.provider,
157
+ })),
158
+ schema_version: config.schema_version,
159
+ selection: {
160
+ mode: config.selection.mode,
161
+ ...(config.selection.model !== undefined ? { model: config.selection.model } : {}),
162
+ ...(config.selection.provider !== undefined ? { provider: config.selection.provider } : {}),
163
+ },
164
+ }
165
+ return `${JSON.stringify(ordered, null, 2)}\n`
166
+ }
167
+
168
+ /**
169
+ * Enable/disable the router in a config copy. The guard mirrors the runtime's
170
+ * fail-close: with remote candidates and no egress consent, an enabled flag
171
+ * would be a lie — enabling requires consent, or a local-only selection.
172
+ * Never touches `egress_consent` (CLI-owned).
173
+ */
174
+ export function setDecisionEnabled(
175
+ config: DecisionRouterConfig,
176
+ enabled: boolean,
177
+ ): { ok: true; config: DecisionRouterConfig } | { ok: false; reason: string } {
178
+ if (enabled) {
179
+ const localOnly = config.selection.mode === 'local' || config.enabled_candidates.length === 0
180
+ if (!localOnly && !config.egress_consent) {
181
+ return {
182
+ ok: false,
183
+ reason: 'remote candidates need egress consent — grant via `decision-router setup-model`',
184
+ }
185
+ }
186
+ }
187
+ return { ok: true, config: { ...config, enabled } }
188
+ }
189
+
190
+ /** Atomic-ish write mirroring the canonical writer's privacy posture (0600). */
191
+ export function writeDecisionRouterConfig(
192
+ config: DecisionRouterConfig,
193
+ env: Record<string, string | undefined> = process.env,
194
+ ): void {
195
+ if (!isValidDecisionConfig(config)) {
196
+ throw new TypeError('Refusing to persist an invalid decision-router configuration')
197
+ }
198
+ const path = decisionRouterConfigPath(env)
199
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
200
+ const temp = `${path}.tui.tmp`
201
+ writeFileSync(temp, serializeDecisionConfig(config), { mode: 0o600 })
202
+ renameSync(temp, path)
203
+ chmodSync(path, 0o600)
204
+ }
205
+
206
+ export function buildDecisionSection(read: DecisionConfigRead): SettingsSection {
207
+ const { config, corrupt } = read
208
+ const rows: SettingsRow[] = [
209
+ {
210
+ id: 'decision.enabled',
211
+ title: `Decision router: ${config.enabled ? 'enabled' : 'disabled'}`,
212
+ description: corrupt
213
+ ? 'config file unreadable/invalid — the runtime fail-closes to disabled'
214
+ : 'the runtime re-reads this file on every gated call — applies live',
215
+ disabled: !config.enabled,
216
+ },
217
+ {
218
+ id: 'decision.selection',
219
+ title: `Selection: ${config.selection.mode}${config.selection.provider ? ` · ${config.selection.provider}` : ''}`,
220
+ description: 'local routes on-device; auto/explicit pick a remote decision model',
221
+ selectable: false,
222
+ },
223
+ ]
224
+ if (config.enabled_candidates.length > 0) {
225
+ rows.push({
226
+ id: 'decision.candidates',
227
+ title: `Candidates: ${config.enabled_candidates.map((candidate) => `${candidate.provider}/${candidate.model}`).join(', ')}`,
228
+ description: config.egress_consent
229
+ ? 'egress consent granted'
230
+ : 'egress consent NOT granted — remote routes fail closed',
231
+ selectable: false,
232
+ })
233
+ }
234
+ return {
235
+ id: 'decision',
236
+ title: 'Decision Model',
237
+ rows,
238
+ hint: corrupt
239
+ ? 'repair via `decision-router setup-model` — writes refused on an invalid file'
240
+ : 'enter: enable/disable · consent and candidates via `decision-router setup-model`',
241
+ }
242
+ }