Repository navigation
feat(proxy): serve the free models from opencode.ai directly - #2
Merged
Merged
Conversation
The gateway used to spawn `opencode serve` and drive it through the SDK: a child process per host, a session per completion, a readiness probe, event subscriptions and a polling fallback. The upstream service is reachable directly, and its free tier accepts exactly one client - its own CLI - so the new lane reproduces what that client presents and talks to the API itself. What the lane reproduces, because a request without it is refused upstream: `Authorization: Bearer public`; the CLI's User-Agent shape; a body carrying OpenCode's own `read` and `shell` definitions; the CLI's `<env>` marker in the system prompt; and a `ses_...` session id whose 12-hex prefix decodes to the current time. Only `opencode.ai` compares the TLS ClientHello, so requests to that host leave through `wreq-js` (a BoringSSL client) while any other base URL uses plain `fetch`, which is what lets the suites point the lane at a stub. The free quota is accounted per session, so one conversation keeps one minted id and a spent one is dropped by value. The completion path is now one streaming upstream call: the request is built in the wire's own spelling (chat, Responses or Messages, chosen by model family), the SSE frames are parsed into the same normalized events the three protocol adapters already consumed, and a non-streaming client is served by aggregating that stream. Tool calls are native upstream calls rather than the text markup the CLI backend required, so the emulation layer is gone. Images travel in each wire's own shape. A thinking level is resolved against a per-model table ported from 9router, which downgrades `max`/`ultra` to the strongest level the model serves instead of letting the upstream refuse it. The tree is TypeScript now: `tsconfig.json` compiles `index.ts`, `src/**` and `test/**` into `dist/` with `rootDir: "."`, `pnpm run build` is `tsc`, and the suites run compiled from `dist/`. Import specifiers keep their `.js` extension because that is the file the compiler emits. Removed with the child they served: `src/backend-auth.ts`, `src/backend- health.ts`, `src/collector.ts`, `src/toolguard.ts` and `src/polyfills.ts`, the spawn/health/session/poll machinery, and the jail and temp-dir handling. BREAKING CHANGE: the CLI is no longer used or required. `OPENCODE_SERVER_URL`, `OPENCODE_SERVER_PASSWORD`, `OPENCODE_PATH`, `OPENCODE_BIND_HOST`, `USE_ISOLATED_HOME` and the health-cache/start- retry keys are gone; `FREE_BASE_URL` (default `https://opencode.ai`) and `FREE_IMPERSONATE` replace them. `DISABLE_TOOLS` now withholds the client's tools from the upstream request instead of filtering tool markup out of the answer.
The lane's transport is what makes the upstream free tier answer at all: requests to opencode.ai must present a TLS ClientHello whose cipher list the gate accepts, and `wreq-js` is the client that can reproduce it. It is pinned to an exact version rather than a caret because its transport is a native binding loaded from a per-platform package, so a reinstall that moved the range could silently change the client the whole lane rests on. `@opencode/client` is removed: it was the generated client for the local server the gateway no longer drives, and no source file imports it any more. `fastify` keeps its narrow caret on purpose - it has no per-platform binding, so a patch or minor release is not a question about which fingerprint this process presents. Scripts follow the compiled layout: `build` is `tsc`, `start` builds and runs `dist/index.js`, `check` is the typecheck plus the repository invariant script, and `test` runs every suite from `dist/`. `test:live` is the opt-in check that makes one real request to opencode.ai.
The old end-to-end suites drove a stub of the deleted `opencode serve` API: sessions, prompts, polls and event subscriptions. They are retired here, and what replaces them asserts the path a client now takes, against `test/lib/stub-free-upstream.ts` - a stand-in for the upstream that enforces the free tier's own gates (Bearer public, the session shape, the User-Agent, OpenCode's `read`/`shell` definitions, the `<env>` marker, the `terminal` name refusal, `stream: true`, no `tool_choice: "none"`), so a lane that stopped presenting the right client is refused the way the real host refuses it. Its expected definitions are imported from the lane rather than copied, so a reworded schema cannot leave the stub accepting what the host rejects. `test/contract.ts` keeps the gateway's own HTTP contract (authentication, CORS, request ids, the 404 sentence, the body policy, per-protocol envelopes, the queue-full 503, `DISABLE_TOOLS`, malformed and oversized bodies). `test/protocols.ts` keeps the Responses and Messages contract, their frame vocabularies, native tool calls and the Anthropic version echo. `test/stream.ts` is new and asserts the upstream-facing half from the parsed bodies and headers the stub recorded: delta order, reasoning, usage, an in-band mid-stream failure, masking of a credential the upstream's own sentence quotes, the overload retry, the fingerprint, session reuse and rotation, a stalled call answering 504 while the slot is released, and a client disconnect cancelling the upstream call. `test/effort.ts` covers the thinking-level table and its downgrade, and `test/vision.ts` covers images in each wire's spelling plus the refusal of a `file`/`document` part. Every suite counts its checks, prints the number it ran and refuses to start on a busy port, so a failure names what it was doing instead of throwing on the first assertion. `test/live-free.ts` is deliberately not part of `pnpm test`: it is the one check that makes a real request, and it is how the TLS gate is proven rather than assumed.
The documentation described a gateway that installs and drives the OpenCode CLI: a backend lifecycle, a readiness probe, sessions, polling, a tool guard and a performance section measured on that path. None of it is true now, and a reader who followed it would configure keys that no longer exist. `README.md` gains an honest description of the lane and its caveats: the free tier accepts the CLI's own client, so the gateway reproduces it, the model list comes from the upstream catalog and changes over time, the transport impersonates only for opencode.ai, and the upstream owns the gate - it can refuse or change it, and running this is the operator's decision. The configuration table, quick start, troubleshooting and security sections are rewritten around `FREE_BASE_URL`, `FREE_IMPERSONATE` and `API_KEY`, and the completion benchmarks measured against the deleted backend are removed rather than restated. `AGENTS.md` keeps every invariant that is still true and replaces the rest. The new ones record what must not be "tidied": the fingerprint values and why each exists, the host-decided transport (which is also what makes the suites possible), one session per conversation with a by- value drop, the overload-only retry, the observation table behind a thinking level, and the TypeScript layout and typing rules. The repository map, the pipeline-to-adapter interface, the commands and the verification section follow the code. `CONTRIBUTING.md` and `docker/README.md` are updated the same way: prerequisites without a CLI, the compiled build, the suite table with what each suite protects, and the container's real configuration path.
The image used to run the sources and install the OpenCode CLI, because the gateway spawned it. Neither is true any more: the project is compiled, and the upstream is reached over HTTP. The build is now two stages - a builder that installs the dev dependencies and runs `tsc`, and a runtime that carries the production dependencies and `dist/` only. Nothing from `src/`, `test/` or the host's own build output reaches the published image, and the platform binding `wreq-js` needs is installed in the runtime stage, where it is loaded from. The entrypoint writes the configuration file at the path the entry point actually reads (`/app/dist/config.json`) and adopts a file mounted at `/app/config.json`, copying rather than linking it because `readConfigFile()` opens with `O_NOFOLLOW`. Two defects this fixes were visible only by running the image: every `-e` value silently fell back to its default because the gateway read a different path, and the OCI labels never reached the produced image because they were declared in the builder stage.
The workflow ran `node --check` over JavaScript sources and two end-to- end suites that booted a stub of the deleted local server. It now typechecks the program, builds it, asserts the repository invariants, runs every suite from `dist/` on Node 20, 22 and 24, and builds the container, checking that it runs non-root, answers `/health`, reports healthy, and that environment values override the stored file. The slow checks are no longer gated behind an environment variable: the suites that hold a stalled upstream or a long silent stream run inside the matrix, so a documented keep-alive line is covered by a build rather than by a memory of running it by hand.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this does
Replaces the local
opencode servebackend with a direct HTTP lane to opencode.ai's own inference API, andmigrates the whole project to TypeScript.
src/opencode-free/): reproduces the client the free tier accepts (Bearer public, the CLIUser-Agent, OpenCode's
read/shelldefinitions, the<env>marker, ases_...id minted from the currenttime), picks the endpoint by model family (chat / Responses / Messages), always streams upstream and aggregates
for non-streaming clients, parses each wire's SSE into the events the protocol adapters already consumed, retries
only the
429 ... overloadedburst, and drops a spent session by value. Images travel in each wire's own shape;tool calls are native upstream calls, so the text-markup emulation is gone. Thinking levels resolve against a
per-model table ported from 9router, which downgrades
max/ultrainstead of letting the upstream refuse them.opencode.aicompares the TLS ClientHello, so that host goes throughwreq-jswhile anyother base URL uses plain
fetch- which is what lets the suites point the lane at a stub.(
backend-auth,backend-health,collector,toolguard,polyfills), plus@opencode/client.tsconfig.jsoncompilesindex.ts,src/**andtest/**intodist/; every source and suitefile is
.ts;allowJsis off.test/contract.ts(HTTP contract),test/protocols.ts(Responses/Messages),test/stream.ts(upstream behaviour: deltas, reasoning, usage, in-bandfailure, masking, overload retry, fingerprint, sessions, stalled budget, disconnect),
test/effort.ts(thinkinglevels),
test/vision.ts(images + the file refusal) run againsttest/lib/stub-free-upstream.ts, which enforcesthe free tier's own gates.
test/live-free.tsis the opt-in check that makes one real request.dist/-only runtime, and CI that typechecks,builds, runs every suite on Node 20/22/24 and verifies the container.
Verification
pnpm run checkpnpm testpnpm run test:live(real request to opencode.ai)opencode/big-pickle200, and a plainfetchfrom this process refused by the upstream gatedocker build+ container assertions/healthhealthy, labels present,dist/-only runtime)Breaking change
The OpenCode CLI is no longer used or required.
OPENCODE_SERVER_URL,OPENCODE_SERVER_PASSWORD,OPENCODE_PATH,OPENCODE_BIND_HOST,USE_ISOLATED_HOMEand the health-cache/start-retry keys are gone;FREE_BASE_URL(default
https://opencode.ai) andFREE_IMPERSONATEreplace them.DISABLE_TOOLSnow withholds the client'stools from the upstream request instead of filtering tool markup out of the answer.