@david18284/dsh-provider-quota 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 David Li
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,130 @@
1
- # Temporary Holding Version
1
+ # dsh-provider-quota
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Subscription quota for your model provider, inside [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness):
4
+ a composer pill that follows the selected model, a popover with the reported windows, and a
5
+ `provider_quota` agent tool. Ships with an **OpenCode Go** reader.
6
+
7
+ [![npm](https://img.shields.io/npm/v/@david18284/dsh-provider-quota?color=blue)](https://www.npmjs.com/package/@david18284/dsh-provider-quota)
8
+ [![license](https://img.shields.io/npm/l/@david18284/dsh-provider-quota)](./LICENSE)
9
+
10
+ ![Quota popover](./docs/media/popover.png)
11
+
12
+ ## What it adds
13
+
14
+ - **Composer pill** — a compact pill next to the host's own readings
15
+ (`39.7M tok · Cache hit 97%`, the context ring): gauge icon, provider label, and the worst
16
+ window's remaining share. It uses the host's pill styling, stays neutral above 20 % left, and
17
+ turns amber at ≤ 20 % and red at ≤ 10 %.
18
+ - **Popover** — click the pill for every reported window: remaining share, a bar, and the time
19
+ until it resets, in a surface styled like the host's statistics dialogs. It reads on open, every
20
+ 60 s while open, and on demand; folded away it reads every 5 minutes.
21
+ - **Follows the selected model provider** — the pill appears only while the session's model runs on
22
+ a provider this bundle can read, and disappears for any other provider without a reload.
23
+ - **`provider_quota` agent tool** — any session can ask for the current quota; returns structured
24
+ numbers per window plus a plain-text summary. Optional `provider` argument; provider defaults to
25
+ the only supported provider when unambiguous.
26
+
27
+ ![Pill in the composer dock](./docs/media/pill-row.png)
28
+
29
+ ## Requirements
30
+
31
+ - DeepSeek Harness `0.2.2-rc.5` or newer (until `0.3.0`), with the Web GUI for the pill.
32
+ - Node.js `>= 24.9.0` (the harness's own floor).
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ dsh plugin --profile web add @david18284/dsh-provider-quota
38
+ ```
39
+
40
+ Or in the Web GUI: **Plugins → Add plugin →** enter the package name. Reload the page once so the
41
+ client module is picked up. Verify with **Plugins → Provider quota** and look for the pill in the
42
+ composer dock of any conversation.
43
+
44
+ Uninstall:
45
+
46
+ ```bash
47
+ dsh plugin --profile web remove @david18284/dsh-provider-quota
48
+ ```
49
+
50
+ ## Use
51
+
52
+ ### Pill thresholds
53
+
54
+ | Remaining quota | Pill icon + reading | Popover bars |
55
+ |---|---|---|
56
+ | > 20 % | neutral | green |
57
+ | ≤ 20 % | amber | amber |
58
+ | ≤ 10 % | red | red |
59
+
60
+ ### Agent tool
61
+
62
+ ```
63
+ provider_quota() # only supported provider, when unambiguous
64
+ provider_quota({"provider": "opencode-go"})
65
+ ```
66
+
67
+ Sample result:
68
+
69
+ ```
70
+ OpenCode Go quota (read 2026-11-28T12:13:14.435Z)
71
+ 5h: 94% left (6% used, resets 2026-11-28T16:02:06.000Z)
72
+ Weekly: 51% left (49% used, resets 2026-11-30T00:00:00.000Z)
73
+ Monthly: 76% left (24% used, resets 2026-12-26T04:33:19.000Z)
74
+ ```
75
+
76
+ ## Supported providers
77
+
78
+ | Provider id | Plan | Windows | Credential |
79
+ |---|---|---|---|
80
+ | `opencode-go` | OpenCode Go | 5-hour, weekly, monthly | `OPENCODE_API_KEY`, else the OpenCode CLI's `auth.json` |
81
+
82
+ The OpenCode Go usage endpoint (`https://opencode.ai/zen/go/v1/usage`) is **not documented as a
83
+ public API**; treat the reader as experimental and expect it to need updating if that endpoint
84
+ changes. A provider failure only removes that provider's surface — the plugin leaves the harness
85
+ and every other provider untouched.
86
+
87
+ ### Adding a provider
88
+
89
+ Both halves keep a small registry:
90
+
91
+ 1. `quota.js` → add an entry to `PROVIDERS` with a label and a `read()` that resolves the
92
+ credential and normalizes the reply to `{ provider, label, fetchedAt, windows[] }`.
93
+ 2. `client.js` → add the same provider id and label to `QUOTA_PROVIDERS`.
94
+
95
+ Caching is per provider; the RPC channel and the tool accept the provider id, and the pill appears
96
+ automatically while that provider is selected. PRs welcome.
97
+
98
+ ## Privacy and credentials
99
+
100
+ - The credential is read **in the harness host process only**; it never reaches the browser or the
101
+ session log.
102
+ - It is sent only to the provider's quota endpoint, and the browser reads quota through the
103
+ authenticated harness RPC bridge (`/provider-quota`), not a public HTTP route.
104
+ - Only quota percentages and reset times are exchanged; no prompts, completions, or session data.
105
+ - Nothing is sent if you never open the pill or call the tool beyond these scheduled reads.
106
+
107
+ ## Development
108
+
109
+ This bundle has no build step and no runtime dependencies: plain ES modules for the host, and one
110
+ `window.__ModuleLoader__` client module. The client reads the selected model provider from the
111
+ harness's model-directory service and asks the host for that provider's quota over RPC.
112
+
113
+ ```bash
114
+ npm run check # syntax + manifest invariants, no dependencies
115
+ npm pack --dry-run # inspect the publishable tarball
116
+ ```
117
+
118
+ For a linked developer install, point the plugin manager at this directory and reload the page.
119
+ Bundle layout: `index.js` (tool + RPC), `quota.js` (provider readers), `client.js` (pill and
120
+ popover), `cordis.patch.yml` (profile row), `locale/` (plugin metadata), `docs/DETAIL.md` (plugin
121
+ detail page).
122
+
123
+ ## Releases
124
+
125
+ Published with npm provenance from GitHub Actions using OIDC trusted publishing — no long-lived
126
+ tokens. Release notes live in [CHANGELOG.md](./CHANGELOG.md).
127
+
128
+ ## License
129
+
130
+ [MIT](./LICENSE) © 2026 David Li
package/client.js ADDED
@@ -0,0 +1,585 @@
1
+ /* Browser half of the provider quota bundle; shipped without a build step. */
2
+ window.__ModuleLoader__.load({
3
+ id: '@david18284/dsh-provider-quota',
4
+ factory(require) {
5
+ 'use strict';
6
+
7
+ const React = require('react');
8
+ const ReactDOM = require('react-dom');
9
+ const h = React.createElement;
10
+ const NS = 'provider-quota';
11
+ const CHANNEL = '/provider-quota';
12
+ /** Poll cadence while the popover is open, and while it is folded away. */
13
+ const OPEN_REFRESH_MS = 60_000;
14
+ const CLOSED_REFRESH_MS = 300_000;
15
+ /** Remaining-share cutoffs for the warning tones, in percent left. */
16
+ const AMBER_AT_PERCENT = 20;
17
+ const RED_AT_PERCENT = 10;
18
+
19
+ /**
20
+ * Provider ids this bundle can render, keyed by the harness LLM provider id.
21
+ * Keep in step with the Host's `PROVIDERS` map in quota.js. A future
22
+ * provider needs a Host reader (credential + normalization) and an entry
23
+ * here; the pill then appears only while that provider is selected.
24
+ */
25
+ const QUOTA_PROVIDERS = {
26
+ 'opencode-go': { label: 'OpenCode Go' },
27
+ };
28
+
29
+ /* Dictionaries for the panel copy; en is also the structural fallback. */
30
+ const en = {
31
+ 'group.label': '{provider} quota',
32
+ 'open': 'Show {provider} quota',
33
+ 'dialog.title': '{provider} quota',
34
+ 'close': 'Close quota',
35
+ 'window.fiveHour': '5h',
36
+ 'window.weekly': 'Weekly',
37
+ 'window.monthly': 'Monthly',
38
+ 'percentLeft': '{percent}%',
39
+ 'percentLeftLong': '{percent}% left',
40
+ 'loading': 'Checking quota…',
41
+ 'error.short': 'Quota unavailable',
42
+ 'retry': 'Retry',
43
+ 'refresh': 'Refresh quota',
44
+ 'refreshing': 'Refreshing…',
45
+ 'updated': 'Updated {time}',
46
+ 'resetsIn': 'Resets in {when}',
47
+ 'resetsAt': 'Resets {when}',
48
+ 'never': 'Reset time not reported',
49
+ 'source': 'Provider-reported',
50
+ };
51
+ const zh = {
52
+ 'group.label': '{provider} 额度',
53
+ 'open': '显示 {provider} 额度',
54
+ 'dialog.title': '{provider} 额度',
55
+ 'close': '关闭额度',
56
+ 'window.fiveHour': '5 小时',
57
+ 'window.weekly': '每周',
58
+ 'window.monthly': '每月',
59
+ 'percentLeft': '{percent}%',
60
+ 'percentLeftLong': '剩余 {percent}%',
61
+ 'loading': '正在查询额度…',
62
+ 'error.short': '额度不可用',
63
+ 'retry': '重试',
64
+ 'refresh': '刷新额度',
65
+ 'refreshing': '正在刷新…',
66
+ 'updated': '更新于 {time}',
67
+ 'resetsIn': '{when}后重置',
68
+ 'resetsAt': '{when}重置',
69
+ 'never': '未报告重置时间',
70
+ 'source': '服务商报告',
71
+ };
72
+
73
+ /** Message template for the active dictionary chain. */
74
+ function translate(key, vars) {
75
+ const template = en[key] ?? key;
76
+ return template.replace(/\{(\w+)\}/g, (_match, name) =>
77
+ vars && vars[name] !== undefined ? String(vars[name]) : `{${name}}`);
78
+ }
79
+
80
+ /** Clamp a percentage into the bar's drawing range. */
81
+ function clampPercent(value) {
82
+ const number = Number(value);
83
+ return Number.isFinite(number) ? Math.max(0, Math.min(100, number)) : 0;
84
+ }
85
+
86
+ /** Severity color for a remaining share, from the host theme. */
87
+ function toneToken(remaining) {
88
+ if (remaining <= RED_AT_PERCENT) return 'var(--dsw-alias-state-error-primary)';
89
+ if (remaining <= AMBER_AT_PERCENT) return 'var(--dsw-alias-state-warn-primary)';
90
+ return 'var(--dsw-alias-state-success-primary)';
91
+ }
92
+
93
+ /** Compact distance from now to an ISO timestamp, such as `4h 19m` or `1d 12h`. */
94
+ function formatDistance(iso, now) {
95
+ const target = Date.parse(iso);
96
+ if (!Number.isFinite(target)) return '';
97
+ const minutes = Math.max(0, Math.round(Math.abs(target - now) / 60_000));
98
+ if (minutes < 60) return `${minutes}m`;
99
+ const hours = Math.floor(minutes / 60);
100
+ const restMinutes = minutes % 60;
101
+ if (hours < 24) return restMinutes === 0 ? `${hours}h` : `${hours}h ${restMinutes}m`;
102
+ const days = Math.floor(hours / 24);
103
+ const restHours = hours % 24;
104
+ return restHours === 0 ? `${days}d` : `${days}d ${restHours}h`;
105
+ }
106
+
107
+ /** Local clock time for the `updated` hint. */
108
+ function formatClock(iso) {
109
+ const date = new Date(iso);
110
+ if (Number.isNaN(date.getTime())) return '—';
111
+ return date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
112
+ }
113
+
114
+ /** Local date and time for a reset tooltip. */
115
+ function formatMoment(iso) {
116
+ const date = new Date(iso);
117
+ if (Number.isNaN(date.getTime())) return '';
118
+ return date.toLocaleString(undefined, {
119
+ month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
120
+ });
121
+ }
122
+
123
+ /* Same compact control as the composer statistics pills: shrink-wrapped
124
+ * anchor, transparent reading at rest, hover/expanded fill from the host. */
125
+ const dockStyle = {
126
+ display: 'inline-flex',
127
+ minWidth: 0,
128
+ fontSize: 'calc(var(--dsh-content-font-size-secondary, 13px) - 1px)',
129
+ lineHeight: 'calc(20px + var(--dsh-content-font-delta-secondary, 0px))',
130
+ };
131
+ const pillStyle = {
132
+ all: 'unset',
133
+ boxSizing: 'border-box',
134
+ display: 'inline-flex',
135
+ alignItems: 'center',
136
+ gap: 6,
137
+ maxWidth: '100%',
138
+ padding: '1px 8px',
139
+ border: 'none',
140
+ borderRadius: 'var(--dsw-radius-sm)',
141
+ background: 'transparent',
142
+ font: 'inherit',
143
+ fontVariantNumeric: 'tabular-nums',
144
+ lineHeight: 'inherit',
145
+ whiteSpace: 'nowrap',
146
+ cursor: 'pointer',
147
+ };
148
+ const pillLabelStyle = {
149
+ minWidth: 0,
150
+ overflow: 'hidden',
151
+ textOverflow: 'ellipsis',
152
+ };
153
+ const pillReadingStyle = {
154
+ flex: 'none',
155
+ fontVariantNumeric: 'tabular-nums',
156
+ };
157
+ const pillSeparatorStyle = { color: 'var(--dsw-alias-separator-primary)' };
158
+ /* Matches the host's menu material: translucent surface, backdrop blur,
159
+ * prominent elevation, and the [data-menu-material] dark-scheme stroke. */
160
+ const panelStyle = {
161
+ position: 'fixed',
162
+ zIndex: 1100,
163
+ boxSizing: 'border-box',
164
+ display: 'grid',
165
+ gap: 10,
166
+ padding: 16,
167
+ borderRadius: 'var(--dsw-radius-lg)',
168
+ border: 0,
169
+ background: 'var(--dsw-specific-menu)',
170
+ backdropFilter: 'var(--dsw-menu-backdrop-filter)',
171
+ WebkitBackdropFilter: 'var(--dsw-menu-backdrop-filter)',
172
+ boxShadow: 'var(--dsw-elevation-prominent)',
173
+ color: 'var(--dsw-alias-label-primary)',
174
+ fontSize: 12,
175
+ lineHeight: '18px',
176
+ };
177
+ const headerStyle = {
178
+ display: 'flex',
179
+ alignItems: 'center',
180
+ justifyContent: 'space-between',
181
+ gap: 12,
182
+ color: 'var(--dsw-alias-label-primary)',
183
+ fontWeight: 500,
184
+ };
185
+ const titleStyle = { display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0 };
186
+ const titleRuleStyle = {
187
+ marginTop: -2,
188
+ marginBottom: 0,
189
+ borderTop: '0.5px solid var(--dsw-alias-border-l2)',
190
+ };
191
+ const closeButtonStyle = {
192
+ all: 'unset',
193
+ cursor: 'pointer',
194
+ color: 'var(--dsw-alias-label-tertiary)',
195
+ fontSize: 14,
196
+ lineHeight: '18px',
197
+ padding: '0 2px',
198
+ borderRadius: 4,
199
+ };
200
+ const rowStyle = { display: 'grid', gap: 4 };
201
+ const rowHeadStyle = {
202
+ display: 'flex',
203
+ alignItems: 'baseline',
204
+ justifyContent: 'space-between',
205
+ gap: 12,
206
+ };
207
+ const rowLabelStyle = { color: 'var(--dsw-alias-label-secondary)' };
208
+ const rowValueStyle = { fontVariantNumeric: 'tabular-nums', fontWeight: 500 };
209
+ const rowResetStyle = { color: 'var(--dsw-alias-label-tertiary)', fontSize: 11.5 };
210
+ const barTrackStyle = {
211
+ display: 'block',
212
+ height: 5,
213
+ borderRadius: 3,
214
+ overflow: 'hidden',
215
+ background: 'var(--dsw-alias-interactive-bg-hover)',
216
+ };
217
+ const footerStyle = {
218
+ display: 'flex',
219
+ alignItems: 'center',
220
+ justifyContent: 'space-between',
221
+ gap: 12,
222
+ paddingTop: 8,
223
+ borderTop: '0.5px solid var(--dsw-alias-border-l2)',
224
+ color: 'var(--dsw-alias-label-tertiary)',
225
+ fontSize: 11.5,
226
+ };
227
+ const actionStyle = {
228
+ all: 'unset',
229
+ cursor: 'pointer',
230
+ color: 'var(--dsw-alias-label-secondary)',
231
+ fontSize: 11.5,
232
+ lineHeight: '16px',
233
+ padding: '2px 6px',
234
+ borderRadius: 6,
235
+ };
236
+ const errorStyle = { color: 'var(--dsw-alias-state-warn-label)', fontSize: 12 };
237
+
238
+ /** 14px gauge glyph, matching the size of host composer-pill icons. */
239
+ function QuotaGlyph(props) {
240
+ const color = props.color || 'currentColor';
241
+ return h('svg', {
242
+ width: 14,
243
+ height: 14,
244
+ viewBox: '0 0 16 16',
245
+ fill: 'none',
246
+ 'aria-hidden': true,
247
+ style: { flex: 'none', color },
248
+ }, [
249
+ h('path', {
250
+ key: 'arc',
251
+ d: 'M3.2 11.4a5.6 5.6 0 1 1 9.6 0',
252
+ stroke: 'currentColor',
253
+ strokeWidth: 1.3,
254
+ strokeLinecap: 'round',
255
+ }),
256
+ h('path', {
257
+ key: 'needle',
258
+ d: 'M8 8l2.6-2.6',
259
+ stroke: 'currentColor',
260
+ strokeWidth: 1.3,
261
+ strokeLinecap: 'round',
262
+ }),
263
+ h('circle', { key: 'hub', cx: 8, cy: 8, r: 1.15, fill: 'currentColor' }),
264
+ ]);
265
+ }
266
+
267
+ /** One quota row: label, remaining share, bar, and reset hint. */
268
+ function QuotaRow(props) {
269
+ const { t, entry, now } = props;
270
+ const remaining = clampPercent(entry.remainingPercent);
271
+ const color = toneToken(remaining);
272
+ const reset = entry.resetsAt ? formatDistance(entry.resetsAt, now) : '';
273
+ const resetText = reset === ''
274
+ ? t('never')
275
+ : t('resetsIn', { when: reset });
276
+ return h('div', {
277
+ style: rowStyle,
278
+ title: entry.resetsAt ? `${formatMoment(entry.resetsAt)}` : undefined,
279
+ }, [
280
+ h('div', { key: 'head', style: rowHeadStyle }, [
281
+ h('span', { key: 'label', style: rowLabelStyle }, t(`window.${entry.id}`, {})),
282
+ h('span', { key: 'value', style: { ...rowValueStyle, color } }, t('percentLeftLong', { percent: Math.round(remaining) })),
283
+ ]),
284
+ h('span', { key: 'bar', style: barTrackStyle, 'aria-hidden': true },
285
+ h('span', {
286
+ style: { display: 'block', width: `${remaining}%`, height: '100%', borderRadius: 3, background: color },
287
+ })),
288
+ h('div', { key: 'reset', style: rowResetStyle }, resetText),
289
+ ]);
290
+ }
291
+
292
+ /**
293
+ * Quota popover: rendered into the document body because the docked
294
+ * composer creates a containing block for fixed descendants.
295
+ */
296
+ function QuotaPopover(props) {
297
+ const { t, label, state, anchorRef, onClose, onRefresh } = props;
298
+ const panelRef = React.useRef(null);
299
+ const closeRef = React.useRef(null);
300
+ const [position, setPosition] = React.useState(undefined);
301
+
302
+ React.useLayoutEffect(() => {
303
+ const place = () => {
304
+ const anchor = anchorRef.current;
305
+ if (anchor === null) return;
306
+ const rect = anchor.getBoundingClientRect();
307
+ const width = Math.min(320, window.innerWidth - 16);
308
+ const left = Math.min(Math.max(8, rect.left), Math.max(8, window.innerWidth - width - 8));
309
+ setPosition({ left, bottom: window.innerHeight - rect.top + 8, width });
310
+ };
311
+ place();
312
+ window.addEventListener('resize', place);
313
+ window.addEventListener('scroll', place, true);
314
+ return () => {
315
+ window.removeEventListener('resize', place);
316
+ window.removeEventListener('scroll', place, true);
317
+ };
318
+ }, [anchorRef]);
319
+
320
+ React.useEffect(() => {
321
+ const onPointerDown = (event) => {
322
+ const panel = panelRef.current;
323
+ const anchor = anchorRef.current;
324
+ if (panel !== null && event.target instanceof Node
325
+ && (panel.contains(event.target) || (anchor !== null && anchor.contains(event.target)))) return;
326
+ onClose(false);
327
+ };
328
+ const onKeyDown = (event) => {
329
+ if (event.key !== 'Escape') return;
330
+ event.preventDefault();
331
+ onClose(true);
332
+ };
333
+ document.addEventListener('mousedown', onPointerDown);
334
+ document.addEventListener('keydown', onKeyDown);
335
+ // Keep keyboard users inside the popover; Escape still closes it.
336
+ closeRef.current?.focus();
337
+ return () => {
338
+ document.removeEventListener('mousedown', onPointerDown);
339
+ document.removeEventListener('keydown', onKeyDown);
340
+ };
341
+ }, [anchorRef, onClose]);
342
+
343
+ const now = Date.now();
344
+ const children = [
345
+ h('div', { key: 'head', style: headerStyle }, [
346
+ h('span', { key: 'title', style: titleStyle }, [
347
+ h(QuotaGlyph, { key: 'glyph' }),
348
+ h('span', { key: 'text' }, t('dialog.title', { provider: label })),
349
+ ]),
350
+ h('button', {
351
+ key: 'close',
352
+ ref: closeRef,
353
+ type: 'button',
354
+ style: closeButtonStyle,
355
+ onClick: () => onClose(true),
356
+ 'aria-label': t('close'),
357
+ title: t('close'),
358
+ }, '✕'),
359
+ ]),
360
+ ];
361
+
362
+ children.push(h('div', { key: 'rule', style: titleRuleStyle }));
363
+
364
+ if (state.status === 'loading') {
365
+ children.push(h('div', { key: 'loading', style: rowResetStyle }, t('loading')));
366
+ } else if (state.status === 'error') {
367
+ children.push(h('div', { key: 'error', style: errorStyle }, state.message));
368
+ children.push(h('div', { key: 'retry' },
369
+ h('button', { type: 'button', style: actionStyle, onClick: onRefresh }, t('retry'))));
370
+ } else {
371
+ for (const entry of state.value.windows) {
372
+ children.push(h(QuotaRow, { key: entry.id, t, entry, now }));
373
+ }
374
+ children.push(h('div', { key: 'footer', style: footerStyle }, [
375
+ h('span', { key: 'updated' }, state.refreshing
376
+ ? t('refreshing')
377
+ : t('updated', { time: formatClock(state.value.fetchedAt) })),
378
+ h('button', {
379
+ key: 'refresh',
380
+ type: 'button',
381
+ style: actionStyle,
382
+ onClick: onRefresh,
383
+ disabled: state.refreshing,
384
+ title: t('refresh'),
385
+ 'aria-label': t('refresh'),
386
+ }, t('refresh')),
387
+ ]));
388
+ }
389
+
390
+ return ReactDOM.createPortal(h('div', {
391
+ ref: panelRef,
392
+ 'data-menu-material': '',
393
+ role: 'dialog',
394
+ 'aria-label': t('dialog.title', { provider: label }),
395
+ tabIndex: -1,
396
+ style: {
397
+ ...panelStyle,
398
+ ...(position === undefined ? { visibility: 'hidden', left: 0, bottom: 0 } : position),
399
+ },
400
+ }, children), document.body);
401
+ }
402
+
403
+ /**
404
+ * Composer-dock entry: a single quota button, with the windows in a popover
405
+ * that opens on click. The dot keeps the worst window glanceable while the
406
+ * panel is folded away.
407
+ */
408
+ function QuotaDock(props) {
409
+ const t = typeof props.t === 'function' ? props.t : translate;
410
+ const loadQuota = props.loadQuota;
411
+ const sessionId = props.sessionId;
412
+ const watchProvider = props.watchProvider;
413
+ const readProvider = props.readProvider;
414
+
415
+ // The selected model's harness provider decides whether this bundle has
416
+ // a quota surface for the session, and which reader it asks for.
417
+ const providerId = React.useSyncExternalStore(
418
+ React.useCallback((notify) => watchProvider(sessionId, notify), [watchProvider, sessionId]),
419
+ React.useCallback(() => readProvider(sessionId), [readProvider, sessionId]),
420
+ );
421
+ const provider = providerId == null ? undefined : QUOTA_PROVIDERS[providerId];
422
+ const supported = provider !== undefined;
423
+ const label = supported ? provider.label : '';
424
+
425
+ const [open, setOpen] = React.useState(false);
426
+ const [state, setState] = React.useState({ status: 'loading', refreshing: true });
427
+ const [tick, setTick] = React.useState(0);
428
+ const [hovered, setHovered] = React.useState(false);
429
+ const buttonRef = React.useRef(null);
430
+
431
+ const refresh = React.useCallback(() => setTick((value) => value + 1), []);
432
+ const close = React.useCallback((returnFocus) => {
433
+ setOpen(false);
434
+ if (returnFocus) buttonRef.current?.focus();
435
+ }, []);
436
+
437
+ // Fold the popover when the selection leaves the supported providers.
438
+ React.useEffect(() => {
439
+ if (!supported) setOpen(false);
440
+ }, [supported]);
441
+
442
+ React.useEffect(() => {
443
+ if (!supported) return undefined;
444
+ const controller = new AbortController();
445
+ let active = true;
446
+ setState((previous) => previous.providerId === providerId && previous.status === 'ready'
447
+ ? { status: 'ready', providerId, value: previous.value, refreshing: true }
448
+ : { status: 'loading', providerId, refreshing: true });
449
+ loadQuota(providerId, controller.signal).then((result) => {
450
+ if (!active) return;
451
+ if (result && result.ok === true) {
452
+ setState({ status: 'ready', providerId, value: result.value, refreshing: false });
453
+ } else {
454
+ setState({
455
+ status: 'error',
456
+ providerId,
457
+ message: (result && result.error && result.error.message) || t('error.short'),
458
+ refreshing: false,
459
+ });
460
+ }
461
+ }, (error) => {
462
+ if (!active || (error && error.name === 'AbortError')) return;
463
+ setState({
464
+ status: 'error',
465
+ providerId,
466
+ message: String((error && error.message) || error),
467
+ refreshing: false,
468
+ });
469
+ });
470
+ const timer = setInterval(() => setTick((value) => value + 1), open ? OPEN_REFRESH_MS : CLOSED_REFRESH_MS);
471
+ return () => {
472
+ active = false;
473
+ controller.abort();
474
+ clearInterval(timer);
475
+ };
476
+ }, [loadQuota, providerId, supported, tick, t, open]);
477
+
478
+ const current = state.providerId === providerId ? state : { status: 'loading', refreshing: true };
479
+ const windows = current.status === 'ready' ? current.value.windows : [];
480
+ const worstEntry = windows.length === 0
481
+ ? undefined
482
+ : windows.reduce((worst, entry) =>
483
+ clampPercent(entry.remainingPercent) < clampPercent(worst.remainingPercent) ? entry : worst);
484
+ const worstPercent = worstEntry === undefined
485
+ ? undefined
486
+ : Math.round(clampPercent(worstEntry.remainingPercent));
487
+ const active = hovered || open;
488
+ const restingColor = active ? 'var(--dsw-alias-label-secondary)' : 'var(--dsw-alias-label-tertiary)';
489
+ const reading = current.status === 'loading'
490
+ ? '…'
491
+ : current.status === 'error'
492
+ ? '—'
493
+ : `${t(`window.${worstEntry.id}`)} ${t('percentLeft', { percent: worstPercent })}`;
494
+ const readingColor = current.status !== 'ready'
495
+ ? restingColor
496
+ : worstPercent <= AMBER_AT_PERCENT
497
+ ? toneToken(worstPercent)
498
+ : restingColor;
499
+ const tooltip = current.status === 'error'
500
+ ? current.message
501
+ : windows.length === 0
502
+ ? t('open', { provider: label })
503
+ : `${label} · ${windows
504
+ .map((entry) => `${t(`window.${entry.id}`)} ${t('percentLeft', { percent: Math.round(clampPercent(entry.remainingPercent)) })}`)
505
+ .join(' · ')}`;
506
+
507
+ // No quota surface for the selected provider: contribute nothing at all.
508
+ if (!supported) return null;
509
+
510
+ return h(React.Fragment, null, [
511
+ h('div', { key: 'dock', style: dockStyle },
512
+ h('button', {
513
+ ref: buttonRef,
514
+ type: 'button',
515
+ onClick: () => { if (open) close(false); else setOpen(true); },
516
+ onMouseEnter: () => setHovered(true),
517
+ onMouseLeave: () => setHovered(false),
518
+ onFocus: () => setHovered(true),
519
+ onBlur: () => setHovered(false),
520
+ 'aria-expanded': open,
521
+ 'aria-haspopup': 'dialog',
522
+ 'aria-label': t('open', { provider: label }),
523
+ title: tooltip,
524
+ style: {
525
+ ...pillStyle,
526
+ background: active ? 'var(--dsw-alias-interactive-bg-hover)' : 'transparent',
527
+ color: restingColor,
528
+ },
529
+ }, [
530
+ h(QuotaGlyph, {
531
+ key: 'glyph',
532
+ color: current.status === 'ready' && worstPercent <= AMBER_AT_PERCENT ? toneToken(worstPercent) : 'currentColor',
533
+ }),
534
+ h('span', { key: 'label', style: pillLabelStyle }, label),
535
+ h('span', { key: 'sep', style: pillSeparatorStyle }, '·'),
536
+ h('span', { key: 'reading', style: { ...pillReadingStyle, color: readingColor } }, reading),
537
+ ])),
538
+ open
539
+ ? h(QuotaPopover, {
540
+ key: 'popover',
541
+ t,
542
+ label,
543
+ state: current,
544
+ anchorRef: buttonRef,
545
+ onClose: close,
546
+ onRefresh: refresh,
547
+ })
548
+ : null,
549
+ ]);
550
+ }
551
+
552
+ return {
553
+ inject: ['slots', 'connection', 'locale', 'modelDirectories'],
554
+ apply(ctx) {
555
+ ctx.effect(() => ctx.locale.register(NS, { en, zh }), 'provider-quota: dictionaries');
556
+ ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({
557
+ name: 'conversation.composer.dock',
558
+ id: 'provider-quota',
559
+ order: 40,
560
+ locale: NS,
561
+ inject: () => ({
562
+ loadQuota: (providerId, signal) =>
563
+ ctx.connection.rpc.call(CHANNEL, 'usage', { provider: providerId }, signal),
564
+ // Read the selected model's provider from the session's model
565
+ // directory, so the pill follows the composer's model seat.
566
+ watchProvider: (sessionId, notify) => {
567
+ try {
568
+ return ctx.modelDirectories.directoryFor(sessionId).store.subscribe(() => notify());
569
+ } catch {
570
+ return () => {};
571
+ }
572
+ },
573
+ readProvider: (sessionId) => {
574
+ try {
575
+ return ctx.modelDirectories.directoryFor(sessionId).store.getSnapshot().current?.provider ?? null;
576
+ } catch {
577
+ return null;
578
+ }
579
+ },
580
+ }),
581
+ }, QuotaDock));
582
+ },
583
+ };
584
+ },
585
+ });
@@ -0,0 +1,5 @@
1
+ # dsh bundle patch: inserts this plugin into a profile's layer stack.
2
+ - insert:
3
+ - id: provider-quota
4
+ name: '@david18284/dsh-provider-quota'
5
+ config: {}
package/docs/DETAIL.md ADDED
@@ -0,0 +1,72 @@
1
+ # Provider quota
2
+
3
+ Shows subscription quota for the model provider selected in the composer, and
4
+ lets any agent read it. Ships with one reader, OpenCode Go; the provider list is
5
+ extensible.
6
+
7
+ ## What it adds
8
+
9
+ - **Composer pill.** One compact pill beside the host's own composer readings
10
+ (`39.7M tok · Cache hit 97%`, the context ring): gauge icon, the provider's
11
+ label (for example *OpenCode Go*), and the worst window's reading, such as
12
+ `Weekly 52%`. It uses the host pill recipe exactly — 12px/20px type,
13
+ `1px 8px` padding, `--dsw-radius-sm`, resting tertiary color, hover and
14
+ `aria-expanded` fill from `--dsw-alias-interactive-bg-hover` — and stays
15
+ neutral above 20 % left, then tints the icon and reading amber at 20 % left
16
+ and red at 10 %. Clicking it opens a popover styled like the host statistics
17
+ dialogs (menu material, 16px radius,
18
+ title rule, value rows) with every provider-reported window: remaining share,
19
+ a bar, and the time until each resets. The popover refreshes immediately when
20
+ opened, again every 60 seconds while open, and on demand with its refresh
21
+ control; folded away it only reads once every five minutes. Escape, the close
22
+ button, or a click outside the panel closes it and returns focus to the pill.
23
+ - **Follows the selected provider.** The pill exists only while the session's
24
+ selected model runs on a provider this bundle can read; switching the
25
+ composer's model seat to another provider removes it, and switching back
26
+ restores it without a reload. The provider's label is part of the copy, so
27
+ adding a provider does not change the layout.
28
+ - **Agent tool `provider_quota`.** Any session in this profile can ask for the
29
+ current quota; the tool returns structured numbers per window plus a
30
+ plain-text summary, and refreshes at most once every 30 seconds. It takes an
31
+ optional `provider` argument and, when omitted, uses the only supported
32
+ provider if there is exactly one; with several supported providers the caller
33
+ must name one. The tool stays available even when another provider is
34
+ selected, because an explicit quota question remains meaningful.
35
+ - **Authenticated Web channel.** The panel does not use a public HTTP route; it
36
+ calls the `/provider-quota` RPC channel over the harness API bridge, so the
37
+ host's existing Origin and browser-authentication checks apply.
38
+
39
+ ## Adding another provider
40
+
41
+ Both halves keep a small registry:
42
+
43
+ 1. `quota.js` — add an entry to `PROVIDERS` with a display label and a `read`
44
+ function that resolves that provider's credential and normalizes its reply
45
+ into `{ provider, label, fetchedAt, windows[] }`.
46
+ 2. `client.js` — add the same provider id with its label to `QUOTA_PROVIDERS`.
47
+
48
+ The RPC channel and the agent tool both accept the provider id, caching is per
49
+ provider, and the pill then appears automatically while that provider is
50
+ selected. Providers without an entry are simply invisible to this bundle.
51
+
52
+ ## Where the shipped OpenCode Go reader gets its credential
53
+
54
+ Read-only, in this order:
55
+
56
+ 1. `OPENCODE_API_KEY` in the harness process environment.
57
+ 2. `$XDG_DATA_HOME/opencode/auth.json`, then `~/.local/share/opencode/auth.json`:
58
+ the `opencode-go` entry's API key, falling back to the `opencode` entry.
59
+
60
+ The key is sent only to `https://opencode.ai/zen/go/v1/usage` and never reaches
61
+ the browser or the session log.
62
+
63
+ ## Limitations
64
+
65
+ - Quota percentages are whatever the provider reports; the harness does not
66
+ estimate or reconcile them.
67
+ - A short window can reset while the popover is open; the displayed time is
68
+ refreshed by the next read rather than by a live timer.
69
+ - No history, charts, or notifications — only the provider's current windows.
70
+ - The pill appears where the composer dock exists, which is inside a
71
+ conversation. Profiles without the Web connection service still get the
72
+ agent tool.
package/icon.svg ADDED
@@ -0,0 +1,9 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="OpenCode Go quota gauge">
2
+ <rect x="2" y="2" width="60" height="60" rx="14" fill="#101a2b"/>
3
+ <circle cx="32" cy="32" r="18" fill="none" stroke="#26374f" stroke-width="6"/>
4
+ <path d="M32 14a18 18 0 0 1 15.6 9" fill="none" stroke="#3ecf8e" stroke-width="6" stroke-linecap="round"/>
5
+ <path d="M47.6 41a18 18 0 0 1-12.4 8.9" fill="none" stroke="#f2b13c" stroke-width="6" stroke-linecap="round"/>
6
+ <path d="M21 46.6A18 18 0 0 1 32 14" fill="none" stroke="#4d8bf5" stroke-width="6" stroke-linecap="round"/>
7
+ <circle cx="32" cy="32" r="4.5" fill="#e8f0fb"/>
8
+ <path d="M32 32l7-7" stroke="#e8f0fb" stroke-width="3" stroke-linecap="round"/>
9
+ </svg>
package/index.js ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Host half of the provider quota bundle.
3
+ *
4
+ * Registers the `provider_quota` agent tool for every session, and (when the
5
+ * Web connection service is mounted) an authenticated `/provider-quota` RPC
6
+ * channel that feeds the composer-dock panel in the browser.
7
+ *
8
+ * The tool definition is built inline instead of with `defineTool` so a
9
+ * workspace-linked bundle needs no harness package imports; the parameters are
10
+ * empty, so there is nothing for a typed wrapper to validate.
11
+ *
12
+ * @module @david18284/dsh-provider-quota
13
+ */
14
+ import {
15
+ defaultQuotaProvider, describeQuota, fetchQuota, isQuotaProvider, QUOTA_PROVIDER_IDS,
16
+ QuotaError, quotaErrorMessage,
17
+ } from './quota.js'
18
+
19
+ /** Cordis plugin name used by loader diagnostics. */
20
+ export const name = 'provider-quota'
21
+
22
+ /** The tool registry is the only mandatory service; the UI channel is optional. */
23
+ export const inject = ['tools']
24
+
25
+ /** Authenticated logical RPC channel the browser panel calls. */
26
+ const RPC_CHANNEL = '/provider-quota'
27
+
28
+ /** The one endpoint this channel serves. */
29
+ const USAGE_ENDPOINT = 'usage'
30
+
31
+ /**
32
+ * Register the model-facing tool and, when the Web connection exists, the
33
+ * browser-facing quota channel.
34
+ * @param ctx - host plugin context.
35
+ */
36
+ export function apply(ctx) {
37
+ ctx.tools.register({
38
+ name: 'provider_quota',
39
+ description: 'Report subscription quota for a supported provider route: the remaining share of each reported '
40
+ + 'window and when each resets. Read live from the provider API; this is subscription quota, not this '
41
+ + 'session\'s token usage.',
42
+ parameters: {
43
+ type: 'object',
44
+ properties: {
45
+ provider: {
46
+ type: 'string',
47
+ description: `Harness provider id to read. Supported: ${QUOTA_PROVIDER_IDS.join(', ')}. `
48
+ + 'Omit it when exactly one provider is supported.',
49
+ },
50
+ },
51
+ },
52
+ output: {
53
+ schema: {
54
+ type: 'object',
55
+ additionalProperties: false,
56
+ required: ['provider', 'label', 'fetchedAt', 'windows'],
57
+ properties: {
58
+ provider: { type: 'string' },
59
+ label: { type: 'string', description: 'Display label of the quota provider.' },
60
+ fetchedAt: { type: 'string', description: 'ISO timestamp of the provider read.' },
61
+ windows: {
62
+ type: 'array',
63
+ items: {
64
+ type: 'object',
65
+ additionalProperties: false,
66
+ required: ['id', 'label', 'status', 'usedPercent', 'remainingPercent'],
67
+ properties: {
68
+ id: { type: 'string', description: 'Stable window id: fiveHour, weekly, or monthly.' },
69
+ label: { type: 'string', description: 'Short display label, such as 5h.' },
70
+ status: { type: 'string', description: 'Provider status, such as ok or rate-limited.' },
71
+ usedPercent: { type: 'number', description: 'Share of the window already used, 0-100.' },
72
+ remainingPercent: { type: 'number', description: 'Share of the window still available, 0-100.' },
73
+ resetsAt: { type: 'string', description: 'ISO timestamp when the window resets, when reported.' },
74
+ },
75
+ },
76
+ },
77
+ },
78
+ },
79
+ render: (_args, value) => [{ type: 'text', text: describeQuota(value) }],
80
+ },
81
+ timeoutMs: 30_000,
82
+ async execute(args, exec) {
83
+ const requested = args?.provider
84
+ const provider = requested === undefined ? defaultQuotaProvider() : requested
85
+ if (typeof provider !== 'string' || !isQuotaProvider(provider)) {
86
+ throw new Error(`No quota reader for provider "${String(provider)}". Supported: ${QUOTA_PROVIDER_IDS.join(', ')}.`)
87
+ }
88
+ return await fetchQuota(provider, { signal: exec.signal })
89
+ },
90
+ })
91
+
92
+ // Without a browser-facing connection service there is nothing to feed; the
93
+ // tool above still works in headless and CLI profiles.
94
+ ctx.inject(['connection', 'webServer'], (child) => {
95
+ // The connection's RPC registry uses the *reading* context as the route
96
+ // owner; carry the injected server onto it so that owner can reach
97
+ // `webServer` when it registers the channel's HTTP route.
98
+ const routeContext = child.extend({ webServer: child.webServer })
99
+ routeContext.connection.rpc.handle(RPC_CHANNEL, async (endpoint, payload, signal) => {
100
+ if (endpoint !== USAGE_ENDPOINT) {
101
+ return {
102
+ ok: false,
103
+ error: { code: 'unknown-endpoint', message: `Unknown endpoint "${endpoint}".`, details: {} },
104
+ }
105
+ }
106
+ let provider = payload?.provider
107
+ if (provider === undefined) {
108
+ try {
109
+ provider = defaultQuotaProvider()
110
+ } catch (error) {
111
+ return {
112
+ ok: false,
113
+ error: { code: 'ambiguous-provider', message: quotaErrorMessage(error), details: {} },
114
+ }
115
+ }
116
+ }
117
+ if (typeof provider !== 'string' || !isQuotaProvider(provider)) {
118
+ return {
119
+ ok: false,
120
+ error: {
121
+ code: 'unknown-provider',
122
+ message: `No quota reader for provider "${String(provider)}". Supported: ${QUOTA_PROVIDER_IDS.join(', ')}.`,
123
+ details: {},
124
+ },
125
+ }
126
+ }
127
+ try {
128
+ return { ok: true, value: await fetchQuota(provider, { signal }) }
129
+ } catch (error) {
130
+ return {
131
+ ok: false,
132
+ error: {
133
+ code: error instanceof QuotaError ? error.code : 'quota-failed',
134
+ message: quotaErrorMessage(error),
135
+ details: {},
136
+ },
137
+ }
138
+ }
139
+ })
140
+ })
141
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Provider quota",
4
+ "description": "Shows subscription quota for the selected model provider beside the composer, and answers quota questions through the provider_quota tool. Ships with an OpenCode Go reader.",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "\u670d\u52a1\u5546\u989d\u5ea6",
4
+ "description": "\u5728\u8f93\u5165\u6846\u65c1\u663e\u793a\u6240\u9009\u6a21\u578b\u670d\u52a1\u5546\u7684\u8ba2\u9605\u989d\u5ea6\uff0c\u5e76\u901a\u8fc7 provider_quota \u5de5\u5177\u56de\u7b54\u989d\u5ea6\u95ee\u9898\u3002\u5185\u7f6e OpenCode Go \u8bfb\u53d6\u5668\u3002",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@david18284/dsh-provider-quota",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Provider subscription quota for DeepSeek Harness: a composer pill that follows the selected model provider, a popover with the reported windows, and a provider_quota agent tool. Ships with an OpenCode Go reader.",
5
+ "license": "MIT",
6
+ "author": "David Li",
7
+ "type": "module",
8
+ "icon": "icon.svg",
9
+ "keywords": [
10
+ "dsh-plugin",
11
+ "deepseek-harness",
12
+ "dsh",
13
+ "quota",
14
+ "usage",
15
+ "opencode",
16
+ "opencode-go",
17
+ "agent-tool"
18
+ ],
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/dli7319/dsh-provider-quota.git"
22
+ },
23
+ "bugs": {
24
+ "url": "https://github.com/dli7319/dsh-provider-quota/issues"
25
+ },
26
+ "homepage": "https://github.com/dli7319/dsh-provider-quota#readme",
27
+ "engines": {
28
+ "dsh": ">=0.2.2-rc.5 <0.3.0",
29
+ "node": ">=24.9.0"
30
+ },
31
+ "scripts": {
32
+ "check": "node scripts/check.mjs"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "exports": {
38
+ ".": "./index.js",
39
+ "./client": "./client.js",
40
+ "./locale/*.json": "./locale/*.json",
41
+ "./icon": "./icon.svg"
42
+ },
43
+ "files": [
44
+ "index.js",
45
+ "quota.js",
46
+ "client.js",
47
+ "cordis.patch.yml",
48
+ "locale",
49
+ "docs/DETAIL.md",
50
+ "icon.svg"
51
+ ],
52
+ "dsh": {
53
+ "bundle": {
54
+ "patch": "./cordis.patch.yml"
55
+ },
56
+ "client": {
57
+ "platform": "web",
58
+ "immediately": true,
59
+ "inject": [
60
+ "@deepseek-ai/dsh-client-ui-conversation",
61
+ "@deepseek-ai/dsh-client-ui-model-selection"
62
+ ]
63
+ }
64
+ }
65
+ }
package/quota.js ADDED
@@ -0,0 +1,285 @@
1
+ /**
2
+ * OpenCode Go quota reader.
3
+ *
4
+ * Resolves the local OpenCode API key (the same credential the OpenCode CLI
5
+ * stores) and reads the provider-reported usage windows from the Go usage
6
+ * endpoint. Shared by the `provider_quota` agent tool and the Web UI RPC
7
+ * channel, so both surfaces report identical numbers.
8
+ *
9
+ * @module @david18284/dsh-provider-quota/quota
10
+ */
11
+ import { readFile } from 'node:fs/promises'
12
+ import { homedir } from 'node:os'
13
+ import { join } from 'node:path'
14
+
15
+ /** Provider endpoint that reports the Go plan's three rolling windows. */
16
+ export const USAGE_URL = 'https://opencode.ai/zen/go/v1/usage'
17
+
18
+ /** One usage window, in reporting order. */
19
+ const WINDOWS = [
20
+ { id: 'rolling', key: 'fiveHour', label: '5h' },
21
+ { id: 'weekly', key: 'weekly', label: 'Weekly' },
22
+ { id: 'monthly', key: 'monthly', label: 'Monthly' },
23
+ ]
24
+
25
+ /** Cooperative request budget for one provider call. */
26
+ const DEFAULT_TIMEOUT_MS = 15_000
27
+
28
+ /** How long one provider reply serves later reads, so a poll loop stays cheap. */
29
+ const CACHE_TTL_MS = 30_000
30
+
31
+ /** A quota read that failed for a reason worth naming to the user or model. */
32
+ export class QuotaError extends Error {
33
+ /**
34
+ * @param code - stable machine-readable reason.
35
+ * @param message - human-readable explanation.
36
+ */
37
+ constructor(code, message) {
38
+ super(message)
39
+ this.name = 'QuotaError'
40
+ this.code = code
41
+ }
42
+ }
43
+
44
+ /** Last successful reply per provider, shared by every caller in this process. */
45
+ const caches = new Map()
46
+
47
+ /** Reads currently in flight per provider, so concurrent callers share one request. */
48
+ const inflights = new Map()
49
+
50
+ /**
51
+ * Candidate OpenCode credential files, most specific first.
52
+ * @param explicit - configured file, when one is set.
53
+ * @returns file paths to try.
54
+ */
55
+ function authFileCandidates(explicit) {
56
+ if (explicit) return [explicit]
57
+ const files = []
58
+ const dataHome = process.env.XDG_DATA_HOME
59
+ if (dataHome) files.push(join(dataHome, 'opencode', 'auth.json'))
60
+ files.push(join(homedir(), '.local', 'share', 'opencode', 'auth.json'))
61
+ return files
62
+ }
63
+
64
+ /**
65
+ * Read the Go API key the OpenCode CLI signed in with.
66
+ * @param explicit - configured credential file, when one is set.
67
+ * @returns the key and the credential source label.
68
+ * @throws {QuotaError} NO_KEY when no credential exists.
69
+ */
70
+ async function resolveApiKey(explicit) {
71
+ const fromEnv = process.env.OPENCODE_API_KEY?.trim()
72
+ if (fromEnv) return { key: fromEnv, source: 'OPENCODE_API_KEY' }
73
+ for (const file of authFileCandidates(explicit)) {
74
+ let text
75
+ try {
76
+ text = await readFile(file, 'utf8')
77
+ } catch (error) {
78
+ if (error?.code === 'ENOENT') continue
79
+ throw new QuotaError('AUTH_FILE_UNREADABLE', `Could not read ${file}: ${error?.message ?? error}`)
80
+ }
81
+ let parsed
82
+ try {
83
+ parsed = JSON.parse(text)
84
+ } catch {
85
+ throw new QuotaError('AUTH_FILE_INVALID', `${file} is not valid JSON`)
86
+ }
87
+ for (const providerId of ['opencode-go', 'opencode']) {
88
+ const record = parsed?.[providerId]
89
+ const key = typeof record?.key === 'string' ? record.key.trim() : ''
90
+ if (key) return { key, source: providerId }
91
+ }
92
+ }
93
+ throw new QuotaError(
94
+ 'NO_KEY',
95
+ 'No OpenCode Go API key found. Sign in with the OpenCode CLI, or set OPENCODE_API_KEY.',
96
+ )
97
+ }
98
+
99
+ /**
100
+ * Normalize one provider reply into the shape both surfaces report.
101
+ * @param body - parsed provider response.
102
+ * @returns the quota snapshot.
103
+ * @throws {QuotaError} BAD_RESPONSE when a window is missing or malformed.
104
+ */
105
+ function normalize(body) {
106
+ const usage = body?.usage
107
+ const windows = []
108
+ for (const window of WINDOWS) {
109
+ const raw = usage?.[window.id]
110
+ if (raw === null || typeof raw !== 'object') {
111
+ throw new QuotaError('BAD_RESPONSE', `OpenCode Go response is missing the ${window.id} window.`)
112
+ }
113
+ if (typeof raw.percent !== 'number' || !Number.isFinite(raw.percent)) {
114
+ throw new QuotaError('BAD_RESPONSE', `OpenCode Go response has no percentage for the ${window.id} window.`)
115
+ }
116
+ const status = typeof raw.status === 'string' ? raw.status : 'unknown'
117
+ const percent = Math.min(100, Math.max(0, raw.percent))
118
+ const exhausted = status === 'rate-limited'
119
+ windows.push({
120
+ id: window.key,
121
+ label: window.label,
122
+ status,
123
+ usedPercent: exhausted ? 100 : percent,
124
+ remainingPercent: exhausted ? 0 : 100 - percent,
125
+ ...(typeof raw.resetsAt === 'string' ? { resetsAt: raw.resetsAt } : {}),
126
+ })
127
+ }
128
+ return {
129
+ provider: 'opencode-go',
130
+ label: 'OpenCode Go',
131
+ fetchedAt: new Date().toISOString(),
132
+ windows,
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Ask the provider for the current Go windows.
138
+ * @param options - credential file, request budget, and caller cancellation.
139
+ * @returns the quota snapshot.
140
+ */
141
+ async function loadOpenCodeGoQuota(options = {}) {
142
+ const { authFile, timeoutMs = DEFAULT_TIMEOUT_MS, signal } = options
143
+ const auth = await resolveApiKey(authFile)
144
+ const controller = new AbortController()
145
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
146
+ const forwardAbort = () => controller.abort()
147
+ if (signal) {
148
+ if (signal.aborted) controller.abort()
149
+ else signal.addEventListener('abort', forwardAbort, { once: true })
150
+ }
151
+ try {
152
+ let response
153
+ try {
154
+ response = await fetch(USAGE_URL, {
155
+ method: 'GET',
156
+ headers: { authorization: `Bearer ${auth.key}`, accept: 'application/json' },
157
+ signal: controller.signal,
158
+ })
159
+ } catch (error) {
160
+ if (controller.signal.aborted) {
161
+ throw new QuotaError('TIMEOUT', `OpenCode Go did not answer within ${timeoutMs} ms.`)
162
+ }
163
+ throw new QuotaError('NETWORK', `Could not reach ${USAGE_URL}: ${error?.message ?? error}`)
164
+ }
165
+ if (!response.ok) {
166
+ const detail = (await response.text().catch(() => '')).replace(auth.key, '[redacted]').slice(0, 200)
167
+ if (response.status === 401) {
168
+ throw new QuotaError('UNAUTHORIZED', 'OpenCode rejected the stored key (HTTP 401). Sign in with OpenCode again.')
169
+ }
170
+ if (response.status === 403) {
171
+ throw new QuotaError('NO_PLAN', 'The stored OpenCode key has no Go plan (HTTP 403).')
172
+ }
173
+ throw new QuotaError('HTTP_ERROR', `OpenCode Go answered HTTP ${response.status}${detail ? `: ${detail}` : ''}`)
174
+ }
175
+ let body
176
+ try {
177
+ body = await response.json()
178
+ } catch {
179
+ throw new QuotaError('BAD_RESPONSE', 'OpenCode Go returned a non-JSON response.')
180
+ }
181
+ return normalize(body)
182
+ } finally {
183
+ clearTimeout(timer)
184
+ signal?.removeEventListener('abort', forwardAbort)
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Every provider this bundle can read, keyed by the harness LLM provider id.
190
+ * Add an entry here (and a client-side label in `client.js`) to support another
191
+ * provider; each entry owns its own credential resolution and normalization.
192
+ */
193
+ const PROVIDERS = new Map([
194
+ ['opencode-go', {
195
+ label: 'OpenCode Go',
196
+ read: (options) => loadOpenCodeGoQuota(options),
197
+ }],
198
+ ])
199
+
200
+ /** Provider ids this bundle can report, in display order. */
201
+ export const QUOTA_PROVIDER_IDS = Object.freeze([...PROVIDERS.keys()])
202
+
203
+ /**
204
+ * Provider a caller means when it names none: the only supported provider when
205
+ * there is exactly one, otherwise callers must choose.
206
+ * @returns the default provider id.
207
+ * @throws {QuotaError} AMBIGUOUS_PROVIDER when several providers are supported.
208
+ */
209
+ export function defaultQuotaProvider() {
210
+ if (QUOTA_PROVIDER_IDS.length === 1) return QUOTA_PROVIDER_IDS[0]
211
+ throw new QuotaError(
212
+ 'AMBIGUOUS_PROVIDER',
213
+ `Several providers are supported (${QUOTA_PROVIDER_IDS.join(', ')}); pass one explicitly.`,
214
+ )
215
+ }
216
+
217
+ /**
218
+ * Whether a harness provider id has a quota reader here.
219
+ * @param providerId - harness LLM provider id.
220
+ * @returns true when the id is supported.
221
+ */
222
+ export function isQuotaProvider(providerId) {
223
+ return PROVIDERS.has(providerId)
224
+ }
225
+
226
+ /**
227
+ * Display label for one supported provider.
228
+ * @param providerId - harness LLM provider id.
229
+ * @returns the label, or undefined for an unsupported id.
230
+ */
231
+ export function quotaProviderLabel(providerId) {
232
+ return PROVIDERS.get(providerId)?.label
233
+ }
234
+
235
+ /**
236
+ * Read one provider's current quota, reusing a recent reply.
237
+ * @param providerId - harness LLM provider id; defaults to OpenCode Go.
238
+ * @param options - credential file, request budget, and caller cancellation.
239
+ * @returns the quota snapshot.
240
+ */
241
+ export async function fetchQuota(providerId = 'opencode-go', options = {}) {
242
+ const provider = PROVIDERS.get(providerId)
243
+ if (provider === undefined) {
244
+ throw new QuotaError(
245
+ 'UNKNOWN_PROVIDER',
246
+ `No quota reader for provider "${providerId}". Supported: ${QUOTA_PROVIDER_IDS.join(', ')}.`,
247
+ )
248
+ }
249
+ const cached = caches.get(providerId)
250
+ if (cached !== undefined && Date.now() - cached.at < CACHE_TTL_MS) return cached.value
251
+ const inflight = inflights.get(providerId)
252
+ if (inflight !== undefined) return inflight
253
+ const pending = provider.read(options).then((value) => {
254
+ caches.set(providerId, { at: Date.now(), value })
255
+ return value
256
+ }).finally(() => {
257
+ inflights.delete(providerId)
258
+ })
259
+ inflights.set(providerId, pending)
260
+ return pending
261
+ }
262
+
263
+ /**
264
+ * One-line-per-window model-facing summary.
265
+ * @param value - quota snapshot from {@link fetchQuota}.
266
+ * @returns plain text for the model.
267
+ */
268
+ export function describeQuota(value) {
269
+ const lines = [`${value.label ?? value.provider} quota (read ${value.fetchedAt})`]
270
+ for (const window of value.windows) {
271
+ const reset = window.resetsAt ? `, resets ${window.resetsAt}` : ''
272
+ lines.push(`${window.label}: ${window.remainingPercent}% left (${window.usedPercent}% used${reset})`)
273
+ }
274
+ return lines.join('\n')
275
+ }
276
+
277
+ /**
278
+ * Render a thrown value as one user-facing sentence.
279
+ * @param error - anything thrown by a quota read.
280
+ * @returns the message.
281
+ */
282
+ export function quotaErrorMessage(error) {
283
+ if (error instanceof QuotaError) return error.message
284
+ return error?.message ? String(error.message) : String(error)
285
+ }