pi-odd-worktree 3.13.0 → 3.15.0

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.
package/lib/odd-view.js CHANGED
@@ -63,6 +63,13 @@ const MIN_WIDTH = 24;
63
63
  const DEFAULT_LIST_WIDTH = layout.paneWidths(layout.innerWidth(80), { listShare: layout.READER_LIST_SHARE }).left;
64
64
  const EMPTY_LIST = 'no odd documents';
65
65
  const EMPTY_HINT = 'create one under odd/tasks/';
66
+ // odd-panel-groups S1: the panel opens with every group folded, so the first frame
67
+ // can stand on a header that holds no document. The pane says what to press instead
68
+ // of claiming a filter matched nothing.
69
+ const FOLDED_HINT = 'enter opens this group';
70
+ // S3: the 2-cell indent a document carries so its text starts at the column its
71
+ // group's name starts at, under the chevron's own column.
72
+ const CHILD_INDENT = ' ';
66
73
  // S2: ONE legend, ONE terminal row — every key rides the same row instead of
67
74
  // a second footer row. `text` is the full token, `short` the compact form used
68
75
  // when the full one does not fit, and `priority` decides what a
@@ -400,8 +407,7 @@ function checkoutGroupName(group) {
400
407
  return group.isMain === true ? 'main' : '';
401
408
  }
402
409
 
403
- function normalizeGroups(raw) {
404
- if (!Array.isArray(raw)) return null;
410
+ function normalizeGroups(raw) { if (!Array.isArray(raw)) return null;
405
411
  const out = [];
406
412
  for (const entry of raw) {
407
413
  if (!entry || typeof entry !== 'object') continue;
@@ -454,9 +460,12 @@ function createOddView(options = {}) {
454
460
  let allMode = false;
455
461
  let requestedAll = false;
456
462
  const notifyToggleAll = typeof options.onToggleAll === 'function' ? options.onToggleAll : null;
457
- // The groups the reader folded away, keyed by checkout, so a fold survives a
458
- // reload of the same listing and a checkout that leaves drops its own key.
459
- const foldedCheckouts = new Set();
463
+ // The groups the reader OPENED, keyed by checkout (odd-panel-groups S1): the set
464
+ // starts empty, so every group is folded and a panel opens as a list of headers —
465
+ // only the group of the document the panel was opened on is expanded (S2). A
466
+ // group that leaves the listing drops its own key, and an expansion survives a
467
+ // reload of the same listing.
468
+ const expandedCheckouts = new Set();
460
469
  let docs = Array.isArray(options.docs) ? options.docs.slice() : [];
461
470
  const entries = new Map();
462
471
  const state = {
@@ -542,11 +551,17 @@ function createOddView(options = {}) {
542
551
 
543
552
  function groupView(group, list) {
544
553
  const key = checkoutGroupKey(group);
554
+ const name = checkoutGroupName(group);
545
555
  return {
546
556
  key,
547
- name: checkoutGroupName(group),
557
+ name,
558
+ // S4: what a header reads. `name` unless two drawn checkouts share it (see
559
+ // `labelHeaders`), which is the only case a folded header could be mistaken
560
+ // for its twin.
561
+ label: name,
562
+ root: typeof group.checkoutRoot === 'string' ? group.checkoutRoot : '',
548
563
  isMain: group.isMain === true,
549
- folded: foldedCheckouts.has(key),
564
+ folded: !expandedCheckouts.has(key),
550
565
  // `list` is what the filter leaves to paint; `total` is what the checkout
551
566
  // owns, so the frame's count never moves with the query.
552
567
  total: group.docs.length,
@@ -554,6 +569,32 @@ function createOddView(options = {}) {
554
569
  };
555
570
  }
556
571
 
572
+ // The last directory before a checkout root: `…/repo-worktrees-a/same checkout`
573
+ // answers `repo-worktrees-a`. Empty when the root has no parent segment.
574
+ function parentSegment(root) {
575
+ const clean = typeof root === 'string' ? root.replace(/\/+$/, '') : '';
576
+ if (clean === '') return '';
577
+ const cut = clean.lastIndexOf('/');
578
+ if (cut <= 0) return '';
579
+ const parent = clean.slice(0, cut);
580
+ return parent.slice(parent.lastIndexOf('/') + 1);
581
+ }
582
+
583
+ // S1/S4: a folded group paints its header ALONE, so two checkouts with the same
584
+ // name would be two identical rows. A name that repeats among the drawn groups
585
+ // is qualified with its parent directory, which is what tells the twins apart;
586
+ // a unique name is left exactly as the checkout named it.
587
+ function labelHeaders(views) {
588
+ const counts = new Map();
589
+ for (const view of views) counts.set(view.name, (counts.get(view.name) || 0) + 1);
590
+ for (const view of views) {
591
+ if ((counts.get(view.name) || 0) < 2) continue;
592
+ const parent = parentSegment(view.root);
593
+ if (parent !== '') view.label = `${parent}/${view.name}`;
594
+ }
595
+ return views;
596
+ }
597
+
557
598
  // S10/S13 (T9): the groups a frame actually draws, or null for the ordinary
558
599
  // flat listing. The main group is ALWAYS drawn so every ODD of main stays
559
600
  // reachable; a worktree group is drawn only while it still has documents after
@@ -569,10 +610,10 @@ function createOddView(options = {}) {
569
610
  .map((group) => ({ group, list: filterAndOrder(group.docs) }))
570
611
  .filter((entry) => entry.list.length > 0);
571
612
  if (worktrees.length === 0) return null;
572
- return [
613
+ return labelHeaders([
573
614
  groupView(main, filterAndOrder(main.docs)),
574
615
  ...worktrees.map((entry) => groupView(entry.group, entry.list)),
575
- ];
616
+ ]);
576
617
  }
577
618
 
578
619
  // S10 (T9): the rows a frame paints. Without groups every row is a document,
@@ -601,7 +642,12 @@ function createOddView(options = {}) {
601
642
  // keeps the plain reader it always had.
602
643
  function rowLabel(row) {
603
644
  if (row.kind === 'header') {
604
- return `${row.group.folded ? GROUP_COLLAPSED_MARK : GROUP_EXPANDED_MARK} ${row.group.name}`;
645
+ const mark = row.group.folded ? GROUP_COLLAPSED_MARK : GROUP_EXPANDED_MARK;
646
+ // S4: the count rides the header, so a folded group still says how much it
647
+ // holds: `main (40 odd)`. It is the group's TOTAL, the same number the title
648
+ // sums, so the two can never disagree (a live query narrows the rows, never
649
+ // the count).
650
+ return `${mark} ${row.group.label} (${row.group.total} odd)`;
605
651
  }
606
652
  const label = row.doc && row.doc.label;
607
653
  if (typeof label === 'string' && label.length > 0) return label;
@@ -646,14 +692,15 @@ function createOddView(options = {}) {
646
692
  }
647
693
 
648
694
  // S6/S10 (T9): the requested document becomes the selection inside whatever
649
- // group holds it — its group is unfolded first, so the row exists to select.
650
- // With no request (or an unknown one) the first DOCUMENT row opens, which is
651
- // the flat list's first row and, in a grouped listing, main's newest ODD
652
- // rather than a header.
695
+ // group holds it, and ITS group is the ONLY one expanded (odd-panel-groups S2):
696
+ // a panel opened from a sidebar ODD shows that ODD, with every other group
697
+ // folded. With no request (or an unknown one) nothing is expanded and the first
698
+ // HEADER opens, which is the folded listing's first row.
653
699
  function mountIndex(request) {
654
700
  const located = locateDocument(request);
655
701
  if (located) {
656
- if (located.group) foldedCheckouts.delete(checkoutGroupKey(located.group));
702
+ expandedCheckouts.clear();
703
+ if (located.group) expandedCheckouts.add(checkoutGroupKey(located.group));
657
704
  const at = rowOfDoc(documentKey(located.doc));
658
705
  if (at >= 0) return at;
659
706
  }
@@ -691,6 +738,12 @@ function createOddView(options = {}) {
691
738
  return activeDocument();
692
739
  }
693
740
 
741
+ // S1: whether the cursor stands on a group header (which holds no document).
742
+ function focusedHeader(rows) {
743
+ const row = rows[state.index] || null;
744
+ return row !== null && row.kind === 'header';
745
+ }
746
+
694
747
  function renderLines(entry, text, width) {
695
748
  entry.lines = renderOddMarkdown(text, {
696
749
  width,
@@ -909,7 +962,7 @@ function createOddView(options = {}) {
909
962
  if (at < 0) {
910
963
  const located = locateDocument(focusedKey);
911
964
  if (located && located.group) {
912
- foldedCheckouts.delete(checkoutGroupKey(located.group));
965
+ expandedCheckouts.add(checkoutGroupKey(located.group));
913
966
  at = rowOfDoc(focusedKey);
914
967
  }
915
968
  }
@@ -938,11 +991,11 @@ function createOddView(options = {}) {
938
991
  repaint();
939
992
  }
940
993
 
941
- // S10 (T9): Enter folds the focused checkout's group — the header stays, the
942
- // documents under it go, and so the focus stays where it was.
994
+ // S10 (T9): Enter opens or closes the focused checkout's group — the header
995
+ // stays, the documents under it come and go, and so the focus stays where it was.
943
996
  function toggleFold(group) {
944
- if (foldedCheckouts.has(group.key)) foldedCheckouts.delete(group.key);
945
- else foldedCheckouts.add(group.key);
997
+ if (expandedCheckouts.has(group.key)) expandedCheckouts.delete(group.key);
998
+ else expandedCheckouts.add(group.key);
946
999
  const at = visibleRows().findIndex((row) => row.kind === 'header' && row.group.key === group.key);
947
1000
  if (at >= 0) state.index = at;
948
1001
  const win = layout.scrollWindow(listCosts(), {
@@ -1049,7 +1102,14 @@ function createOddView(options = {}) {
1049
1102
  }
1050
1103
  continue;
1051
1104
  }
1052
- const wrapped = labelRows(rowLabel(row), listWidth, focused ? '▸ ' : ' ', ' ');
1105
+ // S3: a document reads at the column its group NAME starts at, so the
1106
+ // disclosure chevron keeps a column of its own and the two rows line up
1107
+ // (`▾ main` over ` alpha`). The continuation prefix carries the same
1108
+ // indent, so a wrapped name stays under its own text. Only a GROUPED row
1109
+ // is indented: the flat listing has no header to line up with, and its
1110
+ // frames stay byte-identical.
1111
+ const indent = row.group ? CHILD_INDENT : '';
1112
+ const wrapped = labelRows(rowLabel(row), listWidth, `${focused ? '▸ ' : ' '}${indent}`, ` ${indent}`);
1053
1113
  for (const line of wrapped) {
1054
1114
  listLines.push(highlight(theme, pad(helpers, line, listWidth), focused));
1055
1115
  }
@@ -1060,6 +1120,10 @@ function createOddView(options = {}) {
1060
1120
  if (documentCount() === 0) {
1061
1121
  contentLines.push(paint(theme, 'muted', EMPTY_LIST));
1062
1122
  contentLines.push(paint(theme, 'dim', EMPTY_HINT));
1123
+ } else if (focusedHeader(rows) && state.query.trim() === '') {
1124
+ // S1: the panel opens on a HEADER now, which holds no document. The pane
1125
+ // says how to open one instead of claiming a filter matched nothing.
1126
+ contentLines.push(paint(theme, 'muted', FOLDED_HINT));
1063
1127
  } else {
1064
1128
  contentLines.push(paint(theme, 'muted', `(no matches for filter "${state.query}")`));
1065
1129
  }
@@ -0,0 +1,256 @@
1
+ 'use strict';
2
+ // OpenCode Go subscription usage, read from the read-only endpoint the OpenCode console itself
3
+ // uses: `GET /zen/go/v1/usage`, authenticated with the same API key pi already holds for the
4
+ // `opencode-go` provider.
5
+ //
6
+ // The endpoint answers three windows and reports each as a used percentage plus a reset
7
+ // instant. It does not publish how long a window is, so the spans below are display durations:
8
+ // they drive the label, the meter width and the ordering the shell draws, never the percentage
9
+ // or the reset time.
10
+ //
11
+ // The source this file hands the shell is one payload with four keys — `schema`, `provider`,
12
+ // `pendingNote`, `fetch` — and its `fetch` is the only place the peak schedule becomes the
13
+ // panel's `plan` field, so a refresh from the panel and the widget cannot disagree about which
14
+ // window is running.
15
+
16
+ const { providerById } = require('./peak-providers.js');
17
+ const { peakStateFor } = require('./peak-schedule.js');
18
+ const { panelSchedule } = require('./peak-labels.js');
19
+
20
+ const PROVIDER = 'opencode-go';
21
+
22
+ /** The one URL this package can reach. There is no configuration for it. */
23
+ const USAGE_URL = 'https://opencode.ai/zen/go/v1/usage';
24
+
25
+ /** Matches the shell's own default provider window. */
26
+ const REQUEST_TIMEOUT_MS = 10_000;
27
+
28
+ /** Opt-in diagnostics: fixed reason codes only, never a key or an error text. */
29
+ const DEBUG_ENV = 'PI_OPENCODE_GO_USAGE_DEBUG';
30
+
31
+ /** The schema string the usage-source contract carries. */
32
+ const USAGE_SOURCE_SCHEMA = 'gentle-pi.usage-source/v1';
33
+
34
+ /** What the panel says while nothing has answered yet, so the row is never blank. */
35
+ const PENDING_NOTE = 'opencode-go · press r to fetch';
36
+
37
+ // The row name: the panel prints `<limit name> <window label>` per line, lowercased to match
38
+ // the panel's own lowercase voice.
39
+ const LIMIT_NAME = 'go';
40
+
41
+ const HOUR = 3600;
42
+ const DAY = 24 * HOUR;
43
+
44
+ // The endpoint's three windows. The month is approximated at 30 days because no length is
45
+ // published for it; a calendar month is not always 30 days.
46
+ const WINDOWS = [
47
+ { key: 'rolling', label: '5h', seconds: 5 * HOUR },
48
+ { key: 'weekly', label: 'week', seconds: 7 * DAY },
49
+ { key: 'monthly', label: 'month', seconds: 30 * DAY },
50
+ ];
51
+
52
+ // The two statuses the endpoint is known to answer with. Anything else is treated as a
53
+ // malformed payload rather than guessed at, because the shell keeps its last good snapshot and
54
+ // a wrong number is worse than none.
55
+ const KNOWN_STATUSES = new Set(['ok', 'rate-limited']);
56
+
57
+ /** A full ISO 8601 instant, with an explicit offset or `Z`. */
58
+ const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
59
+
60
+ // The three readiness verdicts a source reports. Only `missing-key` says the provider is
61
+ // unusable; `unknown` covers every failure that says nothing about the key.
62
+ const READY = 'ready';
63
+ const MISSING_KEY = 'missing-key';
64
+ const UNKNOWN = 'unknown';
65
+
66
+ function isRecord(value) {
67
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
68
+ }
69
+
70
+ /**
71
+ * One window, or `undefined` when anything about it is untrustworthy. Fields are read and
72
+ * rebuilt one by one, never merged, so a hostile payload cannot reach this object.
73
+ */
74
+ function parseWindow(value, label, windowSeconds) {
75
+ if (!isRecord(value)) return undefined;
76
+ if (typeof value.status !== 'string' || !KNOWN_STATUSES.has(value.status)) return undefined;
77
+ const percent = value.percent;
78
+ if (typeof percent !== 'number' || !Number.isFinite(percent) || percent < 0 || percent > 100) return undefined;
79
+ if (typeof value.resetsAt !== 'string' || !ISO_INSTANT.test(value.resetsAt)) return undefined;
80
+ const resetAt = Date.parse(value.resetsAt);
81
+ if (!Number.isFinite(resetAt)) return undefined;
82
+ return { label, usedPercent: percent, windowSeconds, resetAt };
83
+ }
84
+
85
+ function readUsage(payload) {
86
+ if (!isRecord(payload) || !isRecord(payload.usage)) return undefined;
87
+ return payload.usage;
88
+ }
89
+
90
+ /**
91
+ * Converts one `/zen/go/v1/usage` payload into the windows the shell draws, or `undefined`
92
+ * when the payload is not exactly the expected shape.
93
+ *
94
+ * All or nothing on purpose: a snapshot missing one window would make a depleted subscription
95
+ * look less used than it is, and the shell already keeps the last valid snapshot through a
96
+ * failed read.
97
+ */
98
+ function parseOpenCodeGoUsage(payload, now) {
99
+ if (!Number.isFinite(now)) return undefined;
100
+ const usage = readUsage(payload);
101
+ if (!usage) return undefined;
102
+ const windows = [];
103
+ for (const { key, label, seconds } of WINDOWS) {
104
+ const window = parseWindow(usage[key], label, seconds);
105
+ if (!window) return undefined;
106
+ windows.push(window);
107
+ }
108
+ const limitReached =
109
+ windows.some((window) => window.usedPercent >= 100) ||
110
+ WINDOWS.some(({ key }) => usage[key].status === 'rate-limited');
111
+ return {
112
+ provider: PROVIDER,
113
+ plan: undefined,
114
+ limits: [{ name: LIMIT_NAME, windows, limitReached, scope: 'provider' }],
115
+ fetchedAt: now,
116
+ };
117
+ }
118
+
119
+ function defaultReport(reason) {
120
+ if (process.env[DEBUG_ENV]) console.error(`[pi-odd-worktree] ${reason}`);
121
+ }
122
+
123
+ async function requestUsage(apiKey, fetchFn, now, timeoutMs) {
124
+ if (typeof apiKey !== 'string' || apiKey.length === 0) return { reason: MISSING_KEY };
125
+ // A referenced timer, never `AbortSignal.timeout`: that helper's timer does not hold the event
126
+ // loop, so a host whose request is the only pending work finds the process drained mid-flight on
127
+ // Node 18-22 and the abort never fires. This timer holds the attempt open until it is cleared.
128
+ const controller = new AbortController();
129
+ const timedOut = () => controller.signal.aborted;
130
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
131
+ try {
132
+ let response;
133
+ try {
134
+ response = await fetchFn(USAGE_URL, {
135
+ method: 'GET',
136
+ headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' },
137
+ cache: 'no-store',
138
+ // A redirect could replay the bearer to another origin.
139
+ redirect: 'error',
140
+ signal: controller.signal,
141
+ });
142
+ } catch {
143
+ return { reason: timedOut() ? 'timeout' : 'network' };
144
+ }
145
+ // Defense in depth: a fetch implementation that follows redirects anyway must not deliver a
146
+ // body read from anywhere but this route.
147
+ if (response.redirected || (response.url && response.url !== USAGE_URL)) return { reason: 'redirect' };
148
+ if (!response.ok) return { reason: `http-${response.status}` };
149
+ let payload;
150
+ try {
151
+ payload = await response.json();
152
+ } catch {
153
+ return { reason: timedOut() ? 'timeout' : 'invalid-json' };
154
+ }
155
+ if (!isRecord(payload) || !isRecord(payload.usage)) return { reason: 'unexpected-shape' };
156
+ const usage = parseOpenCodeGoUsage(payload, now);
157
+ if (usage) return { usage };
158
+ const missing = WINDOWS.find(({ key }) => !isRecord(payload.usage[key]));
159
+ return { reason: missing ? `unexpected-shape:${missing.key}` : 'unexpected-shape' };
160
+ } finally {
161
+ // The attempt settled: nothing may keep the loop (or the controller) alive past it.
162
+ clearTimeout(timer);
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Fetches one usage snapshot, or `undefined` when there is nothing trustworthy to show. The key
168
+ * is used in the `Authorization` header and returned nowhere else; failures resolve to
169
+ * `undefined` and report only a fixed reason code.
170
+ *
171
+ * `plan` is left `undefined` here: the schedule is the source's own addition, applied by
172
+ * `createUsageSource`, so this function stays a plain reader of the route.
173
+ */
174
+ async function fetchOpenCodeGoUsage(apiKey, fetchFn, now, options = {}) {
175
+ const { timeoutMs = REQUEST_TIMEOUT_MS, report = defaultReport } = options;
176
+ const { usage, reason } = await requestUsage(apiKey, fetchFn, now, timeoutMs);
177
+ if (reason) {
178
+ try {
179
+ report(reason);
180
+ } catch {
181
+ // Diagnostics never break a refresh.
182
+ }
183
+ }
184
+ return usage;
185
+ }
186
+
187
+ /**
188
+ * The readiness verdict one failure reason proves. Only `missing-key` says the provider is
189
+ * unusable: a timeout, a network error, a redirect, an HTTP status or a malformed response all
190
+ * report `unknown`, because none of them says anything about whether the key is present and a
191
+ * wrong `missing-key` would clear the peak line for a provider that is logged in.
192
+ */
193
+ function readinessOf(reason) {
194
+ return reason === MISSING_KEY ? MISSING_KEY : UNKNOWN;
195
+ }
196
+
197
+ /**
198
+ * The source's `plan` field: the schedule of the fetch's own instant, peak or off-peak. This
199
+ * provider serves the peak-priced DeepSeek family, so the field describes the registry's
200
+ * `deepseek` window — the same schedule, now read from the provider-agnostic engine.
201
+ */
202
+ function withPlan(usage, now) {
203
+ return { ...usage, plan: panelSchedule(peakStateFor(providerById('deepseek'), now), now) };
204
+ }
205
+
206
+ /**
207
+ * The payload the extension emits for the usage-source contract:
208
+ * `{ schema, provider, pendingNote, fetch }`.
209
+ *
210
+ * `fetch(apiKey, fetchFn, now)` fetches one snapshot, adds the peak schedule as its `plan`, and
211
+ * reports readiness exactly once per fetch: `ready` when a snapshot came back, `missing-key`
212
+ * when there was no key to send, `unknown` when the attempt failed for any other reason.
213
+ * `options` is forwarded to `fetchOpenCodeGoUsage` so a caller can shorten the request window.
214
+ *
215
+ * A throwing `onReadiness` never fails a refresh, exactly like a dead row never fails a menu.
216
+ */
217
+ function createUsageSource({ onReadiness } = {}) {
218
+ const report = (verdict) => {
219
+ try {
220
+ if (typeof onReadiness === 'function') onReadiness(verdict);
221
+ } catch {
222
+ // A dead UI never fails a refresh.
223
+ }
224
+ };
225
+ return {
226
+ schema: USAGE_SOURCE_SCHEMA,
227
+ provider: PROVIDER,
228
+ pendingNote: PENDING_NOTE,
229
+ async fetch(apiKey, fetchFn, now, options = {}) {
230
+ let verdict = UNKNOWN;
231
+ const usage = await fetchOpenCodeGoUsage(apiKey, fetchFn, now, {
232
+ ...options,
233
+ report: (reason) => {
234
+ verdict = readinessOf(reason);
235
+ // Whatever the caller asked to be told stays told, and never decides readiness.
236
+ if (typeof options.report === 'function') options.report(reason);
237
+ },
238
+ });
239
+ if (usage !== undefined) verdict = READY;
240
+ report(verdict);
241
+ return usage === undefined ? undefined : withPlan(usage, now);
242
+ },
243
+ };
244
+ }
245
+
246
+ module.exports = {
247
+ PROVIDER,
248
+ USAGE_URL,
249
+ REQUEST_TIMEOUT_MS,
250
+ DEBUG_ENV,
251
+ USAGE_SOURCE_SCHEMA,
252
+ PENDING_NOTE,
253
+ parseOpenCodeGoUsage,
254
+ fetchOpenCodeGoUsage,
255
+ createUsageSource,
256
+ };
@@ -0,0 +1,64 @@
1
+ 'use strict';
2
+ // The strings this package paints for a peak schedule.
3
+ //
4
+ // Two surfaces, two different freedoms:
5
+ //
6
+ // - The usage panel prints `ProviderUsage.plan` inside its own muted role and never sanitizes it,
7
+ // so the header is plain text: the schedule rides there unconditionally, and red stays reserved
8
+ // for near-limit quota inside the panel. The panel already prints ` · ` before that field, so
9
+ // the field itself carries no leading separator.
10
+ // - The widget line is this package's own row above the editor, so it paints itself: `peak` is
11
+ // amber while the provider is peak-priced and closes that escape right away, so the details
12
+ // after it stay in the terminal's normal foreground instead of inheriting a dimmed amber. The
13
+ // line names the provider from its own registry `label`, so several providers peaking at once
14
+ // are several rows, each telling the human which window it is. Off-peak has no widget line at
15
+ // all.
16
+ //
17
+ // The panel's window labels stay untouched: the rows read `go 5h`, `go week`, `go month`, with
18
+ // the schedule only on the provider line.
19
+ //
20
+ // Nothing here reads a clock; every function takes the instant it must describe.
21
+
22
+ const { formatBoundaryClock, formatPeakState } = require('./peak-schedule.js');
23
+
24
+ /** The key this package owns in pi's widget map. */
25
+ const PEAK_WIDGET_KEY = 'opencode-go-peak-widget';
26
+
27
+ const AMBER = '\x1b[33m';
28
+ const RESET = '\x1b[0m';
29
+
30
+ /**
31
+ * The schedule the panel prints on its provider line, between the provider name and the
32
+ * `updated …` note: `off-peak 3hr 20m`.
33
+ *
34
+ * The panel inserts its own ` · ` before this field, so the field never starts with one: a leading
35
+ * separator here would render as a doubled ` · · `.
36
+ */
37
+ function panelSchedule(state, now) {
38
+ return formatPeakState(state, now);
39
+ }
40
+
41
+ /**
42
+ * One widget line, drawn only while the provider is peak-priced:
43
+ * `peak · 2× deepseek · until 04:00`. There is no off-peak variant; the caller clears the widget
44
+ * instead. The boundary is rendered in the machine's own timezone: `timeZone` is not passed here,
45
+ * only by unit tests that call `formatBoundaryClock` directly.
46
+ *
47
+ * Only the state word carries a color: `peak` is amber and closes it with `\x1b[0m` immediately,
48
+ * so the rest of the line renders in the terminal's own foreground. A dim attribute there would
49
+ * reuse the amber already in effect and paint the details in dull brown-gray, which is neither the
50
+ * amber highlight nor ordinary body text.
51
+ *
52
+ * Everything after the state word comes from the provider's own registry entry, so a provider
53
+ * that publishes a multiplier shows it and one that does not shows nothing invented.
54
+ */
55
+ function peakWidgetLine(provider, state, now) {
56
+ const clock = formatBoundaryClock(state.until, now);
57
+ return `${AMBER}peak${RESET} · ${provider.label} · until ${clock}`;
58
+ }
59
+
60
+ module.exports = {
61
+ PEAK_WIDGET_KEY,
62
+ panelSchedule,
63
+ peakWidgetLine,
64
+ };
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+ // The peak schedules this package knows about, in the order the `Alert` section draws them.
3
+ //
4
+ // Every provider here is a schedule, not a model: the `Alert` row is gated by its own switch and
5
+ // its own window and by nothing else (never by the session's model, never by a usage key), and
6
+ // one row per peaking provider is drawn from this array in declaration order. Adding a provider
7
+ // is adding an entry — the engine, the labels and the wiring all read `zone`, `windows`,
8
+ // `weekdaysOnly`, `setting` and `label` from the entry itself.
9
+ //
10
+ // The windows are half-open `[startHour, endHour)` pairs of LOCAL wall hours in `zone`:
11
+ //
12
+ // deepseek 01:00-04:00 and 06:00-10:00 UTC, Monday through Friday (published in UTC)
13
+ // claude 05:00-11:00 in America/Los_Angeles, Monday through Friday (published in Pacific)
14
+ //
15
+ // DeepSeek's published price multiplier is `2×`, so its `label` says so. Anthropic publishes no
16
+ // multiplier for Claude's window, so Claude's `label` is just the provider name: a made-up `2×`
17
+ // or `1.4×` there would be a number this package has no source for.
18
+
19
+ /** OpenCode Go's DeepSeek windows, in UTC. Both models share the family's published peak. */
20
+ const DEEPSEEK = Object.freeze({
21
+ id: 'deepseek',
22
+ setting: 'Deepseek peak',
23
+ label: '2× deepseek',
24
+ zone: 'UTC',
25
+ windows: Object.freeze([Object.freeze([1, 4]), Object.freeze([6, 10])]),
26
+ weekdaysOnly: true,
27
+ });
28
+
29
+ /**
30
+ * Anthropic's Claude window, in Pacific time: weekdays 05:00-11:00 PT. It is a zone, not a UTC
31
+ * pair, because the published hours move with PDT/PST — 12:00-18:00 UTC in summer, 13:00-19:00
32
+ * UTC in winter. The row prints no multiplier: Anthropic publishes none for the window.
33
+ */
34
+ const CLAUDE = Object.freeze({
35
+ id: 'claude',
36
+ setting: 'Claude peak',
37
+ label: 'claude',
38
+ zone: 'America/Los_Angeles',
39
+ windows: Object.freeze([Object.freeze([5, 11])]),
40
+ weekdaysOnly: true,
41
+ });
42
+
43
+ /** Every schedule, in the order the `Alert` section draws its rows. Frozen: this is the registry. */
44
+ const PROVIDERS = Object.freeze([DEEPSEEK, CLAUDE]);
45
+
46
+ const BY_ID = new Map(PROVIDERS.map((provider) => [provider.id, provider]));
47
+
48
+ /** The provider with this id, or `undefined`: this is how the wiring resolves a stored setting. */
49
+ function providerById(id) {
50
+ if (typeof id !== 'string') return undefined;
51
+ return BY_ID.get(id);
52
+ }
53
+
54
+ /** The ids, in declaration order. A fresh array, so a caller cannot edit the registry through it. */
55
+ function providerIds() {
56
+ return PROVIDERS.map((provider) => provider.id);
57
+ }
58
+
59
+ module.exports = {
60
+ PROVIDERS,
61
+ providerById,
62
+ providerIds,
63
+ };