opencode-next 0.0.0-stage → 1.0.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,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FishBottle7 (original opencode2dsh)
4
+ Copyright (c) 2026 OpenCode-Next-for-DSH contributors
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,340 @@
1
- # Temporary Holding Version
1
+ # OpenCode-Next (`opencode-next`)
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
+ English | [繁體中文](./README.zh-TW.md)
4
+
5
+ Native OpenCode OAuth & OpenCode Go Provider for DeepSeek Harness (DSH).
6
+
7
+ > Derived from [FishBottle7/opencode2dsh](https://github.com/FishBottle7/opencode2dsh). Internal package/provider identifiers (`opencode-next`, `opencode-next`, `opencode-go-subscription`) are preserved for configuration and account compatibility.
8
+
9
+ Connects directly to the official OpenCode `/inference/openai/v1` endpoint using personal OAuth tokens, eliminating 403 `FreeTierError` and harsh single-IP 429 rate limits.
10
+
11
+ ## Highlights
12
+ - **Dual-Track OAuth**: Automatically inherits logged-in OAuth tokens from local OpenCode Desktop (`~/.local/share/opencode/opencode.db`), or standalone browser login via `opencode-next-login` (RFC 8628 Device Authorization Flow).
13
+ - **Official Authenticated Endpoint**: Uses `https://opencode.ai/inference/openai/v1/chat/completions`.
14
+ - **Full Reasoning Stream**: Translates `reasoning_content` deltas directly to DSH `reasoning-delta` chunks in real time.
15
+ - **Full Tool Calling**: Seamless support for DSH agentic tools (read, write, edit, pwsh, etc.).
16
+ - **Live Catalog Sync**: Discovers models directly from `models.opencode.ai`.
17
+ - **Resilient Availability Detection**: New free models appear only after a successful probe; existing models are hidden after two consecutive model-specific failures, while confirmed 404/410 retirements disappear immediately and successful probes restore models automatically.
18
+ - **Settings Page**: A dedicated **OpenCode-Next** section in DSH Settings split into four tabs (**Account**, **Free Models**, **Advanced**, and **OpenCode Go**) to sign in/out, curate which free or Go models appear in the DSH picker, and inspect quota & probe status.
19
+ - **Official v2 Protocol Alignment & Bun Transport**: Native Bun transport with automatic environment detection (`bun.exe`), upstream header alignment (`x-opencode-org-id`, workspace SHA1 hash, `max_completion_tokens`), and transparent bidirectional tool name aliasing to eliminate 429 pseudo-rate-limiting while fully preserving all DSH agent tools.
20
+
21
+ ## Automatic Model Detection
22
+
23
+ The public catalog lists far more free models than the free lane actually
24
+ serves: some entries stay behind with `status: "deprecated"` yet still answer,
25
+ while others look active and return `Model is unavailable`. The public catalog
26
+ is therefore treated as a candidate list, separate from picker availability.
27
+ New candidates are published only after a successful probe. An existing model
28
+ stays in the picker through one recoverable model-specific failure and is hidden
29
+ on the second consecutive failure; a successful probe restores it immediately
30
+ and clears its streak. Explicit 404 `not-found` and 410 `deprecated` responses
31
+ hide a model immediately. A generic 400 `unavailable` marker is not treated as
32
+ proof of retirement and follows the two-failure rule.
33
+
34
+ Two cadences run in the background:
35
+
36
+ | Job | Default interval | What it does |
37
+ | --- | --- | --- |
38
+ | Catalog poll | 15 min | Re-fetches the catalog and probes only newly listed free models |
39
+ | Full re-verification | 6 h | Re-probes every candidate so retired models drop out |
40
+
41
+ Results, the published picker set, and consecutive-failure counters persist to
42
+ `~/.dsh/opencode-next.models.json` and are reused on restart. Existing v1 cache
43
+ files remain readable; newly written cache files include the durable failure
44
+ state so restarting does not reset hysteresis. Stale results still trigger a
45
+ full re-verification, without discarding the last known picker state first.
46
+
47
+ A probe opens a real streaming request and cancels it the moment the status
48
+ line arrives: a healthy model costs ~1–2 s and a dead one ~0.3–1 s, with
49
+ bounded concurrency. If the lane itself is blocked or a sweep is incomplete,
50
+ no partial model verdicts are committed: availability and failure counters stay
51
+ unchanged. A per-model 403 `RegionError` is treated as a model-specific failure,
52
+ not a blocked lane.
53
+
54
+ ### A run stops early, and says where
55
+
56
+ The free lane has a small daily quota, so a probe bails out immediately in two
57
+ cases:
58
+
59
+ | Case | Why it stops |
60
+ | --- | --- |
61
+ | Any model returns `429` (rate limit / quota spent) | Sending 40 more requests would burn the rest of the day's quota |
62
+ | The lane is unreachable (`403` abuse block, `401`, `5xx`, `402`) | Every remaining request would return the same error |
63
+
64
+ Models that were not probed **keep their previous verdict**; they are never
65
+ marked as failed. The settings page shows "this run stopped after N of M" with
66
+ the reason, and that state is written to the cache so it survives a restart. A
67
+ complete run clears the marker.
68
+
69
+ So "13 available but only 4 probe rows" is not data loss — the fourth model hit
70
+ a rate limit and the run stopped there. Re-probe after the quota window resets,
71
+ or use the models already known to work.
72
+
73
+ ### When the quota comes back
74
+
75
+ A 429 carries a `retry-after` header (measured: `5397`, about 90 minutes). The
76
+ plugin reads it and converts it to local time:
77
+
78
+ ```
79
+ Free quota resets 08:18 (in 1 hour 27 minutes).
80
+ ```
81
+
82
+ When upstream omits the header, no time is shown at all — it does not guess.
83
+ That matters: a guessed "about five minutes" makes you hit the same wall every
84
+ five minutes.
85
+
86
+ ### Context window and output limits
87
+
88
+ Capacity comes from the upstream catalog and varies a lot:
89
+
90
+ | Model | Context | Max output |
91
+ | --- | --- | --- |
92
+ | `deepseek-v4.1-flash-free` | 200000 | 32000 |
93
+ | `beam-free` | 1048576 | 131072 |
94
+ | `minimax-m3.1-flash-free` | 1000000 | 512000 |
95
+ | `trinity-large-preview-free` | 131072 | 131072 |
96
+
97
+ The settings page lets you override one model's context window (click the
98
+ number in the Context column). The accepted range is `1024`–`100000000`,
99
+ deliberately wide: the real limit lives upstream, and a narrow hard-coded cap
100
+ would look like a validation bug. Exceeding the upstream limit returns
101
+ `400 context-overflow`, which is reported as "shorten the message or compact",
102
+ never as a retired model.
103
+
104
+ An override only changes DSH's budget calculation; it does not raise the
105
+ upstream limit.
106
+
107
+ ### Configuration
108
+
109
+ ```jsonc
110
+ {
111
+ "autoDetectModels": true, // set false to pin the static list
112
+ "catalogPollMs": 900000, // 15 min; 0 disables new-model polling
113
+ "probeIntervalMs": 21600000, // 6 h full re-verification
114
+ "probeCachePath": "", // default ~/.dsh/opencode-next.models.json
115
+ "streamIdleTimeoutMs": 60000, // fail a silent stream so the runtime can retry
116
+ "imagePixelBudget": 640000, // 800x800; images above this are downscaled
117
+ "imageMaxBytes": 2097152 // 2 MiB per projected image
118
+ }
119
+ ```
120
+
121
+ `streamIdleTimeoutMs` covers the case where the free lane answers `200` and then
122
+ goes quiet: the connection stays open but no frame ever arrives. Without it the
123
+ turn hangs until TCP times out and the runtime sees no error it can retry. The
124
+ watchdog aborts the underlying fetch and raises `TIMEOUT`, which is in
125
+ `SAFE_RETRY_POLICY.retryableCodes`. Waiting for the *first* frame uses the
126
+ shorter of `DEFAULT_FIRST_EVENT_MS` and this value.
127
+
128
+ `imagePixelBudget` and `imageMaxBytes` bound the projection handed to the
129
+ attachment service. They are deliberately fixed rather than adaptive: the
130
+ request-variant id is a hash of the attachment plus this target, so a target
131
+ that drifts between calls would invalidate the cache on every turn.
132
+
133
+ Effort values are taken verbatim from the catalog instead of being guessed:
134
+ upstream rejects unsupported values with `400 [unsupported_value]`, and the
135
+ accepted set differs per model (for example `beam-free` accepts `low` through
136
+ `max` but not `minimal`, while `deepseek-v4.1-flash-free` accepts only `low`,
137
+ `high`, and `max`). The catalog spells "no reasoning" as `none`; DSH spells it
138
+ `off`, and the adapter maps it back on the wire.
139
+
140
+ ## Settings Page (DSH Settings → OpenCode OAuth)
141
+
142
+ DSH Settings gains an "OpenCode OAuth" tab (order 14) with four blocks:
143
+
144
+ | Block | Contents |
145
+ | --- | --- |
146
+ | Header | Health badge (ready / expiring / unprobed / signed out / expired / no model responding) plus a one-line conclusion |
147
+ | Authorization | Credential source, expiry, whether it auto-refreshes; buttons for re-verify, sign in (or sign in again), and sign out |
148
+ | Models | Available vs. total, last probe time, search, an "only problems" filter, per-model status / latency / explanation, and a context-window setting for each model |
149
+ | Diagnostics | Provider id, plugin version, probe interval, catalog poll, image pixel budget and byte cap |
150
+
151
+ Expand a model's **Context window** setting to follow the OpenCode catalog value or enter a manual override. **Restore default** removes that model's override; it does not send a probe request. A manual value changes the capacity and budget DSH receives, but does not raise OpenCode's actual limit or change DSH's compaction policy. Only model IDs and numeric values are stored in `~/.dsh/opencode-next.context.json` (or under `DSH_HOME` when set).
152
+
153
+ After starting a sign-in the tab shows the device code and verification URL, and
154
+ polls every 2 s until authorization completes (15 s otherwise).
155
+
156
+ ### Secrets never leave the host
157
+
158
+ The page reports **whether** a credential exists and **when** it expires, but
159
+ never sends an access or refresh token to the browser, and the page never
160
+ accepts a secret as input. This is deliberate: the tab runs in a browser, so a
161
+ token placed there is readable by any script on the page.
162
+
163
+ ### Why health messages are translated client-side
164
+
165
+ The host's `status.js` builds a fixed Chinese sentence. Rendering it verbatim
166
+ made the English page bilingual, so the page now resolves that sentence from its
167
+ own dictionary by the stable `health` code and falls back to the host string
168
+ only for a code it does not recognize. `test/render.test.mjs` asserts the
169
+ English page contains no Chinese characters, so this cannot regress silently.
170
+
171
+ ### Two concurrent sign-ins request only one device code
172
+
173
+ There is an `await` between "is a sign-in already pending?", "ask upstream for a
174
+ device code", and "record it as pending". Without a guard, two nearly simultaneous
175
+ requests both saw no pending sign-in, each requested its own device code, and the
176
+ second overwrote the first. A user could approve the code shown on screen while
177
+ the plugin was now tracking a different one, so the sign-in appeared to finish
178
+ but left no credential. The symptom is hard to reproduce — it looks like "sign-in
179
+ sometimes needs two attempts" — so `lib/web-api.js` keeps a `deviceCodeRequest`
180
+ promise and makes a concurrent second request share that code instead of asking
181
+ for another.
182
+
183
+ A `loginGeneration` counter covers the other ordering: if the user signs out
184
+ while a request is still awaiting, that request no longer records itself as
185
+ pending and does not return a verification URL (the page would otherwise open a
186
+ sign-in page for a code that is already dead). `test/race.test.mjs` pins these
187
+ behaviours, and `test/race-mutation.test.mjs` removes the guards and confirms the
188
+ checks actually fail — a test that is always green may be testing nothing.
189
+
190
+ ## Failure Classification
191
+
192
+ Upstream failures are classified in `lib/failures.js` and attached to the thrown
193
+ error as a `.failure` snapshot, because that is the only thing the runtime reads.
194
+
195
+ A third-party adapter **must** attach `.failure` whose `failure.code` matches the
196
+ error's own `code`. `normalizeLlmFailure` returns the carried snapshot only when
197
+ the two agree; otherwise it rebuilds one from `harnessErrorCode(error)`, which
198
+ answers `UNKNOWN` for anything that is not a `HarnessError`. A plain `Error`
199
+ with a hand-assigned `.code` is therefore always flattened to `UNKNOWN` — which
200
+ silently defeated the documented retry behaviour, since the watchdog's `TIMEOUT`
201
+ never matched `SAFE_RETRY_POLICY.retryableCodes`.
202
+
203
+ Two other defects in the same path were fixed alongside it:
204
+
205
+ - `403` was not triaged. The body's `error.type` now distinguishes
206
+ `FreeTierError` (the free lane refuses the request) from `RegionError` (this
207
+ model is unavailable from here), so the two produce different explanations
208
+ instead of one generic auth failure.
209
+ - The fallback code was `UPSTREAM`, which is not in DSH's failure-code family.
210
+ Routing is by `HarnessError.code`, so an unrecognized code cannot be matched
211
+ by any retry policy; unmapped 4xx responses now report `TRANSPORT` with an
212
+ `http-<status>` reason, which retries nothing and loses no information.
213
+
214
+ ## Quick Start
215
+
216
+ ### Install via DSH CLI
217
+
218
+ ```bash
219
+ # From npm (once published)
220
+ dsh plugin --profile desktop add opencode-next
221
+
222
+ # Or directly from GitHub
223
+ dsh plugin --profile desktop add github:kizaki-R/OpenCode-Next-for-DSH
224
+ ```
225
+
226
+ *(For Web/Headless profiles, replace `--profile desktop` with `--profile web`.)*
227
+
228
+ ### Installing from a local tarball
229
+
230
+ ```bash
231
+ npm pack
232
+ dsh plugin --profile desktop add ./opencode-next-1.0.0.tgz
233
+ ```
234
+
235
+ > **Re-pack after changing the source.** `npm pack` only includes files matched
236
+ > by the `files` allowlist in `package.json`, so after adding a file (for example
237
+ > `lib/ui.js` or `lib/failures.js`) an un-repacked tarball ships the old code to
238
+ > other machines — with no error, only a missing settings tab or a failure
239
+ > classification that does nothing.
240
+ >
241
+ > To verify: `test/package.test.mjs` (part of `npm test`) unpacks the tarball in
242
+ > the package root and hashes every shipped file against the current source,
243
+ > failing with the exact file names when they diverge. That is far more reliable
244
+ > than discovering the gap on another machine.
245
+
246
+ A `link:` dependency entry embeds an absolute path from the machine that wrote
247
+ it; on another computer it resolves to a directory that does not exist. Use that
248
+ machine's own path, or install the tgz.
249
+
250
+ ### Checks
251
+
252
+ ```bash
253
+ # Smoke test
254
+ npm run smoke
255
+
256
+ # Run full integration test suite
257
+ # (auth, catalog, probe, config resolution, failure classification, plugin entry
258
+ # point, settings page, rendering, concurrency races, content conversion,
259
+ # watchdog, streaming, tool calls, package integrity)
260
+ npm test
261
+ ```
262
+
263
+ ### Package integrity
264
+
265
+ `test/package.test.mjs` checks the artifact, not the source tree. The distinction
266
+ comes from a real slip: the code was finished, the suite was green, and the live
267
+ endpoints verified — but the packed tgz was two hours old and missing four files
268
+ added that day. Installing it on another machine produces **no error at all**;
269
+ it just has no settings tab and a failure classifier that does nothing.
270
+
271
+ That happens because `npm pack` only includes files matched by the `files`
272
+ allowlist, while a development machine gets its code through a junction, so
273
+ **this machine runs the live source and every other machine runs the tarball**.
274
+ The test hashes every `lib/*.js` against the tarball in the package root and
275
+ fails when they diverge, and it also verifies that `exports["./client"]` and
276
+ `dsh.client` point at files that actually ship, and that no shipped source
277
+ hardcodes a disk path.
278
+
279
+ `test/config-layers.test.mjs` covers the three fallback layers that
280
+ `lib/config.js` uses to obtain `schemastery`. None of them raise an error, so a
281
+ break is quiet: the plugin still loads and the defaults are still right, only
282
+ field-level validation (`min`/`max`) silently disappears. The test tells a real
283
+ validator from the built-in stub by checking whether an out-of-range value is
284
+ rejected, and confirms the second layer derives the profile directory from
285
+ `DSH_HOME` / `DSH_PROFILE_DIR` instead of embedding a developer's username in a
286
+ shipped file.
287
+
288
+ ## Free quota follows the exit IP
289
+
290
+ `Free usage limit reached` is counted mainly by network exit IP, and by workspace or organization. A new account, a new device, or a refreshed token on the same exit does not clear a spent quota. Wait for the rolling window, or use another network you control. Switching accounts is not a bypass.
291
+
292
+ A fake 429 with a `retry-after` of about 48,000 seconds is a different failure. Bun transport and the official request shape address that one. They do not raise the real free-tier quota.
293
+
294
+ ## Bun
295
+
296
+ The free lane rejects requests sent by Node.js. This plugin uses a Bun installed on the system; the OpenCode app does not ship a `bun` executable.
297
+
298
+ 1. Install Bun from [bun.sh](https://bun.sh).
299
+ 2. Open DSH Settings → OpenCode OAuth → Advanced.
300
+ 3. If it still says Bun is missing, press Rescan. No DSH restart is required.
301
+
302
+ Detection only accepts an absolute path found on `PATH`, so a same-named binary in the working directory cannot be executed by accident.
303
+
304
+ ## Scoped probes
305
+
306
+ The probe button follows the current filter:
307
+
308
+ | View | Button | What is probed |
309
+ | --- | --- | --- |
310
+ | All, no search | Re-probe | The candidate list |
311
+ | Available | Probe available (n) | Only the models on screen |
312
+ | Any other filter or search | Probe list (n) | Same, via the visible `modelIds` |
313
+
314
+ Results merge. Models not in this run keep their latency, availability, and history in `~/.dsh/opencode-next.models.json`. Switching accounts or restarting DSH does not delete that cache. The filter (for example staying on Available) is remembered in this browser's `localStorage`.
315
+
316
+ To change a context window, click the number in the Context column (for example `200k`). That opens its own dialog; the row does not expand.
317
+
318
+ ## Import from OpenCode Desktop
319
+
320
+ The account section has **Import from OpenCode Desktop**. It reads the Desktop sign-in and does not modify Desktop's database. Importing the same credential again does not create a duplicate; it switches to the existing account. An API-key-only local login is rejected, because the free lane does not accept API keys.
321
+
322
+ `opencode-next-login` writes both `~/.dsh/opencode-next.token.json` and `~/.dsh/opencode-next.accounts.json`. If an account list already exists, DSH prefers it, so a CLI login that only updated the legacy file would not take effect. An identical access token is not added twice; that account becomes active. Each OAuth HTTP call times out after 15 seconds. A denied approval, an expired code, or a timed-out wait is reported; it is not swallowed.
323
+
324
+ ## Anonymous channel
325
+
326
+ The Advanced switch is off by default. When on, inference is sent without the personal token, on a public anonymous lane OpenCode does not promise to keep. It can stop or be throttled at any time, and it is still subject to the exit IP. Turn it on only if that risk is acceptable.
327
+
328
+ ## OpenCode Go (Subscription Verification, Model Preview & Text/Tool Inference)
329
+
330
+ An independent, opt-in `opencode-go-subscription` provider is included alongside `opencode-next` (`goSubscription.enabled` defaults to `false` so existing free OAuth behavior stays unchanged):
331
+
332
+ - **Isolated credential resolution & UI management**: Uses an OpenCode Console Personal API Key via DSH's `credentials` service first (`goSubscription.credentialRef`, default `OPENCODE_GO_API_KEY`), falling back to the environment variable. In Settings → OpenCode Go, you can save or clear the key directly via `ctx.credentials.set` / `ctx.credentials.unset` without exposing or prefilling plaintext keys (if `credentials.set` is unavailable in the current DSH process, the button stays disabled and the key is never written into plugin config or JSON files). It never reuses OAuth tokens (`st_*`), `org_id`, or credentials from other plugins, and never stores plaintext keys in plugin config, status APIs, errors, or logs.
333
+ - **Read-only official endpoints**: Queries `GET https://opencode.ai/inference/go/v1/usage` to verify Go subscription entitlement, followed by `GET https://opencode.ai/inference/go/v1/models` for workspace model metadata (`redirect: 'manual'`, fixed `https://opencode.ai` origin). Key changes or disabling clears the isolated cache (`~/.dsh/opencode-go.cache.json`) and blocks stale in-flight writes.
334
+ - **Chat Completions text & tool calling**: Inference posts exclusively to `POST https://opencode.ai/inference/go/openai/v1/chat/completions` (`redirect: 'manual'`, `stream_options.include_usage`), requiring a real DSH `sessionId` for `x-opencode-session` (missing IDs are rejected without hashing or random UUIDs). It never uses CLI identity headers, Bun transport rewrites, tool aliases/baseline fake tools, auto-account switching, cross-provider fallback, or automatic retries of billed requests.
335
+ - **Startup auto-sync, usage gauges & custom Go picker**: Once a Personal API Key is saved, DSH automatically runs a read-only background refresh (`/usage` and `/models`) on startup (including delayed `credentials` service injection) without consuming inference quota. The OpenCode Go tab displays `5h Limit`, `7D Limit`, and `1M Limit` progress bars, a collapsible `API Key` drawer, and per-model picker checkboxes (`~/.dsh/opencode-next.go-picker.json`).
336
+ - **Selective picker publishing & catalog-driven image input**: Only eligible active Go text/chat models enter DSH's formal model picker. Image input (`image_url` data URIs via DSH `attachments`) is automatically advertised and sent for eligible models whose upstream Go catalog declares `image` / `image/*` input modalities; models without declared image input stay text-only and reject image attachments before any request is sent (never silently dropping images or falling back to free OAuth). Video, audio, and other non-image attachments remain unsupported.
337
+
338
+ ## License & Attribution
339
+
340
+ MIT License — see [LICENSE](./LICENSE). Derived from [FishBottle7/opencode2dsh](https://github.com/FishBottle7/opencode2dsh) (`Copyright (c) 2026 FishBottle7`).