pi-odd-worktree 3.14.0 → 3.15.1
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/README.md +1 -0
- package/extensions/odd-worktree-tools.ts +172 -0
- package/lib/alert-mode.js +82 -0
- package/lib/alert-rows.js +82 -0
- package/lib/opencode-usage.js +256 -0
- package/lib/peak-labels.js +64 -0
- package/lib/peak-providers.js +63 -0
- package/lib/peak-schedule.js +242 -0
- package/lib/user-prompt-card.js +48 -2
- package/package.json +1 -1
- package/tools/alert-mode.test.js +140 -0
- package/tools/alert-rows.test.js +196 -0
- package/tools/opencode-usage-alert.test.js +252 -0
- package/tools/opencode-usage-lifecycle.test.js +110 -0
- package/tools/opencode-usage.test.js +321 -0
- package/tools/peak-labels.test.js +111 -0
- package/tools/peak-providers.test.js +109 -0
- package/tools/peak-schedule.test.js +423 -0
- package/tools/user-prompt-card.test.js +72 -1
package/README.md
CHANGED
|
@@ -85,6 +85,7 @@ The full rules of each step, including every refusal, are in [Create, list, move
|
|
|
85
85
|
## Key Capabilities
|
|
86
86
|
|
|
87
87
|
- **Two halves are optional.** With `gentle-shell-bridge`, `/gentle:customize` has a `Tools` page with an Off/On line for `Codegraph+` (the CodeGraph prompt text, reminders and wiring; its card follows the `Card activity` line like every other card) and one for `Worktrees+` (the worktree tools, `/warp`, the worktree guards and prompt text). Both are On by default; a change needs `/reload` and a new session. See [the module switches](docs/reference.md#the-module-switches).
|
|
88
|
+
- **OpenCode Go usage comes built in, and every peak window has its own switch.** The `opencode-go` provider is registered on Gentle Shell's own usage event, so `/gentle:usage`, the status-bar segment and the panel's `r` refresh work exactly as they do for the providers the shell ships. Above the editor, one row per provider whose peak window is running, in the registry's order: `peak · 2× deepseek · until 04:00` (OpenCode Go bills DeepSeek at double rate in weekdays 01:00–04:00 and 06:00–10:00 UTC) and `peak · claude · until 10:00` (weekdays 05:00–11:00 Pacific; Anthropic publishes no price multiplier there — the subscription window drains faster instead). A row never depends on the model the session uses or on a usage key: only that provider's switch and its window matter. `/gentle:customize` → `Alert`, between `Notifications` and `Layout`, holds one Off/On line per provider — `Deepseek peak`, `Claude peak` — **all Off on a first run**, applied without `/reload`. A third provider costs no change outside the registry. See [the usage source and the peak rows](docs/reference.md#the-opencode-go-usage-source-and-the-peak-rows-above-the-editor).
|
|
88
89
|
- **A create is instant and writes no state.** The directory is the whole record; there is no list file and no lock file.
|
|
89
90
|
- **Deleting refuses on a live session.** The guard reads Gentle Shell's presence records, discloses what it could not resolve, and never auto-warps. Removal is `git worktree remove` and the branch is kept. See [the deletion guard](docs/reference.md#the-deletion-guard-and-its-honest-limit).
|
|
90
91
|
- **A warp is queued, never dropped.** While this session's tools, agent tasks or background jobs are still running, `/warp` keeps the request pending and moves when they finish. See [the queued warp](docs/reference.md#a-warp-waits-for-this-sessions-own-tools-agent-tasks-and-background-jobs).
|
|
@@ -11380,6 +11380,162 @@ function registerModuleRows(api) {
|
|
|
11380
11380
|
}
|
|
11381
11381
|
}
|
|
11382
11382
|
|
|
11383
|
+
// opencode-usage-alert: the OpenCode Go usage source this package carries, and the peak
|
|
11384
|
+
// rows above the editor that the `Alert` page owns. The two halves are one story:
|
|
11385
|
+
//
|
|
11386
|
+
// - The source registers `opencode-go` on `gentle-pi:usage-source/v1`, the same event a
|
|
11387
|
+
// built-in reader uses, so Gentle Shell keeps owning the refresh schedule, the status-bar
|
|
11388
|
+
// segment and the `/gentle:usage` panel. That panel prints `plan` between the provider
|
|
11389
|
+
// name and its `updated …` note, so the schedule rides there whether the window is peak
|
|
11390
|
+
// or not.
|
|
11391
|
+
// - The rows above the editor belong to this package. `lib/peak-providers.js` is the
|
|
11392
|
+
// registry: today DeepSeek (fixed UTC windows, a published 2× price) and Claude (weekdays
|
|
11393
|
+
// 05:00–11:00 Pacific, no published price multiplier — its window drains the subscription
|
|
11394
|
+
// faster instead), and a third provider needs no change here: one row per provider in
|
|
11395
|
+
// peak, in the registry's own order, each gated by its own switch.
|
|
11396
|
+
//
|
|
11397
|
+
// A row never depends on the model this session uses, on the provider being the session's, or
|
|
11398
|
+
// on a usage key being present: the switch and the window are its only gates. Every switch is
|
|
11399
|
+
// read on every sync, so a change lands in the running session without `/reload`.
|
|
11400
|
+
//
|
|
11401
|
+
// Nothing here polls: ONE timer goes to the earliest boundary among the ENABLED providers — a
|
|
11402
|
+
// window that is closing or one that is about to open — and re-arms itself there.
|
|
11403
|
+
const OPENCODE_ALERT_PLACEMENT = "aboveEditor";
|
|
11404
|
+
|
|
11405
|
+
let opencodeAlertTimer = null;
|
|
11406
|
+
// Only the bound `setWidget` seam is held, never the context around it: the timer can outlive
|
|
11407
|
+
// the turn that armed it.
|
|
11408
|
+
let opencodeAlertWidgetUi = null;
|
|
11409
|
+
|
|
11410
|
+
function opencodeAlertLib(name) {
|
|
11411
|
+
try {
|
|
11412
|
+
return libRequire(name);
|
|
11413
|
+
} catch {
|
|
11414
|
+
return null;
|
|
11415
|
+
}
|
|
11416
|
+
}
|
|
11417
|
+
|
|
11418
|
+
// One provider's switch: On only when the stored value says On, and an unreadable store answers
|
|
11419
|
+
// the documented default, Off — the same answer a first run gets.
|
|
11420
|
+
function opencodePeakAlertEnabled(providerId) {
|
|
11421
|
+
const mode = opencodeAlertLib("alert-mode.js");
|
|
11422
|
+
if (!mode || typeof mode.readPeakAlert !== "function") return false;
|
|
11423
|
+
try {
|
|
11424
|
+
return mode.readPeakAlert(issuesSidebarBridge(), providerId) === true;
|
|
11425
|
+
} catch {
|
|
11426
|
+
return false;
|
|
11427
|
+
}
|
|
11428
|
+
}
|
|
11429
|
+
|
|
11430
|
+
function opencodeAlertKey() {
|
|
11431
|
+
const labels = opencodeAlertLib("peak-labels.js");
|
|
11432
|
+
return labels && typeof labels.PEAK_WIDGET_KEY === "string" ? labels.PEAK_WIDGET_KEY : null;
|
|
11433
|
+
}
|
|
11434
|
+
|
|
11435
|
+
function paintOpenCodeAlert(key, content) {
|
|
11436
|
+
const ui = opencodeAlertWidgetUi;
|
|
11437
|
+
if (ui === null) return;
|
|
11438
|
+
try {
|
|
11439
|
+
ui.setWidget(key, content, { placement: OPENCODE_ALERT_PLACEMENT });
|
|
11440
|
+
} catch {
|
|
11441
|
+
// A host that cannot paint this zone shows no row, and nothing else changes.
|
|
11442
|
+
}
|
|
11443
|
+
}
|
|
11444
|
+
|
|
11445
|
+
function clearOpenCodeAlertTimer() {
|
|
11446
|
+
if (opencodeAlertTimer === null) return;
|
|
11447
|
+
clearTimeout(opencodeAlertTimer);
|
|
11448
|
+
opencodeAlertTimer = null;
|
|
11449
|
+
}
|
|
11450
|
+
|
|
11451
|
+
// The rows and the timer, in one place: no row is ever left behind by a state it no longer
|
|
11452
|
+
// describes, and the timer always points at the nearest boundary of an ENABLED provider.
|
|
11453
|
+
function syncOpenCodePeakAlert(now = Date.now()) {
|
|
11454
|
+
clearOpenCodeAlertTimer();
|
|
11455
|
+
const key = opencodeAlertKey();
|
|
11456
|
+
if (key === null) return;
|
|
11457
|
+
// A session that is over owns no seam, so nothing arms a timer for a UI that no longer exists:
|
|
11458
|
+
// the next `session_start` binds one again and syncs from there.
|
|
11459
|
+
if (opencodeAlertWidgetUi === null) return;
|
|
11460
|
+
const peak = opencodeAlertLib("peak-schedule.js");
|
|
11461
|
+
const labels = opencodeAlertLib("peak-labels.js");
|
|
11462
|
+
const registry = opencodeAlertLib("peak-providers.js");
|
|
11463
|
+
if (!peak || !labels || !registry || !Array.isArray(registry.PROVIDERS)) {
|
|
11464
|
+
paintOpenCodeAlert(key, undefined);
|
|
11465
|
+
return;
|
|
11466
|
+
}
|
|
11467
|
+
const lines = [];
|
|
11468
|
+
let earliest = Infinity;
|
|
11469
|
+
for (const provider of registry.PROVIDERS) {
|
|
11470
|
+
// Besides the window itself, the switch is the only gate — never the session's model.
|
|
11471
|
+
if (!opencodePeakAlertEnabled(provider.id)) continue;
|
|
11472
|
+
const state = peak.peakStateFor(provider, now);
|
|
11473
|
+
if (state.kind === "peak") lines.push(labels.peakWidgetLine(provider, state, now));
|
|
11474
|
+
// A provider that is off-peak still owns the instant its window opens.
|
|
11475
|
+
if (Number.isFinite(state.until) && state.until > now && state.until < earliest) earliest = state.until;
|
|
11476
|
+
}
|
|
11477
|
+
if (lines.length === 0) {
|
|
11478
|
+
paintOpenCodeAlert(key, undefined);
|
|
11479
|
+
} else {
|
|
11480
|
+
// One row per provider, in the registry's order: they read as a list instead of one
|
|
11481
|
+
// truncated sentence, and a third provider costs no layout change.
|
|
11482
|
+
paintOpenCodeAlert(key, lines);
|
|
11483
|
+
}
|
|
11484
|
+
if (!Number.isFinite(earliest)) return;
|
|
11485
|
+
// The timer goes to the boundary ITSELF. A timer that fires a hair early finds the same state and
|
|
11486
|
+
// re-arms for the remainder, so no row outlives the window it describes.
|
|
11487
|
+
const delay = Math.max(1, earliest - now);
|
|
11488
|
+
opencodeAlertTimer = setTimeout(() => syncOpenCodePeakAlert(), delay);
|
|
11489
|
+
const timer = opencodeAlertTimer;
|
|
11490
|
+
if (timer && typeof timer.unref === "function") timer.unref();
|
|
11491
|
+
}
|
|
11492
|
+
|
|
11493
|
+
function registerOpenCodeUsageSource(pi) {
|
|
11494
|
+
try {
|
|
11495
|
+
if (!pi || !pi.events || typeof pi.events.emit !== "function") return;
|
|
11496
|
+
const usage = opencodeAlertLib("opencode-usage.js");
|
|
11497
|
+
if (!usage || typeof usage.createUsageSource !== "function") return;
|
|
11498
|
+
// Re-registering replaces the source, so this is safe on every session start and keeps
|
|
11499
|
+
// this extension's load order irrelevant. Nothing here gates a row: whether the panel can
|
|
11500
|
+
// read the key is the panel's business, and an alert follows the switch and the clock.
|
|
11501
|
+
pi.events.emit("gentle-pi:usage-source/v1", usage.createUsageSource());
|
|
11502
|
+
} catch {
|
|
11503
|
+
// The source is optional: a host without the seam keeps every other surface.
|
|
11504
|
+
}
|
|
11505
|
+
}
|
|
11506
|
+
|
|
11507
|
+
// S5/S8 (opencode-usage-alert): the `Alert` page's switches, one line per registry entry.
|
|
11508
|
+
// Each reads its own live value on every build and applies through `onChange`, so the running
|
|
11509
|
+
// session shows or hides that provider's row the moment the human picks On or Off.
|
|
11510
|
+
function registerAlertRows(api) {
|
|
11511
|
+
try {
|
|
11512
|
+
if (!api || typeof api.registerRows !== "function") return;
|
|
11513
|
+
const alerts = opencodeAlertLib("alert-rows.js");
|
|
11514
|
+
if (!alerts || typeof alerts.alertRowsProvider !== "function") return;
|
|
11515
|
+
api.registerRows(
|
|
11516
|
+
alerts.alertRowsProvider({
|
|
11517
|
+
api,
|
|
11518
|
+
onChange: () => syncOpenCodePeakAlert(),
|
|
11519
|
+
}),
|
|
11520
|
+
);
|
|
11521
|
+
} catch {
|
|
11522
|
+
// The page is optional: a bridge that refuses it leaves every row gated by the
|
|
11523
|
+
// documented default alone.
|
|
11524
|
+
}
|
|
11525
|
+
}
|
|
11526
|
+
|
|
11527
|
+
function bindOpenCodeAlertUi(ctx) {
|
|
11528
|
+
const ui = ctx && ctx.ui ? ctx.ui : null;
|
|
11529
|
+
opencodeAlertWidgetUi = ui && typeof ui.setWidget === "function" ? ui : null;
|
|
11530
|
+
}
|
|
11531
|
+
|
|
11532
|
+
function teardownOpenCodePeakAlert() {
|
|
11533
|
+
clearOpenCodeAlertTimer();
|
|
11534
|
+
const key = opencodeAlertKey();
|
|
11535
|
+
if (key !== null) paintOpenCodeAlert(key, undefined);
|
|
11536
|
+
opencodeAlertWidgetUi = null;
|
|
11537
|
+
}
|
|
11538
|
+
|
|
11383
11539
|
// S2 (issues-sidebar): the section reaches the rail ONLY through the bridge's
|
|
11384
11540
|
// published object. A host without it is subscribed to the ready announcement
|
|
11385
11541
|
// ONCE and nothing else happens: no notify, no throw, no other surface touched.
|
|
@@ -11397,6 +11553,7 @@ function registerIssuesSidebar(pi) {
|
|
|
11397
11553
|
// with `mountIssuesSidebar` tearing the old section down first.
|
|
11398
11554
|
if (api !== issuesSidebarApi) {
|
|
11399
11555
|
registerModuleRows(api);
|
|
11556
|
+
registerAlertRows(api);
|
|
11400
11557
|
registerBashDesignRows(api);
|
|
11401
11558
|
registerDiffDesignRows(api);
|
|
11402
11559
|
issuesSidebarApi = api;
|
|
@@ -12181,6 +12338,10 @@ function registerOddWorktreeSurfaceEntries(pi) {
|
|
|
12181
12338
|
} catch {
|
|
12182
12339
|
oddModules = { codegraph: true, worktrees: true };
|
|
12183
12340
|
}
|
|
12341
|
+
// opencode-usage-alert: the OpenCode Go source registers at load AND at every
|
|
12342
|
+
// session start, so either load order works and a session switch re-targets the
|
|
12343
|
+
// same provider. `registerAlertRows` below carries the `Deepseek peak` switch.
|
|
12344
|
+
registerOpenCodeUsageSource(pi);
|
|
12184
12345
|
// S8/S9 (T8): the record of the ODDs this session wrote or edited is NOT part of the
|
|
12185
12346
|
// worktree half: the ODD rail is `Worktrees+`'s surface, so the attribution has to be
|
|
12186
12347
|
// there with that module OFF too. One record per load — a `session_start` restores it
|
|
@@ -12310,6 +12471,11 @@ function registerOddWorktreeSurfaceEntries(pi) {
|
|
|
12310
12471
|
// nothing registered to use the answer, so no probe is dispatched at all — no
|
|
12311
12472
|
// child, no network, nothing said.
|
|
12312
12473
|
if (!ISSUES_GH_CLI_ABSENT) dispatchIssuesGate(ctx);
|
|
12474
|
+
// opencode-usage-alert: the source is re-targeted at every session boundary, and the rows
|
|
12475
|
+
// above the editor belong to the session that draws them.
|
|
12476
|
+
bindOpenCodeAlertUi(ctx);
|
|
12477
|
+
registerOpenCodeUsageSource(pi);
|
|
12478
|
+
syncOpenCodePeakAlert();
|
|
12313
12479
|
});
|
|
12314
12480
|
// A queued warp is session state: shutdown clears its record and its timer so
|
|
12315
12481
|
// nothing outlives the session that asked for the move. S6 (issues-sidebar):
|
|
@@ -12355,6 +12521,9 @@ function registerOddWorktreeSurfaceEntries(pi) {
|
|
|
12355
12521
|
// T4 (odd-rail-session-scope S2): the association is this session's alone, so the
|
|
12356
12522
|
// ended session leaves none behind for a frame drawn before the next start.
|
|
12357
12523
|
oddAssociated = new Set();
|
|
12524
|
+
// opencode-usage-alert: the schedule timer and the rows belong to the session that armed
|
|
12525
|
+
// them, so the ended session leaves neither behind.
|
|
12526
|
+
teardownOpenCodePeakAlert();
|
|
12358
12527
|
// S7: the prompt card's teardown belongs to the lifecycle pair registered before the
|
|
12359
12528
|
// bridge gate — the same owner as its install, so a session whose bridge was never
|
|
12360
12529
|
// present still closes (and its ready announcement can no longer arm an install).
|
|
@@ -12365,6 +12534,9 @@ function registerOddWorktreeSurfaceEntries(pi) {
|
|
|
12365
12534
|
pi.on("session_shutdown", () => {
|
|
12366
12535
|
startupEpoch += 1;
|
|
12367
12536
|
});
|
|
12537
|
+
// opencode-usage-alert: a turn can cross a peak boundary, and the next one re-reads
|
|
12538
|
+
// the clock. It also settles the row right after the switch's own action.
|
|
12539
|
+
pi.on("turn_end", () => syncOpenCodePeakAlert());
|
|
12368
12540
|
if (oddModules.worktrees) pi.on("tool_call", (event, ctx) => handleWorktreeOddEvent(event, ctx, pi));
|
|
12369
12541
|
// S1/S3/S4/S9: the worktree guard, the first `tool_call` observation that refuses a
|
|
12370
12542
|
// `bash` command instead of observing it. It sits beside the naming handler and is
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The peak alerts' switches (S5, S8): ONE stored boolean PER provider, Off by default. The
|
|
3
|
+
// booleans `/gentle:customize` → `Alert` → `Deepseek peak` / `Claude peak` write are the
|
|
4
|
+
// same booleans the peak rows above the input read, which is what keeps a switch and the
|
|
5
|
+
// row it governs from ever disagreeing.
|
|
6
|
+
//
|
|
7
|
+
// One persisted document, through the bridge's own store: `odd-worktree` → `alerts` →
|
|
8
|
+
// `{ peaks: { [providerId]: boolean } }`. A provider is On only when its own entry is
|
|
9
|
+
// exactly `true`, so a first run, an absent or malformed document, an id that was never
|
|
10
|
+
// written, an unreadable store or a host with no bridge all answer Off — and the default is
|
|
11
|
+
// NEVER written eagerly: a user who never touches a switch leaves no document behind at all.
|
|
12
|
+
//
|
|
13
|
+
// Writes are keyed by provider id, so flipping one provider keeps every sibling id of the
|
|
14
|
+
// document (and every sibling key of the store) exactly as it was.
|
|
15
|
+
//
|
|
16
|
+
// Pure over the injected bridge; nothing here touches the host or reads a clock.
|
|
17
|
+
|
|
18
|
+
const OWN_STORE = 'odd-worktree';
|
|
19
|
+
const ALERTS_KEY = 'alerts';
|
|
20
|
+
|
|
21
|
+
const DEFAULT_PEAK = false;
|
|
22
|
+
|
|
23
|
+
function isRecord(value) {
|
|
24
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function storeOf(api) {
|
|
28
|
+
if (api === null || typeof api !== 'object' || typeof api.createStore !== 'function') return null;
|
|
29
|
+
return api.createStore(OWN_STORE);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function storedDocument(store) {
|
|
33
|
+
const stored = store.get(ALERTS_KEY, undefined);
|
|
34
|
+
return isRecord(stored) ? stored : {};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The stored `peaks` map, or an empty one when the document does not carry a usable map. */
|
|
38
|
+
function storedPeaks(store) {
|
|
39
|
+
const peaks = storedDocument(store).peaks;
|
|
40
|
+
return isRecord(peaks) ? peaks : {};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* One provider's switch: On only when its own entry is exactly `true`. An absent document, a
|
|
45
|
+
* malformed one, an unwritten id, a missing store and a throwing store all answer Off and
|
|
46
|
+
* never throw.
|
|
47
|
+
*/
|
|
48
|
+
function readPeakAlert(api, id) {
|
|
49
|
+
try {
|
|
50
|
+
if (typeof id !== 'string' || id === '') return DEFAULT_PEAK;
|
|
51
|
+
const store = storeOf(api);
|
|
52
|
+
if (store === null) return DEFAULT_PEAK;
|
|
53
|
+
return storedPeaks(store)[id] === true;
|
|
54
|
+
} catch {
|
|
55
|
+
return DEFAULT_PEAK;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Persist one provider's switch, keeping every sibling id of the `peaks` map and every
|
|
61
|
+
* sibling key of the `alerts` document and of the store. True when it wrote.
|
|
62
|
+
*/
|
|
63
|
+
function writePeakAlert(api, id, on) {
|
|
64
|
+
try {
|
|
65
|
+
if (typeof id !== 'string' || id === '') return false;
|
|
66
|
+
const store = storeOf(api);
|
|
67
|
+
if (store === null) return false;
|
|
68
|
+
const document = storedDocument(store);
|
|
69
|
+
const peaks = isRecord(document.peaks) ? document.peaks : {};
|
|
70
|
+
store.set(ALERTS_KEY, { ...document, peaks: { ...peaks, [id]: on === true } });
|
|
71
|
+
return true;
|
|
72
|
+
} catch {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
module.exports = {
|
|
78
|
+
DEFAULT_PEAK,
|
|
79
|
+
ALERTS_KEY,
|
|
80
|
+
readPeakAlert,
|
|
81
|
+
writePeakAlert,
|
|
82
|
+
};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The `Alert` page of `/gentle:customize` (S3, S5, S7) and its switches (S4, S8): one
|
|
3
|
+
// Off/On pair PER provider the peak registry declares, in the registry's declaration order,
|
|
4
|
+
// each under its own setting label (`Deepseek peak`, then `Claude peak`), all Off by
|
|
5
|
+
// default. The page sits immediately after `Notifications` and before `Layout`, so it is the
|
|
6
|
+
// `Alert` category every menu that lists both host pages shows between them.
|
|
7
|
+
//
|
|
8
|
+
// The page is built from `lib/peak-providers.js`, so a provider added to the registry gets
|
|
9
|
+
// its pair here with no change to this file or to the extension.
|
|
10
|
+
//
|
|
11
|
+
// Unlike the module switches, these are applied to the RUNNING session: the extension
|
|
12
|
+
// re-arms the peak rows from the stored booleans, so a change calls `onChange()` right after
|
|
13
|
+
// the write and nothing here says "restart" or "/reload". A store that refuses the write
|
|
14
|
+
// THROWS instead of returning quietly — the customize menu's own busy guard reports a row's
|
|
15
|
+
// error, and a switch that silently keeps the old value while the peak row keeps drawing is
|
|
16
|
+
// exactly the disagreement `lib/alert-mode.js` exists to prevent.
|
|
17
|
+
//
|
|
18
|
+
// The rows are a plain bridge provider (`registerRows`): two consecutive rows sharing one
|
|
19
|
+
// `choice.setting` make one `Off On` line. Pure over the injected bridge and callbacks;
|
|
20
|
+
// nothing here touches the host.
|
|
21
|
+
|
|
22
|
+
const { readPeakAlert, writePeakAlert } = require('./alert-mode.js');
|
|
23
|
+
const { PROVIDERS } = require('./peak-providers.js');
|
|
24
|
+
|
|
25
|
+
const CATEGORY = 'Alert';
|
|
26
|
+
const PROVIDER_ID = 'odd-worktree.alert.peak';
|
|
27
|
+
|
|
28
|
+
const VALUES = Object.freeze([
|
|
29
|
+
Object.freeze({ value: 'Off', on: false }),
|
|
30
|
+
Object.freeze({ value: 'On', on: true }),
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The bridge provider for the `Alert` page. The `notify` the extension also hands this
|
|
35
|
+
* factory stays unused on purpose: the change is applied to the running session, so there
|
|
36
|
+
* is no restart to announce and this page prints nothing. A refused write throws and
|
|
37
|
+
* `onChange()` is never called for it, so the running session is only told about a change
|
|
38
|
+
* that was actually kept.
|
|
39
|
+
*/
|
|
40
|
+
function alertRowsProvider({ api, onChange } = {}) {
|
|
41
|
+
return {
|
|
42
|
+
id: PROVIDER_ID,
|
|
43
|
+
category: CATEGORY,
|
|
44
|
+
// The `Alert` page opens right after the host's `Notifications` page and before `Layout`.
|
|
45
|
+
// The bridge derives its page list from the order of the rows once, while it builds the
|
|
46
|
+
// menu, so this has to be the provider's request; a bridge that predates
|
|
47
|
+
// `categoryPlacement` ignores the field and the page opens at the end instead.
|
|
48
|
+
categoryPlacement: { after: 'Notifications' },
|
|
49
|
+
rows() {
|
|
50
|
+
const rows = [];
|
|
51
|
+
for (const provider of PROVIDERS) {
|
|
52
|
+
for (const { value, on } of VALUES) {
|
|
53
|
+
rows.push({
|
|
54
|
+
category: CATEGORY,
|
|
55
|
+
label: () => provider.setting,
|
|
56
|
+
choice: {
|
|
57
|
+
setting: provider.setting,
|
|
58
|
+
value,
|
|
59
|
+
current: () => readPeakAlert(api, provider.id) === on,
|
|
60
|
+
},
|
|
61
|
+
action: () => {
|
|
62
|
+
if (!writePeakAlert(api, provider.id, on)) {
|
|
63
|
+
// The menu reports the throw; nothing was stored, so nothing is applied.
|
|
64
|
+
throw new Error(`${provider.setting} could not be saved`);
|
|
65
|
+
}
|
|
66
|
+
// Applied in the session that is running: the rows the user just switched
|
|
67
|
+
// appear or disappear without a `/reload`.
|
|
68
|
+
if (typeof onChange === 'function') onChange();
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return rows;
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
module.exports = {
|
|
79
|
+
CATEGORY,
|
|
80
|
+
PROVIDER_ID,
|
|
81
|
+
alertRowsProvider,
|
|
82
|
+
};
|
|
@@ -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
|
+
};
|