pantheon-opencode 2.0.0-beta.4 → 2.0.0-beta.6

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.
@@ -23,11 +23,22 @@
23
23
  * dispatch-panel layer must never win while this window is open; field
24
24
  * report beta.2: navigation "stopped working" was exactly that theft).
25
25
  */
26
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
26
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
27
27
  import { join } from 'node:path'
28
28
  import type { Context } from '@opencode/plugin/tui/context'
29
29
  import { createSignal, For, onCleanup, Show } from 'solid-js'
30
30
  import {
31
+ buildAutonomyTab,
32
+ DEFAULT_DECISION_BUDGETS,
33
+ DEFAULT_GOAL_LOOP_PREFS,
34
+ type DecisionBudgets,
35
+ type GoalLoopPrefs,
36
+ MONTHLY_USD_CYCLE,
37
+ PER_DECISION_USD_CYCLE,
38
+ parseUsd,
39
+ } from './autonomy-state.ts'
40
+ import {
41
+ applyDecisionRow,
31
42
  buildDecisionTab,
32
43
  type DecisionConfigRead,
33
44
  readDecisionRouterConfig,
@@ -68,6 +79,7 @@ import {
68
79
  readActivePresetMarker,
69
80
  writeActivePreset,
70
81
  } from './preset-state.ts'
82
+ import { applyTuiRow, buildTuiTab, mutateTuiPrefs, tuiPrefs } from './tui-prefs.ts'
71
83
  import { nextCheckState, type UpdateCheckState } from './update-notice.ts'
72
84
  import {
73
85
  buildUpdatesTab,
@@ -78,12 +90,33 @@ import {
78
90
 
79
91
  export const ROUTE_NAME = 'pantheon-settings'
80
92
 
93
+ /** The input mode the page pushes while mounted (composer layers sleep). */
94
+ export const ROUTE_MODE = 'pantheon-settings'
95
+
81
96
  /** Loose local shape of a host route (the real Route lives in the host typings). */
82
97
  type WindowRoute =
83
98
  | { type: 'home' }
84
99
  | { type: 'session'; sessionID: string }
85
100
  | { type: 'plugin'; name: string; data?: Record<string, unknown> }
86
101
 
102
+ /**
103
+ * Strip a LIVE route object down to the plain shape the route store expects.
104
+ * `router.current()` returns the host's live data (reactive proxies, location
105
+ * objects with cycles) and the host's navigate deep-clones via JSON.stringify
106
+ * — passing the live object through throws "cyclic structures" and the
107
+ * window could never close (field report beta.5, root cause).
108
+ */
109
+ function plainRoute(route: WindowRoute | undefined): WindowRoute {
110
+ if (route === undefined) return { type: 'home' }
111
+ if (route.type === 'session' && 'sessionID' in route && typeof route.sessionID === 'string') {
112
+ return { type: 'session', sessionID: route.sessionID }
113
+ }
114
+ if (route.type === 'plugin' && typeof route.name === 'string') {
115
+ return { type: 'plugin', name: route.name }
116
+ }
117
+ return { type: 'home' }
118
+ }
119
+
87
120
  // ── Shared blocking state (the dispatch panel gates on this) ───────────
88
121
 
89
122
  const [blocking, setBlocking] = createSignal(false)
@@ -132,6 +165,110 @@ function writeOverridesToDisk(load: OverridesLoad): void {
132
165
  writeFileSync(globalOverridesPath(), serializeOverrides(load.global), 'utf8')
133
166
  }
134
167
 
168
+ function userOpenCodeConfigPath(): string {
169
+ const xdgConfig = process.env.XDG_CONFIG_HOME ?? join(process.env.HOME ?? '', '.config')
170
+ return join(xdgConfig, 'opencode', 'opencode.json')
171
+ }
172
+
173
+ /** Read options.goal_loop from the user's opencode.json (fail-open). */
174
+ function readGoalLoopPrefs(): GoalLoopPrefs {
175
+ const fallback = { ...DEFAULT_GOAL_LOOP_PREFS }
176
+ try {
177
+ const parsed = JSON.parse(readFileSync(userOpenCodeConfigPath(), 'utf8')) as {
178
+ options?: { goal_loop?: Partial<GoalLoopPrefs> }
179
+ }
180
+ const raw = parsed?.options?.goal_loop
181
+ if (raw && typeof raw === 'object') {
182
+ return {
183
+ enabled: typeof raw.enabled === 'boolean' ? raw.enabled : fallback.enabled,
184
+ cooldownMs:
185
+ typeof raw.cooldownMs === 'number' && raw.cooldownMs >= 1000
186
+ ? Math.floor(raw.cooldownMs)
187
+ : fallback.cooldownMs,
188
+ maxContinuations:
189
+ typeof raw.maxContinuations === 'number' && raw.maxContinuations >= 1
190
+ ? Math.min(200, Math.floor(raw.maxContinuations))
191
+ : fallback.maxContinuations,
192
+ }
193
+ }
194
+ } catch {
195
+ /* fail-open */
196
+ }
197
+ return fallback
198
+ }
199
+
200
+ /** Read the decision budgets from decision-router.json's `budget` envelope (fail-open). */
201
+ function readDecisionBudgets(): DecisionBudgets {
202
+ const fallback = { ...DEFAULT_DECISION_BUDGETS }
203
+ try {
204
+ const path = join(
205
+ process.env.XDG_CONFIG_HOME ?? join(process.env.HOME ?? '', '.config'),
206
+ 'pantheon',
207
+ 'decision-router.json',
208
+ )
209
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as { budget?: Partial<DecisionBudgets> }
210
+ const raw = parsed?.budget
211
+ if (raw && typeof raw === 'object') {
212
+ return {
213
+ monthlyUsd:
214
+ typeof raw.monthlyUsd === 'number' && raw.monthlyUsd > 0
215
+ ? raw.monthlyUsd
216
+ : fallback.monthlyUsd,
217
+ perDecisionUsd:
218
+ typeof raw.perDecisionUsd === 'number' && raw.perDecisionUsd > 0
219
+ ? raw.perDecisionUsd
220
+ : fallback.perDecisionUsd,
221
+ }
222
+ }
223
+ } catch {
224
+ /* fail-open */
225
+ }
226
+ return fallback
227
+ }
228
+
229
+ /**
230
+ * Surgically set one key under `options` in the user's opencode.json
231
+ * (preserving every other key). Startup-applied options live here — the
232
+ * runtime resolves them once at plugin setup.
233
+ */
234
+ function writeUserOption(key: string, value: unknown): void {
235
+ const path = userOpenCodeConfigPath()
236
+ let doc: Record<string, unknown> = {}
237
+ try {
238
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>
239
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) doc = parsed
240
+ } catch {
241
+ /* start a fresh object — nothing parseable to preserve */
242
+ }
243
+ const options =
244
+ typeof doc.options === 'object' && doc.options !== null && !Array.isArray(doc.options)
245
+ ? { ...(doc.options as Record<string, unknown>) }
246
+ : {}
247
+ options[key] = value
248
+ doc.options = options
249
+ writeFileSync(path, `${JSON.stringify(doc, null, 2)}\n`)
250
+ }
251
+
252
+ /** Merge the `budget` envelope into decision-router.json (0600 preserved). */
253
+ function writeDecisionBudget(budgets: { monthlyUsd: number; perDecisionUsd: number }): void {
254
+ const path = join(
255
+ process.env.XDG_CONFIG_HOME ?? join(process.env.HOME ?? '', '.config'),
256
+ 'pantheon',
257
+ 'decision-router.json',
258
+ )
259
+ let doc: Record<string, unknown> = {}
260
+ try {
261
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>
262
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) doc = parsed
263
+ } catch {
264
+ throw new Error('decision-router.json unreadable — repair via `decision-router setup-model`')
265
+ }
266
+ doc.budget = { ...budgets }
267
+ const temp = `${path}.tui.tmp`
268
+ writeFileSync(temp, `${JSON.stringify(doc, null, 2)}\n`, { mode: 0o600 })
269
+ renameSync(temp, path)
270
+ }
271
+
135
272
  function updateCheckStatePath(): string {
136
273
  const stateDir = process.env.XDG_STATE_HOME ?? join(process.env.HOME ?? '', '.local', 'state')
137
274
  return join(stateDir, 'pantheon', 'update-check.json')
@@ -171,9 +308,16 @@ function persistUpdateCheckState(previous: UpdateCheckState, latest: string | nu
171
308
  }
172
309
 
173
310
  function resolveRunningVersion(): string {
311
+ // The tsdown embed (same source the sidebar footer uses) is authoritative —
312
+ // the naive ../../package.json read breaks in every real layout (the dev
313
+ // tree and the installed TUI copy both put package.json one level above
314
+ // dist, not two — field report beta.5: the header showed vunknown).
315
+ if (typeof __PANTHEON_VERSION__ !== 'undefined' && __PANTHEON_VERSION__ !== '') {
316
+ return __PANTHEON_VERSION__
317
+ }
174
318
  try {
175
319
  const manifest = JSON.parse(
176
- readFileSync(new URL('../../package.json', import.meta.url), 'utf8'),
320
+ readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
177
321
  ) as { version?: string }
178
322
  return manifest.version ?? 'unknown'
179
323
  } catch {
@@ -183,7 +327,7 @@ function resolveRunningVersion(): string {
183
327
 
184
328
  // ── The window view (presentational; both surfaces render it) ──────────
185
329
 
186
- const NAME_WIDTH = 26
330
+ const NAME_WIDTH = 28
187
331
  const VALUE_WIDTH = 22
188
332
 
189
333
  export function SettingsWindow(props: {
@@ -202,12 +346,13 @@ export function SettingsWindow(props: {
202
346
  return (
203
347
  <box flexDirection="column" paddingLeft={1} paddingRight={1} paddingTop={1}>
204
348
  <box flexDirection="row">
205
- <text attributes={1} fg={props.fg}>
349
+ <text flexShrink={0} attributes={1} fg={props.fg}>
206
350
  {`Pantheon v${props.version}`}
207
351
  </text>
208
352
  <For each={props.tabs()}>
209
353
  {(t, index) => (
210
354
  <text
355
+ flexShrink={0}
211
356
  fg={index() === props.page() ? props.fg : props.muted}
212
357
  {...(index() === props.page() ? { attributes: 1 } : {})}
213
358
  >
@@ -215,7 +360,10 @@ export function SettingsWindow(props: {
215
360
  </text>
216
361
  )}
217
362
  </For>
218
- <text fg={props.muted}>{' esc'}</text>
363
+ <box flexGrow={1} />
364
+ <text flexShrink={0} fg={props.muted}>
365
+ {'esc'}
366
+ </text>
219
367
  </box>
220
368
  <text fg={props.muted}>{'─'.repeat(72)}</text>
221
369
  <For each={tab().groups}>
@@ -262,7 +410,9 @@ export function SettingsWindow(props: {
262
410
  )}
263
411
  </For>
264
412
  <Show when={props.notice() !== undefined}>
265
- <text fg={props.warn ?? props.muted}>{`⚠ ${props.notice()}`}</text>
413
+ <text fg={props.notice()?.startsWith('saved') ? props.muted : (props.warn ?? props.muted)}>
414
+ {props.notice()?.startsWith('saved') ? props.notice() : `⚠ ${props.notice()}`}
415
+ </text>
266
416
  </Show>
267
417
  <text fg={draftDirty(props.draft()) ? (props.warn ?? props.fg) : props.muted}>
268
418
  {draftDirty(props.draft())
@@ -309,6 +459,9 @@ function createWindowController(
309
459
  const [selected, setSelected] = createSignal(0)
310
460
  const [load, setLoad] = createSignal(readOverridesLoad())
311
461
  const [decision, setDecision] = createSignal<DecisionConfigRead>(readDecisionRouterConfig())
462
+ const [goalLoop, setGoalLoop] = createSignal<GoalLoopPrefs>(readGoalLoopPrefs())
463
+ const [budgets, setBudgets] = createSignal<DecisionBudgets>(readDecisionBudgets())
464
+ const [autonomyRestartPending, setAutonomyRestartPending] = createSignal(false)
312
465
  const [presetTick, setPresetTick] = createSignal(0)
313
466
  const [lastChecked, setLastChecked] = createSignal<string | undefined>(undefined)
314
467
  const [checking, setChecking] = createSignal(false)
@@ -341,6 +494,12 @@ function createWindowController(
341
494
  buildGatesTab(load()),
342
495
  buildDecisionTab(decision()),
343
496
  buildPresetTab(presetInput()),
497
+ buildTuiTab(tuiPrefs()),
498
+ buildAutonomyTab({
499
+ goalLoop: goalLoop(),
500
+ budgets: budgets(),
501
+ goalLoopRestartPending: autonomyRestartPending(),
502
+ }),
344
503
  buildJ1Tab(process.env, false),
345
504
  buildUpdatesTab(updatesInput()),
346
505
  buildDoctorTab({
@@ -419,6 +578,28 @@ function createWindowController(
419
578
  return { ok: false, reason: 'decision-router disk write failed' }
420
579
  }
421
580
  }
581
+ if (
582
+ id === 'decision.selection.mode' ||
583
+ id === 'decision.selection.target' ||
584
+ id === 'decision.consent'
585
+ ) {
586
+ const current = decision()
587
+ if (current.corrupt) {
588
+ return {
589
+ ok: false,
590
+ reason: 'decision-router.json unreadable — repair via `decision-router setup-model`',
591
+ }
592
+ }
593
+ const staged = applyDecisionRow(current.config, id, value)
594
+ if (staged === current.config) return { ok: false, reason: 'unknown or invalid value' }
595
+ try {
596
+ writeDecisionRouterConfig(staged)
597
+ setDecision({ config: staged, corrupt: false })
598
+ return { ok: true }
599
+ } catch {
600
+ return { ok: false, reason: 'decision-router disk write failed' }
601
+ }
602
+ }
422
603
  if (id === 'preset') {
423
604
  try {
424
605
  if (value === PRESET_NONE) clearActivePreset(globalActivePresetPath())
@@ -432,6 +613,62 @@ function createWindowController(
432
613
  }
433
614
  }
434
615
  }
616
+ if (id.startsWith('autonomy.goal_loop.')) {
617
+ const next = { ...goalLoop() }
618
+ if (id === 'autonomy.goal_loop.enabled') {
619
+ next.enabled = value === 'enabled'
620
+ } else if (id === 'autonomy.goal_loop.maxContinuations') {
621
+ const parsed = Number(value)
622
+ if (!Number.isFinite(parsed) || parsed < 1 || parsed > 200) {
623
+ return { ok: false, reason: 'max continuations must be 1..200' }
624
+ }
625
+ next.maxContinuations = Math.floor(parsed)
626
+ } else if (id === 'autonomy.goal_loop.cooldownMs') {
627
+ const parsed = Number(value)
628
+ if (!Number.isFinite(parsed) || parsed < 1000) {
629
+ return { ok: false, reason: 'cooldown must be >= 1000ms' }
630
+ }
631
+ next.cooldownMs = Math.floor(parsed)
632
+ }
633
+ try {
634
+ writeUserOption('goal_loop', next)
635
+ setGoalLoop(next)
636
+ setAutonomyRestartPending(true)
637
+ return { ok: true }
638
+ } catch {
639
+ return { ok: false, reason: 'opencode.json write failed' }
640
+ }
641
+ }
642
+ if (id === 'autonomy.budget.monthly' || id === 'autonomy.budget.perDecision') {
643
+ const parsed = parseUsd(value)
644
+ if (parsed === null) return { ok: false, reason: 'invalid USD value' }
645
+ const next = { ...budgets() }
646
+ if (id === 'autonomy.budget.monthly') next.monthlyUsd = parsed
647
+ else next.perDecisionUsd = parsed
648
+ try {
649
+ writeDecisionBudget(next)
650
+ setBudgets(next)
651
+ return { ok: true }
652
+ } catch {
653
+ return { ok: false, reason: 'budget write failed' }
654
+ }
655
+ }
656
+ if (id.startsWith('tui.')) {
657
+ // The prefs live in the host's durable reactive store: the mutation is
658
+ // async (persist), but the in-memory store flips immediately — the
659
+ // sidebar/footer/panel re-render on save, no restart. A persist
660
+ // failure surfaces in the notice line when it settles.
661
+ try {
662
+ mutateTuiPrefs((prefsDraft) => applyTuiRow(prefsDraft, id, value))
663
+ .then(() => setNotice(undefined))
664
+ .catch(() =>
665
+ setNotice('tui prefs: persist failed — the change is active for this session only'),
666
+ )
667
+ return { ok: true }
668
+ } catch {
669
+ return { ok: false, reason: 'tui prefs storage unavailable' }
670
+ }
671
+ }
435
672
  return { ok: false, reason: 'unknown staged row' }
436
673
  }
437
674
 
@@ -468,20 +705,21 @@ function createWindowController(
468
705
  }
469
706
 
470
707
  const close = () => {
471
- if (draftDirty(draft())) {
708
+ // A dialog.confirm here would render in the home/session view chrome,
709
+ // which a full-screen ROUTE page replaces — an invisible prompt that
710
+ // pends forever (field report beta.5: esc "did nothing" with staged
711
+ // changes). Close always exits; discarding is announced, never asked.
712
+ const staged = draftCount(draft())
713
+ if (staged > 0) {
714
+ setDraft({})
472
715
  try {
473
- void Promise.resolve(
474
- context.ui.dialog.confirm({
475
- title: 'Pantheon settings',
476
- message: 'Discard unsaved settings changes?',
477
- }),
478
- ).then((confirmed) => {
479
- if (confirmed === true) exit()
716
+ context.ui.toast?.show?.({
717
+ variant: 'info',
718
+ message: `settings: ${staged} staged change${staged === 1 ? '' : 's'} discarded`,
480
719
  })
481
720
  } catch {
482
- /* confirm unavailable — stay open; the user can ctrl+r first */
721
+ /* toast unavailable */
483
722
  }
484
- return
485
723
  }
486
724
  exit()
487
725
  }
@@ -530,6 +768,17 @@ function SettingsPage(props: { context: Context; data: Record<string, any> | und
530
768
  )
531
769
  const theme = context.theme?.text ?? {}
532
770
  const warn = (theme?.feedback as any)?.warning?.base ?? theme.muted
771
+ // The page owns the keyboard while mounted: push an input MODE so the
772
+ // composer's base-mode layers sleep (they eat escape and plain letters —
773
+ // the host's own menus push a mode for exactly this). The page layer is
774
+ // scoped to this mode; cleanup pops it.
775
+ try {
776
+ const popMode = context.keymap?.mode?.push?.(ROUTE_MODE)
777
+ if (popMode !== undefined) onCleanup(() => popMode())
778
+ } catch {
779
+ /* mode API unavailable — composer layers stay active; keys still fall
780
+ through to the mode-less fallback layer below */
781
+ }
533
782
  onCleanup(controller.cleanup)
534
783
  setBlocking(true)
535
784
  pageApi = controller.api
@@ -551,9 +800,14 @@ function SettingsPage(props: { context: Context; data: Record<string, any> | und
551
800
  function navigateBack(context: Context, data?: { returnRoute?: WindowRoute }): void {
552
801
  try {
553
802
  const fallback: WindowRoute = { type: 'home' }
554
- context.ui.router.navigate(data?.returnRoute ?? fallback)
803
+ const destination = data?.returnRoute ?? fallback
804
+ context.ui.toast?.show?.({
805
+ variant: 'info',
806
+ message: `settings: navigating ${JSON.stringify(destination)}`,
807
+ })
808
+ context.ui.router.navigate(destination)
555
809
  } catch {
556
- /* router unavailable — nothing to navigate back to */
810
+ /* router unavailable — the failure is observable only as a stuck page */
557
811
  }
558
812
  }
559
813
 
@@ -636,7 +890,21 @@ export function setupPantheonSettings(context: Context): void {
636
890
  title: 'Close settings',
637
891
  bind: 'escape,q',
638
892
  run: () => {
639
- pageApi?.close()
893
+ try {
894
+ context.ui.toast?.show?.({ variant: 'info', message: 'settings: close command fired' })
895
+ } catch {}
896
+ if (pageApi === undefined) {
897
+ try {
898
+ context.ui.toast?.show?.({
899
+ variant: 'warning',
900
+ message: 'settings: no window controller bound',
901
+ })
902
+ } catch {
903
+ /* toast unavailable */
904
+ }
905
+ return undefined
906
+ }
907
+ pageApi.close()
640
908
  return undefined
641
909
  },
642
910
  },
@@ -722,11 +990,14 @@ export function setupPantheonSettings(context: Context): void {
722
990
  },
723
991
  })),
724
992
  ]
725
- // The PAGE layer: gated on the route, priority 1 beats any stale
726
- // same-bind layer while the window is open (beta.2 field report).
993
+ // The PAGE layer: scoped to the mode the page pushes while mounted, so the
994
+ // composer's base-mode layers sleep and escape/q reach the close command
995
+ // (field report beta.5: a global layer on a route lost escape/q to the
996
+ // composer — the host's own menus push a mode for exactly this). The
997
+ // route gate stays as a belt-and-suspenders against stale modes.
727
998
  try {
728
999
  context.keymap.layer(() => ({
729
- mode: 'global' as const,
1000
+ mode: ROUTE_MODE,
730
1001
  priority: 1,
731
1002
  enabled: () => routeGated(),
732
1003
  commands,
@@ -755,9 +1026,10 @@ export async function openPantheonSettings(context: Context): Promise<void> {
755
1026
  let returnRoute: WindowRoute | undefined
756
1027
  try {
757
1028
  const current = context.ui.router.current()
758
- // Never return INTO the settings page itself.
1029
+ // Never return INTO the settings page itself; always pass a PLAIN
1030
+ // route (see plainRoute — live objects are cyclic).
759
1031
  if (!(current.type === 'plugin' && current.name === ROUTE_NAME)) {
760
- returnRoute = current as WindowRoute
1032
+ returnRoute = plainRoute(current as WindowRoute)
761
1033
  }
762
1034
  } catch {
763
1035
  returnRoute = undefined