opencode-peak-badge 0.4.0 → 0.6.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/dist/tui.js CHANGED
@@ -9,7 +9,7 @@ import { watch } from "fs";
9
9
  import { readFile } from "fs/promises";
10
10
  import { homedir } from "os";
11
11
  import { join } from "path";
12
- import { createMemo, createSignal } from "solid-js";
12
+ import { createEffect, createMemo, createRoot, createSignal, onCleanup } from "solid-js";
13
13
 
14
14
  // src/core.ts
15
15
  var DEFAULT_WINDOWS = [
@@ -21,6 +21,14 @@ var DEFAULT_MODELS = [
21
21
  "re:^opencode/deepseek",
22
22
  "re:^deepseek/deepseek"
23
23
  ];
24
+ function currentNow(fakeTime, realNow = new Date) {
25
+ if (fakeTime) {
26
+ const parsed = new Date(fakeTime);
27
+ if (!Number.isNaN(parsed.getTime()))
28
+ return parsed;
29
+ }
30
+ return realNow;
31
+ }
24
32
  function parseHHMM(value) {
25
33
  const match = /^(\d{1,2}):(\d{2})$/.exec(value.trim());
26
34
  if (!match)
@@ -72,9 +80,9 @@ function buildRule(id, spec, defaultWindows, defaultWeekdays) {
72
80
  };
73
81
  }
74
82
  function resolveRules(options = {}) {
75
- const defaultWindows = parseWindows(options.windows?.length ? options.windows : DEFAULT_WINDOWS);
83
+ const defaultWindows = parseWindows(options.windows ?? DEFAULT_WINDOWS);
76
84
  const defaultWeekdays = options.weekdaysOnly ?? true;
77
- const entries = options.models?.length ? options.models : DEFAULT_MODELS;
85
+ const entries = options.models ?? DEFAULT_MODELS;
78
86
  const exact = new Map;
79
87
  const patterns = [];
80
88
  for (const entry of entries) {
@@ -120,6 +128,10 @@ function resolveRules(options = {}) {
120
128
  fallback: { id: "", windows: defaultWindows, weekdaysOnly: defaultWeekdays }
121
129
  };
122
130
  }
131
+ function isValidModelEntry(entry) {
132
+ const rules = resolveRules({ models: [entry] });
133
+ return rules.exact.size > 0 || rules.patterns.length > 0;
134
+ }
123
135
  function isSafeRegex(source) {
124
136
  let depth = 0;
125
137
  let inClass = false;
@@ -187,17 +199,697 @@ function mergeBadges(states) {
187
199
  }
188
200
  return result;
189
201
  }
202
+ function badgeForModels(input) {
203
+ const states = [];
204
+ if (input.main) {
205
+ const rule = matchRule(input.rules, modelKey(input.main.providerID, input.main.id)) ?? (input.alwaysShow ? input.rules.fallback : undefined);
206
+ const state = badgeFor(input.now, rule, input.labels);
207
+ if (state)
208
+ states.push(state);
209
+ }
210
+ for (const child of input.subagents) {
211
+ const state = badgeFor(input.now, matchRule(input.rules, modelKey(child.providerID, child.id)), input.labels);
212
+ if (state)
213
+ states.push(state);
214
+ }
215
+ return mergeBadges(states);
216
+ }
217
+ function runningSubagentRefs(input) {
218
+ const refs = [];
219
+ const seen = new Set;
220
+ const stack = [...input.family(input.sessionID)];
221
+ while (stack.length > 0) {
222
+ const id = stack.pop();
223
+ if (!id || seen.has(id))
224
+ continue;
225
+ seen.add(id);
226
+ if (input.status(id) === "running") {
227
+ const model = input.model(id);
228
+ if (model)
229
+ refs.push(model);
230
+ }
231
+ for (const nested of input.family(id)) {
232
+ if (!seen.has(nested))
233
+ stack.push(nested);
234
+ }
235
+ }
236
+ return refs;
237
+ }
190
238
 
191
- // src/index.tsx
192
- function currentNow() {
193
- const fake = process.env.OPENCODE_PEAK_HOURS_FAKE_TIME;
194
- if (fake) {
195
- const parsed = new Date(fake);
196
- if (!Number.isNaN(parsed.getTime()))
197
- return parsed;
239
+ // src/rpc.ts
240
+ import { Rpc } from "@opencode/plugin/rpc";
241
+ var Settings = {
242
+ type: "object",
243
+ properties: {
244
+ models: { type: "array", items: { type: "string" } },
245
+ windows: {
246
+ type: "array",
247
+ items: {
248
+ type: "array",
249
+ items: { type: "string" },
250
+ minItems: 2,
251
+ maxItems: 2
252
+ }
253
+ },
254
+ weekdaysOnly: { type: "boolean" },
255
+ pollSeconds: { type: "string" },
256
+ labelPeak: { type: "string" },
257
+ labelOffPeak: { type: "string" },
258
+ subagents: { type: "boolean" },
259
+ alwaysShow: { type: "boolean" },
260
+ debug: { type: "boolean" },
261
+ fakeTime: { type: "string" }
262
+ },
263
+ additionalProperties: false
264
+ };
265
+ var Envelope = {
266
+ type: "object",
267
+ properties: { settings: Settings },
268
+ required: ["settings"],
269
+ additionalProperties: false
270
+ };
271
+ var Empty = { type: "object", additionalProperties: false };
272
+ var PeakBadgeSettingsRpc = Rpc.define({
273
+ id: "peak-badge.settings",
274
+ methods: {
275
+ get: { input: Empty, output: Envelope },
276
+ set: { input: Envelope, output: Envelope },
277
+ reset: { input: Empty, output: Envelope }
278
+ },
279
+ events: {
280
+ updated: { schema: Envelope }
281
+ }
282
+ });
283
+
284
+ // src/settings.ts
285
+ var DEFAULT_POLL_SECONDS = 10;
286
+ var DEFAULT_SETTINGS = {
287
+ models: modelLines(DEFAULT_MODELS),
288
+ windows: DEFAULT_WINDOWS.map(([start, end]) => [start, end]),
289
+ weekdaysOnly: true,
290
+ pollSeconds: String(DEFAULT_POLL_SECONDS),
291
+ labelPeak: "[PEAK]",
292
+ labelOffPeak: "[OFF-PEAK]",
293
+ subagents: true,
294
+ alwaysShow: false,
295
+ debug: false,
296
+ fakeTime: ""
297
+ };
298
+ function defaultSettings() {
299
+ return {
300
+ ...DEFAULT_SETTINGS,
301
+ models: [...DEFAULT_SETTINGS.models],
302
+ windows: DEFAULT_SETTINGS.windows.map(([start, end]) => [start, end])
303
+ };
304
+ }
305
+ function isRecord(value) {
306
+ return typeof value === "object" && value !== null && !Array.isArray(value);
307
+ }
308
+ function isWindowSpec(value) {
309
+ return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "string";
310
+ }
311
+ function isWindowList(value) {
312
+ return Array.isArray(value) && value.every(isWindowSpec);
313
+ }
314
+ function sanitizeSettings(value) {
315
+ const next = defaultSettings();
316
+ if (!isRecord(value))
317
+ return next;
318
+ if (Array.isArray(value.models) && value.models.every((entry) => typeof entry === "string")) {
319
+ next.models = [...value.models];
320
+ }
321
+ if (isWindowList(value.windows)) {
322
+ next.windows = value.windows.map(([start, end]) => [start, end]);
323
+ }
324
+ if (typeof value.weekdaysOnly === "boolean")
325
+ next.weekdaysOnly = value.weekdaysOnly;
326
+ if (typeof value.pollSeconds === "string")
327
+ next.pollSeconds = value.pollSeconds;
328
+ if (typeof value.labelPeak === "string")
329
+ next.labelPeak = value.labelPeak;
330
+ if (typeof value.labelOffPeak === "string")
331
+ next.labelOffPeak = value.labelOffPeak;
332
+ if (typeof value.subagents === "boolean")
333
+ next.subagents = value.subagents;
334
+ if (typeof value.alwaysShow === "boolean")
335
+ next.alwaysShow = value.alwaysShow;
336
+ if (typeof value.debug === "boolean")
337
+ next.debug = value.debug;
338
+ if (typeof value.fakeTime === "string")
339
+ next.fakeTime = value.fakeTime;
340
+ return next;
341
+ }
342
+ function settingsFromEnvelope(value) {
343
+ return sanitizeSettings(isRecord(value) ? value.settings : undefined);
344
+ }
345
+ function resolveSettings(settings) {
346
+ const poll = Number(settings.pollSeconds);
347
+ return {
348
+ rules: resolveRules({
349
+ models: parseModelLines(settings.models),
350
+ windows: settings.windows,
351
+ weekdaysOnly: settings.weekdaysOnly
352
+ }),
353
+ labels: { peak: settings.labelPeak, offPeak: settings.labelOffPeak },
354
+ pollSeconds: Number.isFinite(poll) && poll >= 1 ? poll : DEFAULT_POLL_SECONDS,
355
+ subagents: settings.subagents,
356
+ alwaysShow: settings.alwaysShow,
357
+ debug: settings.debug,
358
+ fakeTime: settings.fakeTime.trim() || undefined
359
+ };
360
+ }
361
+ function modelLines(entries) {
362
+ return entries.map((entry) => typeof entry === "string" ? entry : JSON.stringify(entry));
363
+ }
364
+ function parseModelLine(line) {
365
+ const text = line.trim();
366
+ if (!text)
367
+ return;
368
+ if (!text.startsWith("{") && !text.startsWith("["))
369
+ return text;
370
+ let value;
371
+ try {
372
+ value = JSON.parse(text);
373
+ } catch {
374
+ return;
375
+ }
376
+ if (!isRecord(value))
377
+ return;
378
+ const pattern = typeof value.pattern === "string" && value.pattern.trim() ? value.pattern.trim() : undefined;
379
+ const id = typeof value.id === "string" && value.id.trim() ? value.id.trim() : undefined;
380
+ if (!pattern && !id)
381
+ return;
382
+ let windows;
383
+ if (value.windows !== undefined) {
384
+ if (!isWindowList(value.windows))
385
+ return;
386
+ windows = value.windows.map(([start, end]) => [start, end]);
387
+ }
388
+ if (value.weekdaysOnly !== undefined && typeof value.weekdaysOnly !== "boolean")
389
+ return;
390
+ const weekdaysOnly = typeof value.weekdaysOnly === "boolean" ? value.weekdaysOnly : undefined;
391
+ const entry = pattern ? {
392
+ pattern,
393
+ ...windows !== undefined ? { windows } : {},
394
+ ...weekdaysOnly !== undefined ? { weekdaysOnly } : {}
395
+ } : {
396
+ id,
397
+ ...windows !== undefined ? { windows } : {},
398
+ ...weekdaysOnly !== undefined ? { weekdaysOnly } : {}
399
+ };
400
+ return entry;
401
+ }
402
+ function parseModelLines(lines) {
403
+ const entries = [];
404
+ for (const line of lines) {
405
+ const entry = parseModelLine(line);
406
+ if (entry !== undefined)
407
+ entries.push(entry);
408
+ }
409
+ return entries;
410
+ }
411
+ function isHHMM(value) {
412
+ return parseHHMM(value) !== undefined;
413
+ }
414
+ function isWindowValid(window) {
415
+ return isHHMM(window[0]) && isHHMM(window[1]);
416
+ }
417
+ function isValidModelLine(line) {
418
+ const entry = parseModelLine(line);
419
+ if (entry === undefined || !isValidModelEntry(entry))
420
+ return false;
421
+ if (typeof entry === "object" && entry.windows && !entry.windows.every(isWindowValid))
422
+ return false;
423
+ return true;
424
+ }
425
+ function isValidPollSeconds(raw) {
426
+ const value = Number(raw);
427
+ return raw.trim() !== "" && Number.isFinite(value) && value >= 1;
428
+ }
429
+ function isValidFakeTime(raw) {
430
+ if (!raw.trim())
431
+ return true;
432
+ return !Number.isNaN(new Date(raw).getTime());
433
+ }
434
+ function formatWindows(windows) {
435
+ if (windows.length === 0)
436
+ return "none";
437
+ return windows.map(([start, end]) => `${start} - ${end}`).join(", ");
438
+ }
439
+ function formatModels(models) {
440
+ if (models.length === 0)
441
+ return "none";
442
+ const shown = models.slice(0, 2).join(", ");
443
+ return models.length > 2 ? `${shown}, ...` : shown;
444
+ }
445
+ function onOff(value) {
446
+ return value ? "on" : "off";
447
+ }
448
+
449
+ // src/settings-client.ts
450
+ function settingsError(cause) {
451
+ return cause instanceof Error ? cause.message : String(cause);
452
+ }
453
+ function createSettingsSync(options) {
454
+ let stopEvents;
455
+ let stopped = false;
456
+ function rpc() {
457
+ const client = options.client();
458
+ if (typeof client.rpc !== "function")
459
+ return;
460
+ return client.rpc(PeakBadgeSettingsRpc);
461
+ }
462
+ async function refresh(force = false) {
463
+ const client = rpc();
464
+ if (!client)
465
+ return;
466
+ try {
467
+ const next = settingsFromEnvelope(await client.get({}));
468
+ if (stopped)
469
+ return;
470
+ if (!force && options.canApply && !options.canApply(next))
471
+ return;
472
+ options.set(next);
473
+ } catch (cause) {
474
+ if (!stopped)
475
+ options.onLoadError?.(settingsError(cause));
476
+ }
477
+ }
478
+ function connect() {
479
+ stopped = false;
480
+ stopEvents?.();
481
+ stopEvents = undefined;
482
+ const client = rpc();
483
+ if (client) {
484
+ try {
485
+ stopEvents = client.events.on("updated", (event) => {
486
+ if (stopped)
487
+ return;
488
+ const next = settingsFromEnvelope(event.data);
489
+ if (options.acceptEvent) {
490
+ if (!options.acceptEvent(next))
491
+ return;
492
+ } else if (options.canApply && !options.canApply(next)) {
493
+ return;
494
+ }
495
+ if (!stopped)
496
+ options.set(next);
497
+ });
498
+ } catch (cause) {
499
+ options.onLoadError?.(settingsError(cause));
500
+ }
501
+ }
502
+ refresh();
503
+ }
504
+ async function save(next) {
505
+ const value = sanitizeSettings(next);
506
+ options.set(value);
507
+ const client = rpc();
508
+ if (!client)
509
+ return;
510
+ try {
511
+ const saved = settingsFromEnvelope(await client.set({ settings: value }));
512
+ if (!stopped)
513
+ options.set(saved);
514
+ } catch (cause) {
515
+ if (stopped)
516
+ return;
517
+ options.onSaveError?.(settingsError(cause));
518
+ await refresh(true);
519
+ }
520
+ }
521
+ async function reset() {
522
+ const client = rpc();
523
+ if (!client) {
524
+ options.set(sanitizeSettings(undefined));
525
+ return;
526
+ }
527
+ try {
528
+ const saved = settingsFromEnvelope(await client.reset({}));
529
+ if (!stopped)
530
+ options.set(saved);
531
+ } catch (cause) {
532
+ if (stopped)
533
+ return;
534
+ options.onSaveError?.(settingsError(cause));
535
+ await refresh(true);
536
+ }
537
+ }
538
+ return {
539
+ connect,
540
+ refresh,
541
+ save,
542
+ reset,
543
+ stop: () => {
544
+ stopped = true;
545
+ stopEvents?.();
546
+ stopEvents = undefined;
547
+ }
548
+ };
549
+ }
550
+
551
+ // src/tui-settings.ts
552
+ var MODEL_HELP = "Exact provider/model, re:<pattern>, or a JSON object with id or pattern and optional windows/weekdaysOnly.";
553
+ async function openPeakBadgeSettings(ctx, state) {
554
+ for (;; ) {
555
+ const current = state.settings();
556
+ const choice = await ctx.ui.dialog.select({
557
+ title: "Peak Badge settings",
558
+ placeholder: "Filter settings",
559
+ options: [
560
+ {
561
+ title: "Peak windows",
562
+ value: "windows",
563
+ description: formatWindows(current.windows),
564
+ category: "Peak hours"
565
+ },
566
+ {
567
+ title: "Weekdays only",
568
+ value: "weekdaysOnly",
569
+ description: onOff(current.weekdaysOnly),
570
+ category: "Peak hours"
571
+ },
572
+ {
573
+ title: "Models",
574
+ value: "models",
575
+ description: formatModels(current.models),
576
+ category: "Models"
577
+ },
578
+ {
579
+ title: "Include subagents",
580
+ value: "subagents",
581
+ description: onOff(current.subagents),
582
+ category: "Models"
583
+ },
584
+ {
585
+ title: "Show unmatched models",
586
+ value: "alwaysShow",
587
+ description: onOff(current.alwaysShow),
588
+ category: "Models"
589
+ },
590
+ {
591
+ title: "Peak label",
592
+ value: "labelPeak",
593
+ description: current.labelPeak,
594
+ category: "Badge"
595
+ },
596
+ {
597
+ title: "Off-peak label",
598
+ value: "labelOffPeak",
599
+ description: current.labelOffPeak,
600
+ category: "Badge"
601
+ },
602
+ {
603
+ title: "Debug",
604
+ value: "debug",
605
+ description: onOff(current.debug),
606
+ category: "Badge"
607
+ },
608
+ {
609
+ title: "Poll seconds",
610
+ value: "pollSeconds",
611
+ description: current.pollSeconds,
612
+ category: "Refresh"
613
+ },
614
+ {
615
+ title: "Fake time",
616
+ value: "fakeTime",
617
+ description: current.fakeTime || "real clock",
618
+ category: "Advanced"
619
+ },
620
+ {
621
+ title: "Reset to defaults",
622
+ value: "reset",
623
+ description: "Restore the built-in settings",
624
+ category: "Reset"
625
+ },
626
+ { title: "Done", value: "done", category: "Actions" }
627
+ ]
628
+ });
629
+ if (choice === undefined || choice === "done")
630
+ return;
631
+ switch (choice) {
632
+ case "windows":
633
+ await editWindows(ctx, state);
634
+ break;
635
+ case "models":
636
+ await editModels(ctx, state);
637
+ break;
638
+ case "weekdaysOnly":
639
+ case "subagents":
640
+ case "alwaysShow":
641
+ case "debug":
642
+ await toggle(ctx, state, choice);
643
+ break;
644
+ case "labelPeak":
645
+ case "labelOffPeak":
646
+ await editText(ctx, state, choice);
647
+ break;
648
+ case "pollSeconds":
649
+ await editText(ctx, state, choice, isValidPollSeconds, "Use a number of seconds greater than or equal to 1.");
650
+ break;
651
+ case "fakeTime":
652
+ await editText(ctx, state, choice, isValidFakeTime, "Use an ISO timestamp, or leave it empty to use the real clock.");
653
+ break;
654
+ case "reset":
655
+ await reset(ctx, state);
656
+ break;
657
+ }
658
+ }
659
+ }
660
+ async function toggle(ctx, state, key) {
661
+ const current = state.settings();
662
+ const next = { ...current };
663
+ next[key] = !current[key];
664
+ await state.save(next);
665
+ }
666
+ async function editText(ctx, state, key, validate, invalid) {
667
+ const current = state.settings();
668
+ const value = await ctx.ui.dialog.prompt({
669
+ title: key === "labelPeak" ? "Peak label" : key === "labelOffPeak" ? "Off-peak label" : key === "pollSeconds" ? "Poll seconds" : "Fake time",
670
+ description: key === "labelPeak" || key === "labelOffPeak" ? "Text shown on the badge." : key === "pollSeconds" ? "Seconds between recomputations." : "Refresh the badge with a fixed time for testing.",
671
+ value: current[key]
672
+ });
673
+ if (value === undefined)
674
+ return;
675
+ if (validate && !validate(value)) {
676
+ await ctx.ui.dialog.alert({
677
+ title: "Invalid value",
678
+ message: invalid ?? "That value is not valid. No change was saved."
679
+ });
680
+ return;
681
+ }
682
+ const next = { ...state.settings() };
683
+ next[key] = value;
684
+ await state.save(next);
685
+ }
686
+ async function editWindows(ctx, state) {
687
+ for (;; ) {
688
+ const current = state.settings();
689
+ const choice = await ctx.ui.dialog.select({
690
+ title: "Peak windows (UTC)",
691
+ placeholder: "Filter windows",
692
+ options: [
693
+ ...current.windows.map((window, index) => ({
694
+ title: `${window[0]} - ${window[1]}`,
695
+ value: index,
696
+ description: isWindowValid(window) ? undefined : "invalid; ignored",
697
+ category: "Current"
698
+ })),
699
+ { title: "Add window", value: "add", category: "Actions" },
700
+ ...current.windows.length > 0 ? [{ title: "Remove window", value: "remove", category: "Actions" }] : []
701
+ ]
702
+ });
703
+ if (choice === undefined)
704
+ return;
705
+ if (choice === "add") {
706
+ await addWindow(ctx, state);
707
+ continue;
708
+ }
709
+ if (choice === "remove") {
710
+ await removeWindow(ctx, state);
711
+ continue;
712
+ }
713
+ await editWindow(ctx, state, choice);
198
714
  }
199
- return new Date;
200
715
  }
716
+ async function editWindow(ctx, state, index) {
717
+ const current = state.settings();
718
+ const window = current.windows[index];
719
+ if (!window)
720
+ return;
721
+ const start = await ctx.ui.dialog.prompt({
722
+ title: "Window start",
723
+ description: "UTC time in HH:MM.",
724
+ value: window[0]
725
+ });
726
+ if (start === undefined)
727
+ return;
728
+ const end = await ctx.ui.dialog.prompt({
729
+ title: "Window end",
730
+ description: "UTC time in HH:MM. An end at or before the start wraps midnight.",
731
+ value: window[1]
732
+ });
733
+ if (end === undefined)
734
+ return;
735
+ const next = [start, end];
736
+ if (!isWindowValid(next)) {
737
+ await ctx.ui.dialog.alert({
738
+ title: "Invalid window",
739
+ message: "Use HH:MM for both the start and the end. No change was saved."
740
+ });
741
+ return;
742
+ }
743
+ const settings = state.settings();
744
+ await state.save({
745
+ ...settings,
746
+ windows: settings.windows.map((item, itemIndex) => itemIndex === index ? next : item)
747
+ });
748
+ }
749
+ async function addWindow(ctx, state) {
750
+ const start = await ctx.ui.dialog.prompt({
751
+ title: "Window start",
752
+ description: "UTC time in HH:MM.",
753
+ placeholder: "01:00"
754
+ });
755
+ if (start === undefined)
756
+ return;
757
+ const end = await ctx.ui.dialog.prompt({
758
+ title: "Window end",
759
+ description: "UTC time in HH:MM. An end at or before the start wraps midnight.",
760
+ placeholder: "04:00"
761
+ });
762
+ if (end === undefined)
763
+ return;
764
+ const window = [start, end];
765
+ if (!isWindowValid(window)) {
766
+ await ctx.ui.dialog.alert({
767
+ title: "Invalid window",
768
+ message: "Use HH:MM for both the start and the end. No change was saved."
769
+ });
770
+ return;
771
+ }
772
+ const settings = state.settings();
773
+ await state.save({ ...settings, windows: [...settings.windows, window] });
774
+ }
775
+ async function removeWindow(ctx, state) {
776
+ const current = state.settings();
777
+ const index = await ctx.ui.dialog.select({
778
+ title: "Remove window",
779
+ options: current.windows.map((window, itemIndex) => ({
780
+ title: `${window[0]} - ${window[1]}`,
781
+ value: itemIndex,
782
+ category: "Current"
783
+ }))
784
+ });
785
+ if (index === undefined)
786
+ return;
787
+ await state.save({
788
+ ...current,
789
+ windows: current.windows.filter((_, itemIndex) => itemIndex !== index)
790
+ });
791
+ }
792
+ async function editModels(ctx, state) {
793
+ for (;; ) {
794
+ const current = state.settings();
795
+ const choice = await ctx.ui.dialog.select({
796
+ title: "Models",
797
+ placeholder: "Filter models",
798
+ options: [
799
+ ...current.models.map((model, index) => ({
800
+ title: model || "(empty)",
801
+ value: index,
802
+ description: isValidModelLine(model) ? undefined : "invalid; ignored",
803
+ category: "Current"
804
+ })),
805
+ { title: "Add model", value: "add", category: "Actions" },
806
+ ...current.models.length > 0 ? [{ title: "Remove model", value: "remove", category: "Actions" }] : []
807
+ ]
808
+ });
809
+ if (choice === undefined)
810
+ return;
811
+ if (choice === "add") {
812
+ await addModel(ctx, state);
813
+ continue;
814
+ }
815
+ if (choice === "remove") {
816
+ await removeModel(ctx, state);
817
+ continue;
818
+ }
819
+ await editModel(ctx, state, choice);
820
+ }
821
+ }
822
+ async function editModel(ctx, state, index) {
823
+ const current = state.settings();
824
+ const model = current.models[index];
825
+ if (model === undefined)
826
+ return;
827
+ const value = await ctx.ui.dialog.prompt({
828
+ title: "Model",
829
+ description: MODEL_HELP,
830
+ value: model
831
+ });
832
+ if (value === undefined)
833
+ return;
834
+ if (!isValidModelLine(value)) {
835
+ await ctx.ui.dialog.alert({
836
+ title: "Invalid model",
837
+ message: `${MODEL_HELP} No change was saved.`
838
+ });
839
+ return;
840
+ }
841
+ const settings = state.settings();
842
+ await state.save({
843
+ ...settings,
844
+ models: settings.models.map((item, itemIndex) => itemIndex === index ? value : item)
845
+ });
846
+ }
847
+ async function addModel(ctx, state) {
848
+ const value = await ctx.ui.dialog.prompt({
849
+ title: "Model",
850
+ description: MODEL_HELP,
851
+ placeholder: "provider/model"
852
+ });
853
+ if (value === undefined)
854
+ return;
855
+ if (!isValidModelLine(value)) {
856
+ await ctx.ui.dialog.alert({
857
+ title: "Invalid model",
858
+ message: `${MODEL_HELP} No change was saved.`
859
+ });
860
+ return;
861
+ }
862
+ const settings = state.settings();
863
+ await state.save({ ...settings, models: [...settings.models, value] });
864
+ }
865
+ async function removeModel(ctx, state) {
866
+ const current = state.settings();
867
+ const index = await ctx.ui.dialog.select({
868
+ title: "Remove model",
869
+ options: current.models.map((model, itemIndex) => ({
870
+ title: model || "(empty)",
871
+ value: itemIndex,
872
+ category: "Current"
873
+ }))
874
+ });
875
+ if (index === undefined)
876
+ return;
877
+ await state.save({
878
+ ...current,
879
+ models: current.models.filter((_, itemIndex) => itemIndex !== index)
880
+ });
881
+ }
882
+ async function reset(ctx, state) {
883
+ const confirmed = await ctx.ui.dialog.confirm({
884
+ title: "Reset Peak Badge settings",
885
+ message: "Restore the built-in peak windows, models, labels and flags?",
886
+ label: { confirm: "Reset", cancel: "Cancel" }
887
+ });
888
+ if (confirmed)
889
+ await state.reset();
890
+ }
891
+
892
+ // src/index.tsx
201
893
  function stateDir() {
202
894
  const base = process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state");
203
895
  return join(base, "opencode");
@@ -205,17 +897,66 @@ function stateDir() {
205
897
  var src_default = Plugin.define({
206
898
  id: "peak-badge",
207
899
  setup(ctx) {
208
- const options = ctx.options ?? {};
209
- const rules = resolveRules(options);
210
- const labels = {
211
- peak: options.labelPeak ?? "[PEAK]",
212
- offPeak: options.labelOffPeak ?? "[OFF-PEAK]"
900
+ const [settings, setSettings] = createSignal(sanitizeSettings(undefined));
901
+ function resolved() {
902
+ return resolveSettings(settings());
903
+ }
904
+ function now() {
905
+ const env = process.env.OPENCODE_PEAK_HOURS_FAKE_TIME;
906
+ return currentNow(env || resolved().fakeTime);
907
+ }
908
+ let saving = false;
909
+ const sync = createSettingsSync({
910
+ client: () => ctx.client,
911
+ set: setSettings,
912
+ canApply: () => !saving,
913
+ onSaveError: (message) => {
914
+ ctx.ui.toast.show({
915
+ variant: "error",
916
+ message: `Peak Badge settings: ${message}`
917
+ });
918
+ }
919
+ });
920
+ sync.connect();
921
+ const refreshSettings = () => sync.refresh();
922
+ async function saveSettings(next) {
923
+ saving = true;
924
+ try {
925
+ await sync.save(next);
926
+ } finally {
927
+ saving = false;
928
+ }
929
+ }
930
+ async function resetSettings() {
931
+ saving = true;
932
+ try {
933
+ await sync.reset();
934
+ } finally {
935
+ saving = false;
936
+ }
937
+ }
938
+ const settingsState = {
939
+ settings,
940
+ save: saveSettings,
941
+ reset: resetSettings
213
942
  };
214
- const pollSeconds = Math.max(1, Number(options.pollSeconds) || 10);
215
- const subagents = options.subagents ?? true;
216
- const alwaysShow = options.alwaysShow ?? false;
217
- const debug = options.debug ?? false;
218
- const [tick, setTick] = createSignal(currentNow().getTime());
943
+ ctx.keymap.layer(() => ({
944
+ mode: "global",
945
+ commands: [{
946
+ id: "peak-badge.settings",
947
+ title: "Peak Badge settings",
948
+ description: "Peak windows, models, labels and refresh",
949
+ group: "Peak Badge",
950
+ bind: false,
951
+ palette: true,
952
+ slash: {
953
+ name: "peak-badge",
954
+ aliases: ["peakbadge"]
955
+ },
956
+ run: () => openPeakBadgeSettings(ctx, settingsState)
957
+ }]
958
+ }));
959
+ const [tick, setTick] = createSignal(now().getTime());
219
960
  const [version, setVersion] = createSignal(0);
220
961
  const [homePick, setHomePick] = createSignal(undefined);
221
962
  const [defaultModel, setDefaultModel] = createSignal(undefined);
@@ -225,10 +966,6 @@ var src_default = Plugin.define({
225
966
  let activeSessionID;
226
967
  let lastAppliedKey;
227
968
  let debounceTimer;
228
- const timer = setInterval(() => {
229
- setTick(currentNow().getTime());
230
- applyRecentModel();
231
- }, pollSeconds * 1000);
232
969
  async function applyRecentModel() {
233
970
  const dir = stateDir();
234
971
  try {
@@ -331,28 +1068,15 @@ var src_default = Plugin.define({
331
1068
  }
332
1069
  return homeRef();
333
1070
  }
334
- function activeChildRefs(sessionID) {
335
- if (!subagents)
1071
+ function childRefs(sessionID) {
1072
+ if (!resolved().subagents)
336
1073
  return [];
337
- const refs = [];
338
- const seen = new Set;
339
- const stack = [...ctx.data.session.family(sessionID)];
340
- while (stack.length > 0) {
341
- const id = stack.pop();
342
- if (!id || seen.has(id))
343
- continue;
344
- seen.add(id);
345
- if (ctx.data.session.status(id) === "running") {
346
- const model = sessionModel(id);
347
- if (model)
348
- refs.push(model);
349
- }
350
- for (const nested of ctx.data.session.family(id)) {
351
- if (!seen.has(nested))
352
- stack.push(nested);
353
- }
354
- }
355
- return refs;
1074
+ return runningSubagentRefs({
1075
+ sessionID,
1076
+ family: (id) => ctx.data.session.family(id),
1077
+ status: (id) => ctx.data.session.status(id),
1078
+ model: sessionModel
1079
+ });
356
1080
  }
357
1081
  function badgeView(sessionID) {
358
1082
  version();
@@ -361,24 +1085,18 @@ var src_default = Plugin.define({
361
1085
  picked.delete(sessionID);
362
1086
  activeSessionID = sessionID;
363
1087
  }
364
- const now = new Date(tick());
365
- const states = [];
1088
+ const current = resolved();
366
1089
  const main = mainRef(sessionID);
367
- if (main) {
368
- const rule = matchRule(rules, modelKey(main.providerID, main.id)) ?? (alwaysShow ? rules.fallback : undefined);
369
- const state = badgeFor(now, rule, labels);
370
- if (state)
371
- states.push(state);
372
- }
373
- if (sessionID) {
374
- for (const child of activeChildRefs(sessionID)) {
375
- const state = badgeFor(now, matchRule(rules, modelKey(child.providerID, child.id)), labels);
376
- if (state)
377
- states.push(state);
378
- }
379
- }
1090
+ const state = badgeForModels({
1091
+ now: new Date(tick()),
1092
+ rules: current.rules,
1093
+ labels: current.labels,
1094
+ main,
1095
+ subagents: sessionID ? childRefs(sessionID) : [],
1096
+ alwaysShow: current.alwaysShow
1097
+ });
380
1098
  return {
381
- state: mergeBadges(states),
1099
+ state,
382
1100
  model: main
383
1101
  };
384
1102
  }
@@ -386,7 +1104,7 @@ var src_default = Plugin.define({
386
1104
  return badgeView(sessionID).state;
387
1105
  }
388
1106
  function badgeText(view) {
389
- const model = debug && view.model ? `${view.model.providerID}/${view.model.id}` : "";
1107
+ const model = resolved().debug && view.model ? `${view.model.providerID}/${view.model.id}` : "";
390
1108
  return [view.state?.label ?? "", model].filter(Boolean).join(" ");
391
1109
  }
392
1110
  function renderBadge(sessionID) {
@@ -410,7 +1128,7 @@ var src_default = Plugin.define({
410
1128
  synced.delete(event.data.sessionID);
411
1129
  if (changed || hadPick)
412
1130
  setVersion((value) => value + 1);
413
- })];
1131
+ }), ctx.data.on("server.connected", () => sync.connect())];
414
1132
  const disposeSessionSlot = ctx.ui.slot({
415
1133
  append: "prompt.footer.status",
416
1134
  render: (input) => input.sessionID ? renderBadge(input.sessionID) : null
@@ -419,17 +1137,34 @@ var src_default = Plugin.define({
419
1137
  append: "home.footer.status",
420
1138
  render: () => renderBadge(undefined)
421
1139
  });
1140
+ let pollTimer;
1141
+ const disposeTimer = createRoot((dispose) => {
1142
+ createEffect(() => {
1143
+ const current = resolved();
1144
+ setTick(now().getTime());
1145
+ clearInterval(pollTimer);
1146
+ pollTimer = setInterval(() => {
1147
+ setTick(now().getTime());
1148
+ applyRecentModel();
1149
+ }, current.pollSeconds * 1000);
1150
+ onCleanup(() => clearInterval(pollTimer));
1151
+ });
1152
+ return dispose;
1153
+ });
422
1154
  __test.badge = badge;
423
1155
  __test.badgeText = (sessionID) => badgeText(badgeView(sessionID));
424
- __test.refresh = () => setTick(currentNow().getTime());
1156
+ __test.refresh = (date) => setTick((date ?? now()).getTime());
425
1157
  __test.applyRecentModel = applyRecentModel;
426
1158
  __test.refreshHomeModel = refreshHomeModel;
1159
+ __test.refreshSettings = refreshSettings;
427
1160
  return () => {
1161
+ disposeTimer();
1162
+ clearInterval(pollTimer);
1163
+ sync.stop();
428
1164
  for (const dispose of disposeEvents)
429
1165
  dispose();
430
1166
  disposeSessionSlot();
431
1167
  disposeHomeSlot();
432
- clearInterval(timer);
433
1168
  clearTimeout(debounceTimer);
434
1169
  homeWatcher?.close();
435
1170
  };
@@ -440,11 +1175,12 @@ var __test = {
440
1175
  badgeText: undefined,
441
1176
  refresh: undefined,
442
1177
  applyRecentModel: undefined,
443
- refreshHomeModel: undefined
1178
+ refreshHomeModel: undefined,
1179
+ refreshSettings: undefined
444
1180
  };
445
1181
  export {
446
1182
  __test,
447
1183
  src_default as default
448
1184
  };
449
1185
 
450
- //# debugId=E83A066E22BDCC1364756E2164756E21
1186
+ //# debugId=718B35368DDC906D64756E2164756E21