omp-opencode-bridge 0.0.0-stage → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,892 @@
1
- # Temporary Holding Version
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.
1
+ # omp-opencode-bridge
2
+
3
+ OpenAI/Anthropic-compatible local API bridge for [OpenCode](https://opencode.ai) free-tier models, shipped with the keyless OMP/pi plugin. No account and no API key required.
4
+
5
+ It runs a local server on `http://127.0.0.1:20129/v1` that any OpenAI-compatible client (9Router, Cursor, Continue, LiteLLM, Open WebUI, or the OpenAI SDK) can call directly.
6
+
7
+ ## Origin
8
+
9
+ This repository packages the bridge from
10
+ [azrinaldi/opencode-free-bridge](https://github.com/azrinaldi/opencode-free-bridge)
11
+ (kept as the `upstream` remote) as a TypeScript runtime and an OMP/pi plugin.
12
+ Upstream remains the source for the installer download path and the
13
+ self-updater; this repository is what npm publishes and what
14
+ `omp plugin install` fetches.
15
+
16
+
17
+ ## What's New in v2.0.0
18
+
19
+ - **Bun TLS transport parity:** The official OpenCode CLI ships as a compiled Bun binary, and upstream's free-tier gate inspects the TLS `ClientHello` fingerprint (17 cipher suites and 12 TLS extensions in exact order). The bridge runs on Bun (`bun server.ts`), blocks accidental Node.js startups unless `ALLOW_NODE=1` is set for offline tests, and ships `transport-fingerprint.ts` to verify TLS parity against `transport-baseline.json`.
20
+ - **Full source & catalog derivation:** All hardcoded model tables (`MODEL_MAP`) and model-name substring heuristics have been removed. Client version, commit SHA, session ID recipe (`ses_` + 12 hex + 14 base62), 7 gate headers, 13 tool plugins (parsed from upstream's Effect Schema AST in GitHub source, 12 active per model after `patch` vs `edit`/`write` swap), inference endpoints (`chatUrl` and `responsesUrl`), active free models, shorthand family aliases, and reasoning token limits are derived directly from OpenCode's update API, GitHub repository, and `models.opencode.ai/api.json`.
21
+ - **On-disk catalog cache for instant cold starts:** Caches `models.opencode.ai/api.json` at `~/.opencode-free-bridge/cache/catalog.json` and loads it at startup (`OPENCODE_CACHE_DIR=off` disables disk caching). Shorthand aliases (`mimo`, `longcat`, `beam`), deprecated/paid model checks, and reasoning token budgets work on the very first request and when offline.
22
+ - **Multi-layer reactive self-healing with IP-cooldown protection:** On `403 FreeTierError`, `426 UpgradeRequired`, or `404` on a migrated endpoint path, the bridge refreshes its recipe and catalog, evicts stale session IDs, mints a fresh session ID, escalates to the full tool profile, and retries once transparently. If a full-shape retry still returns `403 FreeTierError` (indicating a per-IP upstream cooldown rather than a stale request shape), subsequent requests within the 30s cooldown window (`GATE_RETRY_COOLDOWN_MS`, `GATE_REFRESH_COOLDOWN_MS`) skip redundant GitHub fetches and duplicate retries so the bridge never amplifies an IP penalty. **Exception:** the gateway's explicit IP-level abuse block (*"detected abusive traffic from this IP address"* / `Detect Abuse Traffic`) is terminal — the bridge answers it verbatim with `X-OpenCode-Gate: ip-abuse` and performs no refresh, session re-mint, or retry, because no client-side change can clear a flag keyed to the egress network.
23
+ - **Gate anchors, so a shape bug can never masquerade as an IP block:** Upstream returns one `403 FreeTierError` — *"OpenCode's free tier can only be used from within OpenCode"* — for at least four unrelated causes: a refused egress IP, a request without a tool named `read`, a User-Agent that is not `opencode/<channel>/<semver>/<name>`, and a request without a session header. Measured by replaying byte-identical requests from a refused egress and a clean one, varying one field at a time: `read` + 11 fabricated tools → `200`, the real `read` renamed → `403`, a fabricated tool *named* `read` → `200`. The bridge therefore pins those anchors (`GATE_ANCHOR_TOOL_NAMES`, `GATE_ANCHOR_HEADER_NAMES`) independently of what the derived recipe and tool profile contain, audits the outgoing request when a `403` arrives, and reports `X-OpenCode-Gate: shape-rejected` plus the missing anchors instead of blaming the network. A second, unambiguous message (*"detected abusive traffic from this IP address"* or `Detect Abuse Traffic`) identifies a network-level block and is answered immediately as `ip-abuse`; only the ambiguous free-tier message goes through the shape audit at all. Upstream's `x-opencode-log-id` is recorded and exposed at `/health` (`identity.gate.lastRejection`) for correlation.
24
+ - **Zero-dead-end universal installer:** `install.sh` finds or installs Bun (and `unzip` when missing on minimal Linux), stages and validates every file before touching a running bridge, retires legacy `opencode-bridge.service` units, rewrites `node` units to `bun`, configures `systemd` (Linux) or `launchd` (macOS), and verifies `/health` and the TLS fingerprint baseline before succeeding.
25
+
26
+ ## Features
27
+
28
+ - **Self-healing client identity:** Derives the OpenCode CLI wire identity at the current release commit SHA and updates automatically when upstream tightens the gate.
29
+ - **Live catalog discovery:** Reads `models.opencode.ai/api.json` (and `/v1/models`) to expose only active free-tier models (`cost.input === 0`, non-deprecated) and reject retired or paid model IDs locally with a clear error.
30
+ - **Dual-protocol support:** Routes requests to `/inference/openai/v1/chat/completions` or `/inference/openai/v1/responses` based on catalog metadata and automatic protocol-mismatch detection.
31
+ - **Reasoning-aware token budgeting:** Applies an additive token floor (`max(requested, 1024) + 4096`) for reasoning models (determined from catalog `reasoning: true` metadata) so short prompts do not return empty content with `finish_reason: "length"`.
32
+ - **Reasoning stream normalization:** Emits thinking tokens under `reasoning_content` for both streaming SSE and non-streaming JSON responses, and forwards client tool calls with automatic name de-collision (`read` -> `read_client` upstream, restored to `read` on return).
33
+ - **Zero dependencies:** Uses only built-in runtime modules (`http`, `crypto`, `fs`, `path`, `net`, `tls`). No `npm install` step.
34
+ - **OMP / pi plugin:** Ships `src/index.ts`, declared under `pi.extensions`, so `omp plugin install omp-opencode-bridge` registers the local bridge as the keyless `opencode-free` provider and manages it with `/opencode-free`. No build step and still no dependencies beyond Node builtins.
35
+ - **Container deployment:** Ships a `Dockerfile` and `docker-compose.yaml` (contributed in PR #1 by @rustam76, completed in v2.1.0). The image pins `oven/bun:1.4.3-slim` — the Bun version is pinned because the free-tier gate inspects the TLS `ClientHello` — runs as the non-root `bun` user, and publishes the port on loopback only.
36
+
37
+ ## Requirements: Bun >= 1.0
38
+
39
+ Bun is required to talk to the live OpenCode gateway. Node.js 24+ (with its built-in TypeScript type stripping) can run the offline unit test suite, but upstream rejects Node.js requests with `403 FreeTierError` because Node's OpenSSL TLS `ClientHello` differs from the compiled OpenCode CLI (which is built on Bun/BoringSSL). The installer installs Bun for you when it is missing.
40
+
41
+ Supported: Linux (systemd) and macOS (launchd). Windows is not supported; use WSL if you need it there.
42
+
43
+ Measured against a raw TCP listener and the live gateway from the same IP within one minute, using identical headers and payload:
44
+
45
+ | Property | OpenCode CLI v2.0.32 | Bridge on Bun | Bridge on Node.js |
46
+ |---|---|---|---|
47
+ | TLS cipher suites offered | 17 | **17 (identical)** | 52 |
48
+ | TLS extensions offered | 12 | **12 (identical order)** | 11 (different order) |
49
+ | Default `Accept-Encoding` | `gzip, deflate, br, zstd` | **identical** | `gzip, deflate` |
50
+ | Live gateway result | `200 OK` | **`200 OK` (6/6)** | `403 FreeTierError` (0/6) |
51
+
52
+ Starting the server with `node server.ts` exits immediately with an explanation so a broken Node deployment cannot fail silently in the background:
53
+
54
+ ```bash
55
+ bun server.ts # required for live traffic
56
+ node server.ts # exits with code 1 and instructions
57
+ ALLOW_NODE=1 node server.ts # starts for offline tests and mocked upstreams only
58
+ ```
59
+
60
+ You can verify that your local Bun binary matches the recorded OpenCode CLI TLS baseline at any time:
61
+
62
+ ```bash
63
+ bun transport-fingerprint.ts --check # exits 0 if ciphers and extensions match
64
+ bun transport-fingerprint.ts # prints current TLS ClientHello JSON
65
+ bun transport-fingerprint.ts --write-baseline # updates transport-baseline.json
66
+ ```
67
+
68
+ ## Install & Update
69
+
70
+ ### One-line installer (Linux & macOS)
71
+
72
+ ```bash
73
+ curl -fsSL https://raw.githubusercontent.com/azrinaldi/opencode-free-bridge/main/install.sh | bash
74
+ ```
75
+
76
+ What `install.sh` does:
77
+ 1. Finds `bun` across `PATH`, `$BUN_INSTALL/bin`, `~/.bun/bin`, `~/.local/bin`, `/usr/local/bin`, and `/opt/bun/bin`, or installs it via `https://bun.sh/install` (installing `unzip` first on minimal Linux images when needed).
78
+ 2. Downloads every file into a staging directory and validates it (in-process JS syntax compilation, JSON parsing, and `bash -n` for `tunnel-doctor.sh`) before touching anything that is already running.
79
+ 3. Checks port availability (`ss` or `lsof`), retires a pre-2.0 `opencode-bridge.service` that would hold port 20129, and stops its own running bridge when upgrading in place.
80
+ 4. Backs up the previous install under `~/.opencode-free-bridge/.backup-*`, then moves the staged files into place.
81
+ 5. Registers and starts the background service (`systemd` system or `--user` unit on Linux, `launchd` agent with `~/Library/Logs/opencode-free-bridge.log` on macOS).
82
+ 6. Waits up to 20 seconds for `/health`, runs the quick self-check, and checks the Bun TLS fingerprint against `transport-baseline.json`.
83
+
84
+ If the bridge does not answer after 20 seconds, the installer exits with code `1` and prints the exact log inspection command. It only prints `Done.` when the bridge is answering.
85
+
86
+ Installer options:
87
+
88
+ ```bash
89
+ PORT=3000 BINDIR=/opt/opencode-free-bridge bash install.sh
90
+ NO_SERVICE=1 bash install.sh # install files only, skip systemd/launchd setup
91
+ ```
92
+
93
+ An occupied port aborts the install before anything is changed. To install alongside an existing service, choose a free port:
94
+
95
+ ```bash
96
+ PORT=20130 bash install.sh
97
+ ```
98
+
99
+ To update an existing installation, re-run the `curl ... | bash` command above. Running instances outside a git checkout also check for new releases in this repository every 6 hours (`AUTO_UPDATE=0` disables self-update).
100
+
101
+ ### Run from a git clone
102
+
103
+ ```bash
104
+ git clone https://github.com/azrinaldi/opencode-free-bridge.git
105
+ cd opencode-free-bridge
106
+ bun server.ts
107
+ ```
108
+
109
+ `bash install.sh` inside the clone installs that working tree (including
110
+ uncommitted or unpushed files) instead of downloading from GitHub. Force a
111
+ download with `SOURCE=remote bash install.sh`.
112
+
113
+ The server listens on `http://127.0.0.1:20129` by default.
114
+ Open `http://127.0.0.1:20129/` for the panel: it shows the live egress state and sets
115
+ an HTTP proxy for every outbound request. See [Egress proxy](#egress-proxy).
116
+
117
+ ### Docker
118
+
119
+ The repository ships a `Dockerfile` and a `docker-compose.yaml` for container
120
+ deployments (single host, no orchestrator needed):
121
+
122
+ ```bash
123
+ git clone https://github.com/azrinaldi/opencode-free-bridge.git
124
+ cd opencode-free-bridge
125
+ docker compose up -d
126
+ ```
127
+
128
+ The bridge is then reachable at `http://127.0.0.1:20129/v1` (API key `public`),
129
+ exactly like a native install, and the model catalog cache survives restarts in
130
+ the `bridge-cache` volume.
131
+
132
+ What the container setup does:
133
+
134
+ - Runs on `oven/bun:1.4.3-slim` as the non-root `bun` user. The Bun version is
135
+ pinned because the free-tier gate inspects the TLS ClientHello: the image
136
+ must produce the same fingerprint as the OpenCode CLI, which
137
+ `transport-baseline.json` records.
138
+ - Publishes the port on **loopback only**. The bridge has no authentication
139
+ (the API key is literally `public`), so publishing on `0.0.0.0` would expose
140
+ an open relay to the whole network. For remote access, put a reverse proxy
141
+ or an SSH tunnel in front of it.
142
+ - Persists the on-disk catalog cache in the `bridge-cache` volume
143
+ (`OPENCODE_CACHE_DIR=/data/cache`), so a restart does not re-fetch the
144
+ upstream model catalog.
145
+ - Persists the panel's egress-proxy setting in the `bridge-state` volume
146
+ (`OPENCODE_BRIDGE_STATE_DIR=/data/state`). Without it, the container
147
+ filesystem is thrown away on recreate and the proxy would silently revert.
148
+ - Runs with `no-new-privileges` and all Linux capabilities dropped.
149
+
150
+ The image is the unit of deployment, so `AUTO_UPDATE` defaults to `0` in the
151
+ compose file: an in-place self-update is reverted by the next
152
+ `docker compose build`. Upgrade with:
153
+
154
+ ```bash
155
+ docker compose build --pull && docker compose up -d
156
+ ```
157
+
158
+ Plain `docker run` works too — set `HOST=0.0.0.0` and publish the port
159
+ yourself:
160
+
161
+ ```bash
162
+ docker build -t opencode-free-bridge .
163
+ docker run -d --name opencode-free-bridge \
164
+ -p 127.0.0.1:20129:20129 \
165
+ -e OPENCODE_CACHE_DIR=/data/cache \
166
+ -e OPENCODE_BRIDGE_STATE_DIR=/data/state \
167
+ -v opencode-free-bridge-cache:/data/cache \
168
+ -v opencode-free-bridge-state:/data/state \
169
+ opencode-free-bridge
170
+ ```
171
+
172
+ ## OMP / pi plugin
173
+
174
+ The same package is an OMP (`omp` CLI) / pi extension:
175
+ installing it registers the bridge as the `opencode-free` provider, so an OMP
176
+ session can use the free models with no API key and no separate server setup.
177
+ The extension starts `bun server.ts` from the installed package on first use
178
+ (reusing an already-running bridge) and stops nothing you started yourself.
179
+
180
+ ```bash
181
+ omp plugin install omp-opencode-bridge # from npm
182
+ omp plugin install . # or link this working tree
183
+ omp plugin list | grep opencode-free
184
+ ```
185
+
186
+ Use a model:
187
+
188
+ ```bash
189
+ omp --model opencode-free/mimo-v2.6-flash-free -p "hello"
190
+ ```
191
+
192
+ Inside a session the `/opencode-free` command exposes the same surface:
193
+
194
+ | Subcommand | Effect |
195
+ |---|---|
196
+ | `status` | bridge health, model count, runtime/version |
197
+ | `models` | registered `opencode-free/<id>` list |
198
+ | `refresh-models` | re-read `GET /v1/models` and re-register the provider |
199
+ | `start` / `stop` / `restart` | control a bridge this plugin spawned |
200
+ | `health` | raw `/health` JSON |
201
+ | `logs` | tail `~/.opencode-free-bridge/omp-plugin.log` |
202
+
203
+ Configuration: `OPENCODE_BRIDGE_PORT` (default `20129`),
204
+ `OPENCODE_BRIDGE_BUN` (bun binary), `OPENCODE_BRIDGE_STATE_DIR` (state, log and
205
+ model-cache directory). The extension entry point is `src/index.ts`, declared
206
+ under `"pi": { "extensions": ["./src/index.ts"] }` — no build step, no
207
+ dependencies beyond Node builtins.
208
+
209
+ ## Usage & Client Setup
210
+
211
+ | Setting | Value |
212
+ |---|---|
213
+ | Base URL | `http://127.0.0.1:20129/v1` |
214
+ | API Key | `public` (any non-empty string is accepted) |
215
+ | Model ID | Any ID returned by `GET http://127.0.0.1:20129/v1/models` |
216
+
217
+ ### 9Router
218
+
219
+ 1. Add a custom OpenAI-compatible provider:
220
+ - **Base URL:** `http://127.0.0.1:20129/v1`
221
+ - **API Key:** `public`
222
+ - **Prefix:** `zen`
223
+ - **Model IDs:** leave empty and click **Import from /models endpoint**
224
+ 2. Models are imported as `zen/big-pickle`, `zen/mimo-v2.6-flash-free`, `zen/nemotron-3-ultra-free`, etc.
225
+ 3. Optional: if you run the bridge on multiple hosts (for example, a laptop and a VPS), register each host as a separate connection in 9Router so per-IP rate limits fail over automatically.
226
+
227
+ **9Router's SSRF guard blocks `127.0.0.1` by default.** The guard exists so a
228
+ request cannot reach an internal address, and the bridge's own base URL looks
229
+ exactly like one. Two ways through, depending on how 9Router was started:
230
+
231
+ | 9Router started… | What to do |
232
+ |---|---|
233
+ | With `ALLOW_PRIVATE_NETWORKING=true` | Nothing. The guard short-circuits for the whole process, so loopback works as documented above. |
234
+ | Without it | Add `ALLOW_PRIVATE_NETWORKING=true` to its service environment and restart. |
235
+
236
+ Symptom without it: the connection's test button fails and chat answers an
237
+ error, both reporting `request to private/reserved IP blocked by SSRF
238
+ protection`. The bridge itself is fine — `curl http://127.0.0.1:20129/health`
239
+ still answers `ok` from that host, so those two symptoms together mean the
240
+ guard, not the bridge.
241
+
242
+ This only applies to 9Router running on the same machine. Every other client
243
+ (LiteLLM, the OpenAI SDK, Cursor) talks to loopback directly and is unaffected.
244
+
245
+ ### LiteLLM, Open WebUI, Continue, Cursor
246
+
247
+ Use the same three settings: Base URL `http://127.0.0.1:20129/v1`, API key `public`, and model IDs from `/v1/models`.
248
+
249
+ ```yaml
250
+ # LiteLLM config.yaml example
251
+ model_list:
252
+ - model_name: zen-mimo
253
+ litellm_params:
254
+ model: openai/mimo-v2.6-flash-free
255
+ api_base: http://127.0.0.1:20129/v1
256
+ api_key: public
257
+ ```
258
+
259
+ ### Anthropic Messages API
260
+
261
+ The bridge also serves Anthropic's native `POST /v1/messages`, so Claude Code and
262
+ the Anthropic SDK can point at it directly. Model ids are the same bare ids the
263
+ OpenAI endpoint uses.
264
+
265
+ | Setting | Value |
266
+ |---|---|
267
+ | Base URL | `http://127.0.0.1:20129` |
268
+ | API key | `public` (sent as `x-api-key`, any non-empty string works) |
269
+ | Path | `/v1/messages` |
270
+
271
+ ```bash
272
+ curl -s http://127.0.0.1:20129/v1/messages \
273
+ -H 'Content-Type: application/json' \
274
+ -H 'x-api-key: public' \
275
+ -d '{"model":"big-pickle","max_tokens":1024,
276
+ "messages":[{"role":"user","content":"Reply with OK"}]}'
277
+ ```
278
+
279
+ ```python
280
+ from anthropic import Anthropic
281
+
282
+ client = Anthropic(base_url="http://127.0.0.1:20129", api_key="public")
283
+ message = client.messages.create(
284
+ model="big-pickle",
285
+ max_tokens=1024,
286
+ messages=[{"role": "user", "content": "Reply with OK"}],
287
+ )
288
+ print(message.content[0].text)
289
+ ```
290
+
291
+ Streaming is real, not replayed: `stream: true` relays each upstream delta as it
292
+ arrives, including `input_json_delta` for tool calls. `POST
293
+ /v1/messages/count_tokens` also answers — with a conservative 4-chars-per-token
294
+ estimate, because this bridge has no Anthropic tokenizer and a made-up exact
295
+ number would be worse than an honest approximation.
296
+
297
+ Anthropic-only parameters with no OpenAI equivalent — `thinking`, `top_k`,
298
+ `metadata`, `container` — are ignored, and the bridge logs one line naming them
299
+ so a caller that expected a thinking budget can see why it got none.
300
+
301
+ ### Coding agents & CLI tools
302
+
303
+ ```bash
304
+ export OPENAI_BASE_URL="http://127.0.0.1:20129/v1"
305
+ export OPENAI_API_KEY="public"
306
+ export MODEL="mimo-v2.6-flash-free"
307
+ ```
308
+
309
+ ### Python (OpenAI SDK)
310
+
311
+ ```python
312
+ from openai import OpenAI
313
+
314
+ client = OpenAI(base_url="http://127.0.0.1:20129/v1", api_key="public")
315
+
316
+ response = client.chat.completions.create(
317
+ model="mimo-v2.6-flash-free",
318
+ messages=[{"role": "user", "content": "Write a Python palindrome checker."}],
319
+ )
320
+ print(response.choices[0].message.content)
321
+ ```
322
+
323
+ ### curl
324
+
325
+ ```bash
326
+ curl -s http://127.0.0.1:20129/v1/chat/completions \
327
+ -H 'Content-Type: application/json' \
328
+ -d '{"model":"mimo-v2.6-flash-free","messages":[{"role":"user","content":"Reply with OK"}]}'
329
+ ```
330
+
331
+ ## Available Free Models
332
+
333
+ The model list is derived dynamically from `models.opencode.ai/api.json` (`cost.input === 0` and `status !== "deprecated"`) and cached at `~/.opencode-free-bridge/cache/catalog.json`.
334
+
335
+ Current active free-tier models in the upstream catalog:
336
+
337
+ | Model ID | Family Shorthand | Reasoning | Max Output Tokens |
338
+ |---|---|---|---|
339
+ | `big-pickle` | `big-pickle` | Yes | 32,000 |
340
+ | `beam-free` | `beam` | Yes | 131,072 |
341
+ | `mimo-v2.6-flash-free` | `mimo` | Yes | 32,000 |
342
+ | `nemotron-3-ultra-free` | `nemotron-free` | Yes | 128,000 |
343
+ | `nemotron-3.5-lightning-free` | - | Yes | 262,144 |
344
+ | `nemotron-3.5-super-vl-free` | - | Yes | 131,072 |
345
+ | `longcat-2.5-preview-free` | `longcat` | Yes | 131,072 |
346
+ | `deepseek-v4.1-flash-free` | `deepseek-flash` | Yes | 32,000 |
347
+ | `glm-5.3-flash-free` | `glm-flash` | Yes | 32,000 |
348
+ | `space-bunny-free` | - | Yes | 524,288 |
349
+
350
+ Query the live list from your running bridge:
351
+
352
+ ```bash
353
+ curl -s http://127.0.0.1:20129/v1/models
354
+ ```
355
+
356
+ Requests for retired models (such as `cat-jam-free`, `muse-spark-1.3-contributor-free`, or `step-5-preview-free`) or paid models (such as `claude-sonnet-4-5` or `gpt-5.4`) are rejected locally with HTTP `404` and an explanation rather than being forwarded upstream to fail with `401 Missing API key`.
357
+
358
+ ## Reasoning Models & Token Budgets
359
+
360
+ Reasoning models spend tokens on chain-of-thought before emitting visible text, and both share the same `max_completion_tokens` ceiling. When a client sends a small `max_tokens` (such as `50` or `100` for a health probe or title generator), a reasoning model can exhaust the entire budget while thinking and return an empty string with `finish_reason: "length"`.
361
+
362
+ `token-budget.ts` checks the model's `reasoning` flag from the catalog (`identity.getModelFacts(modelId)`) and applies an additive floor:
363
+
364
+ | Request Type | Effective `max_completion_tokens` Sent Upstream |
365
+ |---|---|
366
+ | Catalog `reasoning: true` model (or request with `reasoning_effort` set) | `min(max(requested, 1024) + 4096, modelMaxOutput)` |
367
+ | Non-reasoning model | `min(max(requested, 512), modelMaxOutput)` |
368
+
369
+ The client's requested value is never lowered (unless it exceeds the model's catalog `limit.output` or `131072`).
370
+
371
+ ## How Adaptive Identity & Self-Healing Work
372
+
373
+ ```
374
+ Client ──▶ Bridge (:20129, Bun) ──▶ https://opencode.ai/inference/openai/v1/...
375
+ │
376
+ ├─ 1. Handshake: opencode.ai/update/api/latest/cli/npm
377
+ │ -> resolves latest CLI version, minimum floor, and GitHub commit SHA
378
+ ├─ 2. Source AST parser: raw.githubusercontent.com/anomalyco/opencode/<sha>/...
379
+ │ -> extracts session ID recipe, UA template, 7 gate headers,
380
+ │ 13 tool plugins (Effect Schema AST), and model-conditional tool swaps
381
+ ├─ 3. Provider catalog: models.opencode.ai/api.json (cached on disk)
382
+ │ -> extracts inference endpoints, 10 free models, family aliases,
383
+ │ deprecated/paid verdicts, and per-model reasoning/output limits
384
+ └─ 4. On 403 / 426 / 404:
385
+ -> refreshes recipe + catalog, evicts stale session ID, mints fresh
386
+ ses_<12hex><14base62> ID, escalates to full tool profile, retries once
387
+ (throttled for 30s if full-shape retry is still refused by per-IP gate)
388
+ ```
389
+
390
+ ### What is derived dynamically vs. fixed
391
+
392
+ | Layer | Source | Fallback if unreachable |
393
+ |---|---|---|
394
+ | CLI version & minimum floor | `opencode.ai/update/api/latest/cli/npm` (fallback: GitHub `releases.atom`) | `DEFAULT_RECIPE.version` (`2.0.32`) |
395
+ | Session ID charset, length, multiplier | `packages/schema/src/identifier.ts` | 62-char base62, length 26, mult `4096` |
396
+ | Session ID prefix | `packages/schema/src/session-id.ts` | `ses_` |
397
+ | User-Agent template | `packages/core/src/app.ts` | `opencode/${channel}/${version}/${cli}` |
398
+ | Required & optional gate headers | `packages/core/src/session/model-request.ts` | 7 core OpenCode headers |
399
+ | Tool plugin list & wire allowlist | GitHub tree listing of `packages/core/src/tool/plugin/*.ts` + `codemode/tool.ts` | 13 known plugins (`read`, `shell`, `edit`, etc.) |
400
+ | Tool JSON schemas & descriptions | Effect Schema AST parser across plugin `.ts`, sibling `.txt`, and `@opencode/schema/*` | `DEFAULT_TOOLS` (`read`, `shell`) |
401
+ | Model-conditional tool swaps (`edit`/`write` vs `patch`) | `packages/core/src/tool/plugin/patch.ts` | `gpt-*` condition rule |
402
+ | Inference endpoints (`chatUrl`, `responsesUrl`) | `models.opencode.ai/api.json` (`opencode.api`, validated under `*.opencode.ai`) | `https://opencode.ai/inference/openai/v1/*` |
403
+ | Free model list, paid/retired verdicts, family aliases, token limits | `models.opencode.ai/api.json` | `~/.opencode-free-bridge/cache/catalog.json` |
404
+
405
+ ### Inspecting live bridge state
406
+
407
+ ```bash
408
+ curl -s http://127.0.0.1:20129/health
409
+ ```
410
+
411
+ ```json
412
+ {
413
+ "status": "ok",
414
+ "provider": "opencode-free-bridge",
415
+ "version": "2.0.0",
416
+ "runtime": "bun/1.4.2",
417
+ "discoveredModels": 10,
418
+ "identity": {
419
+ "userAgent": "opencode/latest/2.0.32/cli",
420
+ "updateMode": "reactive",
421
+ "sourceTag": "d4a6223d017e17f1beaa91d3e6ecc6511c5132ad",
422
+ "versionFloor": null,
423
+ "lastCheckAgeMs": 1240,
424
+ "ttlMs": 900000,
425
+ "lastError": null,
426
+ "release": {
427
+ "version": "2.0.32",
428
+ "sha": "d4a6223d017e17f1beaa91d3e6ecc6511c5132ad",
429
+ "minimum": false,
430
+ "active": true,
431
+ "channel": "latest",
432
+ "source": "update-api",
433
+ "resolvedAt": 1760740000000,
434
+ "stale": false
435
+ },
436
+ "available": null,
437
+ "headers": [
438
+ "x-opencode-session-id",
439
+ "x-session-affinity",
440
+ "X-Session-Id",
441
+ "User-Agent",
442
+ "x-opencode-project",
443
+ "x-opencode-session",
444
+ "x-opencode-client"
445
+ ],
446
+ "unsentHeaders": [],
447
+ "endpoints": {
448
+ "chatUrl": "https://opencode.ai/inference/openai/v1/chat/completions",
449
+ "responsesUrl": "https://opencode.ai/inference/openai/v1/responses",
450
+ "modelsUrl": "https://opencode.ai/inference/v1/models",
451
+ "catalogBase": "https://opencode.ai/inference/openai/v1"
452
+ },
453
+ "toolNames": [
454
+ "read", "shell", "edit", "write", "glob", "grep", "patch",
455
+ "question", "skill", "subagent", "webfetch", "websearch", "execute"
456
+ ],
457
+ "tools": {
458
+ "source": "source",
459
+ "version": "2.0.32",
460
+ "toolNames": [
461
+ "execute", "edit", "glob", "grep", "patch", "question",
462
+ "read", "shell", "skill", "subagent", "webfetch", "websearch", "write"
463
+ ]
464
+ }
465
+ }
466
+ }
467
+ ```
468
+
469
+ ## Testing, Verification & Gate Drills
470
+
471
+ ```bash
472
+ bun test # 165 offline unit, contract, and regression tests
473
+ bun run verify # live check: probes every discovered free model
474
+ bun run verify:quick # live check: stops at the first model that answers
475
+ bun run drill # runs live + offline self-healing gate drills
476
+ bun run fingerprint:check # checks Bun TLS ClientHello against transport-baseline.json
477
+ ```
478
+
479
+ `verify.ts` exits `0` when a model answers, `2` when the bridge is healthy and its TLS fingerprint matches the baseline but upstream refuses this IP (free-tier allowance or an explicit abuse block), and `1` for a real failure (bridge unreachable, running on Node.js, or TLS fingerprint drift). The `2` case is what a throttled or flagged network looks like: the official OpenCode CLI gets the same `403 FreeTierError` from the same IP at the same moment, so it is not a reason to reinstall or edit headers. The bridge labels the refusal (`X-OpenCode-Gate: ip-throttled | ip-abuse | shape-rejected`), so `verify.ts` no longer depends on upstream keeping identical wording.
480
+
481
+ `gate-drill.ts` deliberately corrupts the bridge's state and verifies that a single client request triggers self-healing and still returns `HTTP 200`:
482
+
483
+ | Drill | Mode | What it corrupts / stages | What it verifies |
484
+ |---|---|---|---|
485
+ | `version-floor` | Live | User-Agent version below floor | `426 UpgradeRequired` -> floor learned -> identity refreshed -> retry succeeds |
486
+ | `empty-tools` | Live | Empty tool profile | Falls back to shipped tool definitions instead of sending `tools: []` |
487
+ | `session-shape` | Live | Unrecognized session ID prefix | `403 FreeTierError` -> recipe refreshed -> old ID evicted -> fresh `ses_...` ID minted |
488
+ | `legacy-shape` | Live | Pre-v1.5 request shape | Control check against live upstream |
489
+ | `routing` | Offline | `chatUrl` repointed after boot | Endpoints are resolved per request from recipe/catalog, not frozen at boot |
490
+ | `allowlist` | Offline | Upstream renames a tool (`shell` -> `run`) | Extracted tool name reaches the wire in `full` scope and retired name is dropped |
491
+ | `retry-endpoint` | Offline | `403` gate rejection + catalog URL change | The self-heal retry uses the newly refreshed endpoint URL |
492
+ | `endpoint-move` | Offline | `404` on retired endpoint path | Re-reads catalog on `404` and retries at the new path transparently |
493
+ | `gate-heal` | Offline | Stale prefix + minimal tool scope | Full heal order: `403` -> refresh -> re-mint session ID -> escalate to full tools -> `200` |
494
+ | `full-corrupt` | Offline | Version `0.9.9`, prefix `old_`, length `20`, hex charset, default tools | One client request heals all corrupted layers simultaneously from source and returns `200` |
495
+
496
+ Before running the 4 live drills, `gate-drill.ts` sends a single CLI-shaped control probe. If the current IP is temporarily throttled by upstream (`403 FreeTierError` on the control probe), the 4 live drills report `SKIP` so they do not extend the IP cooldown, while the 6 offline drills still execute and determine the exit code.
497
+
498
+ ## Configuration
499
+
500
+ | Environment Variable | Default | Description |
501
+ |---|---|---|
502
+ | `PORT` | `20129` | HTTP listen port |
503
+ | `HOST` | `127.0.0.1` | Bind address (keep on `127.0.0.1` or behind a firewall; the server has no auth) |
504
+ | `CORS_ORIGIN` | `""` (localhost only) | Allowed CORS origin(s), comma-separated or `*` |
505
+ | `UPSTREAM_TIMEOUT_MS` | `120000` | Upstream fetch timeout in milliseconds |
506
+ | `MAX_BODY_BYTES` | `10485760` | Maximum request body size in bytes (10 MiB) |
507
+ | `IDENTITY_TTL_MS` | `900000` | Identity freshness TTL in milliseconds (15 minutes) |
508
+ | `UPDATE_MODE` | `reactive` | `reactive` adopts new CLI releases only on `403`/`426` or `minimum: true`; `always` adopts every release on TTL expiry |
509
+ | `GATE_RETRY_COOLDOWN_MS` | `30000` | Cooldown window (ms) after a failed full-shape `403` retry during which duplicate retries are suppressed until identity changes |
510
+ | `GATE_REFRESH_COOLDOWN_MS` | `30000` | Cooldown window (ms) between forced GitHub/catalog refreshes during a `403` burst |
511
+ | `DNS_RESULT_ORDER` | `ipv4first` | DNS resolution order passed to `dns.setDefaultResultOrder` (`ipv4first`, `ipv6first`, `verbatim`). Read by both `server.ts` and `egress-proxy.ts`: the gateway refuses IPv6 egress, so a pool member on a dual-stack host must not dial upstream over AAAA |
512
+ | `TOOL_PROFILE_SCOPE` | `core` | `core` sends the minimal gate anchor (`read`, `shell`) on first attempt and escalates to `full` (all model-applicable tools) on retry; `full` sends the full tool profile on every request |
513
+ | `OPENCODE_CHANNEL` | `latest` | OpenCode release channel (`latest`, `beta`, `dev`) |
514
+ | `OPENCODE_MAJOR` | _(unset)_ | Pin a major version line (for example `2`) |
515
+ | `OPENCODE_USER_AGENT` | _(derived)_ | Override `User-Agent` and disable dynamic identity derivation |
516
+ | `OPENCODE_CATALOG_URL` | `https://models.opencode.ai/api.json` | Provider catalog URL |
517
+ | `OPENCODE_CACHE_DIR` | `~/.opencode-free-bridge/cache` | Directory for the on-disk `catalog.json` cache (`off` disables disk caching) |
518
+ | `OPENCODE_CHAT_URL` | _(derived)_ | Override the upstream Chat Completions endpoint URL |
519
+ | `OPENCODE_RESPONSES_URL` | _(derived)_ | Override the upstream Responses API endpoint URL |
520
+ | `UPSTREAM_RELAY_URL` | _(unset)_ | Route inference through an egress relay (`x-relay-target` / `x-relay-path` contract); empty = direct. See [Optional egress relay](#optional-egress-relay) |
521
+ | `UPSTREAM_PROXY_URL` | _(unset)_ | Operator-level default for the egress proxy (`http://[user:pass@]host:port`). When set it wins over the panel and locks runtime edits. See [Egress proxy](#egress-proxy) |
522
+ | `PANEL_ALLOWED_HOSTS` | _(unset)_ | Extra `Host` names the panel and `/api/proxy` accept (comma-separated), for a reverse proxy in front of the bridge. Loopback names and the configured `HOST` are always accepted |
523
+ | `AUTO_UPDATE` | `1` | Poll GitHub for bridge updates every 6 hours (automatically skipped inside a `.git` checkout; set `0` to disable) |
524
+ | `ALLOW_NODE` | _(unset)_ | Set `ALLOW_NODE=1` to bypass the startup Bun check for offline tests |
525
+
526
+ ### Optional egress relay
527
+
528
+ Set `UPSTREAM_RELAY_URL` to a relay that speaks the same contract as 9Router's
529
+ Cloudflare/Vercel/Deno/Netlify relays. The bridge POSTs to the relay with
530
+ `x-relay-target: <origin>` and `x-relay-path: <path>`, and the relay replays the
531
+ request at that origin; upstream therefore sees the relay's egress IP.
532
+
533
+ ```bash
534
+ UPSTREAM_RELAY_URL="https://relay.example.workers.dev" bun server.ts
535
+ ```
536
+
537
+ The relay covers inference requests and their retries; model discovery and
538
+ identity synchronization stay direct. `/health` reports `egress.mode` (`direct`
539
+ or `relay`) and the relay's origin, without credentials or query strings. Use a
540
+ trusted HTTPS relay: it receives the request headers (including
541
+ `Authorization: Bearer public`) and the full prompt. Changing the variable
542
+ requires a restart.
543
+
544
+ ### Egress proxy
545
+
546
+ Open `http://127.0.0.1:20129/` and enter an HTTP proxy. Every outbound request
547
+ the bridge makes then tunnels through it (`CONNECT`), so upstream sees the
548
+ proxy's IP rather than this machine's. That covers inference, model discovery,
549
+ identity sync, and the self-updater.
550
+
551
+ - **Protocol:** `http://` and `https://` only. Bun's fetch accepts those and
552
+ tunnels TLS itself, so `transport-baseline.json` still matches. SOCKS5 is
553
+ refused by Bun (`UnsupportedProxyProtocol`) and rejected in the panel with
554
+ that reason.
555
+ - **Credentials:** `http://user:pass@host:port`, percent-encoded if they contain
556
+ `@`, `:`, or `/`. They are stored in `~/.opencode-free-bridge/proxy.tson`
557
+ (mode `0600`) and never returned by the panel, `/api/proxy`, or `/health`;
558
+ those show `host:port` only.
559
+ - **Test before trusting it:** *Uji koneksi* fetches the models endpoint through
560
+ the candidate proxy and reports the exit IP from `cdn-cgi/trace`. A 403 there
561
+ means the proxy reaches upstream but its egress is refused.
562
+ - **No restart:** the setting is read on every request. *Matikan proxy* returns
563
+ to direct egress.
564
+ - **Operator override:** `UPSTREAM_PROXY_URL` beats the panel and locks runtime
565
+ edits to it.
566
+ - **Only from this machine:** the panel and `/api/proxy` accept `Host` names of
567
+ loopback (or the configured bind address) plus anything in
568
+ `PANEL_ALLOWED_HOSTS`, reject cross-site requests, and require
569
+ `Content-Type: application/json` for writes. That blocks a random website from
570
+ re-pointing your egress and blocks DNS rebinding. Put a reverse proxy in front
571
+ and add its name to `PANEL_ALLOWED_HOSTS` if you reach the panel that way.
572
+ - **Container:** the compose file mounts the `bridge-state` volume at
573
+ `/data/state` (`OPENCODE_BRIDGE_STATE_DIR`) so the setting survives a
574
+ recreate. Plain `docker run` needs that env var and volume too.
575
+
576
+ ### Egress pool
577
+
578
+ The free-tier allowance is per egress IP, not per account. Running one bridge
579
+ per host multiplies processes, service units and tunnels without giving anything
580
+ a pool does not: the pool rotates the egress while one process keeps the
581
+ identity, the catalog and the session cache in one place.
582
+
583
+ A pool is a list of egress entries. Each keeps its own health, so an entry that
584
+ upstream throttles is skipped until its cooldown ends instead of being retried
585
+ by every request.
586
+
587
+ ```bash
588
+ # in the panel under "Pool egress", one entry per line
589
+ med1=http://pool:token@127.0.0.1:20251
590
+ med2=http://pool:token@127.0.0.1:20252
591
+ ```
592
+
593
+ ```bash
594
+ # operator override: comma- or newline-separated, label=url optional
595
+ UPSTREAM_PROXY_POOL="med1=http://a:1,med2=http://b:2" \
596
+ UPSTREAM_PROXY_STRATEGY=failover \
597
+ bun server.ts
598
+ ```
599
+
600
+ - **Entry shape:** a URL string, `{id,label,url,enabled,weight}`, or
601
+ `{direct: true}` for this machine's own address. `direct` is a first-class
602
+ entry, so the hosting IP can take part in the rotation instead of being the
603
+ fallback used only when every proxy is down.
604
+ - **Strategies:** `round-robin` (default; even spread across healthy entries),
605
+ `failover` (sticky on the first healthy entry, which keeps upstream prompt
606
+ caching on one IP), `random` (weighted).
607
+ - **Cooldown:** a refusal on a pooled egress is recorded against *that* entry.
608
+ The backoff doubles per consecutive failure from `cooldownMs` (default 120 s)
609
+ up to `maxCooldownMs` (default 30 min); a success resets it. A `429` earns four
610
+ times the base window because it is an unambiguous allowance answer.
611
+ - **Always sends:** when every entry is cooling, the one that recovers first is
612
+ used anyway. Refusing would turn a throttled pool into a dead bridge, and
613
+ upstream answers a throttled IP with a normal refusal the caller already
614
+ handles.
615
+ - **Failover on a gate rejection:** the bridge drops the entry that was refused
616
+ and retries through a different one, in the same request. An unreachable proxy
617
+ is also failed over, since nothing reached upstream.
618
+ - **One egress per request:** the protocol-lane, endpoint-migration, 5xx and
619
+ gate retries all reuse the entry the request started on, because upstream ties
620
+ a retry to the address that saw the first attempt. Only the two cases above
621
+ move it.
622
+ - **`/health`** reports `egress.mode: "pool"` and `egress.proxy.pool` with each
623
+ entry's host, state, remaining cooldown and failure count. Credentials are
624
+ never included.
625
+
626
+ #### Health across restarts
627
+
628
+ Cooldowns are written to `<state dir>/pool-health.json` (mode `0600`), so a
629
+ service restart or a host suspend/resume does not forget which IPs are spent and
630
+ re-burn all of them.
631
+
632
+ - A refusal is written immediately; a success is coalesced over one second,
633
+ because a success arrives with every request and a rewrite per request would
634
+ turn a memory update into disk churn.
635
+ - The file is written by rename, so a crash mid-write keeps the previous copy
636
+ instead of leaving a truncated one that would cost every cooldown.
637
+ - Records are keyed by a truncated SHA-256 of the egress identity, not by URL,
638
+ so the file is not a second copy of the proxy credentials. A `label` field
639
+ carries `host:port` (or `direct`), which `/health` already exposes.
640
+ - Saving the pool in the panel keeps existing cooldowns; only an entry that
641
+ leaves the pool loses its record.
642
+ - A corrupt or missing health file costs the cooldowns and nothing else: the
643
+ bridge starts, reports the pool from `proxy.tson`, and treats every entry as
644
+ ready.
645
+
646
+ #### Turning a host into a pool member
647
+
648
+ `egress-proxy.ts` is a dependency-free HTTP proxy for exactly this: it answers
649
+ `CONNECT` and absolute-URI HTTP, and forwards bytes without inspecting them.
650
+ Its TLS is tunneled end to end, so it never sees plaintext.
651
+
652
+ ```bash
653
+ # on the node
654
+ PORT=8888 EGRESS_PROXY_TOKEN=secret bun egress-proxy.ts
655
+
656
+ # from the bridge host: put it on a loopback port, so the proxy itself is never
657
+ # exposed and the tunnel carries the authentication
658
+ ssh -L 127.0.0.1:20251:127.0.0.1:8888 node
659
+ ```
660
+
661
+ `/healthz` is unauthenticated on purpose: it reports a connection count and an
662
+ uptime, nothing about the target or the token, so a monitor does not need the
663
+ credential to ask whether the proxy is up.
664
+
665
+ `/health` reports `egress.mode` (`pool`, `proxy`, `relay`, or `direct`) plus
666
+ `egress.proxy` with the same credential-free description.
667
+
668
+ The proxy applies *in addition to* the relay: with both configured, the request
669
+ is still sent to `UPSTREAM_RELAY_URL`, and that connection is dialled through
670
+ the proxy.
671
+
672
+ ## Troubleshooting
673
+
674
+ ### `403` with "detected abusive traffic" / `Detect Abuse Traffic` (IP-level block)
675
+
676
+ This is not the shape gate and not a stale bridge. The gateway has flagged the
677
+ network's egress IP for abusive traffic; the message says it is unrelated to the
678
+ account. The bridge treats it as terminal: it does **not** refresh the identity,
679
+ re-mint the session id, or retry, and returns the refusal verbatim with
680
+ `X-OpenCode-Gate: ip-abuse`. `/health` reports `identity.gate.status:
681
+ "ip-blocked"` and `identity.gate.lastRejection.kind: "ip-abuse"`.
682
+
683
+ The official OpenCode CLI gets the same answer from the same network. Only
684
+ upstream can clear the flag (`help@anoma.ly`, with the time it started and the
685
+ `x-opencode-log-id` from the response). Until then, change egress (route through
686
+ another host or SSH tunnel), subscribe to OpenCode Go, or wait. Reinstalling the
687
+ bridge or editing headers will not help.
688
+
689
+ ### `403 FreeTierError` persists even after retry
690
+
691
+ When the bridge receives `403 FreeTierError`, it refreshes its recipe from OpenCode's update API and GitHub source tree, re-mints the session ID, escalates to the full tool profile, and retries once. If the message names an explicit IP-level abuse block (`abusive traffic` / `Detect Abuse Traffic`), this path is skipped entirely — see the section above.
692
+
693
+ If that retry also returns `403 FreeTierError` and `/health` shows `"lastError": null` with the current CLI version (for example `opencode/latest/2.0.32/cli`), **your current IP is in a temporary free-tier cooldown upstream**. To prevent extending the penalty, the bridge suppresses duplicate `403` retries and forced GitHub refreshes for `30s` (`GATE_RETRY_COOLDOWN_MS`). Running the official OpenCode CLI binary (`opencode run -m opencode/big-pickle "hi"`) from the same IP at the same moment returns the exact same `403 FreeTierError`. Wait for the per-IP window to reset or route through another host/SSH tunnel.
694
+
695
+ ### `429 RateLimitError` / `BUSY` in `verify.ts`
696
+
697
+ Upstream is throttling the specific model or current IP due to capacity. Try another model ID from `/v1/models`.
698
+
699
+ ### `404 Model '<id>' has been retired upstream`
700
+
701
+ The model was marked `status: "deprecated"` in `models.opencode.ai/api.json` (for example `cat-jam-free`, `muse-spark-1.3-contributor-free`, or `step-5-preview-free`). Query `curl -s http://127.0.0.1:20129/v1/models` and switch your client to one of the active models.
702
+
703
+ ### `bun: command not found` in a fresh SSH session
704
+
705
+ The service runs fine, but `curl https://bun.sh/install | bash` only adds
706
+ `~/.bun/bin` to an *interactive* shell's PATH. A new non-login SSH session, or a
707
+ `sh -c` command, does not see it:
708
+
709
+ ```bash
710
+ export PATH="$HOME/.bun/bin:$PATH" # or use the absolute path
711
+ /root/.bun/bin/bun transport-fingerprint.ts --check
712
+ ```
713
+
714
+ The installer prints the absolute path in its closing summary for this reason.
715
+ The service itself is unaffected: its unit file records the full path.
716
+
717
+ ### `remote port forwarding failed for listen port 20136`
718
+
719
+ The receiving host still has a **stale** listener from a tunnel whose sender rebooted or lost power. The TCP connection died without a FIN, so `sshd` keeps the forwarded port until keepalive notices — ten minutes with the default `ClientAliveInterval 300` × `ClientAliveCountMax 2`. The replacement tunnel then fails even though its own unit is healthy.
720
+
721
+ ```bash
722
+ ./tunnel-doctor.sh # which forwards are stale (listener with no SSH transport)
723
+ ./tunnel-doctor.sh --reap # kill only the stale sessions
724
+ ./tunnel-doctor.sh --check # is the keepalive window short enough?
725
+ ```
726
+
727
+ To close the window itself, on the **receiving** host:
728
+
729
+ ```bash
730
+ # /etc/ssh/sshd_config.d/00-keepalive.conf — the 00- prefix matters
731
+ ClientAliveInterval 30
732
+ ClientAliveCountMax 4 # dead peer detected in 120s
733
+ ```
734
+
735
+ OpenSSH uses the **first** value it reads, so a later-sorting file (for example `99-*.conf`) is silently ignored. Verify with `sshd -T | grep -i clientalive` and `systemctl reload ssh`.
736
+
737
+ ### `429 FreeUsageLimitError` — the quota, or a missing `<env>` block?
738
+
739
+ `429 FreeUsageLimitError` has **two** causes, and the gateway uses the same
740
+ message for both:
741
+
742
+ 1. the free-tier allowance is spent, or
743
+ 2. the request's system prompt is missing the harness environment block.
744
+
745
+ Cause 2 is the one that made the bridge look throttled while the CLI worked.
746
+ Reproduced by capturing the CLI's own request and replaying it byte-for-byte:
747
+ the captured body answers `200`, the same body with only its system prompt
748
+ replaced by a short one answers `429`. Same headers, same session id, same TLS
749
+ stack — the difference is the body.
750
+
751
+ The trigger is precise: an `<env>` block containing a `Working directory:` line.
752
+
753
+ | system prompt | result |
754
+ |---|---|
755
+ | `You are a helpful assistant.` | `429` |
756
+ | 12 KB of generic prompt text | `429` |
757
+ | `<env>Working directory: /tmp</env>` (65 bytes) | `200` |
758
+ | 12 KB generic prompt **plus** the env block | `200` |
759
+
760
+ Length is not the rule, and neither is the model — `big-pickle` and
761
+ `mimo-v2.6-flash-free` split the same way. Sending `tools: []` also produces
762
+ this `429`, which is why an empty tool profile looked like a quota error too.
763
+
764
+ ### `429 FreeUsageLimitError` from a blocked tool name
765
+
766
+ The quota wording also hides a tool-name filter. A request whose only fault is a
767
+ tool named `run_code` is answered with the same `429 FreeUsageLimitError`, even
768
+ when the system prompt, the headers and the token budget are identical to a
769
+ request that answers `200`:
770
+
771
+ | `tools[].function.name` | result |
772
+ |---|---|
773
+ | `run_code` | `429` |
774
+ | `run_code_client` | `429` (the match is on the substring) |
775
+ | `run-code` | `200` |
776
+ | `runcode` | `200` |
777
+ | `run_program` | `200` |
778
+ | `code_exec` | `200` (same schema) |
779
+
780
+ Sending the anchor tool `read` alongside `run_code` does not help, so this is not
781
+ the shape gate and not the allowance. The bridge now sends such a tool upstream
782
+ as `run_program` and restores the client's name on the way back, including
783
+ streamed tool-call deltas, `tool_choice` and tool-result turns, so a client keeps
784
+ its own tool name.
785
+
786
+ The bridge has appended the block since the fix in this release: it derives the
787
+ working directory, workspace root, git-repo flag and platform from its own
788
+ process. A client that already forwards the CLI's prompt keeps its own block
789
+ and does not get a duplicate. If you still see `429` on an up-to-date bridge,
790
+ the allowance really is spent — check with the interleaving probe:
791
+
792
+ ```bash
793
+ for i in 1 2 3; do
794
+ opencode run -m opencode/glm-5.3-flash-free "probe $i" 2>&1 | tail -1
795
+ curl -s http://127.0.0.1:20129/v1/chat/completions \
796
+ -H 'Content-Type: application/json' \
797
+ -d '{"model":"glm-5.3-flash-free","messages":[{"role":"user","content":"probe"}],"max_tokens":8}' \
798
+ | head -c 120; echo
799
+ done
800
+ ```
801
+
802
+ If both refuse, the allowance is spent. If the CLI answers while the bridge
803
+ refuses **in the same minute** on a bridge older than this release, upgrade —
804
+ that is the shape bug, not a quota.
805
+
806
+ #### Why the bridge can be charged earlier than the CLI
807
+
808
+ The default `TOOL_PROFILE_SCOPE=core` sends two tools (`read`, `shell`) and a
809
+ short placeholder note, then escalates to `full` only after a rejection. The
810
+ real CLI always sends the full profile. Measured against a captured CLI request
811
+ (`opencode run`, v2.0.32) and this bridge on the same model:
812
+
813
+ | | CLI | bridge, `core` | bridge, `full` |
814
+ |---|---|---|---|
815
+ | tools | 12 | 2 | 13 |
816
+ | tool schema bytes | 13,991 | 2,522 | 13,972 |
817
+ | system prompt chars | 12,259 | ~470 | ~470 |
818
+ | `max_completion_tokens` | 32,000 | 5,120 | 5,120 |
819
+ | total body bytes | 26,296 | ~3,300 | ~14,500 |
820
+
821
+ `TOOL_PROFILE_SCOPE=full` closes the tool gap and is the safer default when a
822
+ deployment is being throttled ahead of the CLI.
823
+
824
+ The system-prompt gap is **not** cosmetic: before the `<env>` fix in this
825
+ release it was the whole `429` cause. What remains after the fix is the CLI's
826
+ harness prose (persona, communication rules, skill catalogue), which the bridge
827
+ does not ship. That part is accepted by the gateway — the env block is the only
828
+ anchor it checks — so the bridge no longer needs to reproduce the full prompt.
829
+
830
+ ```bash
831
+ # systemd drop-in for a service that runs as a dedicated user
832
+ sudo mkdir -p /etc/systemd/system/opencode-free-bridge.service.d
833
+ printf '[Service]\nEnvironment=TOOL_PROFILE_SCOPE=full\n' \
834
+ | sudo tee /etc/systemd/system/opencode-free-bridge.service.d/10-tool-profile.conf
835
+ sudo systemctl daemon-reload && sudo systemctl restart opencode-free-bridge.service
836
+ ```
837
+
838
+ ### Reverse tunnel dies while the process still looks healthy
839
+
840
+ A deployment that reaches the bridge over `ssh -R` can fail in a way systemd
841
+ cannot see: the `ssh` process stays `active`, the TCP connection stays `ESTAB`,
842
+ and the listener on the far end is gone. `Restart=always` never fires because
843
+ the process never exits. This cost two hours of downtime on a five-node
844
+ deployment before it was diagnosed.
845
+
846
+ The only reliable probe is the endpoint itself. Run it on the host that owns the
847
+ forwarded port, not on the node:
848
+
849
+ ```bash
850
+ #!/bin/bash
851
+ # /usr/local/bin/opencode-tunnel-watchdog.sh — run as root via a systemd timer
852
+ PORT=20136
853
+ LOG=/var/log/opencode-tunnel-watchdog.log
854
+ log() { printf '%s %s\n' "$(date -u +%FT%TZ)" "$*" >> "$LOG"; }
855
+
856
+ if ! curl -sf --max-time 5 http://127.0.0.1:20129/health >/dev/null; then
857
+ log "bridge DOWN - restarting"; systemctl restart opencode-bridge.service; sleep 4
858
+ fi
859
+ if ! pgrep -f "ssh .*-R 127.0.0.1:${PORT}:" >/dev/null; then
860
+ log "tunnel MISSING - restarting"; systemctl restart opencode-tunnel.service; sleep 6
861
+ fi
862
+ pgrep -f "ssh .*-R 127.0.0.1:${PORT}:" >/dev/null \
863
+ && log "SUMMARY ok" || log "SUMMARY FAILED - manual attention needed"
864
+ ```
865
+
866
+ Pair it with a `oneshot` service and a `OnUnitActiveSec=60` timer. The
867
+ `SUMMARY` line is deliberate: without a heartbeat, an empty log is
868
+ indistinguishable from a watchdog that never ran.
869
+
870
+ Restarting the tunnel from a remote host over SSH needs care. `Defaults use_pty`
871
+ in `/etc/sudoers` makes `sudo -n` fail with "a password is required" even when
872
+ `NOPASSWD` is granted, and a nested `ssh host "python3 -c \"...\""` mangles
873
+ quotes. Run the watchdog **as root on the node itself** through systemd instead
874
+ of driving it remotely.
875
+
876
+ ### Checking service logs
877
+
878
+ ```bash
879
+ # Linux (systemd user or system service)
880
+ journalctl --user -u opencode-free-bridge -n 50 --no-pager
881
+ journalctl -u opencode-free-bridge -n 50 --no-pager
882
+
883
+ # macOS (launchd)
884
+ tail -50 ~/Library/Logs/opencode-free-bridge.log
885
+
886
+ # Manual foreground run
887
+ bun ~/.opencode-free-bridge/server.ts
888
+ ```
889
+
890
+ ## License and upstream data
891
+
892
+ This project is licensed under [MIT](./LICENSE). `identity.ts` derives request identity and tool metadata from the [OpenCode source repository](https://github.com/anomalyco/opencode). Its offline fallback includes OpenCode `read` and `shell` tool descriptions and schema fields; related source-shaped fixtures appear in `test/identity.test.js`. See [`THIRD_PARTY_NOTICES.md`](./THIRD_PARTY_NOTICES.md) for the OpenCode MIT notice and contributor credit.