Skip to content

feat(proxy): serve the free models from opencode.ai directly - #2

Merged
dinhdev666 merged 6 commits into
mainfrom
feat/free-lane-typescript
Nov 24, 2026
Merged

dinhdev666 merged 6 commits into
mainfrom
feat/free-lane-typescript

Conversation

@dinhdev666

Copy link
Copy Markdown
Owner

What this does

Replaces the local opencode serve backend with a direct HTTP lane to opencode.ai's own inference API, and
migrates the whole project to TypeScript.

  • The lane (src/opencode-free/): reproduces the client the free tier accepts (Bearer public, the CLI
    User-Agent, OpenCode's read/shell definitions, the <env> marker, a ses_... id minted from the current
    time), 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 ... overloaded burst, 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/ultra instead of letting the upstream refuse them.
  • Transport rule: only opencode.ai compares the TLS ClientHello, so that host goes through wreq-js while any
    other base URL uses plain fetch - which is what lets the suites point the lane at a stub.
  • Removed: the spawn/health/session/poll machinery and the modules that only served it
    (backend-auth, backend-health, collector, toolguard, polyfills), plus @opencode/client.
  • TypeScript: tsconfig.json compiles index.ts, src/** and test/** into dist/; every source and suite
    file is .ts; allowJs is off.
  • Tests: the two suites that drove the deleted CLI stub are retired. test/contract.ts (HTTP contract),
    test/protocols.ts (Responses/Messages), test/stream.ts (upstream behaviour: deltas, reasoning, usage, in-band
    failure, masking, overload retry, fingerprint, sessions, stalled budget, disconnect), test/effort.ts (thinking
    levels), test/vision.ts (images + the file refusal) run against test/lib/stub-free-upstream.ts, which enforces
    the free tier's own gates. test/live-free.ts is the opt-in check that makes one real request.
  • Packaging: two-stage image built from the compiled tree with a dist/-only runtime, and CI that typechecks,
    builds, runs every suite on Node 20/22/24 and verifies the container.

Verification

Check Result
pnpm run check exit 0
pnpm test exit 0 - 915 checks (contract 183, protocols 140, stream 92, effort 27, vision 21, chat 151, responses 245, anthropic 56)
pnpm run test:live (real request to opencode.ai) 5/5 - catalog 200, completion of opencode/big-pickle 200, and a plain fetch from this process refused by the upstream gate
docker build + container assertions exit 0 (non-root, /health healthy, labels present, dist/-only runtime)
CI on this branch (manual dispatch) success: commit messages + Node 20/22/24 + container image

Breaking change

The OpenCode 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 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.
@dinhdev666
dinhdev666 merged commit 084f7a2 into main Nov 24, 2026
10 checks passed
@dinhdev666
dinhdev666 deleted the feat/free-lane-typescript branch November 24, 2026 23:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant