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/AGENTS.md ADDED
@@ -0,0 +1,253 @@
1
+ # AGENTS.md: AI Agent Playbook for `opencode-free-bridge`
2
+
3
+ This file gives AI coding agents (OpenCode, Claude Code, Cursor, Codex, Cline, Aider, etc.) exact instructions for installing, running, connecting, troubleshooting, and modifying `opencode-free-bridge`.
4
+
5
+ ---
6
+
7
+ ## 1. Critical Rules (Read First)
8
+
9
+ 1. **Runtime MUST be Bun (`bun server.ts`).**
10
+ - Do **not** run the production server under Node.js (`node server.ts` intentionally exits with code `1`).
11
+ - Reason: the official OpenCode CLI is compiled with Bun (BoringSSL). Upstream's free-tier gate inspects the TLS `ClientHello` fingerprint (17 ciphers, 12 extensions). Node.js (OpenSSL) offers 52 ciphers and is rejected with `403 FreeTierError`.
12
+ - `ALLOW_NODE=1` is strictly for offline unit tests with mocked `fetch`, never for live traffic.
13
+ 2. **Zero external dependencies.**
14
+ - Do not run `npm install` or add packages to `package.json`. The bridge uses only built-in runtime modules.
15
+ 3. **Never hardcode model IDs or aliases.**
16
+ - Model availability changes frequently upstream. Always query `GET http://127.0.0.1:20129/v1/models` to see active free models.
17
+ - Retired models (such as `cat-jam-free`, `muse-spark-1.3-contributor-free`, `muse-spark-1.2-contributor-free`, `step-5-preview-free`) return HTTP `404` by design.
18
+ 4. **Upstream inference requires `stream: true`.**
19
+ - Upstream rejects non-streaming inference requests with `403 FreeTierError`. `server.ts` always sends `stream: true` upstream and folds SSE back into JSON when a client requests `stream: false`. Any direct diagnostic probe (`verify.ts`, `gate-drill.ts`) must keep `stream: true`.
20
+
21
+ ---
22
+
23
+ ## 2. Installing & Starting the Bridge for a User
24
+
25
+ ### Option A: Standard system install (recommended for persistent background service)
26
+
27
+ Run the installer script. It finds or installs `bun` (installing `unzip` first on minimal Linux if needed), stages and validates files before touching a running service, retires legacy `opencode-bridge.service` units, places files in `~/.opencode-free-bridge`, migrates any `node` service units to `bun`, starts the `opencode-free-bridge` service (`systemd` on Linux, `launchd` on macOS), and verifies `/health` and the TLS baseline:
28
+
29
+ ```bash
30
+ curl -fsSL https://raw.githubusercontent.com/azrinaldi/opencode-free-bridge/main/install.sh | bash
31
+ ```
32
+
33
+ If you are already inside a local clone of this repository, run:
34
+
35
+ ```bash
36
+ bash install.sh
37
+ ```
38
+
39
+ That installs the **working tree**, not GitHub, so an unpushed commit can be
40
+ installed and tested. `SOURCE=remote bash install.sh` forces the download path;
41
+ `SOURCE=local` refuses to fall back to it.
42
+
43
+ Custom port or install directory:
44
+
45
+ ```bash
46
+ PORT=20129 HOST=127.0.0.1 BINDIR="$HOME/.opencode-free-bridge" bash install.sh
47
+ ```
48
+
49
+ ### Option B: Run directly from this repository (foreground or custom process manager)
50
+
51
+ ```bash
52
+ # Ensure bun is on PATH (check ~/.bun/bin/bun or ~/.local/bin/bun if not in default PATH)
53
+ export PATH="$HOME/.bun/bin:$HOME/.local/bin:$PATH"
54
+ bun server.ts
55
+ ```
56
+
57
+ ### Option C: Container deployment (Docker / Docker Compose)
58
+
59
+ ```bash
60
+ docker compose up -d # builds the image and starts the bridge
61
+ docker compose build --pull && docker compose up -d # upgrade
62
+ ```
63
+
64
+ The compose file publishes `127.0.0.1:20129` on loopback only, persists the
65
+ catalog cache in the `bridge-cache` volume, and runs the image as the non-root
66
+ `bun` user. The base image is pinned to `oven/bun:1.4.3-slim` because the
67
+ free-tier gate checks the TLS ClientHello — verify it inside the image with
68
+ `docker compose exec bridge bun transport-fingerprint.ts --check`.
69
+
70
+ `AUTO_UPDATE` is `0` in the compose file: the image is the unit of deployment,
71
+ so an in-place self-update would be reverted by the next build.
72
+
73
+ ### Option D: OMP / pi plugin
74
+
75
+ The package doubles as an `omp` extension (`"pi": { "extensions": ["./src/index.ts"] }`).
76
+ `omp plugin install omp-opencode-bridge` (or `omp plugin install .` for a working
77
+ tree) registers the `opencode-free` provider; the extension starts `bun server.ts`
78
+ from the installed package, reuses an already-healthy bridge on the port, and
79
+ re-reads `/v1/models`. Control it with `/opencode-free status|models|refresh-models|start|stop|restart|health|logs`.
80
+
81
+ ```bash
82
+ omp plugin install .
83
+ omp --model opencode-free/mimo-v2.6-flash-free -p "hello"
84
+ ```
85
+
86
+ Model ids must be resolved before the extension factory returns: a background
87
+ refresh races `omp --model <provider>/<id>` and loses. Keep the blocking
88
+ `await refresh()` in `src/index.ts`.
89
+
90
+ ### Verify the server is healthy
91
+
92
+ ```bash
93
+ # 1. Check health and derived OpenCode CLI identity
94
+ curl -s http://127.0.0.1:20129/health
95
+
96
+ # 2. List currently active free models
97
+ curl -s http://127.0.0.1:20129/v1/models
98
+
99
+ # 3. Verify Bun TLS ClientHello matches the OpenCode CLI baseline
100
+ bun transport-fingerprint.ts --check
101
+
102
+ # 4. Run the quick readiness check (exits 0 if a model answers, 2 if IP quota is throttled, 1 if broken)
103
+ bun verify.ts --quick
104
+
105
+ # 5. Send a test chat completion request
106
+ curl -s http://127.0.0.1:20129/v1/chat/completions \
107
+ -H "Content-Type: application/json" \
108
+ -d '{"model":"mimo-v2.6-flash-free","messages":[{"role":"user","content":"Reply with OK"}]}'
109
+ ```
110
+
111
+ ---
112
+
113
+ ## 3. Connecting Clients & Gateways
114
+
115
+ Use these connection details in any OpenAI-compatible tool:
116
+
117
+ - **Base URL:** `http://127.0.0.1:20129/v1`
118
+ - **API Key:** `public` (or any non-empty string)
119
+ - **Chat Completions Endpoint:** `POST http://127.0.0.1:20129/v1/chat/completions`
120
+ - **Models Endpoint:** `GET http://127.0.0.1:20129/v1/models`
121
+
122
+ ### Egress proxy (panel)
123
+
124
+ `GET http://127.0.0.1:20129/` serves an HTML panel: enter `http://[user:pass@]host:port`, press
125
+ *Simpan dan pakai*, and every outbound request (inference, model discovery, identity sync,
126
+ self-update) is tunnelled through that proxy. *Uji koneksi* probes the models endpoint through the
127
+ candidate and reports the exit IP; *Matikan proxy* returns to direct egress. No restart needed.
128
+
129
+ - HTTP/HTTPS only. SOCKS5 is refused (Bun: `UnsupportedProxyProtocol`). TLS still comes from Bun,
130
+ so `transport-baseline.json` stays valid.
131
+ - Credentials persist in `~/.opencode-free-bridge/proxy.tson` (mode `0600`) and are never returned
132
+ by the panel, `/api/proxy`, or `/health`.
133
+ - API: `GET /api/proxy` (status), `POST /api/proxy` `{"url":"…"}` (set; `""` clears),
134
+ `POST /api/proxy/test` `{"url":"…"}` (probe). Operator override: `UPSTREAM_PROXY_URL`, which
135
+ locks the panel.
136
+ - The panel and `/api/proxy` are an admin surface: writes must be
137
+ `Content-Type: application/json`, cross-site requests are refused, and `Host` must be loopback,
138
+ the bind address, or listed in `PANEL_ALLOWED_HOSTS`. Keep those checks if you touch the route.
139
+ - `/health` → `egress.mode` (`proxy` / `relay` / `direct`) and `egress.proxy` (host:port only).
140
+
141
+ ### Current active free models (also supports family shorthands)
142
+
143
+ Always verify via `GET /v1/models`. As of catalog sync `v2.0.0`:
144
+ - `mimo-v2.6-flash-free` (shorthand: `mimo`)
145
+ - `big-pickle` (shorthand: `big-pickle`)
146
+ - `beam-free` (shorthand: `beam`)
147
+ - `nemotron-3-ultra-free` (shorthand: `nemotron-free`)
148
+ - `nemotron-3.5-lightning-free`
149
+ - `nemotron-3.5-super-vl-free`
150
+ - `longcat-2.5-preview-free` (shorthand: `longcat`)
151
+ - `deepseek-v4.1-flash-free` (shorthand: `deepseek-flash`)
152
+ - `glm-5.3-flash-free` (shorthand: `glm-flash`)
153
+ - `space-bunny-free`
154
+
155
+ ### Multi-host / VPS SSH tunnel setup (to bypass single-IP rate limits)
156
+
157
+ If the user has another machine or VPS running `opencode-free-bridge` on port `20129`, forward a local port via SSH and register both ports in their router (such as 9Router or LiteLLM):
158
+
159
+ ```bash
160
+ ssh -N -L 127.0.0.1:20130:127.0.0.1:20129 user@remote-vps
161
+ ```
162
+
163
+ For a **reverse** tunnel (`-R`, the sending host dials out to the host that runs the router), run it as a systemd unit so it survives a reboot, and point `-i` at a key that actually exists on that host:
164
+
165
+ ```ini
166
+ [Service]
167
+ ExecStart=/usr/bin/ssh -NT -o BatchMode=yes -o ServerAliveInterval=15 \
168
+ -o ServerAliveCountMax=3 -o ExitOnForwardFailure=yes \
169
+ -i /root/.ssh/id_vps_master -p 48222 \
170
+ -R 127.0.0.1:20136:127.0.0.1:20129 root@router-host
171
+ Restart=always
172
+ RestartSec=5
173
+ ```
174
+
175
+ #### Stale forwards after an unclean disconnect
176
+
177
+ A reverse tunnel is held open by an `sshd-session` on the **receiving** host. When the sending host reboots or loses power, the TCP connection dies without a FIN and the receiving sshd keeps the listening socket until it notices. A replacement tunnel then fails with:
178
+
179
+ ```
180
+ Error: remote port forwarding failed for listen port 20136
181
+ ```
182
+
183
+ The default `ClientAliveInterval 300` × `ClientAliveCountMax 2` leaves that window at **ten minutes**. Two fixes, both worth having:
184
+
185
+ 1. **Tighten the keepalive** on the receiving host. OpenSSH uses the **first** value it reads, so the drop-in must sort *before* any existing one:
186
+
187
+ ```bash
188
+ # /etc/ssh/sshd_config.d/00-keepalive.conf (note the 00- prefix)
189
+ ClientAliveInterval 30
190
+ ClientAliveCountMax 4 # dead peer detected after 120s
191
+ ```
192
+
193
+ Verify with `sshd -T | grep -i clientalive`, then `systemctl reload ssh`.
194
+
195
+ 2. **Reap the stale session** when it has already happened. `tunnel-doctor.sh` (shipped in this repo) distinguishes a *live* forward from a stale one by checking whether the sshd session holding the listener still has an established transport — a listener alone proves nothing:
196
+
197
+ ```bash
198
+ ./tunnel-doctor.sh # report
199
+ ./tunnel-doctor.sh --reap # kill sessions with no transport
200
+ ./tunnel-doctor.sh --check # audit the keepalive window
201
+ ```
202
+
203
+ ---
204
+
205
+ ## 4. Troubleshooting Guide for Agents
206
+
207
+ When a user reports an error, diagnose it using this decision table before changing any code or configuration:
208
+
209
+ | Symptom | Root Cause | Action to Take |
210
+ |---|---|---|
211
+ | `node server.ts` exits with `opencode-free-bridge requires Bun` | Server was launched with Node.js instead of Bun | Launch with `bun server.ts` (or run `bash install.sh` to rewrite the systemd/launchd service unit to use `bun`). |
212
+ | `HTTP 403` whose message names `abusive traffic`, `Detect Abuse Traffic`, or `Abuse of traffic` (response header `X-OpenCode-Gate: ip-abuse`; `/health` -> `identity.gate.status: "ip-blocked"`) | The gateway flagged the egress IP. It is unrelated to the account and to the request shape, so no identity change can clear it. | Do **not** reinstall, edit headers, or retry. The bridge already skips refresh/retry and returns the refusal verbatim. Confirm with the official CLI from the same network; only upstream can clear it (`help@anoma.ly`, quote `x-opencode-log-id`). Change egress (SSH tunnel/relay) or wait. |
213
+ | `HTTP 403 FreeTierError` returned to client **after** logs show `refreshing identity and retrying once with full tool set` or `skipping retry because a full-shape retry already failed <30s ago` (and `verify.ts` exits `2` with `GATE`) | **Two distinct causes, one indistinguishable upstream message.** Read the log tail: it now ends with either *"the request carried every anchor the gate checks, so this is the egress"* or *"this bridge produced a shape the gate refuses — missing …"*. The second is a bridge bug, not a quota problem. | **First read the verdict in the log line.** If it says the shape was complete, the egress is refused: do not modify headers or code, run `bun gate-drill.ts` and check `upstream control` (`HTTP 403 -> gate CLOSED` means this IP is refused; the official `opencode` CLI fails identically from it). If it names missing anchors, the derived recipe/tool profile lost one — inspect `/health` → `identity.gate.anchors` and `identity.gate.lastRejection`. The bridge suppresses duplicate 403 retries and forced GitHub refreshes for 30s (`GATE_RETRY_COOLDOWN_MS`, `GATE_REFRESH_COOLDOWN_MS`) so it does not extend an IP penalty. |
214
+ | `verify.ts` exits `1` with `TLS fingerprint drift detected` or `Server is running on Node.js` | The runtime's TLS `ClientHello` does not match `transport-baseline.json` | Run `bun transport-fingerprint.ts --check` to inspect cipher/extension differences, and ensure the service runs under a current Bun 1.4+ binary. |
215
+ | `bun: command not found` in a fresh SSH session, but the service is healthy | `bun.sh/install` only edits an interactive shell's PATH | Use the absolute path (`~/.bun/bin/bun`) or export `PATH="$HOME/.bun/bin:$PATH"`. Do not reinstall. |
216
+ | `HTTP 429` or `BUSY` in `verify.ts` | **Two causes, one message.** Either the model/IP capacity is spent, or the request's system prompt lacks the harness `<env>` block (`<env>` + a `Working directory:` line) — the gateway answers both with `429 FreeUsageLimitError`. Measured: a 65-byte env block passes while a 12 KB generic prompt fails, and `tools: []` fails too. | If the bridge is older than the `<env>` fix, upgrade first. Otherwise switch model ID from `GET /v1/models`, or wait for the allowance window. Confirm by interleaving `opencode run -m opencode/<model>` with a `curl` to the bridge in the same minute: both refusing means capacity; CLI answering while the bridge refuses means a shape bug. `verify.ts` now stops the sweep at the first `429` (before 2026-10-25 it swept all 11 models, prolonging the penalty). |
217
+ | `HTTP 404 Model '<id>' has been retired upstream` | Client requested a deprecated model (e.g. `cat-jam-free`, `muse-spark-*`, `step-5-preview-free`) | Fetch `GET /v1/models` and update the client configuration to use an active model ID. |
218
+ | `HTTP 404 Model '<id>' is not on the free tier` | Client requested a paid model (e.g. `gpt-5.4`, `claude-sonnet-4-5`) | The bridge only serves zero-cost models (`cost.input === 0`). Pick a model from `GET /v1/models`. |
219
+ | Port conflict (`port 20129 is occupied by another process`) during `install.sh` | Another non-bridge process is listening on port 20129 | Stop the conflicting process or install on another port (`PORT=20130 bash install.sh`). Legacy `opencode-bridge.service` and the bridge's own process are retired/replaced automatically. |
220
+ | Proxy set in the panel, but `/health` still shows `egress.mode: "direct"` | The setting is read per request; a locked panel (`locked: true`) means `UPSTREAM_PROXY_URL` in the environment owns it | Read `egress.proxy.source` (`file` / `env` / `none`) and `egress.proxy.error`. To change an env-locked proxy, edit the service unit and restart. |
221
+ | *Uji koneksi* reports `403` from the proxy | The proxy tunnel works but upstream refuses that egress IP | Pick a different proxy; the IP is refused, not the request shape. Run `bun verify.ts --quick` after switching to confirm. |
222
+ | Panel rejects `socks5://…` | Bun fetch supports HTTP/HTTPS proxies only and throws `UnsupportedProxyProtocol` for SOCKS | Use `http://host:port` (Clash/v2ray expose a mixed HTTP port), or terminate SOCKS in a local HTTP proxy. |
223
+
224
+ ---
225
+
226
+ ## 5. Repository Architecture & Codebase Guide (For Contributors)
227
+
228
+ | File | Responsibility |
229
+ |---|---|
230
+ | `server.ts` | HTTP server (panel at `/`, `/v1/chat/completions`, `/v1/models`, `/health`, `/api/proxy` with the `adminRequestError` CSRF/Host guard), Bun runtime guard, tolerant loading of `proxy.ts`/`panel.ts` plus `repairMissingModules()` so a half-installed tree boots and heals, configurable DNS result order (`DNS_RESULT_ORDER`), session affinity cache, client tool aliasing (`read` -> `read_client`), SSE stream normalization (`reasoning_content`, `usage`, `finish_reason`), 403/426/404 reactive retry loop with 30s IP-cooldown retry suppression (`GATE_RETRY_COOLDOWN_MS`), terminal IP-abuse branch (`X-OpenCode-Gate: ip-abuse`, no refresh/retry), egress proxy (`proxy.netFetch` on inference, discovery, and self-update) plus the optional `UPSTREAM_RELAY_URL` relay (`x-relay-target` / `x-relay-path`), and 6-hour self-updater (`checkAndApplyUpdate`), which stages any module the incoming `server.ts` requires even when the running `UPDATE_FILES` list predates it. |
231
+ | `identity.ts` | Adaptive OpenCode CLI synchronization: release handshake (`opencode.ai/update/api`), GitHub source fetcher (`identifier.ts`, `session-id.ts`, `app.ts`, `model-request.ts`, `tool/plugin/*.ts`, `codemode/tool.ts`), Effect Schema AST parser (`extractToolFromSource`), provider catalog parser & disk cache (`~/.opencode-free-bridge/cache/catalog.json`), 30s forced-refresh cooldown (`GATE_REFRESH_COOLDOWN_MS`), terminal `isIpAbuseRejection` guard, and pooled CSPRNG session ID generator (`createSessionId`). |
232
+ | `token-budget.ts` | Additive token budget calculation (`max(requested, 1024) + 4096` for reasoning models, `max(requested, 512)` for standard models), driven by catalog `modelFacts`. |
233
+ | `proxy.ts` | Egress: URL validation (HTTP/HTTPS only, percent-encoded credentials), persistence in `<state dir>/proxy.tson` (mode `0600`) for both a single proxy and a pool, `UPSTREAM_PROXY_URL`/`UPSTREAM_PROXY_POOL` overrides with panel lock, per-entry health with exponential cooldown (`markFailure`/`markSuccess`/`pick`) persisted in `<state dir>/pool-health.json` (mode `0600`, keyed by a truncated SHA-256 of the egress identity so it never duplicates proxy credentials, written by rename, refusal immediate / success coalesced), `withProxy`/`netFetch` (explicit egress argument) used by every outbound call in `server.ts` and `identity.ts`, and `testProxy`/`testPool` (upstream probe + `cdn-cgi/trace` exit IP). |
234
+ | `egress-proxy.ts` | Dependency-free HTTP proxy for turning a host into a pool member: CONNECT plus absolute-URI HTTP, optional `EGRESS_PROXY_TOKEN` (Basic, password only), unauthenticated `/healthz`. Binds loopback by default; reachability is the tunnel's job. Pins `dns.setDefaultResultOrder(DNS_RESULT_ORDER \|\| "ipv4first")`: it dials the upstream itself for every CONNECT, and the gateway refuses IPv6 egress, so on a dual-stack host Bun's default `verbatim` order would tunnel every request out over the refused family. |
235
+ | `panel.ts` | The HTML panel served at `/`: same-origin form that reads and writes `/api/proxy`, shows live status without credentials, and escapes every config value. |
236
+ | `src/index.ts` | The OMP / pi extension (not part of the bridge process): registers the `opencode-free` provider, spawns or reuses `bun server.ts`, caches discovered models in `~/.opencode-free-bridge/omp-models.json`, and implements `/opencode-free`. Uses node builtins only; the `pi` API is declared as local structural types. |
237
+ | `transport-fingerprint.ts` | Captures the runtime's raw TLS `ClientHello` bytes against a local TCP listener and compares cipher suites and extension order against `transport-baseline.json`. |
238
+ | `gate-drill.ts` | End-to-end self-healing drill suite (4 live drills + 6 deterministic offline drills including `full-corrupt`). |
239
+ | `verify.ts` | Live model readiness checker (`bun verify.ts` / `bun verify.ts --quick`); sends `stream: true` and halts immediately on `gate-closed` (`403` with `X-OpenCode-Gate: ip-throttled` or `ip-abuse`, or the free-tier/abuse message) **and on the first `429` allowance** — both mean the sweep must stop so the IP cooldown is not extended. |
240
+ | `install.sh` | Cross-platform installer and `node` -> `bun` service unit migrator for Linux (`systemd`) and macOS (`launchd`). |
241
+ | `Dockerfile` | Container image for the bridge: pinned `oven/bun:1.4.3-slim` base (the Bun version is pinned because the free-tier gate checks the TLS ClientHello), non-root `bun` user, writable `/app` so the in-place self-updater can stage its temp files, `OPENCODE_CACHE_DIR=/data/cache` for the catalog cache, and `OPENCODE_BRIDGE_STATE_DIR=/data/state` for the panel's proxy setting. |
242
+ | `docker-compose.yaml` | Single-service container deployment: restart policy, loopback-only port publish (`127.0.0.1:20129:20129` — the bridge has no auth), persistent `bridge-cache` and `bridge-state` volumes, `no-new-privileges` + `cap_drop: [ALL]`, health check, and `AUTO_UPDATE=0` (the image is the unit of deployment). |
243
+ | `.dockerignore` | Keeps `.git`, `.github`, and `test/` out of the build context: a `.git` directory inside the image defeats the self-updater's `git-checkout` guard, and a published image should not carry one. |
244
+
245
+ ### Mandatory verification before committing changes
246
+
247
+ Any code change in this repository must pass all three checks:
248
+
249
+ ```bash
250
+ bun test test/*.test.js
251
+ bun transport-fingerprint.ts --check
252
+ bun gate-drill.ts
253
+ ```
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 azrinaldi
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.