opencode-peak-badge 0.3.0 → 0.5.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/README.md CHANGED
@@ -1,112 +1,117 @@
1
1
  # opencode-peak-badge
2
2
 
3
- [![GitHub Tag](https://img.shields.io/github/v/tag/hugobatista/opencode-peak-badge?logo=github&label=latest)](https://github.com/hugobatista/opencode-peak-badge/releases)
4
- [![Lint](https://img.shields.io/github/actions/workflow/status/hugobatista/opencode-peak-badge/lint.yml?label=Lint)](https://github.com/hugobatista/opencode-peak-badge/actions/workflows/lint.yml)
5
- [![Test](https://img.shields.io/github/actions/workflow/status/hugobatista/opencode-peak-badge/test.yml?label=Test)](https://github.com/hugobatista/opencode-peak-badge/actions/workflows/test.yml)
3
+ [![GitHub Tag](https://img.shields.io/github/v/tag/hugobatista/opencode-peak-badge?logo=github&label=latest)](https://go.hugobatista.com/gh/opencode-peak-badge/releases)
4
+ [![Lint](https://img.shields.io/github/actions/workflow/status/hugobatista/opencode-peak-badge/lint.yml?label=Lint)](https://go.hugobatista.com/gh/opencode-peak-badge/actions/workflows/lint.yml)
5
+ [![Test](https://img.shields.io/github/actions/workflow/status/hugobatista/opencode-peak-badge/test.yml?label=Test)](https://go.hugobatista.com/gh/opencode-peak-badge/actions/workflows/test.yml)
6
6
  [![npm](https://img.shields.io/npm/v/opencode-peak-badge.svg)](https://www.npmjs.com/package/opencode-peak-badge)
7
7
 
8
- OpenCode TUI plugin. Shows a `[PEAK]` / `[OFF-PEAK]` badge next to the model
9
- name in the prompt bar, so you always know whether the active model is billed
10
- at peak rates. When a subagent session is running, its model is tracked too:
11
- peak wins across the main model and all busy subagents. Updates live — no
12
- restart needed when a session crosses a peak window boundary.
8
+ `[PEAK]` / `[OFF-PEAK]` badge for OpenCode TUI and OpenCode Desktop. It follows
9
+ the active model's configured peak-hour rules; running subagents are included and
10
+ peak wins. Updates live, including when a session crosses a boundary.
13
11
 
14
12
  ![Demo](docs/demo-peak.png)
15
13
 
16
- ## What it does
17
-
18
- - Renders a badge in `session_prompt_right` and `home_prompt_right` (both
19
- slots) whenever a model with configured peak hours is active — or always,
20
- with `alwaysShow: true`.
21
- - `[PEAK]` renders in the theme's warning color. `[OFF-PEAK]` renders in the
22
- muted color. The badge shows in **both** states for tracked models.
23
- - Recomputes every `pollSeconds` (default 10) and watches `model.json` for
24
- immediate model updates.
25
- - Tracks all descendant subagent sessions through their `parentID` chain.
26
- While a subagent session is busy, its model is checked against the peak
27
- windows. Peak wins: if any busy subagent is in peak hours, the badge shows
28
- `[PEAK]`. Disable with `subagents: false`.
29
- - Resolves the active model at session start from `session.created` /
30
- `session.updated` events, with a `session.get` fallback, so the badge shows
31
- before the first prompt. It also watches OpenCode's `model.json`, so picking
32
- a model updates the badge immediately — both on the home screen and in a
33
- session — instead of waiting for the next poll tick or the next prompt.
34
- - Follows model changes inside a session from `session.next.model.switched`
35
- and `message.updated`. Session events always win over the global
36
- `model.json` pick, so a model chosen earlier cannot shadow a later change
37
- (for example when an agent switch changes the session model).
38
- - Shows nothing for models without configured peak hours, unless
39
- `alwaysShow: true` forces the badge for the main model from the top-level
40
- `windows` / `weekdaysOnly`.
41
- - Provider-agnostic: track any model that has peak pricing by adding a rule
42
- under `models`. Built-in defaults cover DeepSeek models, which is where peak
43
- hours are known today.
14
+ ## Features
15
+
16
+ - TUI: footer badge for the session (`prompt.footer.status`) and Home
17
+ (`home.footer.status`).
18
+ - Desktop: header chip for the session (`session.header`) and status strip on
19
+ Home (`window.bottom`).
20
+ - Provider-agnostic; built-in rules cover DeepSeek models.
21
+ - Tracks running subagent sessions; if any is peak, the parent shows `[PEAK]`.
22
+ - Configurable models, UTC windows, labels, polling and fallback (`alwaysShow`).
44
23
 
45
24
  ## Requirements
46
25
 
47
- - OpenCode TUI >= 1.14 (TUI plugin support).
48
- - [Bun](https://bun.sh) to install dependencies (dev only).
26
+ - **OpenCode 2.4.2 or newer.** The TUI and Desktop use the V2 plugin API; the
27
+ desktop GUI requires 2.4.2+ and targets 2.4.2. The GUI plugin API is experimental.
28
+ - **Bun** for development.
49
29
 
50
30
  ## Install
51
31
 
52
32
  ```sh
53
- opencode plugin opencode-peak-badge --global
33
+ opencode plugin add opencode-peak-badge
34
+ ```
35
+
36
+ This writes the package to the global `opencode.json(c)`, which both the TUI and
37
+ Desktop read.
38
+
39
+ Manual alternative:
40
+
41
+ ```jsonc
42
+ {
43
+ "$schema": "https://opencode.ai/config.json",
44
+ "plugins": ["opencode-peak-badge"]
45
+ }
46
+ ```
47
+
48
+ To pass options:
49
+
50
+ ```jsonc
51
+ {
52
+ "$schema": "https://opencode.ai/config.json",
53
+ "plugins": [
54
+ { "package": "opencode-peak-badge", "options": { "pollSeconds": 30 } }
55
+ ]
56
+ }
54
57
  ```
55
58
 
56
- Or add the package name to `~/.config/opencode/tui.json`:
59
+ **TUI-only:** add the package to `~/.config/opencode/cli.json`:
57
60
 
58
61
  ```jsonc
59
62
  {
60
- "$schema": "https://opencode.ai/tui.json",
61
- "plugin": ["opencode-peak-badge"]
63
+ "plugins": ["opencode-peak-badge"]
62
64
  }
63
65
  ```
64
66
 
65
- Restart OpenCode. Config is loaded at startup; there is no hot reload.
67
+ Desktop reads only `opencode.json(c)`, not `cli.json`. Use one
68
+ `opencode.json(c)` entry for both, and remove duplicates from `cli.json`.
66
69
 
67
- Verify. Start a session with a tracked model (for example
68
- `opencode-go/deepseek-v4-flash`) and confirm the badge appears next to the
69
- model name in the prompt bar. To force a known state, see
70
+ OpenCode reloads plugins when config changes; `/reload` forces a full reload. A
71
+ package update may need a client restart (Desktop loads the GUI bundle from the
72
+ installed package).
73
+
74
+ Verify with a tracked model (for example `opencode-go/deepseek-v4-flash`): the TUI
75
+ footer badge, or the Desktop header chip. To force a state, see
70
76
  [Evaluation](#evaluation).
71
77
 
72
- ### Install from source (local dev)
78
+ ### Desktop surfaces
73
79
 
74
- 1. Clone the repository and install dependencies:
80
+ - **Session:** `session.header` chip next to the context indicator. The active
81
+ timeline uses `composer.model()`; a cached hidden timeline uses the committed
82
+ model. Compact headers show the icon only, with the full label as tooltip. The
83
+ exact order relative to native header actions is host-controlled; `order` only
84
+ sorts plugin contributions.
85
+ - **Home / draft:** `window.bottom` strip shown while no session is routed. It
86
+ uses `client.model.default()`; it may lag behind the Home picker until a session
87
+ starts.
88
+ - The parent session chip aggregates running subagents. A subagent's own header
89
+ follows that subagent's model.
90
+ - Settings → Extensions → Plugins can disable the GUI.
75
91
 
76
- ```sh
77
- git clone https://github.com/hugobatista/opencode-peak-badge.git ~/code/projects/opencode-peak-badge
78
- cd ~/code/projects/opencode-peak-badge
79
- bun install
80
- ```
92
+ ### OpenCode V1 (legacy)
81
93
 
82
- 2. Register the plugin in `~/.config/opencode/tui.json` with an absolute
83
- path to `src/index.tsx`:
94
+ `0.3.0` is the last V1-compatible release; npm `latest` is V2. Pin it:
84
95
 
85
- ```jsonc
86
- {
87
- "$schema": "https://opencode.ai/tui.json",
88
- "plugin": [
89
- "/home/your-user/code/projects/opencode-peak-badge/src/index.tsx"
90
- ]
91
- }
92
- ```
96
+ ```sh
97
+ opencode plugin opencode-peak-badge@opencode-v1 --global
98
+ ```
93
99
 
94
- The defaults below apply when no options are given. To override, use the
95
- tuple form (see [Configuration](#configuration)).
100
+ Or in `~/.config/opencode/tui.json`:
96
101
 
97
- 3. Restart OpenCode. Config is loaded at startup; there is no hot reload.
102
+ ```jsonc
103
+ { "plugin": ["opencode-peak-badge@opencode-v1"] }
104
+ ```
98
105
 
99
106
  ## Configuration
100
107
 
101
- Add options as the second element of a tuple entry:
102
-
103
108
  ```jsonc
104
109
  {
105
- "$schema": "https://opencode.ai/tui.json",
106
- "plugin": [
107
- [
108
- "/home/your-user/code/projects/opencode-peak-badge/src/index.tsx",
109
- {
110
+ "$schema": "https://opencode.ai/config.json",
111
+ "plugins": [
112
+ {
113
+ "package": "opencode-peak-badge",
114
+ "options": {
110
115
  "models": [
111
116
  "re:^opencode-go/deepseek",
112
117
  "re:^opencode/deepseek",
@@ -114,13 +119,9 @@ Add options as the second element of a tuple entry:
114
119
  ],
115
120
  "windows": [["01:00", "04:00"], ["06:00", "10:00"]],
116
121
  "weekdaysOnly": true,
117
- "pollSeconds": 10,
118
- "subagents": true,
119
- "alwaysShow": false,
120
- "labelPeak": "[PEAK]",
121
- "labelOffPeak": "[OFF-PEAK]"
122
+ "pollSeconds": 10
122
123
  }
123
- ]
124
+ }
124
125
  ]
125
126
  }
126
127
  ```
@@ -129,192 +130,108 @@ Add options as the second element of a tuple entry:
129
130
 
130
131
  | Option | Default | Description |
131
132
  |---|---|---|
132
- | `models` | built-in patterns for any DeepSeek model (OpenCode Go, OpenCode Zen, DeepSeek direct) | Models with peak hours. Override to track any `provider/model`. Each entry is a `"provider/model"` exact string, a `"re:<pattern>"` regex string, or an object with per-model `windows`/`weekdaysOnly` overrides. Matching is against the full `provider/model` key (case-insensitive). Exact `id` entries win over regex patterns; otherwise the first matching entry in list order wins. |
133
- | `windows` | `[["01:00","04:00"],["06:00","10:00"]]` | Peak windows in UTC. Each is `["HH:MM","HH:MM"]`, half-open `[start, end)`. A window whose end is ≤ its start wraps past midnight. |
134
- | `weekdaysOnly` | `true` | When true, weekends are always off-peak. |
135
- | `pollSeconds` | `10` | How often the badge recomputes (minimum 1). Also acts as a safety net to re-read `model.json` for picked model updates. |
136
- | `subagents` | `true` | Track subagent sessions while they are busy. Peak wins over the main model's state. |
137
- | `alwaysShow` | `false` | When true, always show a badge for the main model, using the top-level `windows`/`weekdaysOnly` when no model rule matches. |
138
- | `labelPeak` | `"[PEAK]"` | Text shown during peak hours. |
139
- | `labelOffPeak` | `"[OFF-PEAK]"` | Text shown during off-peak hours. |
140
-
141
- `models` entries are additive to the defaults? No. Supplying `models`
142
- **replaces** the default list. Provide the full list you want tracked.
143
-
144
- ### Subagents
145
-
146
- When an OpenCode task spawns a subagent session, that child session carries a
147
- `parentID` pointing at the session that spawned it. The plugin registers child
148
- sessions from `session.created` / `session.updated` and tracks the child's
149
- model. Tracing the `parentID` chain, all **descendant** sessions of the current
150
- one participate — a subagent's own subagents count too. While a session is
151
- `busy`, its model enters the badge computation:
152
-
153
- - If any busy subagent has a matching rule and is in peak hours, the badge
154
- shows `[PEAK]`, whatever the main model says (`peak` wins).
155
- - Otherwise the badge follows the main model's state.
156
- - Idle or deleted subagent sessions are ignored.
157
- - Subagent sessions whose model has no configured peak hours add nothing.
158
- - `session.status` events refresh the badge immediately when a subagent goes
159
- busy or idle; no need to wait for the next poll tick.
160
-
161
- `alwaysShow` only affects the main model; a subagent never renders a badge from
162
- the fallback windows. Set `subagents: false` to ignore subagents entirely.
163
-
164
- ### Agent switches (plan / build) with different models
165
-
166
- When agents in a session use different models, the badge follows the change
167
- from `session.next.model.switched` and `message.updated`. There is one
168
- limitation: the TUI Tab agent cycle does **not** emit any event or persist the
169
- chosen model — the cycle and the per-agent model pick are stored only in the
170
- TUI's local state (`agent.move` + `agent.moveModel`, solid signals). The plugin
171
- cannot observe them.
172
-
173
- Concretely, between pressing Tab and submitting the next prompt the badge
174
- keeps the last known session model. On prompt submission OpenCode publishes
175
- `session.next.model.switched` (with the model selected for that agent) and
176
- `message.updated` (with the resolved assistant/user model), and the badge
177
- updates in the same tick.
178
-
179
- If you need an immediate update, pick the model explicitly from the model
180
- list — this writes to `model.json` and the badge reacts immediately.
181
-
182
- This behavior was verified on OpenCode 1.18.x. If a future version starts
183
- emitting an event on agent cycle, the badge will react automatically.
184
-
185
- ### alwaysShow
186
-
187
- By default the plugin shows nothing for models without a matching rule. Set
188
- `alwaysShow: true` to always render a badge in the prompt bar: unmatched main
189
- models use the top-level `windows` / `weekdaysOnly` (defaults or your
190
- overrides). Combined with `subagents`, a busy subagent in peak hours still wins
191
- over an off-peak main model.
192
-
193
- ## Background: peak pricing is property of channel + model
194
-
195
- Peak hours are a property of the **channel + model pair**, not of the model
196
- alone. The plugin is provider-agnostic: it renders a badge whenever the active
197
- `provider/model` key matches a configured rule, and prices are billable at peak
198
- in the channels you configure. Add any model you care about — the plugin does
199
- not know or care which provider it belongs to.
200
-
201
- The built-in defaults target DeepSeek models, because that is where peak
202
- pricing is known today. Current facts (per OpenCode docs):
203
-
204
- - **OpenCode Go** — DeepSeek V4 Pro, V4 Flash and V4 Flash Vision Exp: peak =
205
- Mon–Fri 01:00–04:00 and 06:00–10:00 UTC; everything else, including weekends,
206
- is off-peak (2× price in peak). No other Go model has peak hours. The same
207
- windows apply to newer ids such as `deepseek-v4.1-*`. OpenCode also exposes
208
- Flash as the alias `opencode-go/deepseek-flash`; the default patterns match
209
- every `opencode-go/deepseek*` id.
210
- - **OpenCode Zen** — bills the same DeepSeek models (`opencode/deepseek-*`) at
211
- DeepSeek's list price, so the same peak windows apply.
212
- - **DeepSeek direct API (BYOK)** — the same peak windows apply to
213
- `deepseek/deepseek-*`.
214
-
215
- In Lisbon time (WEST, UTC+1) the DeepSeek windows are 02:00–05:00 and
216
- 07:00–11:00; in winter (WET, UTC+0) the UTC windows apply as-is. The plugin
217
- computes in UTC, so DST is a non-issue.
218
-
219
- ### Exact matching
220
-
221
- Match one `provider/model` id exactly (case-insensitive). This is the simplest
222
- form and avoids regex entirely:
133
+ | `models` | DeepSeek patterns | Rules to track. Replaces the defaults. Strings are exact `provider/model` or `re:<regex>`; objects add per-model `windows`/`weekdaysOnly`. An empty array tracks nothing. |
134
+ | `windows` | `[["01:00","04:00"],["06:00","10:00"]]` | Peak windows in UTC. Each is `["HH:MM","HH:MM"]`, half-open; end ≤ start wraps midnight. An empty array means no peak windows. |
135
+ | `weekdaysOnly` | `true` | Weekends are always off-peak. |
136
+ | `pollSeconds` | `10` | Recompute interval (minimum 1). Live events also trigger updates. |
137
+ | `fakeTime` | unset | Fixed ISO timestamp for testing. Overrides `OPENCODE_PEAK_HOURS_FAKE_TIME` in the TUI and works in Desktop. |
138
+ | `subagents` | `true` | Include running subagent sessions; peak wins. |
139
+ | `alwaysShow` | `false` | Show the main model even without a matching rule, using the top-level windows. |
140
+ | `labelPeak` | `"[PEAK]"` | Peak label. |
141
+ | `labelOffPeak` | `"[OFF-PEAK]"` | Off-peak label. |
142
+ | `debug` | `false` | Append the detected `provider/model` to the badge. |
143
+
144
+ `models` **replaces** the default list; provide every model you want tracked. An
145
+ empty array tracks nothing.
146
+
147
+ ### Model matching
148
+
149
+ - Exact `provider/model`, case-insensitive.
150
+ - `re:<pattern>` regex, case-insensitive.
151
+ - Object form for per-model overrides: `{ "id": "provider/model", "windows": [...], "weekdaysOnly": false }`, or the same with `pattern` instead of `id`.
152
+ - Exact entries beat regex patterns; otherwise the first match wins. Invalid
153
+ patterns are ignored.
154
+ - JSON escapes backslashes: use `"re:^opencode-go/deepseek\\.v4"`.
223
155
 
224
156
  ```jsonc
225
- {
226
- "models": [
227
- "opencode-go/deepseek-v4-flash",
228
- "opencode/deepseek-v4-pro"
229
- ]
230
- }
157
+ "models": [
158
+ "opencode-go/deepseek-v4-flash",
159
+ "re:^opencode/deepseek",
160
+ { "pattern": "^my-provider/.*$", "windows": [["09:00", "17:00"]], "weekdaysOnly": false }
161
+ ]
231
162
  ```
232
163
 
233
- Give a single model its own windows or weekday behavior with the object form:
164
+ ## Behavior
234
165
 
235
- ```jsonc
236
- {
237
- "models": [
238
- { "id": "opencode-go/deepseek-v4-flash", "windows": [["09:00", "17:00"]], "weekdaysOnly": false }
239
- ]
240
- }
241
- ```
166
+ - **TUI model source:** committed session model, plus the uncommitted picker
167
+ selection from `$XDG_STATE_HOME/opencode/model.json`. A committed model wins;
168
+ Home uses the pick, then `client.model.default()`.
169
+ - **Subagents:** running descendants from `data.session.family()`; peak wins.
170
+ `subagents: false` ignores them; `alwaysShow` only affects the main model.
171
+ - **Peak hours:** UTC defaults are Mon–Fri 01:00–04:00 and 06:00–10:00, weekends
172
+ off-peak. Defaults cover DeepSeek on OpenCode Go, OpenCode Zen and the DeepSeek
173
+ direct API; add rules for any other provider/model.
174
+ - **TUI agent cycle:** the Tab agent cycle may not update until the next prompt;
175
+ selecting a model explicitly updates immediately.
176
+
177
+ ## Evaluation
178
+
179
+ TUI, before launching:
242
180
 
243
- ### Regex matching
181
+ ```sh
182
+ OPENCODE_PEAK_HOURS_FAKE_TIME=2026-09-07T08:30:00Z opencode # peak
183
+ OPENCODE_PEAK_HOURS_FAKE_TIME=2026-09-07T12:00:00Z opencode # off-peak
184
+ ```
244
185
 
245
- Exact ids match one model. To track every current and future model id that
246
- fits a pattern, use the `re:` prefix on a string, or the `pattern` object form
247
- (which also allows per-model overrides):
186
+ Desktop uses the `fakeTime` option, because the Electron renderer may not receive
187
+ the environment variable:
248
188
 
249
189
  ```jsonc
250
190
  {
251
- "models": [
252
- "re:^opencode-go/deepseek",
253
- { "pattern": "^my-provider/.*$", "windows": [["09:00", "17:00"]] }
191
+ "plugins": [
192
+ {
193
+ "package": "opencode-peak-badge",
194
+ "options": { "fakeTime": "2026-09-07T08:30:00Z" }
195
+ }
254
196
  ]
255
197
  }
256
198
  ```
257
199
 
258
- Matching rules:
259
-
260
- - Patterns are compiled case-insensitively and tested against the full
261
- `provider/model` key.
262
- - An exact `id` entry always beats a regex pattern, regardless of list order.
263
- - Otherwise the first matching entry wins (list order).
264
- - An invalid or empty pattern is ignored.
265
-
266
- Escaping: `models` is JSON, so backslashes must be doubled. For example, to
267
- match a literal dot use `"re:^opencode-go/deepseek\\.v4"`. To avoid escaping,
268
- prefer plain `-` and `?` characters as in the defaults above.
269
-
270
- ## Evaluation
271
-
272
- Set the environment variable before launching OpenCode to force a specific
273
- instant. The variable is read on every tick, so changing it mid-session takes
274
- effect within `pollSeconds`:
275
-
276
- ```sh
277
- OPENCODE_PEAK_HOURS_FAKE_TIME=2026-09-07T08:30:00Z opencode # peak (Mon 08:30 UTC)
278
- OPENCODE_PEAK_HOURS_FAKE_TIME=2026-09-07T12:00:00Z opencode # off-peak (Mon 12:00 UTC)
279
- ```
280
-
281
- Unset the variable to use real time.
200
+ `fakeTime` overrides the TUI environment variable. Remove it to use real time.
282
201
 
283
202
  ## Uninstall
284
203
 
285
- Remove the plugin entry from `plugin` in `~/.config/opencode/tui.json` and
286
- restart OpenCode.
287
-
288
- ## Development
289
-
290
204
  ```sh
291
- bun install
292
- bun run typecheck # tsc --noEmit, strict
293
- bun test # unit (core logic) + functional (mocked TUI api)
294
- bun run build # dist/tui.js + dist/tui.d.ts (npm entrypoint)
205
+ opencode plugin remove opencode-peak-badge
295
206
  ```
296
207
 
297
- - `src/core.ts` — pure logic: window parsing, UTC peak check, per-model config
298
- resolution. No TUI imports. Fully unit-tested.
299
- - `src/index.tsx` — the TUI plugin (`id: "peak-badge"`). The plugin loader
300
- reads the default export only; the `__test` named export is a test hook.
301
- - `scripts/build.ts` — bundles `src/index.tsx` to `dist/tui.js` with
302
- `@opencode-ai/plugin`, `@opentui/*` and `solid-js` external. The npm
303
- `exports["./tui"]` entry points at `dist`, never at `src` (the Solid
304
- transform does not run inside `node_modules`).
208
+ Or remove the entry from `opencode.jsonc` / `cli.json`. Desktop only reads
209
+ `opencode.json(c)`.
305
210
 
306
- ## Pre-release checklist
211
+ ## Development
307
212
 
308
213
  ```sh
309
214
  bun install
310
- bun run typecheck
311
- bun test
312
- bun run build
313
- npm pack --dry-run
215
+ bun run typecheck # TUI + GUI TypeScript configs
216
+ bun test # core + mocked TUI tests
217
+ bun run build # dist/tui.js, dist/server.js, dist/gui-experimental.cjs
314
218
  ```
315
219
 
316
- Inspect the pack list (`dist/`, `README.md`, `LICENSE` only). Scan for
317
- secrets before `npm publish`.
220
+ Local development: build, add the absolute repository directory to
221
+ `opencode.json(c)`, then reload. A local directory with `name` and `exports`
222
+ resolves `./tui`, `.` (server) and `./gui-experimental`; Desktop needs
223
+ `dist/gui-experimental.cjs`. For TUI-only development, point at `src/index.tsx`
224
+ instead.
225
+
226
+ - `src/core.ts` — pure rules, badge/subagent resolution and the fake-time clock.
227
+ - `src/index.tsx` — TUI part (`id: peak-badge`).
228
+ - `src/gui.tsx` — Desktop part (`session.header` chip + `window.bottom`).
229
+ - `src/server.ts` — identity-only server part; gives the GUI the `peak-badge` id.
230
+ - `scripts/build.ts` — TUI and server bundles; `vite.config.ts` — GUI CJS bundle.
231
+
232
+ Release check: `npm pack --dry-run`. The package must include `dist/tui.js`,
233
+ `dist/server.js` and `dist/gui-experimental.cjs`; scan for secrets before
234
+ publishing.
318
235
 
319
236
  ## License
320
237
 
package/dist/core.d.ts CHANGED
@@ -18,6 +18,7 @@ export type PeakHoursOptions = {
18
18
  windows?: WindowSpec[];
19
19
  weekdaysOnly?: boolean;
20
20
  pollSeconds?: number;
21
+ fakeTime?: string;
21
22
  labelPeak?: string;
22
23
  labelOffPeak?: string;
23
24
  subagents?: boolean;
@@ -39,8 +40,13 @@ export type BadgeState = {
39
40
  label: string;
40
41
  peak: boolean;
41
42
  };
43
+ export type ModelRef = {
44
+ providerID: string;
45
+ id: string;
46
+ };
42
47
  export declare const DEFAULT_WINDOWS: WindowSpec[];
43
48
  export declare const DEFAULT_MODELS: ModelEntrySpec[];
49
+ export declare function currentNow(fakeTime?: string, realNow?: Date): Date;
44
50
  export declare function parseHHMM(value: string): number | undefined;
45
51
  export declare function parseWindow(spec: WindowSpec): MinuteWindow | undefined;
46
52
  export declare function parseWindows(specs: readonly WindowSpec[]): MinuteWindow[];
@@ -54,3 +60,20 @@ export declare function badgeFor(now: Date, rule: ResolvedModelRule | undefined,
54
60
  offPeak: string;
55
61
  }): BadgeState | undefined;
56
62
  export declare function mergeBadges(states: Array<BadgeState | undefined>): BadgeState | undefined;
63
+ export declare function badgeForModels(input: {
64
+ now: Date;
65
+ rules: RuleSet;
66
+ labels: {
67
+ peak: string;
68
+ offPeak: string;
69
+ };
70
+ main: ModelRef | undefined;
71
+ subagents: readonly ModelRef[];
72
+ alwaysShow: boolean;
73
+ }): BadgeState | undefined;
74
+ export declare function runningSubagentRefs(input: {
75
+ sessionID: string;
76
+ family: (sessionID: string) => readonly string[];
77
+ status: (sessionID: string) => "idle" | "running";
78
+ model: (sessionID: string) => ModelRef | undefined;
79
+ }): ModelRef[];
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const a=require("solid-js/web"),v=require("@opencode/plugin/gui"),g=require("solid-js"),j=[["01:00","04:00"],["06:00","10:00"]],V=["re:^opencode-go/deepseek","re:^opencode/deepseek","re:^deepseek/deepseek"];function I(e,t=new Date){if(e){const n=new Date(e);if(!Number.isNaN(n.getTime()))return n}return t}function O(e){const t=/^(\d{1,2}):(\d{2})$/.exec(e.trim());if(!t)return;const n=Number(t[1]),o=Number(t[2]);if(!(n>23||o>59))return n*60+o}function J(e){const t=O(e[0]),n=O(e[1]);if(!(t===void 0||n===void 0))return{start:t,end:n}}function k(e){const t=[];for(const n of e){const o=J(n);o&&t.push(o)}return t}function G(e,t){return t.end<=t.start?e>=t.start||e<t.end:e>=t.start&&e<t.end}function Q(e,t,n=!0){if(n){const i=e.getUTCDay();if(i===0||i===6)return!1}const o=e.getUTCHours()*60+e.getUTCMinutes();return t.some(i=>G(o,i))}function T(e,t){return`${e}/${t}`.trim().toLowerCase()}function P(e,t,n,o){return{id:e,windows:t.windows?.length?k(t.windows):n,weekdaysOnly:t.weekdaysOnly??o}}function X(e={}){const t=k(e.windows??j),n=e.weekdaysOnly??!0,o=e.models??V,i=new Map,w=[];for(const f of o)if(typeof f=="string"){const c=f.trim();if(!c)continue;if(c.toLowerCase().startsWith("re:")){const m=c.slice(3);if(!m.trim())continue;const h=$(m);if(!h)continue;w.push({id:m,regex:h,windows:t,weekdaysOnly:n})}else{const m=c.toLowerCase();i.set(m,P(m,{},t,n))}}else if("pattern"in f){const c=f.pattern;if(!c.trim())continue;const m=$(c);if(!m)continue;w.push({id:c,regex:m,windows:f.windows?.length?k(f.windows):t,weekdaysOnly:f.weekdaysOnly??n})}else{const c=f.id.trim().toLowerCase();if(!c)continue;i.set(c,P(c,f,t,n))}return{exact:i,patterns:w,fallback:{id:"",windows:t,weekdaysOnly:n}}}function Y(e){let t=0,n=!1;for(let o=0;o<e.length;o++){const i=e[o];if(i==="\\"){o++;continue}if(i==="["){n=!0;continue}if(i==="]"){n=!1;continue}if(!n){if(i==="(")t++;else if(i===")")t=Math.max(0,t-1);else if(t>0&&"+*}".includes(i))return!1}}return!0}function $(e){try{return Y(e)?new RegExp(e,"i"):void 0}catch{return}}function N(e,t){const n=e.exact.get(t);if(n)return n;for(const o of e.patterns)if(o.regex.test(t))return o}function R(e,t,n){if(!t)return;const o=Q(e,t.windows,t.weekdaysOnly);return{label:o?n.peak:n.offPeak,peak:o}}function Z(e){let t;for(const n of e)if(n){if(!t){t=n;continue}n.peak&&!t.peak&&(t=n)}return t}function W(e){const t=[];if(e.main){const n=N(e.rules,T(e.main.providerID,e.main.id))??(e.alwaysShow?e.rules.fallback:void 0),o=R(e.now,n,e.labels);o&&t.push(o)}for(const n of e.subagents){const o=R(e.now,N(e.rules,T(n.providerID,n.id)),e.labels);o&&t.push(o)}return Z(t)}function ee(e){const t=[],n=new Set,o=[...e.family(e.sessionID)];for(;o.length>0;){const i=o.pop();if(!(!i||n.has(i))){if(n.add(i),e.status(i)==="running"){const w=e.model(i);w&&t.push(w)}for(const w of e.family(i))n.has(w)||o.push(w)}}return t}var L=a.template("<span>");const te={display:"inline-flex","align-items":"center",gap:"4px","font-size":"11px","font-weight":"600","letter-spacing":"0.02em","white-space":"nowrap"};function b(e){return e?.providerID&&e.id?{providerID:e.providerID,id:e.id}:void 0}function ne(e){return e?{providerID:e.providerID,id:e.modelID}:void 0}const se=v.Plugin.define({setup(e){const t=e.options??{},n=X(t),o={peak:t.labelPeak??"[PEAK]",offPeak:t.labelOffPeak??"[OFF-PEAK]"},i=Math.max(1,Number(t.pollSeconds)||10),w=t.subagents??!0,f=t.alwaysShow??!1,c=t.debug??!1,m=typeof t.fakeTime=="string"?t.fakeTime:void 0,[h,x]=g.createSignal(I(m).getTime()),[A,E]=g.createSignal(void 0),p=new Set;function S(s,r,d){p.has(r)||(p.add(r),s.sync(d).catch(()=>p.delete(r)))}function D(s){const r=c&&s.model?`${s.model.providerID}/${s.model.id}`:"";return[s.state?.label??"",r].filter(Boolean).join(" ")}function F(s){const r=s.active===!1?void 0:ne(s.screen.composer.model());if(r)return r;const d=s.session.server.data.session,l=b(d.get(s.session.id)?.model);return l||S(d,s.session.key,s.session.id),l}function U(s,r){const d=s.session.server.data.session,l=b(d.get(r)?.model);return l||S(d,`${s.session.server.id}
2
+ ${r}`,r),l}function H(s){const r=F(s),d=w?ee({sessionID:s.session.id,family:u=>s.session.server.data.session.family(u),status:u=>s.session.server.data.session.status(u),model:u=>U(s,u)}):[];return{state:W({now:new Date(h()),rules:n,labels:o,main:r,subagents:d,alwaysShow:f}),model:r}}function _(s){const r=g.createMemo(()=>H(s.input));return a.createComponent(g.Show,{get when(){return D(r())},children:d=>(()=>{var l=L();return a.style(l,te),a.insert(l,a.createComponent(g.Show,{get when(){return r().state},children:u=>a.createComponent(g.Show,{get when(){return u().peak},get fallback(){return a.createComponent(e.ui.Icon,{name:"circle-check",size:"small"})},get children(){return a.createComponent(e.ui.Icon,{name:"warning",size:"small"})}})}),null),a.insert(l,a.createComponent(g.Show,{get when(){return!s.input.compact},get children(){return d()}}),null),a.effect(u=>{var C=d(),M=s.input.compact?d():void 0;return C!==u.e&&a.setAttribute(l,"title",u.e=C),M!==u.t&&a.setAttribute(l,"aria-label",u.t=M),u},{e:void 0,t:void 0}),l})()})}const B=g.createMemo(()=>{const s=A();return{state:W({now:new Date(h()),rules:n,labels:o,main:s,subagents:[],alwaysShow:f}),model:s}});function K(){const s=D(B());return s?(()=>{var r=L();return a.insert(r,s),r})():null}async function y(){try{const s=await e.client.model.default();E(b(s.data))}catch{}}y();function q(){try{for(const s of e.servers.list()){const r=e.servers.get(s);if(r?.builtin)return r.data}}catch{}}v.createKeyed(()=>q(),s=>g.onCleanup(s.on("model.updated",()=>{y()})));const z=setInterval(()=>{x(I(m).getTime()),e.sessions.current()||y()},i*1e3);return e.add(v.Slot,{at:"session.header",order:100,render:s=>a.createComponent(_,{input:s})}),e.add(v.Slot,{at:"window.bottom",order:10,render:()=>a.createComponent(g.Show,{get when(){return!e.sessions.current()},get children(){return a.createComponent(K,{})}})}),()=>{clearInterval(z)}}});exports.default=se;
@@ -0,0 +1,3 @@
1
+ import { Plugin } from "@opencode/plugin";
2
+ declare const _default: Plugin.Plugin;
3
+ export default _default;
package/dist/server.js ADDED
@@ -0,0 +1,11 @@
1
+ // src/server.ts
2
+ import { Plugin } from "@opencode/plugin";
3
+ var server_default = Plugin.define({
4
+ id: "peak-badge",
5
+ setup() {}
6
+ });
7
+ export {
8
+ server_default as default
9
+ };
10
+
11
+ //# debugId=7462091FD6D1ECD864756E2164756E21
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/server.ts"],
4
+ "sourcesContent": [
5
+ "import { Plugin } from \"@opencode/plugin\"\n\n// Identity-only server part. It gives the package (and therefore its GUI part)\n// the id `peak-badge`, matching the TUI part. The badge itself is computed in\n// each client; nothing runs here.\nexport default Plugin.define({\n id: \"peak-badge\",\n setup() {},\n})\n"
6
+ ],
7
+ "mappings": ";AAAA;AAKA,IAAe,wBAAO,OAAO;AAAA,EAC3B,IAAI;AAAA,EACJ,KAAK,GAAG;AACV,CAAC;",
8
+ "debugId": "7462091FD6D1ECD864756E2164756E21",
9
+ "names": []
10
+ }
package/dist/tui.d.ts CHANGED
@@ -1,13 +1,12 @@
1
- import type { TuiPluginModule } from "@opencode-ai/plugin/tui";
2
- import { badgeFor } from "./core";
3
- type TestBadge = (sessionID?: string) => ReturnType<typeof badgeFor>;
1
+ /** @jsxImportSource @opentui/solid */
2
+ import { Plugin } from "@opencode/plugin/tui";
3
+ import { type BadgeState } from "./core";
4
+ declare const _default: Plugin.Definition;
5
+ export default _default;
4
6
  export declare const __test: {
5
- badge: TestBadge | undefined;
7
+ badge: ((sessionID?: string) => BadgeState | undefined) | undefined;
6
8
  badgeText: ((sessionID?: string) => string) | undefined;
7
- refresh: (() => void) | undefined;
9
+ refresh: ((date?: Date) => void) | undefined;
8
10
  applyRecentModel: (() => Promise<void>) | undefined;
11
+ refreshHomeModel: (() => Promise<void>) | undefined;
9
12
  };
10
- declare const plugin: TuiPluginModule & {
11
- id: string;
12
- };
13
- export default plugin;