@goodandready/dsh-opencode-provider 0.0.0-stage → 0.5.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/CHANGELOG.md ADDED
@@ -0,0 +1,97 @@
1
+ # Changelog
2
+
3
+ ## 0.5.1
4
+
5
+ - Remove the non-standard inline key card from Settings → Models. Provider cards stay standard; the key is edited only through **Изменить** on the OpenCode settings page.
6
+
7
+ ## 0.5.0
8
+
9
+ - **Parity release**: TUI settings section, plan-aware Go picker, request-wide image budget and tool-schema normalization.
10
+ - Package identity is now scoped: `@goodandready/dsh-opencode-provider` (unscoped npm name belongs to an unrelated package).
11
+ - Custom composer cost pill and custom analytics cost columns removed; cost is shown only by DSH's native display.
12
+ - One-click plugin update in Settings → OpenCode: registry status, badge, exact `dsh plugin add`, restart notice, loopback/same-origin POST guard.
13
+ - English, Chinese and Russian READMEs and a visual-verification asset ship in the package and GitHub tree.
14
+ - **Usage analytics dashboard** in the quota panel: KPI grid, 7/30/90 window, and Models / Days / Sessions tables; success/errors show `—` because the local projection does not expose failed attempts. Cost is not duplicated: DSH's native display is the only cost surface.
15
+ - **Tool limit fix**: tools are deduplicated by name and capped at OpenCode's 128-item maximum before every transport, fixing `HTTP 400: maximum number of items is 128` in tool-heavy profiles.
16
+ - **Test connection** button in the key card: pick a model, run a minimal real request, see latency and the reply.
17
+ - `POST /dsh-opencode/test` Host route with a 60-second budget.
18
+ - Sidebar quota bars now change color at 75% (warning) and 90% (critical).
19
+ - Write routes require a literal loopback `Host` (not just a loopback socket) in addition to same-origin and JSON checks, closing DNS-rebinding key exfiltration.
20
+ - Analytics no longer fabricates `100%` success / `0` errors; the local projection returns `null` and the UI shows `—`.
21
+ - Go plan filtering now fails open for models that exist only in the live catalog; known Console models stay hidden.
22
+ - Tool truncation at the 128-item provider limit logs a one-time warning instead of failing silently.
23
+ - TUI settings refresh after `/config` account changes; analytics requests have an error state and a generation guard against the 7/30/90 race.
24
+ - Projection analytics reads run with bounded parallelism; `.commandcode/` is ignored; provider registration logs at boot.
25
+ - Tool-result images are replaced with an offload placeholder instead of failing the whole request in every transport.
26
+ - Core harness tools (`read`, `write`, `edit`, `bash`, `glob`, `grep`, …) survive the 128-tool cap even when a large MCP set is present.
27
+ - `GET /dsh-opencode/health` reports provider registration, account count and model count for startup diagnostics.
28
+ - The TUI settings section polls live config, so accounts/allowlist changes made from the terminal refresh without a restart.
29
+ - Client colors moved to DSH theme variables; the `zh` dictionary is a real translation; draft/route/widget helpers moved to `settings-draft.ts`, `settings-widgets.tsx`, `routes-public.ts` and `routes-values.ts`; quota triggers expose real `aria-expanded` panel state.
30
+ - Tests grew to 84, including TUI polling, health, core-tool preservation and tool-result image placeholders.
31
+ - Rotation now also triggers on quota/usage-limit bodies (400/402/403/429), with a 10-minute or `Retry-After` cooldown for quota rejections.
32
+ - The last account is marked on rejection as well; account rows expose `mark`/`coolingUntil`, show a cooldown badge, and the active marker follows the first non-cooling key.
33
+ - Per-account quota reads: `/state.accounts[].usage` is fetched for each distinct key (`UsageReader` caches per key), the active account drives the sidebar and quota panel, Accounts rows show 5h/week/month chips, and the panel has an accounts table. Verified live: `default` 1/5/2 and `Go #2` 9/4/100 with `rate-limited` monthly until 22 Oct 08:21.
34
+ - Request heatmap (Monday-first weekday × local hour) in the quota panel. The adapter appends `{at, provider, model, purpose?}` to `~/.dsh/storages/dsh-opencode/requests.jsonl` and `/analytics` merges the aggregate; prompts, responses and keys are never stored. Live: two `/test` calls produced `Tue 13:00 = 2`.
35
+ - Heatmap accuracy: `session-title` / `compaction` calls are excluded and exact duplicate records collapse. Live after two real chat messages: analytics shows 2 OpenCode sessions (`deepseek-v4.1-flash` ≈$0.00079, `beam-free` Free), while the heatmap counts 6 main requests instead of 8 raw records.
36
+ - A 24-hour aggregate strip under the heatmap sums the selected window by hour across all days; its bars use the same intensity scale and tooltips.
37
+ - Per-model heatmap: `/analytics` returns a `models[]` series (provider/model, total, hours, grid), and the panel offers an **All models / model** selector when more than one model has traffic. Live: `deepseek-v4.1-flash` 2, `minimax-m3.1-flash-free` 1.
38
+ - Account cooldowns persist across restarts in `~/.dsh/storages/dsh-opencode/cooldowns.json`, keyed by a SHA-256 fingerprint (raw keys are never written). Expired entries are dropped and the file is capped at 50. Live: after a restart, `Go #2` kept its `quota` mark until 22 Oct 08:21 while the restored default key was active.
39
+ - Model → account rules: first matching glob (case-insensitive `*`/`?`) pins a preferred account for that model, with the other accounts kept as fallbacks. Config is normalized and exposed through `/state`; Settings has an editor. Live: `*free* → Go #2` round-tripped through `/config` and `/state`, then cleared.
40
+ - Sidebar quota card redesigned to match the clinebot meter: theme-native ring, active account name, highest-window percent, and 5-hour / weekly / monthly rows with remaining quota, reset countdown and thin bars. Uses DSH CSS variables and has a narrow rail variant. The header percentage is right-aligned with the row values.
41
+ - Quota panel now has its own vertical scroll (`height: 100%`, viewport max-height, `overflow-y: auto`), so content below the fold is reachable; verified in Desktop by opening the panel and scrolling to **Usage by model**.
42
+ - Quota panel polish: the badge now says **Active account** (not "Pinned account" when `activeAccount` is empty), Accounts rows show persisted cooldown / provider rate-limit badges (for example `Quota cooldown · 2d`), and the 5-hour/weekly/monthly bars show date+time with a relative reset (`1% · 20.10, 17:11 (2h)`).
43
+ - `/opencode` gained `accounts`, `models`, `rules` and `test [model]`; `status` now includes per-account quotas and rules.
44
+ - Request log compaction at 2 MB (newest 5000 lines) and a `npm run check` / `npm run release` workflow plus GitHub Actions CI (`typecheck`, tests, build, pack).
45
+ - Live-verified two-account rotation in DSH Desktop: with an invalid default key, `/test` switched to `Go #2` and returned `OK`. A later run found `Go #2` at its monthly limit (98% before the tests) and showed `quota` with the provider's reset.
46
+ - `GET /dsh-opencode/analytics` and the **Usage by model** table in the quota panel (7/30/90 days). It aggregates only numeric metadata from the local session projection cache; a session is attributed to its last-used model.
47
+ - Verified live in DSH Desktop 0.2.1-rc.2; install there from the packed tarball (a directory path triggers the Desktop CLI's `dsh-desktop-runtime` alias bug).
48
+
49
+ ## 0.4.1
50
+
51
+ - Accounts card can set each account's key from the page; unconfigured accounts are listed with a missing-key badge.
52
+ - Live catalog refresh button (`POST /dsh-opencode/models/refresh`).
53
+ - Quota warning banners at 80% and 95% in the settings page.
54
+ - Expandable subscription-limits table: per model, Go and Go Plus monthly allowance plus 5h/week/month request estimates.
55
+
56
+ ## 0.4.0
57
+
58
+ - Per-model OpenCode Go subscription limits: monthly dollar allowance and estimated requests for the 5-hour, weekly and monthly windows, for Go and Go Plus.
59
+ - Limits appear in the model picker description and as a badge in the settings model list; hovering shows both plans.
60
+ - Added `src/subscription-limits.ts` with the official table and formatting helpers.
61
+ - Tests: limits table integrity, formatting, and route-gated model descriptions.
62
+
63
+ ## 0.3.1
64
+
65
+ - Composer session-cost estimate (`≈`/`≥`/`Free`) from the generated price snapshot and the `tokenUsage`/`modelSelection` projections.
66
+ - Model price badges in the settings page; model picker descriptions now include per-1M input/output rates.
67
+ - OpenCode auth-entry autocomplete from the entries actually present in `auth.json`.
68
+ - Broadened live tool-loop coverage (Grok, Muse, Qwen).
69
+
70
+ ## 0.3.0
71
+
72
+ - Browser settings page (`Settings → OpenCode`): key management, quota bars, accounts, model allowlist, per-model transport overrides, connection settings.
73
+ - Sidebar quota card (opt-in) and the center-column quota panel.
74
+ - Host HTTP routes under `/dsh-opencode/*` with same-origin enforcement.
75
+ - Key import from OpenCode's `auth.json` through the credentials seam.
76
+ - Client bundle built as a `window.__ModuleLoader__` module with React externalized.
77
+
78
+ ## 0.2.0
79
+
80
+ - Native Anthropic Messages transport (thinking blocks, signatures, tool use).
81
+ - Native OpenAI Responses transport.
82
+ - Native Google Generative AI transport with `thoughtSignature` replay.
83
+ - Image input on every transport, through `ctx.attachments.readImageRequest`.
84
+ - Multi-account pool with pre-stream 401/403/429 rotation and per-key cooldowns.
85
+ - `/opencode` command with status and quota windows.
86
+ - Reasoning-effort mapping and output caps.
87
+ - Expanded unit tests and live smoke scripts.
88
+
89
+ ## 0.1.0
90
+
91
+ - Initial P1 skeleton.
92
+ - Registers `opencode` and `opencode-go` routes on the dsh `llm` service.
93
+ - OpenAI Chat transport over the Go unified gateway.
94
+ - Stable `x-opencode-session` derived from the durable session id.
95
+ - Key resolution from config, the credential seam, OpenCode `auth.json`, and the launch environment.
96
+ - Live model catalog with a generated `models.dev` fallback.
97
+ - Text, reasoning, streamed tool calls, usage, and classified provider errors.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-opencode-provider contributors
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/NOTICE ADDED
@@ -0,0 +1,15 @@
1
+ dsh-opencode-provider
2
+ =====================
3
+
4
+ This project is an unofficial community integration. It is not affiliated
5
+ with OpenCode, Anomaly, or DeepSeek Harness.
6
+
7
+ Architectural ideas and wire-contract research were informed by these MIT
8
+ projects:
9
+
10
+ - dsh-commandcode-provider — https://github.com/Mars-Sea/dsh-commandcode-provider
11
+ - dsh-clinebot — https://github.com/GooDAnDReaDY/dsh-clinebot
12
+ - opencode2dsh — https://github.com/FishBottle7/opencode2dsh (reference for the
13
+ anonymous free-lane header requirements; that bypass is not implemented here)
14
+
15
+ Model metadata is generated from https://models.dev.
package/README.md CHANGED
@@ -1,3 +1,302 @@
1
- # Temporary Holding Version
1
+ # 📦 @goodandready/dsh-opencode-provider
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
+ <div align="center">
4
+
5
+ <h3>OpenCode Console & OpenCode Go LLM Provider for DeepSeek Harness</h3>
6
+
7
+ <p>
8
+ <a href="https://goodandready.app/"><img src="https://img.shields.io/badge/🌐_DSH_Hub-goodandready.app-ff4500.svg?style=for-the-badge&labelColor=1a1a2e" alt="GoodAndReady Showcase"></a>
9
+ <a href="https://www.npmjs.com/package/@goodandready/dsh-opencode-provider"><img src="https://img.shields.io/npm/v/@goodandready/dsh-opencode-provider?style=for-the-badge&color=crimson&logo=npm" alt="npm version"></a>
10
+ <a href="https://github.com/GooDAnDReaDY/dsh-opencode-provider/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge" alt="License"></a>
11
+ </p>
12
+
13
+ </div>
14
+
15
+ <table align="center">
16
+ <tr>
17
+ <td align="center">
18
+ ⭐ <strong>If you like this plugin, please star it on GitHub</strong> — it shows me that the plugin is useful to you and motivates me to keep developing it.
19
+ <br><br>
20
+ 🐛 <strong>If you find a bug or would like to request a feature</strong>, open a GitHub issue in any language — I will review your proposal and implement useful suggestions in a future plugin version.
21
+ </td>
22
+ </tr>
23
+ </table>
24
+
25
+ ---
26
+
27
+ OpenCode / OpenCode Go provider plugin for [DeepSeek Harness](https://deepseek-harness.github.io/deepseek-harness/) (dsh).
28
+
29
+ It registers two native LLM routes:
30
+
31
+ | Route | Product | Base |
32
+ |---|---|---|
33
+ | `opencode` | OpenCode Console / Zen (pay-as-you-go) | `https://opencode.ai/inference` |
34
+ | `opencode-go` | OpenCode Go / Go Plus subscription | `https://opencode.ai/inference/go` |
35
+
36
+ Requests resolve the key per call, so a changed credential reaches the next request without a restart.
37
+
38
+ ## Architecture
39
+
40
+ ```mermaid
41
+ graph LR
42
+ subgraph DSH["DeepSeek Harness Core"]
43
+ Agent["DSH Agent / Chat"]
44
+ Creds["Credentials / auth.json"]
45
+ end
46
+
47
+ subgraph Plugin["dsh-opencode-provider"]
48
+ Router{"Route Selector"}
49
+ Pool["Multi-Account Pool<br/>(Auto-Rotation & Cooldowns)"]
50
+ Heatmap["Heatmap & Quota Telemetry<br/>(5h / Week / Month)"]
51
+
52
+ subgraph Transports["4 Wire Transports"]
53
+ T1["OpenAI Chat"]
54
+ T2["Anthropic Messages<br/>(Thinking Signatures)"]
55
+ T3["OpenAI Responses"]
56
+ T4["Google GenAI<br/>(thoughtSignature Replay)"]
57
+ end
58
+ end
59
+
60
+ subgraph OpenCode["OpenCode Gateway"]
61
+ Console["opencode (Console / Zen)"]
62
+ Go["opencode-go (Go / Go Plus)"]
63
+ end
64
+
65
+ Agent --> Router
66
+ Creds -.-> Pool
67
+ Router -->|opencode| Pool
68
+ Router -->|opencode-go| Pool
69
+ Pool --> Heatmap
70
+ Pool --> Transports
71
+ T1 & T2 & T3 & T4 --> Console & Go
72
+ ```
73
+
74
+ ## What works
75
+
76
+ - **Four wire transports**, chosen per model:
77
+ - OpenAI Chat Completions (DeepSeek, GLM, Kimi, MiMo, LongCat, Hy3, Step, …).
78
+ - Anthropic Messages (Claude Haiku, MiniMax, Qwen).
79
+ - OpenAI Responses (GPT, Grok, Muse).
80
+ - Google Generative AI (Gemini).
81
+ - **Text, reasoning, streamed tool calls, usage, finish reasons.**
82
+ - **Images** through the durable attachment service, rendered natively per transport.
83
+ - **Replay of provider metadata** where the endpoint requires it:
84
+ - Anthropic thinking signatures.
85
+ - Gemini `thoughtSignature` on historical function calls.
86
+ - **Multi-account rotation** before a stream starts: 401/403/429 and quota/usage-limit bodies (400/402/403/429). An invalid key cools down for 24h, a quota rejection for 10 minutes or `Retry-After`, a rate limit for 60s or `Retry-After`. A request already streaming is never replayed on another account; the next request uses the next usable key.
87
+ - **Per-account quotas**: each account row shows its own 5-hour / weekly / monthly usage, the active account drives the sidebar and quota panel, and the panel lists every account side by side.
88
+ - **Model → account rules**: first matching glob pins a preferred account for that model; the other accounts remain fallbacks if it fails or is cooling.
89
+ - **Request heatmap** in the quota panel: a Monday-first weekday × hour grid in local time, plus a 24-hour aggregate strip underneath. A selector switches between all requests and any single model. The adapter appends `{at, provider, model, purpose?}` to `~/.dsh/storages/dsh-opencode/requests.jsonl`; no prompt, response or key is stored. Auxiliary `session-title`/`compaction` calls are excluded from the heatmap and exact duplicate records collapse. The log compacts at 2 MB to the newest 5000 lines. Collection starts with this build — the projection cache only has `lastPromptAt`, not per-request timestamps.
90
+ - **Stable `x-opencode-session`** derived from the durable session id, so retries and every turn of a conversation reuse the same routing key.
91
+ - **Live catalog** from `/v1/models` with a generated `models.dev` fallback.
92
+ - **Per-model subscription limits** from the OpenCode Go pricing table: monthly dollar allowance plus estimated requests for the 5-hour, weekly and monthly windows, for both Go and Go Plus. Shown in the model picker and the settings page; estimates only — the gateway remains the authority.
93
+ - **`/opencode` command** for status, usage, accounts, models, rules, and `test [model]`.
94
+ - **TUI settings section** for the terminal profile (`/settings → OpenCode`) with the key, endpoints, allowlist, active account and timeouts.
95
+ - **One-click plugin update** in Settings → OpenCode: current/latest version, an update badge, and an **Update now** button that installs the exact npm version through the DSH CLI and asks for a restart. The host endpoint is `GET/POST /dsh-opencode/update`.
96
+ - **Plan-aware Go picker**: hides models outside the Go table unless turned off; descriptions carry `Go`, `Console` or `FREE`.
97
+ - **Request-wide image budget** (newest images win, oldest become an omitted placeholder) and **object-root tool-schema normalization** for MCP/third-party tools.
98
+ - **Usage analytics dashboard** in the quota panel: KPI cards (requests, tokens, success, input/output, reasoning, cache, TTFT, latency, errors), a 7/30/90 selector, and Models / Days / Sessions tables. Success and error cards show `—`: the local projection does not expose failed attempts or reasoning tokens.
99
+ - **Usage by model** from the local session projection cache: sessions and tokens per OpenCode model. Only numeric metadata is read; titles and message content stay local.
100
+ - **Browser UI**:
101
+ - **Settings → OpenCode**: key status, paste/import/clear, quota bars, accounts, model allowlist, per-model transport overrides, connection settings.
102
+ - **Sidebar quota card** (off by default): a ring with the active account and the highest window, then 5-hour / weekly / monthly rows with remaining quota, reset countdown and bars; clicking opens the full quota panel in the center column. The panel scrolls internally, so the heatmap and usage table below the fold stay reachable.
103
+ - **Cost** is shown only by DSH's native cost display; the plugin does not add a second composer pill.
104
+ - Model price badges in the settings page; the OpenCode auth-entry field autocompletes from `auth.json`.
105
+ - Host routes under `/dsh-opencode/*` serve state and accept writes only from a loopback Host with same-origin and JSON checks; `GET /dsh-opencode/health` reports provider registration, accounts and model count.
106
+ - The provider keeps core harness tools (`read`, `write`, `edit`, `bash`, `glob`, `grep`, …) when a large MCP set is trimmed to OpenCode's 128-tool limit.
107
+
108
+ ## Install
109
+
110
+ Build and pack first:
111
+
112
+ ```bash
113
+ npm install
114
+ npm run build
115
+ npm pack
116
+ ```
117
+
118
+ Install the **packed tarball** into a profile:
119
+
120
+ ```bash
121
+ dsh plugin --profile web add /absolute/path/to/goodandready-dsh-opencode-provider-0.5.1.tgz
122
+ # DSH Desktop:
123
+ dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-opencode-provider-0.5.1.tgz
124
+
125
+ # Or install the published package:
126
+ dsh plugin --profile web add @goodandready/dsh-opencode-provider@0.5.1
127
+ ```
128
+
129
+ Restart dsh (or DSH Desktop), then pick `OpenCode` or `OpenCode Go` in the model picker.
130
+
131
+ > **Use the tarball, not the directory.** On dsh 0.2.1-rc.2 the Desktop CLI aliases a local
132
+ > directory passed to `dsh plugin add` as `@deepseek-ai/dsh-desktop-runtime` and overwrites
133
+ > the target's `package.json`. Installing the packed `.tgz` avoids that path and installs
134
+ > the package under its real name.
135
+
136
+ ## Verified in DSH Desktop
137
+
138
+ Tested against DSH Desktop **0.2.1-rc.2**:
139
+
140
+ - the plugin loads and `/dsh-opencode/state` returns `200`;
141
+ - the key is picked up from `~/.local/share/opencode/auth.json`;
142
+ - the live catalog returned 37 models with prices and Go limits;
143
+ - quota windows returned `rolling / weekly / monthly`;
144
+ - `/dsh-opencode/analytics` scanned 7 local sessions (0 OpenCode sessions yet, as expected before the first OpenCode chat);
145
+ - `/dsh-opencode/test` against the default flash model returned `{"ok":true,"text":"OK"}`;
146
+ - a second Go account was added, the default key was temporarily replaced with an invalid one, and `/test` rotated to the second account and still returned `OK`;
147
+ - the second account was already at ~98% of its monthly allowance; the rotation test pushed it over, so a later run surfaced `QUOTA`, marked the default as `invalid-credential` and `Go #2` as `quota` until its reset, with no active account;
148
+ - per-account usage returned `default` 1% / 5% / 2% and `Go #2` 9% / 4% / **100%** monthly (`rate-limited`), so the exhausted account is visible without a failed request;
149
+ - two `/test` requests produced `Tue 13:00 = 2` in the heatmap and two lines in `requests.jsonl`; the 24-hour strip shows the same value at 13:00;
150
+ - a third request with a free-tier model added a second per-model series, so the model selector is populated;
151
+ - after restarting Desktop, `Go #2` still showed its persisted `quota` cooldown while the restored default key was active;
152
+ - setting `*free* → Go #2` through `/config` returned the normalized rule from `/state`, and clearing it returned `[]`; the account list stayed unchanged;
153
+ - the redesigned sidebar card was checked in Desktop: `OpenCode Go` with a 5% ring, `5-Hour Window 99% remaining · 3h`, `Weekly Window 95% remaining · 6d`, `Monthly Window 98% remaining · 29d`; it uses the DSH theme variables and matches the meter's row/ring layout;
154
+ - a real chat produced two OpenCode sessions: one standard flash model (4105 in / 243 out, ≈$0.00079) and one free model (10670 in / 171 out, Free); the heatmap counted 6 main requests (the two title calls and exact duplicates are filtered);
155
+ - the renderer loaded the client bundle (`settings.opencode` is present in its code cache).
156
+
157
+ Open **Settings → OpenCode** and enable *Show the quota card in the sidebar* if you want the sidebar meter.
158
+
159
+ ## Configure
160
+
161
+ ```yaml
162
+ - id: llm-opencode
163
+ name: "@goodandready/dsh-opencode-provider"
164
+ config:
165
+ apiKeyEnv: OPENCODE_API_KEY # default
166
+ # apiKey: oc_sk_... # composition only, never commit
167
+ openCodeAuthEntry: opencode-go
168
+ requestTimeoutMs: 300000
169
+ streamIdleTimeoutMs: 300000
170
+ visibleModels: []
171
+ modelTransports: {}
172
+ # contextWindowOverrides: { model-id: 65536 }
173
+ # maxOutputTokens: 32768
174
+ accounts:
175
+ - label: Go #2
176
+ apiKeyEnv: OPENCODE_API_KEY_2
177
+ activeAccount: '' # label or credential name to pin
178
+ ```
179
+
180
+ Every field except `apiKey` is volatile and appears in dsh settings.
181
+
182
+ ### Keys
183
+
184
+ 1. `config.apiKey` (composition only, `role('secret')`).
185
+ 2. The dsh credential seam under `apiKeyEnv`.
186
+ 3. `~/.local/share/opencode/auth.json` → entry `openCodeAuthEntry` (default `opencode-go`), written by OpenCode's own `/connect`.
187
+ 4. The launch environment (process, project `.env`, `$DSH_HOME/.env`).
188
+
189
+ Extra `accounts` resolve the same way (literal key or credential reference). If you already use OpenCode, the plugin picks up the stored Go key automatically.
190
+
191
+ ### Accounts and rotation
192
+
193
+ Add a second account in **Settings → OpenCode → Accounts**: give it a name and a credential reference (for example `OPENCODE_API_KEY_2`), paste its key, then Save. The default account (the key card at the top) always serves first unless `activeAccount` pins another one.
194
+
195
+ Rotation happens **before any content is streamed**. When the serving key is rejected with an invalid credential, a rate limit, or an exhausted quota, the adapter marks that key and retries the same request with the next usable account. An exhausted pinned account still falls back to the others; it returns to service once its cooldown passes. A request that has already started streaming is not replayed on another account.
196
+
197
+ Each account row shows the current cooldown (`Invalid key`, `Quota cooldown · 23h`, `Rate limited · 30s`) and its own quota chips. The active marker moves to the first account that is not cooling down. The last account is marked too, so a failed turn explains which key ended it. Quota cooldowns honor the provider's reset (`Retry-After`) when present. The quota panel repeats the numbers in an accounts table, and the sidebar meter uses the active account.
198
+
199
+ Cooldowns survive restarts: deadlines and reasons are stored in `~/.dsh/storages/dsh-opencode/cooldowns.json` keyed by a SHA-256 fingerprint — raw keys are never written. Expired entries are dropped on load, and the file keeps at most 50 entries.
200
+
201
+ ### Model → account rules
202
+
203
+ Pin a model to a preferred account with a glob. The first matching rule wins; `*` and `?` are supported and matching is case-insensitive. The named account is tried first, and the other accounts remain fallbacks if it is cooling, missing, or rejected — a rule is a preference, not a hard filter. An unknown account label is ignored, and rules apply to both `opencode` and `opencode-go`.
204
+
205
+ Configure them in **Settings → OpenCode → Model → account rules**, or in YAML:
206
+
207
+ ```yaml
208
+ modelAccountRules:
209
+ - pattern: "*free*"
210
+ account: "free"
211
+ - pattern: "your-provider-*"
212
+ account: "go"
213
+ ```
214
+
215
+ The account label is the same one shown in **Accounts** (`default` or the extra account's name).
216
+
217
+ ### Request heatmap
218
+
219
+ The quota panel has a **Request heatmap**: rows are Monday–Sunday, columns are local-time hours, and each cell counts calls made through this adapter (including tool-loop steps and `Test connection`). Auxiliary `session-title` and `compaction` calls are excluded, and exact duplicate records collapse; tool-loop steps are separate adapter requests, so one chat message is not necessarily one cell. Hover a cell to see the exact count. A 24-hour strip below the grid aggregates the same window by hour across all days, so the daily shape stays readable even when the grid is sparse. When more than one model has traffic, a selector switches the grid and strip to a single model; each option shows its total. The data is append-only metadata in `~/.dsh/storages/dsh-opencode/requests.jsonl`; it never includes prompts, responses or keys. Because the local projection cache stores only the last prompt time per session, the heatmap starts collecting with this build and grows as you use the plugin.
220
+
221
+ ## Settings page
222
+
223
+ Open **Settings → OpenCode**:
224
+
225
+ - **Key** — status, paste a new key, import the key OpenCode already stored, clear it, or run a **Test connection** against a chosen model and see the latency and reply.
226
+ - **Quota** — 5-hour, weekly and monthly bars with reset dates, plus warning banners at 80% and 95%.
227
+ - **Accounts** — add extra accounts by credential reference, set each account's key from the page, see whether it is configured, pin one, or return to automatic rotation.
228
+ - **Models** — search, refresh the live catalog, uncheck models to build an allowlist, override the wire transport per model, and see each model's input/output price plus its Go request estimate (`Go 34.7K/5h`). Hover the estimate for the full Go / Go Plus monthly allowance and 5h/week/month request counts; expand **Subscription limits** for a table of every model with both plans.
229
+ - **Connection** — API bases, usage endpoint, timeouts, output cap, context override, sidebar-card switch. The OpenCode auth-entry field autocompletes from the keys present in `auth.json`.
230
+ - **Plugin update** — current/latest version, update badge, and **Update now**. It installs the exact registry version through the normal `dsh plugin add` path, blocks a second click while installing, and reports when DSH must be restarted.
231
+
232
+ The sidebar quota card is **off by default**. Enable *Show the quota card in the sidebar* in the settings page; clicking the card opens the full quota panel, which also carries the **Usage by model** table (7/30/90-day window).
233
+
234
+ The Host serves `/dsh-opencode/state`, `/health`, `/analytics`, `/config`, `/key`, `/key/clear`, `/auth-import`, `/refresh`, `/models/refresh`, `/test` and `/update`. Writes require JSON, are refused for cross-origin requests, and are restricted to loopback (`127.0.0.1` / `::1`); reads stay same-origin. This keeps key and configuration writes off a LAN-exposed web server until the host's own auth token can be integrated.
235
+
236
+ ## Updates
237
+
238
+ The **Plugin update** card in Settings → OpenCode calls `GET /dsh-opencode/update`, which compares the installed `package.json` with the npm registry. When a newer version exists, **Update now** sends the same-origin request with `x-dsh-plugin-update: 1`; the Host runs the normal DSH CLI:
239
+
240
+ ```text
241
+ dsh plugin --profile <profile> add --config.minimumReleaseAge=0 @goodandready/dsh-opencode-provider@<exact-version>
242
+ ```
243
+
244
+ The update is blocked while another update is running, never uses `--force`, and never installs from a worktree or a `file:` path. The card reports that DSH must be restarted after a successful install. If the runtime does not expose the CLI entry, the card says that automatic update is unavailable and points to the DSH plugin manager; the status check still works.
245
+
246
+ ## Visual verification
247
+
248
+ ![OpenCode quota and analytics panel](media/visual-verification.png)
249
+
250
+ Captured from the exact 0.5.0 release candidate in DSH Desktop in the dark theme.
251
+
252
+ ## Command
253
+
254
+ ```
255
+ /opencode status # accounts, per-account quotas, rules
256
+ /opencode usage # quota windows only
257
+ /opencode accounts # labels, source, active/cooling, 5h/wk/mo
258
+ /opencode models # ids, FREE/Go limits
259
+ /opencode rules # model → account rules
260
+ /opencode test [model] # minimal real request
261
+ ```
262
+
263
+ ## Verified API facts
264
+
265
+ - `GET /inference/go/v1/models` is public and returns the live Go roster.
266
+ - `GET /zen/go/v1/usage` returns `rolling` (5h), `weekly`, `monthly` with `percent` and `resetsAt`. It is undocumented; the plugin treats it as fail-open.
267
+ - The unified `POST /zen/go/v1/chat/completions` accepts OpenAI-compatible **and** Anthropic-backed models, but **not** Responses-only or Google models.
268
+ - Responses-only models and Gemini need their native endpoints, which the plugin uses.
269
+ - Gemini requires replaying `thoughtSignature` on historical function calls; the Google transport stores it in dsh's replay state.
270
+ - `x-opencode-session` is mandatory. A stable opaque value is enough for a Go key; the canonical `ses_*` shape and CLI impersonation are only needed for the anonymous free lane, which this plugin deliberately does not implement.
271
+ - Free-tier anonymous keys are rejected with `403 FreeTierError`; free models work normally with an active Go subscription.
272
+
273
+ ## Development
274
+
275
+ ```bash
276
+ npm run typecheck
277
+ npm run build
278
+ npm test
279
+ npm run check # typecheck + tests + build
280
+ npm run release # check + packed tarball
281
+ npm run sync:models # regenerate src/models.generated.ts from models.dev
282
+ ```
283
+
284
+ GitHub Actions runs `npm run check` and `npm pack` on push/PR (`.github/workflows/ci.yml`).
285
+
286
+ ## Limitations
287
+
288
+ - Verbatim file attachments are not forwarded yet; images are.
289
+ - The usage endpoint is unofficial and may change; chat never depends on it.
290
+ - Cost is displayed only by DSH's native cost display; this plugin has no second composer cost pill.
291
+ - Automatic update requires the DSH CLI entry in the runtime. When it is not exposed, the update card shows the current/latest status and directs the user to the DSH plugin manager.
292
+ - Subscription request counts are OpenCode's published estimates, not enforced quotas. They can change when OpenCode updates the Go pricing table; the gateway is the final authority.
293
+ - Usage-by-model aggregates the local projection cache and attributes a whole session to its last-used model; a session that switched models is therefore approximate. It never reads prompt text or titles.
294
+ - `opencode` (Console) billing shows no per-model allowance; the Go route is the primary target.
295
+ - The anonymous free lane (`Bearer public` + CLI impersonation) is not implemented.
296
+ - The UI requires a web profile (the Host needs `ctx.webServer`); the TUI keeps the `/opencode` command and the model routes.
297
+ - Write routes are loopback-only; a web profile exposed to a LAN can read state but cannot save configuration or keys until the host auth token is integrated.
298
+
299
+ ## License
300
+
301
+ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY). See [LICENSE](./LICENSE) and [NOTICE](./NOTICE).
302
+