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,6 +1,6 @@
1
- import { createComponent, createElement, createTextNode, effect, insert, insertNode, memo, setProp } from "@opentui/solid";
1
+ import { createComponent, createElement, createTextNode, effect, insert, insertNode, memo, mergeProps, setProp, spread } from "@opentui/solid";
2
2
  import { execFile } from "node:child_process";
3
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
6
6
  import { dirname, join } from "node:path";
@@ -59,6 +59,176 @@ function formatSpent(cost) {
59
59
  const MODEL_USAGE_VISIBLE_CEILING = 3;
60
60
  const MODEL_USAGE_MESSAGE_LIMIT = 400;
61
61
  const MODEL_USAGE_SESSION_LIMIT = 8;
62
+ /** Exact top-level key set — anything else fail-closes the runtime. */
63
+ const DECISION_CONFIG_KEYS = Object.freeze([
64
+ "egress_consent",
65
+ "enabled",
66
+ "enabled_candidates",
67
+ "schema_version",
68
+ "selection"
69
+ ]);
70
+ const DEFAULT_DECISION_CONFIG = Object.freeze({
71
+ schema_version: 2,
72
+ enabled: false,
73
+ selection: Object.freeze({ mode: "local" }),
74
+ egress_consent: false,
75
+ enabled_candidates: Object.freeze([])
76
+ });
77
+ Object.freeze([
78
+ "openai-decisions",
79
+ "typesafe-jev",
80
+ "opencode-console-jev",
81
+ "openrouter-jev",
82
+ "vercel-gateway-jev",
83
+ "cloudflare-workers-jev"
84
+ ]);
85
+ function decisionRouterConfigPath(env = process.env) {
86
+ const xdg = env.XDG_CONFIG_HOME;
87
+ const home = env.HOME ?? "";
88
+ const root = xdg ?? join(home, ".config");
89
+ return join(root, "pantheon", "decision-router.json");
90
+ }
91
+ /** Fail-open read: a missing file is the default; an invalid one is reported, not guessed. */
92
+ function readDecisionRouterConfig(env = process.env) {
93
+ let raw;
94
+ try {
95
+ raw = JSON.parse(readFileSync(decisionRouterConfigPath(env), "utf8"));
96
+ } catch (error) {
97
+ if (error?.code === "ENOENT") return {
98
+ config: cloneDefault(),
99
+ corrupt: false
100
+ };
101
+ return {
102
+ config: cloneDefault(),
103
+ corrupt: true
104
+ };
105
+ }
106
+ if (isValidDecisionConfig(raw)) return {
107
+ config: raw,
108
+ corrupt: false
109
+ };
110
+ return {
111
+ config: cloneDefault(),
112
+ corrupt: true
113
+ };
114
+ }
115
+ function cloneDefault() {
116
+ return {
117
+ schema_version: DEFAULT_DECISION_CONFIG.schema_version,
118
+ enabled: DEFAULT_DECISION_CONFIG.enabled,
119
+ selection: { ...DEFAULT_DECISION_CONFIG.selection },
120
+ egress_consent: DEFAULT_DECISION_CONFIG.egress_consent,
121
+ enabled_candidates: [...DEFAULT_DECISION_CONFIG.enabled_candidates]
122
+ };
123
+ }
124
+ /** The exact-key, exact-shape validation the runtime applies (fail-closed otherwise). */
125
+ function isValidDecisionConfig(value) {
126
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
127
+ const record = value;
128
+ const keys = Object.keys(record).sort();
129
+ if (keys.length !== DECISION_CONFIG_KEYS.length) return false;
130
+ for (const key of DECISION_CONFIG_KEYS) if (!keys.includes(key)) return false;
131
+ if (record.schema_version !== 2) return false;
132
+ if (typeof record.enabled !== "boolean") return false;
133
+ if (typeof record.egress_consent !== "boolean") return false;
134
+ if (!isValidSelection(record.selection)) return false;
135
+ if (!Array.isArray(record.enabled_candidates)) return false;
136
+ for (const candidate of record.enabled_candidates) {
137
+ if (typeof candidate !== "object" || candidate === null) return false;
138
+ const entry = candidate;
139
+ if (typeof entry.provider !== "string" || typeof entry.model !== "string") return false;
140
+ if (Object.keys(entry).length !== 2) return false;
141
+ }
142
+ return true;
143
+ }
144
+ function isValidSelection(value) {
145
+ if (typeof value !== "object" || value === null) return false;
146
+ const selection = value;
147
+ if (selection.mode !== "local" && selection.mode !== "auto" && selection.mode !== "explicit") return false;
148
+ const keys = Object.keys(selection).sort();
149
+ for (const key of keys) if (key !== "mode" && key !== "provider" && key !== "model") return false;
150
+ if (selection.provider !== void 0 && typeof selection.provider !== "string") return false;
151
+ if (selection.model !== void 0 && typeof selection.model !== "string") return false;
152
+ return true;
153
+ }
154
+ /** Stable serializer: exact keys in sorted order, 2-space, trailing newline. */
155
+ function serializeDecisionConfig(config) {
156
+ const ordered = {
157
+ egress_consent: config.egress_consent,
158
+ enabled: config.enabled,
159
+ enabled_candidates: config.enabled_candidates.map((candidate) => ({
160
+ model: candidate.model,
161
+ provider: candidate.provider
162
+ })),
163
+ schema_version: config.schema_version,
164
+ selection: {
165
+ mode: config.selection.mode,
166
+ ...config.selection.model !== void 0 ? { model: config.selection.model } : {},
167
+ ...config.selection.provider !== void 0 ? { provider: config.selection.provider } : {}
168
+ }
169
+ };
170
+ return `${JSON.stringify(ordered, null, 2)}\n`;
171
+ }
172
+ /**
173
+ * Enable/disable the router in a config copy. The guard mirrors the runtime's
174
+ * fail-close: with remote candidates and no egress consent, an enabled flag
175
+ * would be a lie — enabling requires consent, or a local-only selection.
176
+ * Never touches `egress_consent` (CLI-owned).
177
+ */
178
+ function setDecisionEnabled(config, enabled) {
179
+ if (enabled) {
180
+ if (!(config.selection.mode === "local" || config.enabled_candidates.length === 0) && !config.egress_consent) return {
181
+ ok: false,
182
+ reason: "remote candidates need egress consent — grant via `decision-router setup-model`"
183
+ };
184
+ }
185
+ return {
186
+ ok: true,
187
+ config: {
188
+ ...config,
189
+ enabled
190
+ }
191
+ };
192
+ }
193
+ /** Atomic-ish write mirroring the canonical writer's privacy posture (0600). */
194
+ function writeDecisionRouterConfig(config, env = process.env) {
195
+ if (!isValidDecisionConfig(config)) throw new TypeError("Refusing to persist an invalid decision-router configuration");
196
+ const path = decisionRouterConfigPath(env);
197
+ mkdirSync(dirname(path), {
198
+ recursive: true,
199
+ mode: 448
200
+ });
201
+ const temp = `${path}.tui.tmp`;
202
+ writeFileSync(temp, serializeDecisionConfig(config), { mode: 384 });
203
+ renameSync(temp, path);
204
+ chmodSync(path, 384);
205
+ }
206
+ function buildDecisionSection(read) {
207
+ const { config, corrupt } = read;
208
+ const rows = [{
209
+ id: "decision.enabled",
210
+ title: `Decision router: ${config.enabled ? "enabled" : "disabled"}`,
211
+ description: corrupt ? "config file unreadable/invalid — the runtime fail-closes to disabled" : "the runtime re-reads this file on every gated call — applies live",
212
+ disabled: !config.enabled
213
+ }, {
214
+ id: "decision.selection",
215
+ title: `Selection: ${config.selection.mode}${config.selection.provider ? ` · ${config.selection.provider}` : ""}`,
216
+ description: "local routes on-device; auto/explicit pick a remote decision model",
217
+ selectable: false
218
+ }];
219
+ if (config.enabled_candidates.length > 0) rows.push({
220
+ id: "decision.candidates",
221
+ title: `Candidates: ${config.enabled_candidates.map((candidate) => `${candidate.provider}/${candidate.model}`).join(", ")}`,
222
+ description: config.egress_consent ? "egress consent granted" : "egress consent NOT granted — remote routes fail closed",
223
+ selectable: false
224
+ });
225
+ return {
226
+ id: "decision",
227
+ title: "Decision Model",
228
+ rows,
229
+ hint: corrupt ? "repair via `decision-router setup-model` — writes refused on an invalid file" : "enter: enable/disable · consent and candidates via `decision-router setup-model`"
230
+ };
231
+ }
62
232
  //#endregion
63
233
  //#region src/pantheon-settings-state.ts
64
234
  /** Mirrors routing.yml `behaviors:` — drift-pinned by the registry test. */
@@ -110,11 +280,57 @@ new Set(SETTINGS_BEHAVIORS.map((b) => b.id));
110
280
  function isBehaviorDisabled(effective, id) {
111
281
  return effective[id]?.action === "disable";
112
282
  }
113
- /** Toggle: disabled -> enabled (entry removed); enabled -> disabled (entry written). */
114
- function toggledOverrides(effective, id, reason = "toggled in /pantheon-settings") {
283
+ /** The rows up/down can reach and enter can dispatch on, in order. */
284
+ function selectableRows(section) {
285
+ return section.rows.filter((row) => row.selectable !== false);
286
+ }
287
+ /** Flat selection order across every section of the window. */
288
+ function flatSelectableRows(sections) {
289
+ return sections.flatMap((section) => selectableRows(section));
290
+ }
291
+ function firstSelectableId(sections) {
292
+ return flatSelectableRows(sections)[0]?.id;
293
+ }
294
+ /**
295
+ * Merge for DISPLAY only, mirroring the runtime precedence: the project file
296
+ * wins per id (whole entry). The window still writes only the global file.
297
+ */
298
+ function mergedOverrides(load) {
299
+ return {
300
+ ...load.global,
301
+ ...load.project
302
+ };
303
+ }
304
+ function canWriteOverrides(load) {
305
+ return !load.corruptGlobal;
306
+ }
307
+ const TOGGLE_REASON = "toggled in /pantheon-settings";
308
+ /**
309
+ * Toggle: disabled -> enabled; enabled -> disabled.
310
+ *
311
+ * A `replace` entry is never destroyed by a toggle ("never trap user state"):
312
+ * disabling keeps its `content` under the disable entry, and re-enabling
313
+ * restores the replace. A settings-written disable (no content) is removed
314
+ * outright so the overrides file does not accumulate toggle noise.
315
+ */
316
+ function toggledOverrides(effective, id, reason = TOGGLE_REASON) {
115
317
  const next = { ...effective };
116
- if (next[id]?.action === "disable") delete next[id];
117
- else next[id] = {
318
+ const entry = next[id];
319
+ if (entry?.action === "disable") {
320
+ if (entry.content !== void 0) next[id] = entry.reason === reason ? {
321
+ action: "replace",
322
+ content: entry.content
323
+ } : {
324
+ action: "replace",
325
+ content: entry.content,
326
+ ...entry.reason !== void 0 ? { reason: entry.reason } : {}
327
+ };
328
+ else delete next[id];
329
+ } else next[id] = entry?.content !== void 0 ? {
330
+ action: "disable",
331
+ reason,
332
+ content: entry.content
333
+ } : {
118
334
  action: "disable",
119
335
  reason
120
336
  };
@@ -125,165 +341,743 @@ function serializeOverrides(effective) {
125
341
  for (const id of Object.keys(effective).sort()) ordered[id] = effective[id];
126
342
  return `${JSON.stringify(ordered, null, 2)}\n`;
127
343
  }
344
+ /**
345
+ * The Gates & Overrides page: behavior state from BOTH overrides files.
346
+ * A project-owned entry wins the runtime merge and the window only writes
347
+ * the global file, so project rows are marked and not togglable here.
348
+ */
349
+ function buildGatesSection(load) {
350
+ const merged = mergedOverrides(load);
351
+ const rows = SETTINGS_BEHAVIORS.map((behavior) => {
352
+ const fromProject = load.project[behavior.id] !== void 0;
353
+ return {
354
+ id: `gate.${behavior.id}`,
355
+ title: fromProject ? `${behavior.title} (project)` : behavior.title,
356
+ description: behavior.description,
357
+ disabled: isBehaviorDisabled(merged, behavior.id),
358
+ selectable: !fromProject,
359
+ source: fromProject ? "project" : "global"
360
+ };
361
+ });
362
+ return {
363
+ id: "gates",
364
+ title: "Gates & Overrides",
365
+ hint: canWriteOverrides(load) ? "enter: disable/enable · writes pantheon-overrides.json (global)" : "overrides file unreadable — writes refused; repair with `pantheon-opencode doctor --fix`",
366
+ rows
367
+ };
368
+ }
369
+ function buildAboutSection(version) {
370
+ return {
371
+ id: "about",
372
+ title: "About",
373
+ rows: [{
374
+ id: "about.version",
375
+ title: `Pantheon v${version}`,
376
+ description: "OpenCode 2.x only — the V1 contract is removed.",
377
+ selectable: false
378
+ }, {
379
+ id: "about.behaviors",
380
+ title: `${SETTINGS_BEHAVIORS.length} togglable behaviors`,
381
+ description: "Docs: docs/design/2.0-settings-and-install.md",
382
+ selectable: false
383
+ }]
384
+ };
385
+ }
386
+ //#endregion
387
+ //#region src/update-notice.ts
388
+ /**
389
+ * Update notifier core (TUI-local copy — the bundle must stay self-contained,
390
+ * same precedent as cost-data.ts/model-pricing.ts).
391
+ *
392
+ * Pin + notify, never silent auto-update: one notice per newer version,
393
+ * TTL-cached, offline-safe, and a stable install is never advertised a beta
394
+ * (the update guard owns that crossing). docs/design/2.0-settings-and-install.md
395
+ */
396
+ const UPDATE_CHECK_TTL_MS = 216e5;
397
+ /** Semver-ish compare for X.Y.Z[-beta.N]; betas sort before their release. */
398
+ function comparePantheonVersions(left, right) {
399
+ const parse = (version) => {
400
+ const match = String(version).trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-beta\.(\d+))?$/);
401
+ if (!match) return null;
402
+ const [, major = "", minor = "", patch = "", beta = ""] = match;
403
+ return {
404
+ core: [
405
+ +major,
406
+ +minor,
407
+ +patch
408
+ ],
409
+ beta: beta === "" ? Number.POSITIVE_INFINITY : +beta
410
+ };
411
+ };
412
+ const a = parse(left);
413
+ const b = parse(right);
414
+ if (!a || !b) return 0;
415
+ const [aMajor, aMinor, aPatch] = a.core;
416
+ const [bMajor, bMinor, bPatch] = b.core;
417
+ if (aMajor !== bMajor) return aMajor - bMajor;
418
+ if (aMinor !== bMinor) return aMinor - bMinor;
419
+ if (aPatch !== bPatch) return aPatch - bPatch;
420
+ return a.beta - b.beta;
421
+ }
422
+ function pickUpdateNotice(input) {
423
+ const { currentVersion, latestVersion, state = {}, nowMs = Date.now() } = input;
424
+ const ttlMs = input.ttlMs ?? 216e5;
425
+ if (nowMs - (state.lastCheckMs ?? 0) < ttlMs) return null;
426
+ if (state.lastNotifiedVersion === latestVersion) return null;
427
+ const stable = (version) => !/-beta\.\d+$/.test(version);
428
+ if (stable(currentVersion) && !stable(latestVersion)) return null;
429
+ if (comparePantheonVersions(latestVersion, currentVersion) <= 0) return null;
430
+ return {
431
+ version: latestVersion,
432
+ message: `pantheon-opencode ${latestVersion} available — changelog in /pantheon-settings, adopt with \`pantheon-opencode update\``
433
+ };
434
+ }
435
+ /** The state to persist after a check (notified or not) for the TTL. */
436
+ function nextCheckState(previous, notice, nowMs) {
437
+ const lastNotifiedVersion = notice?.version ?? previous.lastNotifiedVersion;
438
+ return {
439
+ lastCheckMs: nowMs,
440
+ ...lastNotifiedVersion !== void 0 ? { lastNotifiedVersion } : {}
441
+ };
442
+ }
443
+ //#endregion
444
+ //#region src/doctor-state.ts
445
+ /**
446
+ * doctor-state.ts — the Doctor section of the settings window (read-only).
447
+ *
448
+ * TUI-local replica (the bundle must stay self-contained — the installed copy
449
+ * physically lacks the repo tree, so doctor.mjs itself is unreachable). Only
450
+ * the FILE-DERIVABLE checks are mirrored here; everything that spawns
451
+ * processes, reads the network, or writes (MCP smoke, python validators, git,
452
+ * venv pins, --fix quarantines) stays in the CLI and the section says so.
453
+ *
454
+ * The install-state path mirrors doctor's checkInstallVersionDrift
455
+ * (`<config>/opencode/.pantheon/install-state.json`); the Node floor is
456
+ * drift-pinned against scripts/node-engine-policy.mjs by
457
+ * tests/tui-doctor-state.test.mjs.
458
+ */
459
+ /** Drift-pinned against scripts/node-engine-policy.mjs MIN_SUPPORTED_NODE_VERSION. */
460
+ const MIN_SUPPORTED_NODE_VERSION = "26.4.0";
461
+ function opencodePantheonDir(env = process.env) {
462
+ const xdg = env.XDG_CONFIG_HOME;
463
+ const home = env.HOME ?? "";
464
+ const root = xdg ?? join(home, ".config");
465
+ return join(root, "opencode", ".pantheon");
466
+ }
467
+ /**
468
+ * H2: the installed package version (install-state) vs the running one.
469
+ * Fail-open: a missing/unreadable state file means "unknown", not a failure —
470
+ * pre-2.0 installs may not have one.
471
+ */
472
+ function classifyInstallVersion(runningVersion, env = process.env) {
473
+ let installed = null;
474
+ try {
475
+ const path = join(opencodePantheonDir(env), "install-state.json");
476
+ const raw = JSON.parse(readFileSync(path, "utf8"));
477
+ if (typeof raw?.pantheon_version === "string" && raw.pantheon_version !== "") installed = raw.pantheon_version;
478
+ } catch {
479
+ installed = null;
480
+ }
481
+ if (installed === null) return {
482
+ status: "unknown",
483
+ installed: null
484
+ };
485
+ const compared = comparePantheonVersions(installed, runningVersion);
486
+ if (compared === 0) return {
487
+ status: "ok",
488
+ installed
489
+ };
490
+ return {
491
+ status: compared < 0 ? "older" : "newer",
492
+ installed
493
+ };
494
+ }
495
+ function isSupportedNodeFloor(version) {
496
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+([\w.-]+))?$/.exec(String(version));
497
+ const minimum = /^v?(\d+)\.(\d+)\.(\d+)/.exec(MIN_SUPPORTED_NODE_VERSION);
498
+ if (!match || !minimum) return false;
499
+ const [, major = "", minor = "", patch = "", prerelease = ""] = match;
500
+ if (prerelease !== "") return false;
501
+ const [, minMajor = "0", minMinor = "0", minPatch = "0"] = minimum;
502
+ const currentParts = [
503
+ +major,
504
+ +minor,
505
+ +patch
506
+ ];
507
+ const minimumParts = [
508
+ +minMajor,
509
+ +minMinor,
510
+ +minPatch
511
+ ];
512
+ for (let index = 0; index < 3; index += 1) {
513
+ const currentPart = currentParts[index] ?? 0;
514
+ const minimumPart = minimumParts[index] ?? 0;
515
+ if (currentPart !== minimumPart) return currentPart > minimumPart;
516
+ }
517
+ return true;
518
+ }
519
+ /** K: validate both overrides files against the window's registry. */
520
+ function classifyOverridesHealth(load) {
521
+ if (load.corruptGlobal) return {
522
+ status: "corrupt",
523
+ unknownIds: []
524
+ };
525
+ const known = new Set(SETTINGS_BEHAVIORS.map((behavior) => behavior.id));
526
+ const unknownIds = Object.keys({
527
+ ...load.global,
528
+ ...load.project
529
+ }).filter((id) => !known.has(id));
530
+ return {
531
+ status: unknownIds.length > 0 ? "unknown-ids" : "clean",
532
+ unknownIds
533
+ };
534
+ }
535
+ function classifyDecisionConfigHealth(env = process.env) {
536
+ if (!existsSync(join(env.XDG_CONFIG_HOME ?? join(env.HOME ?? "", ".config"), "pantheon", "decision-router.json"))) return { status: "absent" };
537
+ return readDecisionRouterConfig(env).corrupt ? { status: "corrupt" } : { status: "ok" };
538
+ }
539
+ function buildDoctorSection(input) {
540
+ const env = input.env ?? process.env;
541
+ const rows = [];
542
+ const version = classifyInstallVersion(input.runningVersion, env);
543
+ rows.push({
544
+ id: "doctor.version",
545
+ title: version.status === "ok" ? `Installed version: v${version.installed} — matches` : version.status === "older" ? `Installed v${version.installed} is older than the runtime v${input.runningVersion}` : version.status === "newer" ? `Installed v${version.installed} is newer than the runtime v${input.runningVersion}` : "Installed version: unknown (no install-state)",
546
+ description: version.status === "older" ? "refresh with `pantheon-opencode update`" : "read from <config>/opencode/.pantheon/install-state.json",
547
+ marker: version.status === "ok" ? "[✓]" : version.status === "older" ? "[!]" : "[i]",
548
+ selectable: false
549
+ });
550
+ const nodeOk = isSupportedNodeFloor(input.nodeVersion);
551
+ rows.push({
552
+ id: "doctor.node",
553
+ title: `Node runtime: ${input.nodeVersion.replace(/^v/, "")}`,
554
+ description: nodeOk ? `meets the >= ${MIN_SUPPORTED_NODE_VERSION} floor` : `below the >= ${MIN_SUPPORTED_NODE_VERSION} floor — tooling may refuse`,
555
+ marker: nodeOk ? "[✓]" : "[!]",
556
+ selectable: false
557
+ });
558
+ const overrides = classifyOverridesHealth(input.load);
559
+ rows.push({
560
+ id: "doctor.overrides",
561
+ title: overrides.status === "clean" ? "Overrides: valid" : overrides.status === "corrupt" ? "Overrides: global file unreadable" : `Overrides: ${overrides.unknownIds.length} unknown id(s)`,
562
+ description: overrides.status === "unknown-ids" ? `${overrides.unknownIds.join(", ")} — harmless; repair with doctor --fix` : overrides.status === "corrupt" ? "writes are refused until repaired (doctor --fix)" : "both files parse against the behavior registry",
563
+ marker: overrides.status === "clean" ? "[✓]" : overrides.status === "corrupt" ? "[✗]" : "[!]",
564
+ selectable: false
565
+ });
566
+ const decision = classifyDecisionConfigHealth(env);
567
+ rows.push({
568
+ id: "doctor.decision",
569
+ title: decision.status === "ok" ? "Decision config: valid" : decision.status === "corrupt" ? "Decision config: unreadable — runtime fail-closes" : "Decision config: absent (local defaults)",
570
+ description: "read from <config>/pantheon/decision-router.json",
571
+ marker: decision.status === "corrupt" ? "[✗]" : "[✓]",
572
+ selectable: false
573
+ });
574
+ return {
575
+ id: "doctor",
576
+ title: "Doctor",
577
+ rows,
578
+ hint: "file checks only — the full doctor (MCP smoke, venv, git) is `pantheon-opencode doctor`"
579
+ };
580
+ }
581
+ //#endregion
582
+ //#region src/j1-gate-status.ts
583
+ const J1_FLAG_ENV = "PANTHEON_J1_RISK_SCORE";
584
+ const J1_THRESHOLD_ENV = "PANTHEON_J1_ENFORCE_THRESHOLD";
585
+ const J1_THRESHOLD_DEFAULT = .8;
586
+ /** `1`/`on`/`true` map to `shadow` for back-compatibility with the shipped setup. */
587
+ const FLAG_ON = /* @__PURE__ */ new Set([
588
+ "1",
589
+ "on",
590
+ "true",
591
+ "shadow"
592
+ ]);
593
+ function j1ModeFromEnv(env = process.env) {
594
+ const raw = (env["PANTHEON_J1_RISK_SCORE"] ?? "").trim().toLowerCase();
595
+ if (raw === "enforce") return "enforce";
596
+ if (raw === "warn") return "warn";
597
+ return FLAG_ON.has(raw) ? "shadow" : "off";
598
+ }
599
+ /** Invalid or out-of-range values fall back to the default — a typo must not disable the gate. */
600
+ function j1ThresholdFromEnv(env = process.env) {
601
+ const text = (env["PANTHEON_J1_ENFORCE_THRESHOLD"] ?? "").trim();
602
+ if (text === "") return J1_THRESHOLD_DEFAULT;
603
+ const raw = Number(text);
604
+ if (!Number.isFinite(raw) || raw < 0 || raw > 1) return J1_THRESHOLD_DEFAULT;
605
+ return raw;
606
+ }
607
+ const MODE_DESCRIPTION = {
608
+ off: "nothing fires (hard zero)",
609
+ shadow: "observe + record; invisible in the session",
610
+ warn: "RESERVED — behaves as shadow in this release",
611
+ enforce: "high-risk scores DENY the tool call (fail-open on gate unavailability)"
612
+ };
613
+ function buildJ1Section(env, disabledByOverride) {
614
+ const mode = j1ModeFromEnv(env);
615
+ const threshold = j1ThresholdFromEnv(env);
616
+ const gateState = disabledByOverride ? "disabled via overrides" : mode === "off" ? "off (env unset)" : "active";
617
+ const rows = [
618
+ {
619
+ id: "j1.mode",
620
+ title: `Mode: ${mode}`,
621
+ description: MODE_DESCRIPTION[mode],
622
+ ...disabledByOverride ? { marker: "[!]" } : {},
623
+ selectable: false
624
+ },
625
+ {
626
+ id: "j1.threshold",
627
+ title: `Enforce threshold: ${threshold}`,
628
+ description: "deny at or above; 0..1, default 0.8",
629
+ selectable: false
630
+ },
631
+ {
632
+ id: "j1.gate",
633
+ title: `Gate: ${gateState}`,
634
+ description: "the runtime plugin reads this once at startup",
635
+ selectable: false
636
+ }
637
+ ];
638
+ return {
639
+ id: "j1",
640
+ title: "J1 Risk Gate",
641
+ hint: `set ${J1_FLAG_ENV} / ${J1_THRESHOLD_ENV} — restart applies`,
642
+ rows
643
+ };
644
+ }
645
+ //#endregion
646
+ //#region src/preset-state.ts
647
+ /**
648
+ * preset-state.ts — the Model Preset section of the settings window.
649
+ *
650
+ * TUI-local replica (the bundle must stay self-contained). The preset NAMES
651
+ * mirror routing.yml's `presets:` and are drift-pinned by
652
+ * tests/tui-preset-state.test.mjs against `loadPresetDefs()`. The marker file
653
+ * shape mirrors scripts/install/model-picker.mjs's `buildActivePresetFile`
654
+ * (version 1), and the readers (`resolveActivePreset`, vision.ts candidates)
655
+ * only consult `.preset`, so the window writes `source: 'tui-settings'`.
656
+ *
657
+ * Scope note: the window writes the GLOBAL marker only
658
+ * (`<config-dir>/opencode/.pantheon/active-preset.json`). A project marker
659
+ * wins (it precedes the global path in every runtime candidate list), so it
660
+ * is displayed read-only. `none` DELETES the marker with a .bak backup — the
661
+ * same contract as the CLI's `set-tier none`.
662
+ */
663
+ /** Mirrors routing.yml `presets:` — drift-pinned against loadPresetDefs(). */
664
+ const PRESET_NAMES = Object.freeze([
665
+ "go-free",
666
+ "go-fast",
667
+ "go-premium",
668
+ "go-hybrid",
669
+ "anthropic",
670
+ "openai"
671
+ ]);
672
+ function globalActivePresetPath(env = process.env) {
673
+ const xdg = env.XDG_CONFIG_HOME;
674
+ const home = env.HOME ?? "";
675
+ const root = xdg ?? join(home, ".config");
676
+ return join(root, "opencode", ".pantheon", "active-preset.json");
677
+ }
678
+ function projectActivePresetPath() {
679
+ return join(process.cwd(), ".pantheon", "active-preset.json");
680
+ }
681
+ /** Fail-open read: missing/corrupt marker = no active preset. */
682
+ function readActivePresetMarker(path) {
683
+ try {
684
+ const raw = JSON.parse(readFileSync(path, "utf8"));
685
+ if (typeof raw?.preset !== "string" || raw.preset === "" || raw.preset === "none") return null;
686
+ return {
687
+ name: raw.preset,
688
+ updatedAt: typeof raw.updated_at === "string" ? raw.updated_at : ""
689
+ };
690
+ } catch {
691
+ return null;
692
+ }
693
+ }
694
+ function writeMarkerAtomically(path, content) {
695
+ mkdirSync(dirname(path), { recursive: true });
696
+ const temp = `${path}.tui.tmp`;
697
+ writeFileSync(temp, content);
698
+ renameSync(temp, path);
699
+ }
700
+ /** Select a preset globally: .bak backup, atomic write, version-1 marker. */
701
+ function writeActivePreset(path, name, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
702
+ if (!PRESET_NAMES.includes(name)) throw new TypeError(`Refusing to persist unknown preset "${name}"`);
703
+ backupMarker(path);
704
+ writeMarkerAtomically(path, `${JSON.stringify({
705
+ version: 1,
706
+ preset: name,
707
+ source: "tui-settings",
708
+ updated_at: nowIso
709
+ }, null, 2)}\n`);
710
+ }
711
+ /** Clear the global marker (the `none` contract): .bak backup, then remove. */
712
+ function clearActivePreset(path) {
713
+ backupMarker(path);
714
+ rmSync(path, { force: true });
715
+ }
716
+ function backupMarker(path) {
717
+ if (!existsSync(path)) return;
718
+ mkdirSync(dirname(path), { recursive: true });
719
+ copyFileSync(path, `${path}.bak`);
720
+ }
721
+ function buildPresetSection(input) {
722
+ const rows = PRESET_NAMES.map((name) => ({
723
+ id: `preset.${name}`,
724
+ title: name,
725
+ description: input.globalName === name ? "active (global)" : "enter: activate globally",
726
+ disabled: input.globalName === name
727
+ }));
728
+ rows.push({
729
+ id: "preset.none",
730
+ title: "none",
731
+ description: "clear the global marker — opencode defaults",
732
+ disabled: input.globalName === null,
733
+ marker: input.globalName === null ? "[x]" : "[ ]"
734
+ });
735
+ if (input.projectName !== null) rows.push({
736
+ id: "preset.project",
737
+ title: `${input.projectName} (project)`,
738
+ description: `${projectActivePresetPath()} wins over the global marker`,
739
+ marker: "[!]",
740
+ selectable: false
741
+ });
742
+ return {
743
+ id: "preset",
744
+ title: "Model Preset",
745
+ rows,
746
+ hint: "enter: activate globally · writes <config>/opencode/.pantheon/active-preset.json"
747
+ };
748
+ }
749
+ //#endregion
750
+ //#region src/update-status.ts
751
+ /** The running version's channel: a `-beta.N` suffix rides the beta dist-tag. */
752
+ function updateChannelFor(version) {
753
+ return /-beta\.\d+$/.test(version) ? "beta" : "stable";
754
+ }
755
+ /** The npm dist-tag the registry check should query for the channel. */
756
+ function registryTagForChannel(channel) {
757
+ return channel === "beta" ? "beta" : "latest";
758
+ }
759
+ function registryUrlForChannel(channel) {
760
+ return `https://registry.npmjs.org/pantheon-opencode/${registryTagForChannel(channel)}`;
761
+ }
762
+ function formatAgo(ms) {
763
+ if (ms < 6e4) return "just now";
764
+ if (ms < 36e5) return `${Math.floor(ms / 6e4)}m ago`;
765
+ if (ms < 864e5) return `${Math.floor(ms / 36e5)}h ago`;
766
+ return `${Math.floor(ms / 864e5)}d ago`;
767
+ }
768
+ function buildUpdatesSection(input) {
769
+ const nowMs = input.nowMs ?? Date.now();
770
+ const channel = updateChannelFor(input.currentVersion);
771
+ const lastCheckMs = input.state.lastCheckMs;
772
+ const latest = input.lastCheckedVersion ?? input.state.lastNotifiedVersion;
773
+ const rows = [{
774
+ id: "update.channel",
775
+ title: `Channel: ${channel}`,
776
+ description: "stable tracks npm `latest`; beta tracks npm `beta`",
777
+ selectable: false
778
+ }, {
779
+ id: "update.check",
780
+ title: "Check now",
781
+ description: input.checking ? "checking…" : lastCheckMs ? `last check ${formatAgo(nowMs - lastCheckMs)}` : "never checked",
782
+ marker: " → ",
783
+ selectable: true
784
+ }];
785
+ if (latest) {
786
+ const stable = (version) => !/-beta\.\d+$/.test(version);
787
+ const newer = comparePantheonVersions(latest, input.currentVersion) > 0 && !(stable(input.currentVersion) && !stable(latest));
788
+ rows.push({
789
+ id: "update.latest",
790
+ title: newer ? `Update available: v${latest}` : `Up to date (latest seen v${latest})`,
791
+ description: newer ? "adopt with `pantheon-opencode update`" : "checked against the registry",
792
+ marker: newer ? "[!]" : "[✓]",
793
+ selectable: false
794
+ });
795
+ }
796
+ return {
797
+ id: "updates",
798
+ title: "Updates",
799
+ hint: `refresh = \`pantheon-opencode update\` · notice TTL ${UPDATE_CHECK_TTL_MS / 36e5}h`,
800
+ rows
801
+ };
802
+ }
128
803
  //#endregion
129
804
  //#region src/pantheon-settings.tsx
130
805
  /** @jsxImportSource @opentui/solid */
131
806
  /**
132
807
  * pantheon-settings.tsx — the /pantheon-settings window.
133
808
  *
134
- * Three pages (Gates / Overrides+About), keyboard-first: `up`/`down` select,
135
- * `enter`/`space` toggles the selected behavior (writes the GLOBAL overrides
136
- * file — the same one the installer and doctor consume), `tab` flips pages,
137
- * `escape`/`q` closes. The gated-layer pattern mirrors the dispatch panel and
138
- * whats-new windows. Every failure path is silent (fail-open).
809
+ * One section per page, keyboard-first: `tab` cycles sections, `up`/`down`
810
+ * select, `enter`/`space` dispatches the selected row (the Gates section
811
+ * writes the GLOBAL overrides file — the same one the installer and doctor
812
+ * consume; Updates runs a registry check). `escape`/`q` closes. The
813
+ * gated-layer pattern mirrors the dispatch panel and whats-new windows.
814
+ * Every failure path is silent (fail-open).
139
815
  */
140
816
  function globalOverridesPath() {
141
817
  const xdgConfig = process.env.XDG_CONFIG_HOME ?? join(process.env.HOME ?? "", ".config");
142
818
  return join(xdgConfig, "opencode", "pantheon-overrides.json");
143
819
  }
144
- function readOverridesFromDisk() {
820
+ function projectOverridesPath() {
821
+ return join(process.cwd(), ".pantheon", "overrides.json");
822
+ }
823
+ /** Read one overrides file; a missing file is empty, an unreadable one is corrupt. */
824
+ function readOneOverrides(path) {
825
+ try {
826
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
827
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {
828
+ value: {},
829
+ corrupt: true
830
+ };
831
+ return {
832
+ value: parsed,
833
+ corrupt: false
834
+ };
835
+ } catch (error) {
836
+ return {
837
+ value: {},
838
+ corrupt: error?.code !== "ENOENT"
839
+ };
840
+ }
841
+ }
842
+ function readOverridesLoad() {
843
+ const globalRead = readOneOverrides(globalOverridesPath());
844
+ const projectRead = readOneOverrides(projectOverridesPath());
845
+ return {
846
+ global: globalRead.value,
847
+ project: projectRead.value,
848
+ corruptGlobal: globalRead.corrupt
849
+ };
850
+ }
851
+ function writeOverridesToDisk(load) {
852
+ writeFileSync(globalOverridesPath(), serializeOverrides(load.global), "utf8");
853
+ }
854
+ function updateCheckStatePath() {
855
+ const stateDir = process.env.XDG_STATE_HOME ?? join(process.env.HOME ?? "", ".local", "state");
856
+ return join(stateDir, "pantheon", "update-check.json");
857
+ }
858
+ function readUpdateCheckState() {
145
859
  try {
146
- return JSON.parse(readFileSync(globalOverridesPath(), "utf8"));
860
+ return JSON.parse(readFileSync(updateCheckStatePath(), "utf8"));
147
861
  } catch {
148
862
  return {};
149
863
  }
150
864
  }
151
- function writeOverridesToDisk(effective) {
152
- writeFileSync(globalOverridesPath(), serializeOverrides(effective), "utf8");
865
+ /**
866
+ * Registry check for the RUNNING version's channel (beta installs ask the
867
+ * beta dist-tag). Resolves with the latest version seen, or null offline.
868
+ */
869
+ async function fetchLatestForChannel(currentVersion) {
870
+ try {
871
+ const response = await fetch(registryUrlForChannel(updateChannelFor(currentVersion)), { signal: AbortSignal.timeout(5e3) });
872
+ return String((await response.json())?.version ?? "") || null;
873
+ } catch {
874
+ return null;
875
+ }
153
876
  }
154
- /** Rows shown on the Gates page: behavior state from the overrides file. */
155
- function buildSettingsRows(effective) {
156
- return SETTINGS_BEHAVIORS.map((behavior) => ({
157
- id: behavior.id,
158
- title: behavior.title,
159
- description: behavior.description,
160
- disabled: isBehaviorDisabled(effective, behavior.id)
161
- }));
877
+ function persistUpdateCheckState(previous, latest) {
878
+ try {
879
+ const path = updateCheckStatePath();
880
+ mkdirSync(join(path, ".."), { recursive: true });
881
+ writeFileSync(path, `${JSON.stringify(nextCheckState(previous, latest ? {
882
+ version: latest,
883
+ message: ""
884
+ } : null, Date.now()), null, 2)}\n`);
885
+ } catch {}
886
+ }
887
+ function resolveRunningVersion$1() {
888
+ try {
889
+ return JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version ?? "unknown";
890
+ } catch {
891
+ return "unknown";
892
+ }
162
893
  }
163
894
  function SettingsContent(props) {
164
- const marker = (row) => row.disabled ? "[x]" : "[ ]";
895
+ const section = () => props.sections()[props.page()] ?? {
896
+ id: "empty",
897
+ title: "",
898
+ rows: []
899
+ };
165
900
  return (() => {
166
- var _el$ = createElement("box"), _el$9 = createElement("box"), _el$0 = createElement("text"), _el$1 = createTextNode(`tab: page · up/down: select · enter: toggle · esc/q: close`);
167
- insertNode(_el$, _el$9);
168
- insertNode(_el$, _el$0);
901
+ var _el$ = createElement("box"), _el$2 = createElement("text"), _el$3 = createElement("text"), _el$5 = createElement("box"), _el$7 = createElement("text"), _el$8 = createTextNode(`tab: section · up/down: select · enter: apply · esc/q: close`);
902
+ insertNode(_el$, _el$2);
903
+ insertNode(_el$, _el$3);
904
+ insertNode(_el$, _el$5);
905
+ insertNode(_el$, _el$7);
169
906
  setProp(_el$, "flexDirection", "column");
170
907
  setProp(_el$, "paddingLeft", 1);
171
908
  setProp(_el$, "paddingRight", 1);
172
909
  setProp(_el$, "paddingTop", 1);
173
- insert(_el$, createComponent(Show, {
174
- get when() {
175
- return props.page() === 0;
910
+ setProp(_el$2, "attributes", 1);
911
+ insert(_el$2, () => section().title);
912
+ insertNode(_el$3, createTextNode(`──────────────────────────────────────`));
913
+ insert(_el$, createComponent(For, {
914
+ get each() {
915
+ return section().rows;
176
916
  },
177
- get fallback() {
917
+ children: (row) => {
918
+ const isSelected = () => row.selectable !== false && row.id === props.selectedId();
919
+ const marker = () => row.marker ?? (row.disabled ? "[x]" : "[ ]");
178
920
  return (() => {
179
- var _el$10 = createElement("box"), _el$11 = createElement("text"), _el$13 = createElement("text");
180
- insertNode(_el$10, _el$11);
181
- insertNode(_el$10, _el$13);
182
- setProp(_el$10, "flexDirection", "column");
183
- insertNode(_el$11, createTextNode(`About`));
184
- setProp(_el$11, "attributes", 1);
185
- insertNode(_el$13, createTextNode(`──────────────────────────────────────`));
186
- insert(_el$10, createComponent(For, {
187
- get each() {
188
- return props.about();
921
+ var _el$9 = createElement("box"), _el$0 = createElement("text");
922
+ insertNode(_el$9, _el$0);
923
+ setProp(_el$9, "flexDirection", "column");
924
+ spread(_el$0, mergeProps({ get fg() {
925
+ return memo(() => !!isSelected())() ? props.fg : props.muted;
926
+ } }, () => isSelected() ? { attributes: 1 } : {}), true);
927
+ insert(_el$0, () => `${marker()} ${row.title}${isSelected() ? " <-" : ""}`);
928
+ insert(_el$9, createComponent(Show, {
929
+ get when() {
930
+ return row.description !== "";
189
931
  },
190
- children: (line) => (() => {
191
- var _el$15 = createElement("text");
192
- insert(_el$15, line);
193
- effect((_$p) => setProp(_el$15, "fg", props.muted, _$p));
194
- return _el$15;
195
- })()
932
+ get children() {
933
+ var _el$1 = createElement("text");
934
+ insert(_el$1, () => ` ${row.description}`);
935
+ effect((_$p) => setProp(_el$1, "fg", props.muted, _$p));
936
+ return _el$1;
937
+ }
196
938
  }), null);
197
- effect((_p$) => {
198
- var _v$ = props.fg, _v$2 = props.muted;
199
- _v$ !== _p$.e && (_p$.e = setProp(_el$11, "fg", _v$, _p$.e));
200
- _v$2 !== _p$.t && (_p$.t = setProp(_el$13, "fg", _v$2, _p$.t));
201
- return _p$;
202
- }, {
203
- e: void 0,
204
- t: void 0
205
- });
206
- return _el$10;
939
+ return _el$9;
207
940
  })();
941
+ }
942
+ }), _el$5);
943
+ setProp(_el$5, "height", 1);
944
+ insert(_el$, createComponent(Show, {
945
+ get when() {
946
+ return section().hint !== void 0;
208
947
  },
209
948
  get children() {
210
- return [
211
- (() => {
212
- var _el$2 = createElement("text");
213
- insertNode(_el$2, createTextNode(`Gates &amp; Overrides`));
214
- setProp(_el$2, "attributes", 1);
215
- effect((_$p) => setProp(_el$2, "fg", props.fg, _$p));
216
- return _el$2;
217
- })(),
218
- (() => {
219
- var _el$4 = createElement("text");
220
- insertNode(_el$4, createTextNode(`──────────────────────────────────────`));
221
- effect((_$p) => setProp(_el$4, "fg", props.muted, _$p));
222
- return _el$4;
223
- })(),
224
- createComponent(For, {
225
- get each() {
226
- return props.rows();
227
- },
228
- children: (row, index) => (() => {
229
- var _el$16 = createElement("box"), _el$17 = createElement("text"), _el$18 = createElement("text");
230
- insertNode(_el$16, _el$17);
231
- insertNode(_el$16, _el$18);
232
- setProp(_el$16, "flexDirection", "column");
233
- insert(_el$17, () => `${marker(row)} ${row.title}${props.selected() === index() ? " <-" : ""}`);
234
- insert(_el$18, () => ` ${row.description}`);
235
- effect((_p$) => {
236
- var _v$3 = props.selected() === index() ? props.fg : props.muted, _v$4 = props.selected() === index() ? 1 : void 0, _v$5 = props.muted;
237
- _v$3 !== _p$.e && (_p$.e = setProp(_el$17, "fg", _v$3, _p$.e));
238
- _v$4 !== _p$.t && (_p$.t = setProp(_el$17, "attributes", _v$4, _p$.t));
239
- _v$5 !== _p$.a && (_p$.a = setProp(_el$18, "fg", _v$5, _p$.a));
240
- return _p$;
241
- }, {
242
- e: void 0,
243
- t: void 0,
244
- a: void 0
245
- });
246
- return _el$16;
247
- })()
248
- }),
249
- (() => {
250
- var _el$6 = createElement("box");
251
- setProp(_el$6, "height", 1);
252
- return _el$6;
253
- })(),
254
- (() => {
255
- var _el$7 = createElement("text");
256
- insertNode(_el$7, createTextNode(`enter: disable/enable · writes pantheon-overrides.json (global)`));
257
- effect((_$p) => setProp(_el$7, "fg", props.muted, _$p));
258
- return _el$7;
259
- })()
260
- ];
949
+ var _el$6 = createElement("text");
950
+ insert(_el$6, () => section().hint);
951
+ effect((_$p) => setProp(_el$6, "fg", props.muted, _$p));
952
+ return _el$6;
261
953
  }
262
- }), _el$9);
263
- setProp(_el$9, "height", 1);
264
- insertNode(_el$0, _el$1);
265
- insert(_el$0, () => `${props.page() + 1}/2 · `, _el$1);
266
- effect((_$p) => setProp(_el$0, "fg", props.muted, _$p));
954
+ }), _el$7);
955
+ insertNode(_el$7, _el$8);
956
+ insert(_el$7, () => `${props.page() + 1}/${props.sections().length} · `, _el$8);
957
+ effect((_p$) => {
958
+ var _v$ = props.fg, _v$2 = props.muted, _v$3 = props.muted;
959
+ _v$ !== _p$.e && (_p$.e = setProp(_el$2, "fg", _v$, _p$.e));
960
+ _v$2 !== _p$.t && (_p$.t = setProp(_el$3, "fg", _v$2, _p$.t));
961
+ _v$3 !== _p$.a && (_p$.a = setProp(_el$7, "fg", _v$3, _p$.a));
962
+ return _p$;
963
+ }, {
964
+ e: void 0,
965
+ t: void 0,
966
+ a: void 0
967
+ });
267
968
  return _el$;
268
969
  })();
269
970
  }
270
971
  /**
271
- * Entry glue: read the overrides state, then show the window through the host
272
- * dialog stack once. The gated keymap layer is inert while the window is
273
- * closed. Never throws.
972
+ * Entry glue: read both overrides files, then show the window through the
973
+ * host dialog stack once. The gated keymap layer is inert while the window
974
+ * is closed. Never throws.
274
975
  */
275
976
  async function maybeShowPantheonSettings(context) {
276
977
  try {
277
978
  const [open, setOpen] = createSignal(false);
278
979
  const [page, setPage] = createSignal(0);
279
- const [selected, setSelected] = createSignal(0);
280
- const [effective, setEffective] = createSignal(readOverridesFromDisk());
281
- const rows = () => buildSettingsRows(effective());
282
- const about = () => [
283
- `Pantheon v${resolveRunningVersion$1()}`,
284
- `${SETTINGS_BEHAVIORS.length} togglable behaviors · OpenCode 2.x only`,
285
- "Docs: docs/design/2.0-settings-and-install.md"
980
+ const [load, setLoad] = createSignal(readOverridesLoad());
981
+ const [lastChecked, setLastChecked] = createSignal(void 0);
982
+ const [checking, setChecking] = createSignal(false);
983
+ const [decision, setDecision] = createSignal(readDecisionRouterConfig());
984
+ const [presetTick, setPresetTick] = createSignal(0);
985
+ const currentVersion = resolveRunningVersion$1();
986
+ const updatesInput = () => {
987
+ const input = {
988
+ currentVersion,
989
+ state: readUpdateCheckState(),
990
+ checking: checking(),
991
+ nowMs: Date.now()
992
+ };
993
+ const seen = lastChecked();
994
+ if (seen !== void 0) input.lastCheckedVersion = seen;
995
+ return input;
996
+ };
997
+ const presetInput = () => {
998
+ presetTick();
999
+ return {
1000
+ globalName: readActivePresetMarker(globalActivePresetPath())?.name ?? null,
1001
+ projectName: readActivePresetMarker(projectActivePresetPath())?.name ?? null
1002
+ };
1003
+ };
1004
+ const sections = () => [
1005
+ buildGatesSection(load()),
1006
+ buildDecisionSection(decision()),
1007
+ buildPresetSection(presetInput()),
1008
+ buildJ1Section(process.env, isBehaviorDisabled(mergedOverrides(load()), "gate-j1-risk-gate")),
1009
+ buildUpdatesSection(updatesInput()),
1010
+ buildDoctorSection({
1011
+ runningVersion: currentVersion,
1012
+ nodeVersion: process.versions.node,
1013
+ load: load()
1014
+ }),
1015
+ buildAboutSection(currentVersion)
286
1016
  ];
1017
+ const [selectedId, setSelectedId] = createSignal(firstSelectableId(sections()));
1018
+ const move = (delta) => {
1019
+ const list = flatSelectableRows(sections());
1020
+ if (list.length === 0) return;
1021
+ const current = list.findIndex((row) => row.id === selectedId());
1022
+ const nextIndex = current === -1 ? 0 : Math.min(Math.max(current + delta, 0), list.length - 1);
1023
+ setSelectedId(list[nextIndex]?.id);
1024
+ };
1025
+ const flipSection = () => {
1026
+ const count = sections().length;
1027
+ const next = (page() + 1) % count;
1028
+ setPage(next);
1029
+ const target = sections()[next];
1030
+ if (target === void 0) return;
1031
+ const within = flatSelectableRows([target])[0];
1032
+ if (within) setSelectedId(within.id);
1033
+ };
1034
+ const toggleSelectedGate = () => {
1035
+ const id = selectedId();
1036
+ if (id === void 0 || !id.startsWith("gate.")) return false;
1037
+ if (!canWriteOverrides(load())) return void 0;
1038
+ const behaviorId = id.slice(5);
1039
+ const next = {
1040
+ ...load(),
1041
+ global: toggledOverrides(load().global, behaviorId)
1042
+ };
1043
+ try {
1044
+ writeOverridesToDisk(next);
1045
+ setLoad(next);
1046
+ } catch {}
1047
+ };
1048
+ const checkUpdatesNow = () => {
1049
+ if (checking()) return void 0;
1050
+ setChecking(true);
1051
+ fetchLatestForChannel(currentVersion).then((latest) => {
1052
+ if (latest) setLastChecked(latest);
1053
+ persistUpdateCheckState(readUpdateCheckState(), latest);
1054
+ }).catch(() => {}).finally(() => setChecking(false));
1055
+ };
1056
+ const toggleDecisionEnabled = () => {
1057
+ const current = decision();
1058
+ if (current.corrupt) return void 0;
1059
+ const next = setDecisionEnabled(current.config, !current.config.enabled);
1060
+ if (!next.ok) return void 0;
1061
+ try {
1062
+ writeDecisionRouterConfig(next.config);
1063
+ setDecision({
1064
+ config: next.config,
1065
+ corrupt: false
1066
+ });
1067
+ } catch {}
1068
+ };
1069
+ const applySelectedPreset = () => {
1070
+ const id = selectedId();
1071
+ if (id === void 0) return void 0;
1072
+ const name = id.startsWith("preset.") ? id.slice(7) : null;
1073
+ if (name === null || name === "project") return void 0;
1074
+ const path = globalActivePresetPath();
1075
+ try {
1076
+ if (name === "none") clearActivePreset(path);
1077
+ else writeActivePreset(path, name);
1078
+ setPresetTick((tick) => tick + 1);
1079
+ } catch {}
1080
+ };
287
1081
  let dismiss = () => {};
288
1082
  try {
289
1083
  context.keymap.layer(() => ({
@@ -305,7 +1099,7 @@ async function maybeShowPantheonSettings(context) {
305
1099
  bind: "down,j",
306
1100
  run: () => {
307
1101
  if (!open()) return false;
308
- setSelected((current) => Math.min(current + 1, rows().length - 1));
1102
+ move(1);
309
1103
  }
310
1104
  },
311
1105
  {
@@ -314,28 +1108,29 @@ async function maybeShowPantheonSettings(context) {
314
1108
  bind: "up,k",
315
1109
  run: () => {
316
1110
  if (!open()) return false;
317
- setSelected((current) => Math.max(current - 1, 0));
1111
+ move(-1);
318
1112
  }
319
1113
  },
320
1114
  {
321
1115
  id: "pantheon.settings.toggle",
322
- title: "Disable/enable the selected behavior",
1116
+ title: "Apply the selected row",
323
1117
  bind: "enter,space",
324
1118
  run: () => {
325
1119
  if (!open()) return false;
326
- const row = rows()[selected()];
327
- if (row === void 0) return false;
328
- setEffective(toggledOverrides(effective(), row.id));
329
- writeOverridesToDisk(effective());
1120
+ const id = selectedId();
1121
+ if (id?.startsWith("gate.")) return toggleSelectedGate();
1122
+ if (id === "decision.enabled") return toggleDecisionEnabled();
1123
+ if (id?.startsWith("preset.")) return applySelectedPreset();
1124
+ if (id === "update.check") return checkUpdatesNow();
330
1125
  }
331
1126
  },
332
1127
  {
333
- id: "pantheon.settings.page",
334
- title: "Flip page",
1128
+ id: "pantheon.settings.section",
1129
+ title: "Next section",
335
1130
  bind: "tab",
336
1131
  run: () => {
337
1132
  if (!open()) return false;
338
- setPage((current) => current === 0 ? 1 : 0);
1133
+ flipSection();
339
1134
  }
340
1135
  }
341
1136
  ]
@@ -343,21 +1138,21 @@ async function maybeShowPantheonSettings(context) {
343
1138
  } catch {}
344
1139
  const close = () => {
345
1140
  setOpen(false);
1141
+ };
1142
+ dismiss = () => {
346
1143
  try {
347
1144
  context.ui.dialog.clear();
348
1145
  } catch {}
1146
+ close();
349
1147
  };
350
- dismiss = close;
351
1148
  setOpen(true);
352
1149
  setPage(0);
353
1150
  try {
354
1151
  const theme = context.theme?.text ?? {};
355
1152
  context.ui.dialog.show(() => createComponent(SettingsContent, {
356
- rows,
357
- selected,
1153
+ sections,
358
1154
  page,
359
- version: resolveRunningVersion$1,
360
- about,
1155
+ selectedId,
361
1156
  get fg() {
362
1157
  return theme.base;
363
1158
  },
@@ -365,16 +1160,12 @@ async function maybeShowPantheonSettings(context) {
365
1160
  return theme.muted;
366
1161
  }
367
1162
  }), close);
1163
+ try {
1164
+ context.ui.dialog.set?.({ size: "xlarge" });
1165
+ } catch {}
368
1166
  } catch {}
369
1167
  } catch {}
370
1168
  }
371
- function resolveRunningVersion$1() {
372
- try {
373
- return JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version ?? "unknown";
374
- } catch {
375
- return "unknown";
376
- }
377
- }
378
1169
  //#endregion
379
1170
  //#region src/sidebar-width.ts
380
1171
  const GRAPHEMES = new Intl.Segmenter(void 0, { granularity: "grapheme" });
@@ -497,46 +1288,6 @@ function cellWidth(value) {
497
1288
  for (const { segment } of GRAPHEMES.segment(value)) width += graphemeWidth(segment);
498
1289
  return width;
499
1290
  }
500
- /** Semver-ish compare for X.Y.Z[-beta.N]; betas sort before their release. */
501
- function comparePantheonVersions(left, right) {
502
- const parse = (version) => {
503
- const match = String(version).trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-beta\.(\d+))?$/);
504
- if (!match) return null;
505
- return {
506
- core: [
507
- +match[1],
508
- +match[2],
509
- +match[3]
510
- ],
511
- beta: match[4] === void 0 ? Number.POSITIVE_INFINITY : +match[4]
512
- };
513
- };
514
- const a = parse(left);
515
- const b = parse(right);
516
- if (!a || !b) return 0;
517
- for (let index = 0; index < 3; index += 1) if (a.core[index] !== b.core[index]) return a.core[index] - b.core[index];
518
- return a.beta - b.beta;
519
- }
520
- function pickUpdateNotice(input) {
521
- const { currentVersion, latestVersion, state = {}, nowMs = Date.now() } = input;
522
- const ttlMs = input.ttlMs ?? 216e5;
523
- if (nowMs - (state.lastCheckMs ?? 0) < ttlMs) return null;
524
- if (state.lastNotifiedVersion === latestVersion) return null;
525
- const stable = (version) => !/-beta\.\d+$/.test(version);
526
- if (stable(currentVersion) && !stable(latestVersion)) return null;
527
- if (comparePantheonVersions(latestVersion, currentVersion) <= 0) return null;
528
- return {
529
- version: latestVersion,
530
- message: `pantheon-opencode ${latestVersion} available — changelog in /pantheon-settings, adopt with \`pantheon-opencode update\``
531
- };
532
- }
533
- /** The state to persist after a check (notified or not) for the TTL. */
534
- function nextCheckState(previous, notice, nowMs) {
535
- return {
536
- lastCheckMs: nowMs,
537
- lastNotifiedVersion: notice?.version ?? previous.lastNotifiedVersion
538
- };
539
- }
540
1291
  /** Prefix of the "+N more" line appended when the bullet budget is exceeded. */
541
1292
  const WHATS_NEW_MORE_PREFIX = "… +";
542
1293
  const EMPTY_HIGHLIGHTS = {
@@ -724,7 +1475,7 @@ async function readChangelogForBundle(bundleUrl) {
724
1475
  }
725
1476
  /** The ambient build-time version, or null outside a tsdown build. */
726
1477
  function embeddedVersion() {
727
- return "2.0.0-beta.1";
1478
+ return "2.0.0-beta.2";
728
1479
  }
729
1480
  /**
730
1481
  * Resolve the running Pantheon version for the what's-new window: the plugin
@@ -3356,13 +4107,13 @@ async function checkForPantheonUpdate(context) {
3356
4107
  };
3357
4108
  const persist = (notice) => {
3358
4109
  mkdirSync(join(stateDir, "pantheon"), { recursive: true });
3359
- writeFileSync(statePath, JSON.stringify(nextCheckState(readState(), notice, Date.now()), null, 2) + "\n");
4110
+ writeFileSync(statePath, `${JSON.stringify(nextCheckState(readState(), notice, Date.now()), null, 2)}\n`);
3360
4111
  };
3361
4112
  const response = await fetch("https://registry.npmjs.org/pantheon-opencode/latest", { signal: AbortSignal.timeout(5e3) });
3362
4113
  const latest = String((await response.json())?.version ?? "");
3363
4114
  if (!latest) return;
3364
4115
  const notice = pickUpdateNotice({
3365
- currentVersion: "2.0.0-beta.1",
4116
+ currentVersion: "2.0.0-beta.2",
3366
4117
  latestVersion: latest,
3367
4118
  state: readState(),
3368
4119
  nowMs: Date.now()
@@ -4142,7 +4893,7 @@ function Sidebar(props) {
4142
4893
  setProp(_el$12, "width", "100%");
4143
4894
  setProp(_el$12, "padding", 1);
4144
4895
  setProp(_el$13, "attributes", 1);
4145
- insert(_el$13, `Pantheon v2.0.0-beta.1`);
4896
+ insert(_el$13, `Pantheon v2.0.0-beta.2`);
4146
4897
  insert(_el$14, () => presetHeaderLine(model.preset().name ?? "", model.provider()));
4147
4898
  insert(_el$12, createComponent(Show, {
4148
4899
  get when() {
@@ -4884,7 +5635,7 @@ function HomeStatus(props) {
4884
5635
  const muted = () => props.context.theme?.text?.muted ?? props.context.theme?.text?.base;
4885
5636
  return (() => {
4886
5637
  var _el$72 = createElement("text");
4887
- insert(_el$72, () => `Pantheon v2.0.0-beta.1${preset().name ? ` ▸ ${preset().name}` : ""}`);
5638
+ insert(_el$72, () => `Pantheon v2.0.0-beta.2${preset().name ? ` ▸ ${preset().name}` : ""}`);
4888
5639
  effect((_$p) => setProp(_el$72, "fg", muted(), _$p));
4889
5640
  return _el$72;
4890
5641
  })();