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/server.ts ADDED
@@ -0,0 +1,3766 @@
1
+ #!/usr/bin/env bun
2
+ const dns = require("dns");
3
+ // `ipv6first` only exists from Node 22, and an unsupported order throws
4
+ // ERR_INVALID_ARG_VALUE at module load — which kills the bridge before it
5
+ // listens instead of merely changing a preference. Fall back in order.
6
+ const DNS_RESULT_ORDER = (() => {
7
+ const wanted = String(process.env.DNS_RESULT_ORDER || "ipv4first").trim().toLowerCase();
8
+ for (const order of [wanted, "ipv4first", "verbatim"]) {
9
+ try {
10
+ dns.setDefaultResultOrder(order);
11
+ if (order !== wanted) {
12
+ console.warn(
13
+ `[opencode-free-bridge] DNS_RESULT_ORDER=${wanted} is not supported by this Node (${process.versions.node}); using ${order}`
14
+ );
15
+ }
16
+ return order;
17
+ } catch {}
18
+ }
19
+ return null;
20
+ })();
21
+ const http = require("http");
22
+ const crypto = require("crypto");
23
+ let VERSION = "1.5.0";
24
+ try {
25
+ VERSION = require("./package.json").version || VERSION;
26
+ } catch {}
27
+ const { effectiveMaxTokens } = require("./token-budget");
28
+ const { handleAnthropicMessages, handleCountTokens } = require("./anthropic");
29
+ // TypeScript type declarations only — erased at load. `proxy` and `panel` are
30
+ // required dynamically, so their API is described here rather than imported.
31
+ declare const Bun: {
32
+ version: string;
33
+ Transpiler?: new (options: { loader: string }) => { transformSync(source: string): string };
34
+ };
35
+
36
+ /** The node:http request surface this file uses. */
37
+ interface IncomingRequestLike {
38
+ method?: string;
39
+ url?: string;
40
+ headers: Record<string, string | string[] | undefined>;
41
+ on(event: string, listener: (...args: unknown[]) => void): unknown;
42
+ once(event: string, listener: (...args: unknown[]) => void): unknown;
43
+ off?(event: string, listener: (...args: unknown[]) => void): unknown;
44
+ removeListener?(event: string, listener: (...args: unknown[]) => void): unknown;
45
+ pause?(): void;
46
+ destroy?(): void;
47
+ [key: string]: unknown;
48
+ }
49
+
50
+ /** The node:http response surface this file uses. */
51
+ interface ServerResponseLike {
52
+ headersSent: boolean;
53
+ writableEnded: boolean;
54
+ writeHead(status: number, headers?: Record<string, string | number>): unknown;
55
+ setHeader(name: string, value: string | number): unknown;
56
+ write(chunk: string): unknown;
57
+ end(chunk?: unknown): unknown;
58
+ on(event: string, listener: (...args: unknown[]) => void): unknown;
59
+ once(event: string, listener: (...args: unknown[]) => void): unknown;
60
+ off(event: string, listener: (...args: unknown[]) => void): unknown;
61
+ destroy(): void;
62
+ [key: string]: unknown;
63
+ }
64
+
65
+ /** A `fetch` response, as `proxy.netFetch` returns one. */
66
+ interface FetchHeaders {
67
+ get(name: string): string | null;
68
+ }
69
+
70
+ interface StreamReader {
71
+ read(): Promise<{ done: boolean; value?: Uint8Array }>;
72
+ cancel(): Promise<unknown>;
73
+ }
74
+
75
+ interface FetchResponse {
76
+ ok: boolean;
77
+ status: number;
78
+ headers: FetchHeaders;
79
+ text(): Promise<string>;
80
+ json(): Promise<unknown>;
81
+ body: { getReader(): StreamReader };
82
+ }
83
+
84
+ /** One pool entry as `proxy.pick()` returns it. */
85
+ interface EgressChoice {
86
+ url: string | null;
87
+ cooling?: boolean;
88
+ }
89
+
90
+ /** A recorded egress failure, as `proxy.markFailure` takes it. */
91
+ interface EgressFailure {
92
+ reason?: string;
93
+ cooldownMs?: number | null;
94
+ }
95
+
96
+ /** One entry of the egress pool, as `proxy.describe().pool` reports it. */
97
+ interface ProxyPool {
98
+ active: boolean;
99
+ enabled: number;
100
+ size: number;
101
+ strategy: string;
102
+ cooldownMs: number;
103
+ }
104
+
105
+ /** The egress block `proxy.describe()` returns. */
106
+ interface ProxyState {
107
+ mode: string;
108
+ proxy: string | null;
109
+ pool?: ProxyPool;
110
+ [key: string]: unknown;
111
+ }
112
+
113
+ /** Egress-proxy API this server calls. `proxy.ts` implements it; PROXY_FALLBACK stubs it. */
114
+ interface ProxyApi {
115
+ getProxyUrl(): string;
116
+ withProxy(init: unknown): unknown;
117
+ netFetch(url: string, init?: unknown, egressUrl?: string | null): Promise<FetchResponse>;
118
+ describe(): ProxyState;
119
+ setProxyUrl(url: string): ProxySetResult;
120
+ testProxy(url: string, options?: { probeUrl?: string }): Promise<ProxyTestResult>;
121
+ setPool?: (spec: unknown) => ProxyPoolResult;
122
+ parsePoolEntry?: (entry: unknown, index: number) => ParsedPoolEntry;
123
+ displayHost?: (url: string | null) => string;
124
+ pick?: (options?: { exclude?: string | null }) => EgressChoice;
125
+ markFailure?: (url: string | null, info?: EgressFailure) => void;
126
+ markSuccess?: (url: string | null) => void;
127
+ describeUsage?: () => unknown;
128
+ recoveryProbeTick?: () => Promise<unknown>;
129
+ }
130
+
131
+ /** Result of changing the single-proxy setting. */
132
+ interface ProxySetResult {
133
+ ok: boolean;
134
+ error?: string;
135
+ mode?: string;
136
+ proxy?: string;
137
+ }
138
+
139
+ /** Result of installing an egress pool. */
140
+ interface ProxyPoolResult {
141
+ ok: boolean;
142
+ error?: string;
143
+ pool: ProxyPool;
144
+ }
145
+
146
+ /** Result of probing one candidate proxy. */
147
+ interface ProxyTestResult {
148
+ ok: boolean;
149
+ apiStatus?: number | null;
150
+ exitIp?: string | null;
151
+ latencyMs?: number | null;
152
+ error?: string | null;
153
+ [key: string]: unknown;
154
+ }
155
+
156
+ /** One parsed pool entry, as `proxy.parsePoolEntry` returns it. */
157
+ interface ParsedPoolEntry {
158
+ ok: boolean;
159
+ error?: string;
160
+ entry: { id: string; label: string; url: string };
161
+ }
162
+
163
+ /** One entry in the persistent upstream-session cache. */
164
+ interface SessionCacheEntry {
165
+ sessionId: string;
166
+ lastSeen: number;
167
+ }
168
+
169
+ /** What the outgoing request actually carried, used to tell a shape bug from an IP block. */
170
+ interface GateShape {
171
+ hasReadTool: boolean;
172
+ toolCount: number;
173
+ userAgentOk: boolean;
174
+ userAgent: string;
175
+ sessionHeaders: string[];
176
+ }
177
+
178
+ /** The last gate rejection, as reported by /health. */
179
+ interface GateDiagnostic {
180
+ at: number;
181
+ kind: "free-tier-gate" | "ip-abuse";
182
+ status: number;
183
+ logId: string | null;
184
+ message?: string;
185
+ shape?: GateShape;
186
+ shapeOk?: boolean;
187
+ missing?: string[];
188
+ model: string;
189
+ }
190
+
191
+ /** The last upstream 5xx, as reported by /health. */
192
+ interface UpstreamErrorRecord {
193
+ at: number;
194
+ status: number;
195
+ logId: string | null;
196
+ cfRay: string | null;
197
+ cfPlacement: string | null;
198
+ message: string;
199
+ model: string;
200
+ }
201
+
202
+ /** The egress one client request is pinned to, and how it has fared. */
203
+ interface EgressState {
204
+ egress: EgressChoice;
205
+ egressUrl: string | null;
206
+ transportFailures: number;
207
+ }
208
+
209
+ /** Wire endpoints resolved for one request. */
210
+ interface Endpoints {
211
+ responsesUrl: string;
212
+ chatUrl: string;
213
+ modelsUrl: string;
214
+ }
215
+
216
+ /** Upstream request body for the chosen protocol lane, plus the tool alias map. */
217
+ interface UpstreamPayload {
218
+ upstreamBody: Record<string, unknown>;
219
+ aliasToOriginal: Map<string, string>;
220
+ }
221
+
222
+ /** Result of merging the client's tools with the fingerprint tools. */
223
+ interface ToolFingerprintResult {
224
+ tools: unknown[];
225
+ appended: string[];
226
+ placeholderNote: string;
227
+ aliasToOriginal: Map<string, string>;
228
+ originalToAlias: Map<string, string>;
229
+ }
230
+
231
+ /** Outcome of one self-update attempt. */
232
+ interface UpdateResult {
233
+ updated: boolean;
234
+ reason?: string;
235
+ version?: string;
236
+ error?: string;
237
+ }
238
+
239
+ /** Files a boot-time repair downloaded, and files it could not. */
240
+ interface RepairResult {
241
+ repaired: string[];
242
+ failed: string[];
243
+ }
244
+
245
+ /**
246
+ * Load a sibling module, or a fallback when the file is not on disk yet.
247
+ *
248
+ * This exists because of a real upgrade path: 2.1.0's self-updater had no
249
+ * `proxy.ts`/`panel.ts` in its file list, so updating that install to 2.2.0
250
+ * wrote a `server.ts` that required modules the updater never fetched. A hard
251
+ * `require` turned that into a crash loop (`Cannot find module './proxy'`)
252
+ * after the restart, with no way back except reinstalling. A missing optional
253
+ * module must degrade to direct egress, never prevent the process from booting.
254
+ *
255
+ * Only a missing *own* module is tolerated. If `proxy.ts` exists but requires
256
+ * something absent, that is a broken install and the error must surface.
257
+ */
258
+ function loadLocalModule(name: string, fallback: unknown): unknown {
259
+ try {
260
+ return require(`./${name}`);
261
+ } catch (err) {
262
+ if (err.code !== "MODULE_NOT_FOUND" || !String(err.message).includes(`'./${name}'`)) throw err;
263
+ return fallback;
264
+ }
265
+ }
266
+
267
+ const PROXY_FALLBACK: ProxyApi = {
268
+ getProxyUrl: () => "",
269
+ withProxy: (init: unknown) => init,
270
+ netFetch: (url: string, init?: unknown) => fetch(url, init),
271
+ describe: () => ({
272
+ mode: "direct",
273
+ proxy: null,
274
+ hasCredentials: false,
275
+ source: "none",
276
+ locked: false,
277
+ configPath: null,
278
+ error: "proxy.js belum terpasang; egress langsung. Jalankan ulang install.sh.",
279
+ }),
280
+ setProxyUrl: () => ({
281
+ ok: false,
282
+ error: "proxy.js belum terpasang. Jalankan ulang install.sh atau tunggu perbaikan otomatis.",
283
+ }),
284
+ testProxy: async () => ({ ok: false, error: "proxy.js belum terpasang." }),
285
+ };
286
+
287
+ /** The panel renderer this server calls; `panel.ts` implements it. */
288
+ interface PanelApi {
289
+ renderPanel(state: ProxyState, meta: { version: string; port: number }): string;
290
+ }
291
+
292
+ const PANEL_FALLBACK = {
293
+ renderPanel: () =>
294
+ "<!doctype html><meta charset=\"utf-8\"><title>opencode-free-bridge</title>" +
295
+ "<body style=\"font:16px/1.5 system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem\">" +
296
+ "<h1>Instalasi belum lengkap</h1>" +
297
+ "<p><code>proxy.js</code> dan <code>panel.js</code> tidak ditemukan di direktori ini. " +
298
+ "Bridge tetap berjalan dengan egress langsung. Jalankan ulang " +
299
+ "<code>install.sh</code> untuk memasang panel.</p></body>",
300
+ };
301
+
302
+ // Egress proxy and the panel that configures it. Loaded before anything else
303
+ // touches the network so the first request already honours a saved proxy.
304
+ let proxy = loadLocalModule("proxy", PROXY_FALLBACK) as ProxyApi;
305
+ let panel = loadLocalModule("panel", PANEL_FALLBACK) as PanelApi;
306
+
307
+ /**
308
+ * Local modules this server requires by relative path. The self-updater uses
309
+ * this to refuse an update that would install a `server.ts` whose imports are
310
+ * not part of the release, and boot uses it to repair a half-installed tree.
311
+ */
312
+ function localRequires(source: unknown): string[] {
313
+ const names = new Set();
314
+ // Strip comments first: the doc comment above names `require("./x")` as an
315
+ // example, and scanning it produced a bogus `x.ts` dependency.
316
+ const text = String(source || "")
317
+ .replace(/\/\*[\s\S]*?\*\//g, "")
318
+ .replace(/(^|[^:])\/\/[^\n]*/g, "$1");
319
+ // `require("./x")` and the tolerant `loadLocalModule("x", …)` loader both
320
+ // name a file that must be present for this server to work.
321
+ for (const re of [/\brequire\(\s*["']\.\/([A-Za-z0-9._-]+)["']\s*\)/g, /\bloadLocalModule\(\s*["']([A-Za-z0-9._-]+)["']/g]) {
322
+ let match;
323
+ while ((match = re.exec(text))) {
324
+ if (match[1].endsWith(".json")) continue;
325
+ const name = match[1].endsWith(".ts") ? match[1] : `${match[1]}.ts`;
326
+ names.add(name);
327
+ }
328
+ }
329
+ return [...names];
330
+ }
331
+
332
+ /**
333
+ * Fetch files that `server.ts` requires but that are not on disk.
334
+ *
335
+ * 2.1.0 shipped a self-updater whose file list predated `proxy.ts`/`panel.ts`,
336
+ * so an update to 2.2.0 wrote a server that could not boot. That install now
337
+ * starts with the fallbacks above; this repairs it on the next boot instead of
338
+ * leaving the panel permanently unavailable. Best-effort: a failure keeps the
339
+ * fallback, never blocks startup.
340
+ */
341
+ async function repairMissingModules(dir: string = __dirname): Promise<RepairResult> {
342
+ const fs = require("fs");
343
+ const path = require("path");
344
+ const required = new Set(localRequires(fs.readFileSync(path.join(dir, "server.ts"), "utf8")));
345
+ for (const name of ["proxy.ts", "panel.ts"]) required.add(name);
346
+ const missing = [...required].filter((f) => !fs.existsSync(path.join(dir, f)));
347
+ const repaired = [];
348
+ const failed = [];
349
+ for (const file of missing) {
350
+ try {
351
+ const res = await fetch(`${UPDATE_BASE_URL}/${file}?cb=${Date.now()}`, {
352
+ headers: { "Cache-Control": "no-cache" },
353
+ signal: AbortSignal.timeout(8000),
354
+ });
355
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
356
+ const text = await res.text();
357
+ if (!text || text.length < 20) throw new Error("empty response");
358
+ const syntax = moduleSyntaxError(text);
359
+ if (syntax) throw new Error(syntax);
360
+ const tmp = path.join(dir, `.${file}.repair.${process.pid}`);
361
+ fs.writeFileSync(tmp, text, "utf8");
362
+ fs.renameSync(tmp, path.join(dir, file));
363
+ repaired.push(file);
364
+ } catch (err) {
365
+ failed.push(`${file}: ${err.message}`);
366
+ }
367
+ }
368
+ if (repaired.length && path.resolve(dir) === path.resolve(__dirname)) {
369
+ proxy = loadLocalModule("proxy", PROXY_FALLBACK) as ProxyApi;
370
+ panel = loadLocalModule("panel", PANEL_FALLBACK) as PanelApi;
371
+ console.log(`[opencode-free-bridge] Repaired missing module(s): ${repaired.join(", ")}`);
372
+ } else if (repaired.length) {
373
+ console.log(`[opencode-free-bridge] Repaired missing module(s): ${repaired.join(", ")}`);
374
+ }
375
+ if (failed.length) {
376
+ console.warn(
377
+ `[opencode-free-bridge] Could not repair ${failed.join(", ")}; ` +
378
+ "running with direct egress. Re-run install.sh to fix this install."
379
+ );
380
+ }
381
+ return { repaired, failed };
382
+ }
383
+
384
+ const PORT = parseInt(process.env.PORT || "20129", 10);
385
+ const HOST = process.env.HOST || "127.0.0.1";
386
+ const UPSTREAM_TIMEOUT_MS = parseInt(process.env.UPSTREAM_TIMEOUT_MS || "120000", 10);
387
+ const MAX_BODY_BYTES = parseInt(process.env.MAX_BODY_BYTES || String(10 * 1024 * 1024), 10);
388
+ const GATE_RETRY_COOLDOWN_MS = parseInt(
389
+ process.env.GATE_RETRY_COOLDOWN_MS || "30000",
390
+ 10
391
+ );
392
+ const CORS_ORIGIN = process.env.CORS_ORIGIN !== undefined ? process.env.CORS_ORIGIN : "";
393
+ // Optional egress relay. When set, every upstream inference request is sent to
394
+ // this relay URL instead of directly to opencode.ai, with the real origin and
395
+ // path carried in x-relay-target / x-relay-path (the same header contract
396
+ // 9Router's Cloudflare/Vercel/Deno/Netlify relays speak). The relay performs
397
+ // the final fetch, so upstream sees the relay's egress IP. Empty = direct.
398
+ const UPSTREAM_RELAY_URL = (process.env.UPSTREAM_RELAY_URL || "").trim();
399
+
400
+ /**
401
+ * Origin-only label for `/health`. The configured relay URL may carry
402
+ * credentials or a token in the query string; those must not be handed to any
403
+ * client that can reach the local health endpoint.
404
+ */
405
+ function relayLabel(url: string): string {
406
+ try {
407
+ return new URL(url).origin;
408
+ } catch {
409
+ return "configured";
410
+ }
411
+ }
412
+
413
+ // Wire endpoints. These are *defaults*; the live values come from identity.ts,
414
+ // which resolves them from the upstream provider catalog (`opencode.api` in
415
+ // models.opencode.ai/api.json) at refresh time. Reading them per request means
416
+ // a /zen/v1 → /inference/v1 style migration applies without a restart.
417
+ const OPENCODE_RESPONSES_URL =
418
+ process.env.OPENCODE_RESPONSES_URL || "https://opencode.ai/inference/v1/responses";
419
+ const OPENCODE_CHAT_URL =
420
+ process.env.OPENCODE_CHAT_URL || "https://opencode.ai/inference/v1/chat/completions";
421
+ const OPENCODE_MODELS_URL =
422
+ process.env.OPENCODE_MODELS_URL || "https://opencode.ai/inference/v1/models";
423
+ const OPENCODE_RELEASES_ATOM_URL =
424
+ process.env.OPENCODE_RELEASES_ATOM_URL || "https://github.com/anomalyco/opencode/releases.atom";
425
+ const UPDATE_HINT =
426
+ "Update opencode-free-bridge: curl -fsSL https://raw.githubusercontent.com/azrinaldi/opencode-free-bridge/main/install.sh | bash";
427
+ // Self-update (like the CLI's `update: auto`): poll this repo's package.json and
428
+ // replace the installed files when a newer release exists. Enabled by default;
429
+ // AUTO_UPDATE=0 disables it. Files are syntax-checked before being swapped in,
430
+ // and the swap is rename-per-file, so a partial download can never leave a
431
+ // broken install.
432
+ const UPDATE_BASE_URL =
433
+ process.env.OPENCODE_BRIDGE_UPDATE_BASE ||
434
+ "https://raw.githubusercontent.com/azrinaldi/opencode-free-bridge/main";
435
+ const AUTO_UPDATE = process.env.AUTO_UPDATE !== "0" && process.env.AUTO_UPDATE !== "false";
436
+ const UPDATE_FILES = [
437
+ "package.json",
438
+ "identity.ts",
439
+ "token-budget.ts",
440
+ "verify.ts",
441
+ "gate-drill.ts",
442
+ "transport-fingerprint.ts",
443
+ "transport-baseline.json",
444
+ "tunnel-doctor.sh",
445
+ "proxy.ts",
446
+ "panel.ts",
447
+ "egress-proxy.ts",
448
+ "anthropic.ts",
449
+ "server.ts",
450
+ "THIRD_PARTY_NOTICES.md",
451
+ ];
452
+ let updateInFlight: Promise<UpdateResult> | null = null;
453
+ let lastUpdateCheck = 0;
454
+ const UPDATE_CHECK_TTL_MS = 6 * 60 * 60 * 1000;
455
+
456
+ /**
457
+ * Compare two `x.y.z` versions. Returns true when `remote` is newer.
458
+ */
459
+ function isNewerVersion(current: unknown, remote: unknown): boolean {
460
+ const a = String(current).split(".").map(Number);
461
+ const b = String(remote).split(".").map(Number);
462
+ for (let i = 0; i < 3; i++) {
463
+ const av = Number.isFinite(a[i]) ? a[i] : 0;
464
+ const bv = Number.isFinite(b[i]) ? b[i] : 0;
465
+ if (bv !== av) return bv > av;
466
+ }
467
+ return false;
468
+ }
469
+
470
+ /** Parse a downloaded module without executing it. TS needs Bun's transpiler;
471
+ * `new Function` only understands the JS subset it strips to. */
472
+ function moduleSyntaxError(text: string): string | null {
473
+ const src = String(text).replace(/^#!.*\n/, "");
474
+ try {
475
+ if (typeof Bun !== "undefined" && Bun.Transpiler) new Bun.Transpiler({ loader: "ts" }).transformSync(src);
476
+ else new Function(src);
477
+ return null;
478
+ } catch (err) {
479
+ return err instanceof Error ? err.message : String(err);
480
+ }
481
+ }
482
+
483
+ /**
484
+ * The CLI's `update: auto`, in miniature: check this repo's published
485
+ * package.json, and when it is newer, download every shipped file into a temp
486
+ * file, syntax-check the JS, then rename them into place and exit so the
487
+ * service manager restarts us. Any failure leaves the running install intact.
488
+ *
489
+ * Deliberately *not* on the request path: it runs alongside model discovery,
490
+ * at most once per UPDATE_CHECK_TTL_MS.
491
+ */
492
+ async function checkAndApplyUpdate(): Promise<UpdateResult> {
493
+ if (!AUTO_UPDATE) return { updated: false, reason: "disabled" };
494
+ if (updateInFlight) return updateInFlight;
495
+ if (Date.now() - lastUpdateCheck < UPDATE_CHECK_TTL_MS) {
496
+ return { updated: false, reason: "fresh" };
497
+ }
498
+ const fs = require("fs");
499
+ const path = require("path");
500
+ if (
501
+ process.env.AUTO_UPDATE !== "1" &&
502
+ process.env.AUTO_UPDATE !== "force" &&
503
+ !process.env.OPENCODE_BRIDGE_UPDATE_BASE &&
504
+ fs.existsSync(path.join(__dirname, ".git"))
505
+ ) {
506
+ return { updated: false, reason: "git-checkout" };
507
+ }
508
+ updateInFlight = (async () => {
509
+ lastUpdateCheck = Date.now();
510
+ const tmpFiles = [];
511
+ const cb = Date.now();
512
+ try {
513
+ const pkgRes = await proxy.netFetch(`${UPDATE_BASE_URL}/package.json?cb=${cb}`, {
514
+ headers: { "Cache-Control": "no-cache" },
515
+ signal: AbortSignal.timeout(8000),
516
+ });
517
+ if (!pkgRes.ok) throw new Error(`HTTP ${pkgRes.status} fetching package.json`);
518
+ const remotePkg = await pkgRes.json();
519
+ const remoteVersion = String(remotePkg?.version || "").trim();
520
+ if (!/^\d+\.\d+\.\d+$/.test(remoteVersion)) throw new Error("invalid remote version");
521
+ if (!isNewerVersion(VERSION, remoteVersion)) {
522
+ return { updated: false, reason: "up-to-date" };
523
+ }
524
+
525
+ for (const file of UPDATE_FILES) {
526
+ const res = await proxy.netFetch(`${UPDATE_BASE_URL}/${file}?cb=${cb}`, {
527
+ headers: { "Cache-Control": "no-cache" },
528
+ signal: AbortSignal.timeout(15000),
529
+ });
530
+ if (!res.ok) throw new Error(`HTTP ${res.status} fetching ${file}`);
531
+ const text = await res.text();
532
+ if (!text || text.length < 20) throw new Error(`empty response for ${file}`);
533
+ if (file.endsWith(".ts")) {
534
+ const syntax = moduleSyntaxError(text);
535
+ if (syntax) throw new Error("syntax check failed for " + file + ": " + syntax);
536
+ } else if (file.endsWith(".json")) {
537
+ try {
538
+ JSON.parse(text);
539
+ } catch (err) {
540
+ throw new Error(`invalid JSON in ${file}: ${err.message}`);
541
+ }
542
+ } else if (file.endsWith(".sh")) {
543
+ // `new Function` cannot parse bash. Check the shebang here and let
544
+ // `bash -n` parse it below, once it is on disk.
545
+ if (!/^#!.*\b(ba)?sh\b/.test(text)) throw new Error(`${file} is not a shell script`);
546
+ }
547
+ const tmpPath = path.join(__dirname, `.${file}.tmp.${process.pid}`);
548
+ fs.writeFileSync(tmpPath, text, "utf8");
549
+ if (file.endsWith(".sh")) {
550
+ let parsed = true;
551
+ try {
552
+ require("child_process").execFileSync("bash", ["-n", tmpPath], {
553
+ stdio: "ignore",
554
+ timeout: 5000,
555
+ });
556
+ } catch (err) {
557
+ // No bash on this host is not a syntax failure; the shebang check
558
+ // above is all we can do there. Anything else is a real rejection.
559
+ if (!err || err.code !== "ENOENT") {
560
+ try {
561
+ fs.unlinkSync(tmpPath);
562
+ } catch {}
563
+ parsed = false;
564
+ throw new Error(`syntax check failed for ${file}: ${err.message}`);
565
+ }
566
+ }
567
+ if (parsed) fs.chmodSync(tmpPath, 0o755);
568
+ }
569
+ tmpFiles.push({ tmpPath, targetPath: path.join(__dirname, file) });
570
+ }
571
+
572
+ // A release can add a module that an older `UPDATE_FILES` list does not
573
+ // name. 2.1.0 -> 2.2.0 did exactly that: the new server.ts required
574
+ // ./proxy and ./panel, the old updater never fetched them, and the
575
+ // restart crash-looped. Read the *incoming* server.ts and stage every
576
+ // local module it imports, so the file list in the running process can
577
+ // never be the reason a valid release fails to boot.
578
+ const incoming = tmpFiles.find((f) => path.basename(f.targetPath) === "server.ts");
579
+ if (incoming) {
580
+ const declared = new Set(tmpFiles.map((f) => path.basename(f.targetPath)));
581
+ for (const file of localRequires(fs.readFileSync(incoming.tmpPath, "utf8"))) {
582
+ if (declared.has(file) || fs.existsSync(path.join(__dirname, file))) continue;
583
+ const res = await proxy.netFetch(`${UPDATE_BASE_URL}/${file}?cb=${cb}`, {
584
+ headers: { "Cache-Control": "no-cache" },
585
+ signal: AbortSignal.timeout(15000),
586
+ });
587
+ if (!res.ok) throw new Error(`HTTP ${res.status} fetching required module ${file}`);
588
+ const text = await res.text();
589
+ if (!text || text.length < 20) throw new Error(`empty response for required module ${file}`);
590
+ const reqSyntax = moduleSyntaxError(text);
591
+ if (reqSyntax) throw new Error(`syntax check failed for required module ${file}: ${reqSyntax}`);
592
+ const tmpPath = path.join(__dirname, `.${file}.tmp.${process.pid}`);
593
+ fs.writeFileSync(tmpPath, text, "utf8");
594
+ tmpFiles.push({ tmpPath, targetPath: path.join(__dirname, file) });
595
+ declared.add(file);
596
+ console.log(`[opencode-free-bridge] Staged newly required module ${file}`);
597
+ }
598
+ }
599
+
600
+ for (const { tmpPath, targetPath } of tmpFiles) fs.renameSync(tmpPath, targetPath);
601
+ console.log(
602
+ `[opencode-free-bridge] Self-updated ${VERSION} → ${remoteVersion}; exiting for service restart.`
603
+ );
604
+ server.close(() => process.exit(0));
605
+ setTimeout(() => process.exit(0), 2000).unref();
606
+ return { updated: true, version: remoteVersion };
607
+ } catch (err) {
608
+ for (const { tmpPath } of tmpFiles) {
609
+ try {
610
+ if (fs.existsSync(tmpPath)) fs.unlinkSync(tmpPath);
611
+ } catch {}
612
+ }
613
+ console.warn(`[opencode-free-bridge] Self-update skipped: ${err.message}`);
614
+ return { updated: false, error: err.message };
615
+ } finally {
616
+ updateInFlight = null;
617
+ }
618
+ })();
619
+ return updateInFlight;
620
+ }
621
+
622
+ function isFreeTierCliGateError(status: number, errType: unknown, errMsg: unknown): boolean {
623
+ if (errType === "FreeTierError" || errType === "UpgradeRequired") return true;
624
+ // 426 is the version-floor handshake: upstream names the minimum client
625
+ // version it will accept. Treat it as a gate signal so the identity layer can
626
+ // adopt that floor and retry.
627
+ if (status === 426) return true;
628
+ if (status !== 403 && status !== 401) return false;
629
+ const m = String(errMsg || "").toLowerCase();
630
+ return (
631
+ m.includes("freetiererror") ||
632
+ m.includes("free tier") ||
633
+ m.includes("free models") ||
634
+ m.includes("opencode cli") ||
635
+ m.includes("only available in opencode") ||
636
+ m.includes("upgrade required") ||
637
+ m.includes("or newer is required")
638
+ );
639
+ }
640
+ const identity = require("./identity");
641
+
642
+ /**
643
+ * Wire endpoints for this request. Environment variables pin them; otherwise
644
+ * the values derived from the upstream provider catalog are used, falling back
645
+ * to the shipped defaults until the first successful refresh. Resolved per
646
+ * call, so a catalog change applies on the next request.
647
+ */
648
+ function resolveEndpoints(modelId: string | null = null): Endpoints {
649
+ const derived = identity.getEndpoints(modelId);
650
+ return {
651
+ responsesUrl: process.env.OPENCODE_RESPONSES_URL || derived.responsesUrl || OPENCODE_RESPONSES_URL,
652
+ chatUrl: process.env.OPENCODE_CHAT_URL || derived.chatUrl || OPENCODE_CHAT_URL,
653
+ modelsUrl: process.env.OPENCODE_MODELS_URL || derived.modelsUrl || OPENCODE_MODELS_URL,
654
+ };
655
+ }
656
+
657
+ // The identity (user-agent, session-id format, header set) is owned by
658
+ // identity.ts, which derives it from opencode's public source and refreshes it
659
+ // lazily — on request, never on a timer. `currentUserAgent` mirrors it for the
660
+ // few call sites that need a plain string.
661
+ let currentUserAgent = process.env.OPENCODE_USER_AGENT || identity.getUserAgent();
662
+
663
+ function syncUserAgent(): string {
664
+ if (!process.env.OPENCODE_USER_AGENT) currentUserAgent = identity.getUserAgent();
665
+ return currentUserAgent;
666
+ }
667
+
668
+ /**
669
+ * Send an inference request to `url`, optionally through the configured egress
670
+ * relay. The relay contract is the one 9Router's deployable relays speak:
671
+ * POST <relay> with `x-relay-target: <origin>` and `x-relay-path: <path>`, and
672
+ * the relay replays method/headers/body at that origin. The origin and path
673
+ * never travel in the URL, so a relay deployed at a bare workers.dev hostname
674
+ * works unchanged.
675
+ *
676
+ * The request body is serialized once by the caller and passed as a string, so
677
+ * every retry path can replay it.
678
+ *
679
+ * A configured egress proxy applies to whichever URL is finally fetched, so a
680
+ * relay deployment can itself be dialled through the proxy.
681
+ *
682
+ * `egressUrl` pins the egress for this call. The chat handler picks one egress
683
+ * per request and reuses it across retries, so a retry that must stay on the IP
684
+ * that answered does not silently move to a different one mid-conversation.
685
+ * Without it, a pool picks per call.
686
+ */
687
+ function upstreamFetch(url: string, init: Record<string, unknown>, egressUrl: string | null = null): Promise<FetchResponse> {
688
+ if (!UPSTREAM_RELAY_URL) return proxy.netFetch(url, init, egressUrl);
689
+ const parsed = new URL(url);
690
+ const headers = { ...(init.headers || {}) };
691
+ headers["x-relay-target"] = parsed.origin;
692
+ headers["x-relay-path"] = parsed.pathname + parsed.search;
693
+ return proxy.netFetch(UPSTREAM_RELAY_URL, { ...init, headers }, egressUrl);
694
+ }
695
+
696
+ /**
697
+ * Send a request through the chosen egress, and move to the next pool entry when
698
+ * the egress itself is unreachable.
699
+ *
700
+ * A dead proxy is not an upstream refusal: nothing reached upstream, so retrying
701
+ * on another entry costs one connection, while returning a 500 to the client
702
+ * wastes the request entirely. This is the failure mode a pool exists to absorb.
703
+ *
704
+ * With one proxy (or none) there is nothing to fail over to, so the transport
705
+ * error is rethrown for the caller's existing handling.
706
+ */
707
+ async function egressFetch(url: string, init: Record<string, unknown>, state: EgressState): Promise<FetchResponse> {
708
+ try {
709
+ const res = await upstreamFetch(url, init, state.egressUrl);
710
+ state.transportFailures = 0;
711
+ return res;
712
+ } catch (err) {
713
+ const pool = proxy.describe().pool;
714
+ const canFailover = pool && pool.active && pool.enabled > 1;
715
+ if (!canFailover || !state.egressUrl) throw err;
716
+
717
+ proxy.markFailure(state.egressUrl, { reason: `transport: ${err.message}`.slice(0, 200) });
718
+ const next = proxy.pick({ exclude: state.egressUrl });
719
+ if (!next.url || next.url === state.egressUrl) throw err;
720
+
721
+ console.warn(
722
+ `[opencode-free-bridge] Egress ${
723
+ proxy.displayHost(state.egressUrl) || "direct"
724
+ } unreachable (${err.message}); retrying through ${proxy.displayHost(next.url) || "direct"}`
725
+ );
726
+ state.egress = next;
727
+ state.egressUrl = next.url;
728
+ state.transportFailures = (state.transportFailures || 0) + 1;
729
+ // One hop only. A pool where every entry is down must surface the error
730
+ // instead of walking the whole list inside a single client request.
731
+ return upstreamFetch(url, init, state.egressUrl);
732
+ }
733
+ }
734
+
735
+ /**
736
+ * Cooldown implied by an upstream `Retry-After` header, in milliseconds.
737
+ *
738
+ * A spent free-tier allowance answers 429 with `Retry-After` set to the seconds
739
+ * until the daily reset (observed ~77415s). Honouring it means a spent egress
740
+ * stays out of rotation until the allowance actually returns, instead of being
741
+ * retried every few minutes and burning a request on each attempt.
742
+ *
743
+ * Returns null when the header is missing or unparseable, so callers fall back
744
+ * to their previous fixed cooldown. Delta-seconds is the form upstream sends;
745
+ * an HTTP-date is also accepted because the header allows it.
746
+ */
747
+ function retryAfterMs(res: FetchResponse | null): number | null {
748
+ const raw = res?.headers?.get?.("retry-after");
749
+ if (!raw) return null;
750
+ const text = String(raw).trim();
751
+ if (/^\d+$/.test(text)) {
752
+ const secs = parseInt(text, 10);
753
+ return secs > 0 ? secs * 1000 : null;
754
+ }
755
+ const at = Date.parse(text);
756
+ if (Number.isNaN(at)) return null;
757
+ const delta = at - Date.now();
758
+ return delta > 0 ? delta : null;
759
+ }
760
+ /**
761
+ * Record a refusal against the egress that produced it.
762
+ *
763
+ * An empty URL is the `direct` pool entry, which is a real egress, so this
764
+ * cannot test truthiness: only a missing state means "nothing to record".
765
+ */
766
+ function recordEgressFailure(state: EgressState | null, { reason, cooldownMs = null }: EgressFailure = {}): void {
767
+ const url = state && state.egressUrl;
768
+ if (url === null || url === undefined) return;
769
+ const pool = proxy.describe().pool;
770
+ if (!pool || !pool.active) return;
771
+ proxy.markFailure(url, { reason, cooldownMs });
772
+ }
773
+
774
+ function isValidV2UserAgent(ua: unknown): boolean {
775
+ const match = String(ua || "")
776
+ .trim()
777
+ .match(/^opencode\/[a-z0-9-]+\/(\d+)\.\d+\.\d+\/[a-z0-9-]+$/i);
778
+ return Boolean(match) && parseInt(match[1], 10) >= 2;
779
+ }
780
+
781
+ /**
782
+ * A User-Agent the free-tier gate accepts, or the identity's own.
783
+ *
784
+ * Measured (clean egress, `read` tool present): a request without a
785
+ * `User-Agent`, with a bare `opencode`, or with `Mozilla/5.0 …` / `curl/8.18.0`
786
+ * is refused with the same 403 FreeTierError that a blocked IP gets. Only the
787
+ * `opencode/<channel>/<semver>/<name>` shape passes, and the version is not
788
+ * checked for freshness (`opencode/9.9.9` was accepted).
789
+ *
790
+ * `OPENCODE_USER_AGENT` is an operator override, so it is honoured — but an
791
+ * override that the gate would reject is reported instead of silently
792
+ * producing a 403 that looks like an allowance problem.
793
+ */
794
+ function gateSafeUserAgent(): string {
795
+ const override = process.env.OPENCODE_USER_AGENT;
796
+ if (override && /^opencode\/[A-Za-z0-9-]+\/\d+\.\d+\.\d+\/[A-Za-z0-9-]+$/i.test(String(override).trim())) {
797
+ return String(override).trim();
798
+ }
799
+ if (override) {
800
+ console.warn(
801
+ "[opencode-free-bridge] OPENCODE_USER_AGENT does not match the shape the free-tier gate accepts " +
802
+ "(opencode/<channel>/<semver>/<name>); using the derived identity instead"
803
+ );
804
+ }
805
+ const derived = syncUserAgent();
806
+ if (/^opencode\//i.test(derived)) return derived;
807
+ // Last resort: the derived identity itself is malformed. Keep the request
808
+ // shaped as an opencode client rather than sending something the gate refuses.
809
+ return "opencode/latest/0.0.0/cli";
810
+ }
811
+
812
+ // --- ID Generator (matches OpenCode v2 CLI format) ---
813
+ // The shape (charset, total length, multiplier, prefix) comes from identity.ts,
814
+ // which derives it from opencode's own `packages/schema/src/identifier.ts`.
815
+ // Kept as a thin wrapper here so existing call sites and tests keep working.
816
+ function createId(descending: boolean, timestamp: number = Date.now()): string {
817
+ return identity.createId(descending, timestamp);
818
+ }
819
+
820
+ // Live model list, discovered from upstream at boot and refreshed hourly.
821
+ // No hardcoded fallback: an empty list honestly means "upstream not reached
822
+ // yet", so gateways/harnesses apply their own fallback instead of being
823
+ // served a stale lie.
824
+ let activeModels: unknown[] = [];
825
+ let cachedModelsPayload = '{"object":"list","data":[]}';
826
+ let lastDiscoveryTime = 0;
827
+ const DISCOVERY_TTL_MS = 60 * 60 * 1000; // Auto-refresh every 1 hour
828
+ // Single-flight: concurrent /v1/models hits after TTL expiry share one upstream
829
+ // fetch instead of stampeding (50 parallel GETs = 1 upstream call, not 50).
830
+ let discoveryInFlight: Promise<void> | null = null;
831
+ // CLI version feed is slow (5s timeout) and changes rarely: cache 6h, refresh
832
+ // in parallel so model discovery never waits on it.
833
+ let lastCliVersionCheckTime = 0;
834
+ const CLI_VERSION_TTL_MS = 6 * 60 * 60 * 1000;
835
+
836
+ function rebuildDiscoveryPayloads(): void {
837
+ cachedModelsPayload = JSON.stringify({ object: "list", data: activeModels });
838
+ }
839
+ rebuildDiscoveryPayloads();
840
+
841
+ function isLocalOrigin(origin: unknown): boolean {
842
+ if (typeof origin !== "string" || !origin) return false;
843
+ return /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/i.test(origin.trim());
844
+ }
845
+
846
+ const LOOPBACK_HOST_RE = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\]|::1)$/i;
847
+
848
+ /** Hostname from a `Host` header, without the port. IPv6 literals keep brackets off. */
849
+ function hostnameOf(hostHeader: unknown): string {
850
+ const raw = String(hostHeader || "").trim();
851
+ if (!raw) return "";
852
+ const v6 = raw.match(/^\[([^\]]+)\](?::\d+)?$/);
853
+ if (v6) return v6[1];
854
+ return raw.replace(/:\d+$/, "");
855
+ }
856
+
857
+ /**
858
+ * Admin-surface gate: the panel and `/api/proxy` can change where every
859
+ * outbound request goes, so they must not be reachable from a foreign page or
860
+ * a rebound DNS name.
861
+ *
862
+ * The bridge is a local tool with no authentication. Two browser attacks
863
+ * matter here:
864
+ *
865
+ * - CSRF: any page the operator visits could POST to 127.0.0.1 and point the
866
+ * egress at an attacker's proxy. A form POST cannot set
867
+ * `Content-Type: application/json`, so requiring it removes the simple
868
+ * request; the Origin/Sec-Fetch-Site checks below cover the rest.
869
+ * - DNS rebinding: an attacker domain resolving to 127.0.0.1 makes the
870
+ * browser send `Host: evil.example`, which a loopback-only listener would
871
+ * otherwise accept.
872
+ *
873
+ * `PANEL_ALLOWED_HOSTS` (comma-separated) adds names for a reverse proxy or a
874
+ * deliberate LAN deployment. A bind address other than a wildcard is allowed
875
+ * automatically, so `HOST=192.168.1.5` keeps its own panel working.
876
+ */
877
+ function allowedAdminHosts(): Set<string> {
878
+ const hosts = new Set(["localhost", "127.0.0.1", "::1"]);
879
+ for (const extra of String(process.env.PANEL_ALLOWED_HOSTS || "").split(",")) {
880
+ const trimmed = extra.trim().toLowerCase();
881
+ if (trimmed) hosts.add(trimmed);
882
+ }
883
+ const bound = String(HOST || "").toLowerCase();
884
+ const wildcard = !bound || bound === "0.0.0.0" || bound === "::" || bound === "[::]";
885
+ if (!wildcard) hosts.add(bound);
886
+ if (wildcard) {
887
+ // A wildcard bind is usually reached by one of this machine's own
888
+ // addresses (LAN IP, VPS public IP). Those are safe to accept and make
889
+ // `HOST=0.0.0.0` usable without configuration; a rebound attacker domain
890
+ // is still not in this set. Domain names go in PANEL_ALLOWED_HOSTS.
891
+ const os = require("os");
892
+ for (const list of Object.values(os.networkInterfaces())) {
893
+ for (const addr of list || []) {
894
+ if (addr && addr.address) hosts.add(String(addr.address).toLowerCase());
895
+ }
896
+ }
897
+ }
898
+ return hosts;
899
+ }
900
+
901
+ function adminRequestError(req: IncomingRequestLike): string | null {
902
+ const host = hostnameOf(req.headers?.host).toLowerCase();
903
+ if (!host) return "Header Host wajib ada.";
904
+ if (!allowedAdminHosts().has(host)) {
905
+ return `Host ${host} tidak diizinkan. Panel hanya menerima host lokal; tambahkan ke PANEL_ALLOWED_HOSTS bila ini memang disengaja.`;
906
+ }
907
+
908
+ const site = String(req.headers?.["sec-fetch-site"] || "").toLowerCase();
909
+ if (site === "cross-site") {
910
+ return "Permintaan lintas-situs ditolak. Buka panel langsung dari host ini.";
911
+ }
912
+
913
+ // An Origin must match the Host this request was sent to (which covers the
914
+ // panel itself and an SSH/tunnel forward that keeps the browser's origin),
915
+ // or be explicitly allow-listed in CORS_ORIGIN. A loopback origin on a
916
+ // *different* port is another local service, not this panel, so it is not
917
+ // trusted automatically.
918
+ const origin = String(req.headers?.origin || "").trim();
919
+ if (origin) {
920
+ let originHost = "";
921
+ try {
922
+ originHost = new URL(origin).hostname.toLowerCase();
923
+ } catch {
924
+ return `Origin ${origin} tidak valid.`;
925
+ }
926
+ const configured = String(CORS_ORIGIN || "")
927
+ .split(",")
928
+ .map((s) => s.trim())
929
+ .filter(Boolean);
930
+ if (originHost !== host && !configured.includes(origin)) {
931
+ return `Origin ${origin} tidak diizinkan.`;
932
+ }
933
+ }
934
+ return null;
935
+ }
936
+
937
+
938
+ /**
939
+ * Kept for callers and tests that expect the old name. Consults the handshake
940
+ * and derives the rest of the recipe from opencode's source.
941
+ *
942
+ * This is a *poll*: it bypasses the identity freshness guard so the release
943
+ * check happens on its own schedule, but adoption still follows UPDATE_MODE.
944
+ * In `reactive` mode a release that has not moved the gate is recorded (and
945
+ * reported by /health as `identity.available`) without being adopted — forcing
946
+ * it here would silently turn `reactive` into `always` every 6h.
947
+ *
948
+ * The `lastCliVersionCheckTime` guard keeps the handshake read at most once per
949
+ * CLI_VERSION_TTL_MS even when called repeatedly.
950
+ */
951
+ async function refreshCliVersion(): Promise<UpdateResult> {
952
+ const now = Date.now();
953
+ if (now - lastCliVersionCheckTime < CLI_VERSION_TTL_MS) {
954
+ return { updated: false, reason: "fresh" };
955
+ }
956
+ const result = await identity.refresh({ recheck: true });
957
+ syncUserAgent();
958
+ lastCliVersionCheckTime = now;
959
+ return result;
960
+ }
961
+
962
+ // Auto-discovery from OpenCode upstream gateway.
963
+ // Single-flight: concurrent callers share one in-flight fetch.
964
+ // The CLI-version feed refreshes in parallel (fire-and-forget) so a slow
965
+ // 5s feed never delays the model list.
966
+ async function discoverModels(): Promise<void> {
967
+ if (discoveryInFlight) return discoveryInFlight;
968
+ discoveryInFlight = (async () => {
969
+ refreshCliVersion().catch(() => {});
970
+ checkAndApplyUpdate().catch(() => {});
971
+ try {
972
+ const res = await proxy.netFetch(resolveEndpoints().modelsUrl, {
973
+ headers: {
974
+ "Authorization": "Bearer public",
975
+ "User-Agent": currentUserAgent,
976
+ },
977
+ signal: AbortSignal.timeout(15000),
978
+ });
979
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
980
+ const json = await res.json();
981
+ const items = json.data || [];
982
+
983
+ // The gateway is the live source of truth: its /models entries carry the
984
+ // price applied right now (`cost.text.input/output.price`), and an id it
985
+ // stopped serving disappears from the list. The provider catalog still
986
+ // supplies families, reasoning flags and endpoints, but its `status` field
987
+ // lags — it kept `minimax-m3.1-flash-free` marked deprecated after upstream
988
+ // was already serving it free. So the gateway's price is reconciled into the
989
+ // verdicts first, and only an unknown price falls back to the catalog's
990
+ // ruling (or, before the first catalog read, to the `-free` suffix).
991
+ const promoted = identity.applyGatewayPricing(items);
992
+ if (promoted.length > 0) {
993
+ console.log(
994
+ `[opencode-free-bridge] Gateway price list re-ruled: ${promoted.slice(0, 6).join(", ")}${promoted.length > 6 ? ` (+${promoted.length - 6})` : ""}`
995
+ );
996
+ }
997
+ const ownedBy = new Map(items.map((i) => [String(i.id || "").toLowerCase(), i]));
998
+ const kept = [];
999
+ const seen = new Set();
1000
+ const keep = (id) => {
1001
+ const lower = String(id).toLowerCase();
1002
+ if (seen.has(lower)) return;
1003
+ seen.add(lower);
1004
+ kept.push(id);
1005
+ };
1006
+ // Only ids the gateway is serving right now are advertised: a catalog-free
1007
+ // model missing from /models is retired, and advertising it sends clients
1008
+ // into a 404 that burns their per-IP burst quota.
1009
+ for (const item of items) {
1010
+ const id = String(item.id || "");
1011
+ const lower = id.toLowerCase();
1012
+ if (lower.startsWith("jev-")) continue; // systemone evaluator models
1013
+ const verdict = identity.getCatalogVerdict(lower);
1014
+ if (verdict === "free") {
1015
+ keep(id);
1016
+ continue;
1017
+ }
1018
+ if (verdict) continue; // paid or deprecated, and the gateway agrees
1019
+ // No ruling at all: the catalog has not been read yet in this process.
1020
+ // Guess from the name, then correct itself on the next refresh.
1021
+ if (!lower.endsWith("-free") && !lower.includes("-contributor") && lower !== "big-pickle") continue;
1022
+ keep(id);
1023
+ }
1024
+
1025
+ const freeItems = kept.map((id) => ({
1026
+ id,
1027
+ object: "model",
1028
+ owned_by: ownedBy.get(String(id).toLowerCase())?.owned_by || "opencode",
1029
+ }));
1030
+
1031
+ if (freeItems.length > 0) {
1032
+ activeModels = freeItems;
1033
+ rebuildDiscoveryPayloads();
1034
+ lastDiscoveryTime = Date.now();
1035
+ console.log(`[opencode-free-bridge] Auto-discovered ${activeModels.length} free models from upstream gateway.`);
1036
+ return;
1037
+ }
1038
+ } catch (err) {
1039
+ console.warn(`[opencode-free-bridge] Auto-discovery warning: ${err.message}. Model list stays empty until upstream answers.`);
1040
+ }
1041
+ })();
1042
+ try {
1043
+ return await discoveryInFlight;
1044
+ } finally {
1045
+ discoveryInFlight = null;
1046
+ }
1047
+ }
1048
+
1049
+ function normalizeModel(rawModel: unknown): string {
1050
+ if (typeof rawModel !== "string") return "";
1051
+ const stripped = rawModel.trim().replace(/^(opencode\/|oc\/|zen\/|9router\/|openai\/)/i, "").trim();
1052
+ if (!stripped) return "";
1053
+ // A name that is already a real model id is passed through untouched; only a
1054
+ // shorthand is resolved. The catalog's families are consulted first, so a
1055
+ // revision that retired keeps resolving to a live sibling without a bridge
1056
+ // release; the static table below remains for names the catalog does not
1057
+ // group (and for the case where the catalog has not been read yet).
1058
+ const lower = stripped.toLowerCase();
1059
+ const verdict = identity.getCatalogVerdict(lower);
1060
+ // This bridge is free-tier only: it sends `Authorization: Bearer public` and
1061
+ // has no way to authenticate a paid request. A paid id would therefore only
1062
+ // earn a 401/402 upstream, so it is not passed through — an alias that points
1063
+ // at one is allowed to fall through to a free sibling instead.
1064
+ if (verdict === "free") return stripped;
1065
+ const derived = identity.resolveModelAlias(lower);
1066
+ if (derived) return derived;
1067
+ // No static table behind this. A shorthand either derives from the catalog's
1068
+ // own `family` field or it is passed through as a literal model id. Anything
1069
+ // else would be a name this bridge invented, and an invented name can outlive
1070
+ // the model it points at.
1071
+ return stripped;
1072
+ }
1073
+
1074
+ // Protocol routing: which models want /responses instead of /chat/completions.
1075
+ //
1076
+ // The shipped default is empty on purpose. It used to seed two `muse-spark`
1077
+ // ids, both of which the catalog now marks deprecated, plus a `includes("muse")`
1078
+ // fallback — a name rule for a model family that no longer exists. Every live
1079
+ // free model speaks the chat lane (catalog: `@ai-sdk/openai-compatible`), and a
1080
+ // model that needs the other lane is learned from upstream's own
1081
+ // `ModelProtocolUnsupported` reply, which is a fact rather than a guess.
1082
+ // `RESPONSES_MODELS` still seeds the set when upstream ships a Responses-only
1083
+ // model before the bridge has met it.
1084
+ const responsesModelSet = new Set(
1085
+ (process.env.RESPONSES_MODELS || "")
1086
+ .split(",")
1087
+ .map((s) => s.trim().toLowerCase())
1088
+ .filter(Boolean)
1089
+ );
1090
+ const chatModelSet = new Set();
1091
+
1092
+ function isResponsesModel(modelId: unknown): boolean {
1093
+ const lower = String(modelId || "").trim().toLowerCase();
1094
+ if (!lower) return false;
1095
+ if (chatModelSet.has(lower)) return false;
1096
+ if (responsesModelSet.has(lower)) return true;
1097
+ return false;
1098
+ }
1099
+
1100
+ /** Test hook: forget learned lane assignments (they persist by design). */
1101
+ function __resetProtocolLanes(): void {
1102
+ chatModelSet.clear();
1103
+ responsesModelSet.clear();
1104
+ for (const m of (process.env.RESPONSES_MODELS || "").split(",")) {
1105
+ const id = m.trim().toLowerCase();
1106
+ if (id) responsesModelSet.add(id);
1107
+ }
1108
+ }
1109
+
1110
+ function markProtocolSupport(modelId: unknown, useResponses: boolean): void {
1111
+ const lower = String(modelId || "").trim().toLowerCase();
1112
+ if (!lower) return;
1113
+ if (useResponses) {
1114
+ responsesModelSet.add(lower);
1115
+ chatModelSet.delete(lower);
1116
+ } else {
1117
+ chatModelSet.add(lower);
1118
+ responsesModelSet.delete(lower);
1119
+ }
1120
+ }
1121
+
1122
+ // --- Tool fingerprint (dynamic) -------------------------------------------
1123
+ //
1124
+ // Upstream /inference/v1 validates the `tools` array in the request body, and
1125
+ // this is the layer that has moved most often: first the array had to exist,
1126
+ // then it had to contain specific tool names, then (per 9router#4837) the exact
1127
+ // schemas. Hardcoding those definitions here meant a code change every time.
1128
+ //
1129
+ // The definitions now come from identity.ts, which derives them at the release
1130
+ // commit SHA named by the update handshake:
1131
+ // 1. source — `read.ts` / `shell.ts` at that immutable commit
1132
+ // 2. DEFAULT_TOOLS — shipped fallback, used until a source read succeeds
1133
+ //
1134
+ // The names below are kept for the call sites and tests that predate the
1135
+ // change; they are read from the live profile, not frozen at load time.
1136
+ function getFingerprintNames(scope: string | null = null, modelId: string | null = null): string[] {
1137
+ // Only the names actually sent upstream. A capture carries ~10 tools but
1138
+ // `TOOL_PROFILE_SCOPE=core` sends a subset; treating the unsent ones as
1139
+ // fingerprints would alias an unrelated client tool (`glob` → `glob_client`)
1140
+ // for no reason. The model matters too: the release swaps `edit`+`write` for
1141
+ // `patch` on GPT models, so the fingerprint set follows the same rule.
1142
+ return identity.getToolList(false, scope, modelId).map((t) => t.function.name);
1143
+ }
1144
+
1145
+ function getFingerprintDefinitions(): Record<string, unknown> {
1146
+ return identity.getTools();
1147
+ }
1148
+
1149
+ function getCanonicalTools(flat: boolean, scope: string | null = null, modelId: string | null = null): unknown[] {
1150
+ return identity.getToolList(flat, scope, modelId);
1151
+ }
1152
+
1153
+ /**
1154
+ * Stable JSON for schema comparison. Key order must not affect equality: two
1155
+ * definitions that differ only in property order are the same schema.
1156
+ */
1157
+ function stableStringify(val: unknown): string {
1158
+ if (!val || typeof val !== "object") return JSON.stringify(val);
1159
+ if (Array.isArray(val)) return "[" + val.map(stableStringify).join(",") + "]";
1160
+ const keys = Object.keys(val).sort();
1161
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + stableStringify(val[k])).join(",") + "}";
1162
+ }
1163
+
1164
+ const EMPTY_MAP = Object.freeze(new Map());
1165
+ const paramSigCache = new WeakMap();
1166
+ function getParamSig(params: unknown): string {
1167
+ if (!params || typeof params !== "object") return stableStringify(params);
1168
+ let sig = paramSigCache.get(params);
1169
+ if (sig === undefined) {
1170
+ sig = stableStringify(params);
1171
+ paramSigCache.set(params, sig);
1172
+ }
1173
+ return sig;
1174
+ }
1175
+
1176
+ function buildIpThrottleHeaders(freeTierMsg: unknown, diagnostic: { shapeOk?: boolean; logId?: string | null } | null = null): Record<string, string> {
1177
+ if (!freeTierMsg) return { "Content-Type": "application/json" };
1178
+ const retryAfterSec = Math.max(1, Math.ceil((GATE_RETRY_COOLDOWN_MS || 30000) / 1000));
1179
+ const headers = {
1180
+ "Content-Type": "application/json",
1181
+ "Retry-After": String(retryAfterSec),
1182
+ // `shape-ok` means the request carried every anchor the gate checks, so the
1183
+ // refusal is about this egress. `shape-rejected` means the bridge produced
1184
+ // a request the gate refuses — a bridge bug that returns the identical
1185
+ // upstream error. Callers that alert on this can tell the two apart.
1186
+ "X-OpenCode-Gate": diagnostic && diagnostic.shapeOk === false ? "shape-rejected" : "ip-throttled",
1187
+ };
1188
+ if (diagnostic && diagnostic.logId) headers["X-OpenCode-Log-Id"] = diagnostic.logId;
1189
+ return headers;
1190
+ }
1191
+
1192
+ function resolveIpThrottleStatus(upstreamStatus: number, freeTierMsg: unknown): number {
1193
+ if (freeTierMsg && process.env.IP_LIMIT_STATUS === "429") return 429;
1194
+ return upstreamStatus;
1195
+ }
1196
+
1197
+ /**
1198
+ * Is this client-supplied tool already byte-identical to the fingerprint we
1199
+ * would inject? If so it can be passed through untouched.
1200
+ */
1201
+ function isExactFingerprintDef(tool: unknown, key: string): boolean {
1202
+ const want = identity.getTools()[key];
1203
+ if (!want || !tool || typeof tool !== "object") return false;
1204
+ const def = tool.function && typeof tool.function === "object" ? tool.function : tool;
1205
+ return (
1206
+ def.description === want.description &&
1207
+ getParamSig(def.parameters) === getParamSig(want.parameters)
1208
+ );
1209
+ }
1210
+
1211
+ function buildPlaceholderNote(appendedNames: unknown): string {
1212
+ if (!Array.isArray(appendedNames) || appendedNames.length === 0) return "";
1213
+ const list = appendedNames.map((n) => `\`${n}\``).join(" or ");
1214
+ return appendedNames.length > 1
1215
+ ? `Do not call the ${list} tools; they are placeholders that do nothing. Use the other tools you have been given instead.`
1216
+ : `Do not call the ${list} tool; it is a placeholder that does nothing. Use the other tools you have been given instead.`;
1217
+ }
1218
+
1219
+ function getToolName(tool: unknown): string {
1220
+ if (!tool || typeof tool !== "object") return "";
1221
+ if (typeof tool.name === "string") return tool.name.trim();
1222
+ if (tool.function && typeof tool.function.name === "string") return tool.function.name.trim();
1223
+ return "";
1224
+ }
1225
+
1226
+ // Client tools whose name alone makes upstream answer 429 FreeUsageLimitError.
1227
+ // Measured on 2026-11-03 against the live gateway with an otherwise passing
1228
+ // request: a tool called `run_code` is refused, while the same schema under
1229
+ // `run-code`, `runcode`, `run_program` or `code_exec` answers 200, and
1230
+ // `run_code_client` is refused too, so the match is on the substring. The
1231
+ // refusal carries the quota wording, which makes it look like a spent
1232
+ // allowance; it is a name filter. `prepareToolsWithFingerprint` renames such a
1233
+ // tool on the way out and restores the client's name on the way back.
1234
+ const BLOCKED_TOOL_NAME_PATTERNS = [/run_code/i];
1235
+ const BLOCKED_TOOL_ALIAS = "run_program";
1236
+
1237
+ function isBlockedToolName(name: string): boolean {
1238
+ return BLOCKED_TOOL_NAME_PATTERNS.some((pattern) => pattern.test(name));
1239
+ }
1240
+
1241
+ /**
1242
+ * Merge the client's tools with the fingerprint tools the gate requires.
1243
+ *
1244
+ * Three cases per required tool:
1245
+ * - client already sends it verbatim → keep the client's copy
1246
+ * - client sends the same name with a different schema → rename the client's
1247
+ * copy (`read_client`) so both survive, and map responses back
1248
+ * - client does not send it at all → append the fingerprint definition
1249
+ *
1250
+ * The definitions are resolved per call from identity.ts, so a profile update
1251
+ * takes effect on the next request without a restart.
1252
+ */
1253
+ function prepareToolsWithFingerprint(clientTools: unknown[] = [], flat: boolean = false, scope: string | null = null, modelId: string | null = null): ToolFingerprintResult {
1254
+ const fingerprintNames = getFingerprintNames(scope, modelId);
1255
+ const canonical = getCanonicalTools(flat, scope, modelId);
1256
+ const canonicalByName = new Map(
1257
+ canonical.map((t) => [flat ? t.name : t.function.name, t])
1258
+ );
1259
+
1260
+ if (!Array.isArray(clientTools) || clientTools.length === 0) {
1261
+ return {
1262
+ tools: canonical,
1263
+ appended: fingerprintNames,
1264
+ placeholderNote: buildPlaceholderNote(fingerprintNames),
1265
+ aliasToOriginal: EMPTY_MAP,
1266
+ originalToAlias: EMPTY_MAP,
1267
+ };
1268
+ }
1269
+
1270
+ const aliasToOriginal = new Map();
1271
+ const originalToAlias = new Map();
1272
+ const normalized = [];
1273
+ const takenNames = new Set(clientTools.map(getToolName).filter(Boolean));
1274
+ const presentExactFingerprints = new Set();
1275
+
1276
+ for (const t of clientTools) {
1277
+ const name = getToolName(t);
1278
+ if (!name) continue;
1279
+ const def = t.function && typeof t.function === "object" ? t.function : t;
1280
+ const description = def.description || "";
1281
+ const parameters = def.parameters || { type: "object", properties: {} };
1282
+
1283
+ if (isBlockedToolName(name)) {
1284
+ let alias = BLOCKED_TOOL_ALIAS;
1285
+ for (let i = 2; takenNames.has(alias); i++) {
1286
+ alias = `${BLOCKED_TOOL_ALIAS}${i}`;
1287
+ }
1288
+ takenNames.add(alias);
1289
+ aliasToOriginal.set(alias, name);
1290
+ originalToAlias.set(name, alias);
1291
+ normalized.push(
1292
+ flat
1293
+ ? { type: "function", name: alias, description, parameters }
1294
+ : { type: "function", function: { name: alias, description, parameters } }
1295
+ );
1296
+ continue;
1297
+ }
1298
+
1299
+ if (fingerprintNames.includes(name)) {
1300
+ if (presentExactFingerprints.has(name)) continue;
1301
+ if (isExactFingerprintDef(t, name)) {
1302
+ presentExactFingerprints.add(name);
1303
+ normalized.push(
1304
+ flat
1305
+ ? { type: "function", name, description, parameters, strict: false }
1306
+ : { type: "function", function: { name, description, parameters } }
1307
+ );
1308
+ continue;
1309
+ }
1310
+ // Client defined its own tool under a name the gate fingerprints: alias
1311
+ // it so the exact fingerprint can still be injected alongside.
1312
+ if (originalToAlias.has(name)) continue;
1313
+ let alias = `${name}_client`;
1314
+ for (let i = 2; takenNames.has(alias); i++) {
1315
+ alias = `${name}_client${i}`;
1316
+ }
1317
+ takenNames.add(alias);
1318
+ aliasToOriginal.set(alias, name);
1319
+ originalToAlias.set(name, alias);
1320
+ normalized.push(
1321
+ flat
1322
+ ? { type: "function", name: alias, description, parameters }
1323
+ : { type: "function", function: { name: alias, description, parameters } }
1324
+ );
1325
+ continue;
1326
+ }
1327
+
1328
+ normalized.push(
1329
+ flat
1330
+ ? { type: "function", name, description, parameters }
1331
+ : { type: "function", function: { name, description, parameters } }
1332
+ );
1333
+ }
1334
+
1335
+ const appended = [];
1336
+ for (const name of fingerprintNames) {
1337
+ if (presentExactFingerprints.has(name)) continue;
1338
+ const def = canonicalByName.get(name);
1339
+ if (!def) continue;
1340
+ normalized.push(def);
1341
+ appended.push(name);
1342
+ }
1343
+
1344
+ return {
1345
+ tools: normalized,
1346
+ appended,
1347
+ placeholderNote:
1348
+ appended.length === fingerprintNames.length
1349
+ ? buildPlaceholderNote(fingerprintNames)
1350
+ : buildPlaceholderNote(appended),
1351
+ aliasToOriginal,
1352
+ originalToAlias,
1353
+ };
1354
+ }
1355
+
1356
+ function prepareResponsesTools(clientTools: unknown[] = [], modelId: string | null = null): unknown[] {
1357
+ return prepareToolsWithFingerprint(clientTools, true, null, modelId).tools;
1358
+ }
1359
+
1360
+ function prepareChatTools(clientTools: unknown[] = [], modelId: string | null = null): unknown[] {
1361
+ return prepareToolsWithFingerprint(clientTools, false, null, modelId).tools;
1362
+ }
1363
+
1364
+ function restoreClientToolName(name: unknown, aliasToOriginal: Map<string, string> | null): unknown {
1365
+ if (!name || !aliasToOriginal || aliasToOriginal.size === 0) return name;
1366
+ return aliasToOriginal.get(name) || name;
1367
+ }
1368
+
1369
+ function extractContent(content: unknown): string {
1370
+ if (typeof content === "string") return content;
1371
+ if (Array.isArray(content)) {
1372
+ return content
1373
+ .map((p) => {
1374
+ if (typeof p === "string") return p;
1375
+ if (p?.type === "text" && typeof p.text === "string") return p.text;
1376
+ if (p?.text) return String(p.text);
1377
+ return "";
1378
+ })
1379
+ .filter(Boolean)
1380
+ .join("\n");
1381
+ }
1382
+ return content ? JSON.stringify(content) : "";
1383
+ }
1384
+
1385
+ // First-N-chars text without ever serializing the whole value: strings are
1386
+ // sliced directly, arrays join only text parts up to the limit, objects fall
1387
+ // back to a bounded stringify. Used for the headerless session signature so
1388
+ // a multi-MB system prompt is never JSON.stringified just for a hash.
1389
+ function shortText(content: unknown, limit: number = 1000): string {
1390
+ if (typeof content === "string") return content.slice(0, limit);
1391
+ if (Array.isArray(content)) {
1392
+ let out = "";
1393
+ for (const p of content) {
1394
+ if (out.length >= limit) break;
1395
+ if (typeof p === "string") out += p;
1396
+ else if (p?.type === "text" && typeof p.text === "string") out += p.text;
1397
+ else if (p?.text) out += String(p.text);
1398
+ }
1399
+ return out.slice(0, limit);
1400
+ }
1401
+ if (!content) return "";
1402
+ try {
1403
+ return JSON.stringify(content).slice(0, limit);
1404
+ } catch {
1405
+ return String(content).slice(0, limit);
1406
+ }
1407
+ }
1408
+
1409
+ function messageSignatureSample(content: unknown, limit: number = 1000): string {
1410
+ if (typeof content === "string") {
1411
+ const len = content.length;
1412
+ if (len <= limit) return `${len}:${content}`;
1413
+ const half = Math.floor(limit / 2);
1414
+ return `${len}:${content.slice(0, half)}..${content.slice(len - half)}`;
1415
+ }
1416
+ if (Array.isArray(content)) {
1417
+ const head = shortText(content, Math.floor(limit / 2));
1418
+ const last = content[content.length - 1];
1419
+ const tail = shortText(last ? [last] : [], Math.floor(limit / 2));
1420
+ return `${content.length}:${head}..${tail}`;
1421
+ }
1422
+ return shortText(content, limit);
1423
+ }
1424
+
1425
+ function transformResponsesContent(content: unknown, role: string = "user"): unknown {
1426
+ if (typeof content === "string") return content;
1427
+ if (Array.isArray(content)) {
1428
+ const hasNonText = content.some(
1429
+ (p) =>
1430
+ p &&
1431
+ typeof p === "object" &&
1432
+ (p.type === "image_url" || p.type === "input_image" || p.type === "input_file")
1433
+ );
1434
+ if (!hasNonText) return extractContent(content);
1435
+ const textType = role === "assistant" ? "output_text" : "input_text";
1436
+ const parts = [];
1437
+ for (const p of content) {
1438
+ if (typeof p === "string") {
1439
+ parts.push({ type: textType, text: p });
1440
+ } else if (p && typeof p === "object") {
1441
+ if (p.type === "text" || p.type === "input_text" || p.type === "output_text") {
1442
+ parts.push({ type: textType, text: String(p.text ?? "") });
1443
+ } else if (p.type === "image_url") {
1444
+ const imageUrl = typeof p.image_url === "string" ? p.image_url : p.image_url?.url;
1445
+ if (imageUrl) parts.push({ type: "input_image", image_url: imageUrl });
1446
+ } else if (p.type === "input_image" || p.type === "input_file") {
1447
+ parts.push(p);
1448
+ } else if (p.text) {
1449
+ parts.push({ type: textType, text: String(p.text) });
1450
+ }
1451
+ }
1452
+ }
1453
+ return parts;
1454
+ }
1455
+ return extractContent(content);
1456
+ }
1457
+
1458
+ // Convert OpenAI messages to OpenCode input format (for Responses API)
1459
+ function transformToResponsesInput(messages: unknown[] = [], originalToAlias: Map<string, string> | null = null): unknown[] {
1460
+ const input = [];
1461
+ for (const m of Array.isArray(messages) ? messages : []) {
1462
+ if (!m) continue;
1463
+ if (m.role === "system" || m.role === "developer") {
1464
+ continue;
1465
+ }
1466
+ if (m.role === "tool") {
1467
+ input.push({
1468
+ type: "function_call_output",
1469
+ call_id: m.tool_call_id || "call_unknown",
1470
+ output: typeof m.content === "string" ? m.content : JSON.stringify(m.content ?? ""),
1471
+ });
1472
+ continue;
1473
+ }
1474
+ if (m.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
1475
+ if (m.content) {
1476
+ input.push({
1477
+ role: "assistant",
1478
+ content: transformResponsesContent(m.content, "assistant"),
1479
+ });
1480
+ }
1481
+ for (const tc of m.tool_calls) {
1482
+ const fn = tc.function || {};
1483
+ const rawName = fn.name || "unknown";
1484
+ const mappedName =
1485
+ originalToAlias && originalToAlias.has(rawName) ? originalToAlias.get(rawName) : rawName;
1486
+ input.push({
1487
+ type: "function_call",
1488
+ call_id: tc.id || `call_${crypto.randomBytes(8).toString("hex")}`,
1489
+ name: mappedName,
1490
+ arguments: typeof fn.arguments === "string" ? fn.arguments : JSON.stringify(fn.arguments || {}),
1491
+ });
1492
+ }
1493
+ continue;
1494
+ }
1495
+ const role = m.role || "user";
1496
+ input.push({ role, content: transformResponsesContent(m.content, role) });
1497
+ }
1498
+ return input;
1499
+ }
1500
+
1501
+ /**
1502
+ * The harness environment block the real CLI appends to every system prompt.
1503
+ *
1504
+ * Measured against the live gateway on 2026-10-25: a request whose system
1505
+ * prompt does not contain this block is answered with `429 FreeUsageLimitError`,
1506
+ * byte-for-byte the message the gateway uses for an exhausted allowance. The
1507
+ * trigger is the `<env>` block with a `Working directory:` line, not the prompt
1508
+ * length and not the model: a 12 KB generic prompt is refused, a 65-byte
1509
+ * `<env>Working directory: /tmp</env>` is accepted, and the same split holds
1510
+ * for big-pickle and mimo. That made a *shape* problem look like a quota
1511
+ * problem — the CLI answered while the bridge did not, in the same minute.
1512
+ *
1513
+ * The CLI builds this from its own session context, so the values here are the
1514
+ * bridge's honest equivalents: its working directory and whether that is a git
1515
+ * repository. Reproducing the block is what makes the bridge's request
1516
+ * indistinguishable from the CLI's on this gate.
1517
+ *
1518
+ * Cached per working directory: the values cannot change while the process runs
1519
+ * (the bridge never chdir's), and probing them costs a `git` subprocess —
1520
+ * measured at 2.5 ms, which is real money on every request.
1521
+ */
1522
+ let harnessEnvBlockCache: { cwd: string | null; block: string } = { cwd: null, block: "" };
1523
+ function buildHarnessEnvBlock(): string {
1524
+ const cwd = process.cwd();
1525
+ if (harnessEnvBlockCache.cwd === cwd && harnessEnvBlockCache.block) {
1526
+ return harnessEnvBlockCache.block;
1527
+ }
1528
+ let isRepo = "no";
1529
+ try {
1530
+ const { execFileSync } = require("child_process");
1531
+ execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
1532
+ cwd,
1533
+ encoding: "utf8",
1534
+ stdio: ["ignore", "pipe", "ignore"],
1535
+ timeout: 2000,
1536
+ });
1537
+ isRepo = "yes";
1538
+ } catch {}
1539
+ const block = [
1540
+ "Here is some useful information about the environment you are running in:",
1541
+ "<env>",
1542
+ ` Working directory: ${cwd}`,
1543
+ ` Workspace root folder: ${cwd}`,
1544
+ ` Is directory a git repo: ${isRepo}`,
1545
+ " Platform: " + process.platform,
1546
+ "</env>",
1547
+ ].join("\n");
1548
+ harnessEnvBlockCache = { cwd, block };
1549
+ return block;
1550
+ }
1551
+ /**
1552
+ * Append the harness env block to a system prompt unless the client already
1553
+ * sent one. A client that forwards the CLI's own prompt (or any prompt with an
1554
+ * `<env>` block) keeps it verbatim — only the missing anchor is added.
1555
+ */
1556
+ function withHarnessEnvBlock(systemText: unknown): string {
1557
+ const text = typeof systemText === "string" ? systemText : "";
1558
+ if (/<env>[\s\S]*?Working directory:/.test(text)) return text;
1559
+ const block = buildHarnessEnvBlock();
1560
+ return text.trim() ? `${text.replace(/\s+$/, "")}\n\n${block}` : block;
1561
+ }
1562
+ function extractSystemInstructions(messages: unknown[] = [], explicitInstructions: unknown = "", placeholderNote: string = ""): string {
1563
+ const parts = [];
1564
+ if (typeof explicitInstructions === "string" && explicitInstructions.trim()) {
1565
+ parts.push(explicitInstructions.trim());
1566
+ }
1567
+ for (const m of Array.isArray(messages) ? messages : []) {
1568
+ if (!m || (m.role !== "system" && m.role !== "developer")) continue;
1569
+ const text = extractContent(m.content).trim();
1570
+ if (text) parts.push(text);
1571
+ }
1572
+ if (placeholderNote) {
1573
+ parts.push(placeholderNote);
1574
+ }
1575
+ return withHarnessEnvBlock(parts.join("\n\n"));
1576
+ }
1577
+
1578
+ function transformChatMessages(messages: unknown[] = [], originalToAlias: Map<string, string> | null = null, placeholderNote: string = ""): unknown[] {
1579
+ const out = [];
1580
+ for (const m of Array.isArray(messages) ? messages : []) {
1581
+ if (!m) continue;
1582
+ if (
1583
+ originalToAlias &&
1584
+ originalToAlias.size > 0 &&
1585
+ m.role === "assistant" &&
1586
+ Array.isArray(m.tool_calls)
1587
+ ) {
1588
+ out.push({
1589
+ ...m,
1590
+ tool_calls: m.tool_calls.map((tc) => {
1591
+ const fnName = tc?.function?.name;
1592
+ if (fnName && originalToAlias.has(fnName)) {
1593
+ return { ...tc, function: { ...tc.function, name: originalToAlias.get(fnName) } };
1594
+ }
1595
+ return tc;
1596
+ }),
1597
+ });
1598
+ } else {
1599
+ out.push(m);
1600
+ }
1601
+ }
1602
+
1603
+ if (placeholderNote) {
1604
+ const first = out[0];
1605
+ if (first?.role === "system" || first?.role === "developer") {
1606
+ if (typeof first.content === "string") {
1607
+ out[0] = { ...first, content: `${first.content}\n\n${placeholderNote}` };
1608
+ } else if (Array.isArray(first.content)) {
1609
+ out[0] = { ...first, content: [...first.content, { type: "text", text: `\n\n${placeholderNote}` }] };
1610
+ } else {
1611
+ out.unshift({ role: "system", content: placeholderNote });
1612
+ }
1613
+ } else {
1614
+ out.unshift({ role: "system", content: placeholderNote });
1615
+ }
1616
+ }
1617
+
1618
+ // The gateway refuses a request whose system prompt lacks the harness `<env>`
1619
+ // block with the same `429 FreeUsageLimitError` it uses for an exhausted
1620
+ // allowance. See buildHarnessEnvBlock. A client that already forwarded the
1621
+ // CLI's prompt keeps its own block; only the missing anchor is added.
1622
+ const sysIndex = out.findIndex((m) => m?.role === "system" || m?.role === "developer");
1623
+ if (sysIndex === -1) {
1624
+ out.unshift({ role: "system", content: buildHarnessEnvBlock() });
1625
+ } else {
1626
+ const sys = out[sysIndex];
1627
+ if (typeof sys.content === "string") {
1628
+ out[sysIndex] = { ...sys, content: withHarnessEnvBlock(sys.content) };
1629
+ } else if (Array.isArray(sys.content)) {
1630
+ const text = extractContent(sys.content);
1631
+ if (!/<env>[\s\S]*?Working directory:/.test(text)) {
1632
+ out[sysIndex] = {
1633
+ ...sys,
1634
+ content: [...sys.content, { type: "text", text: `\n\n${buildHarnessEnvBlock()}` }],
1635
+ };
1636
+ }
1637
+ } else {
1638
+ out[sysIndex] = { ...sys, content: buildHarnessEnvBlock() };
1639
+ }
1640
+ }
1641
+ return out;
1642
+ }
1643
+
1644
+ function buildUpstreamPayload(body: Record<string, unknown>, targetModel: string, useResponses: boolean, scope: string | null = null): UpstreamPayload {
1645
+ const requestedTokens =
1646
+ body.max_output_tokens ?? body.max_completion_tokens ?? body.max_tokens;
1647
+ const maxTokens = effectiveMaxTokens(requestedTokens, targetModel, body);
1648
+ const { tools, placeholderNote, aliasToOriginal, originalToAlias } = prepareToolsWithFingerprint(
1649
+ body.tools,
1650
+ useResponses,
1651
+ scope,
1652
+ targetModel
1653
+ );
1654
+ if (useResponses) {
1655
+ const upstreamBody = {
1656
+ model: targetModel,
1657
+ input: transformToResponsesInput(body.messages, originalToAlias),
1658
+ stream: true,
1659
+ max_output_tokens: maxTokens,
1660
+ tools,
1661
+ tool_choice: "auto",
1662
+ };
1663
+ const instructions = extractSystemInstructions(
1664
+ body.messages,
1665
+ body.instructions,
1666
+ placeholderNote
1667
+ );
1668
+ if (instructions) {
1669
+ upstreamBody.instructions = instructions;
1670
+ }
1671
+ if (typeof body.temperature === "number") upstreamBody.temperature = body.temperature;
1672
+ if (typeof body.top_p === "number") upstreamBody.top_p = body.top_p;
1673
+ return { upstreamBody, aliasToOriginal };
1674
+ }
1675
+
1676
+ // Field names and order match the CLI's own request: `max_completion_tokens`
1677
+ // (not the legacy `max_tokens`), `store: false`, and `tools` before `stream`.
1678
+ // Upstream accepts both spellings today, but sending the CLI's exact shape
1679
+ // removes a difference that costs nothing to erase.
1680
+ const upstreamBody = {
1681
+ model: targetModel,
1682
+ messages: transformChatMessages(body.messages, originalToAlias, placeholderNote),
1683
+ tools,
1684
+ stream: true,
1685
+ stream_options: { include_usage: true },
1686
+ max_completion_tokens: maxTokens,
1687
+ store: false,
1688
+ };
1689
+ if (typeof body.temperature === "number") upstreamBody.temperature = body.temperature;
1690
+ if (typeof body.top_p === "number") upstreamBody.top_p = body.top_p;
1691
+ if (body.stop !== undefined) upstreamBody.stop = body.stop;
1692
+ if (body.response_format !== undefined) upstreamBody.response_format = body.response_format;
1693
+ if (body.reasoning_effort !== undefined) upstreamBody.reasoning_effort = body.reasoning_effort;
1694
+
1695
+ // Upstream v2 rejects tool_choice: "none" with 403 FreeTierError.
1696
+ if (body.tool_choice && body.tool_choice !== "none") {
1697
+ if (
1698
+ typeof body.tool_choice === "object" &&
1699
+ body.tool_choice.function?.name &&
1700
+ originalToAlias.has(body.tool_choice.function.name)
1701
+ ) {
1702
+ upstreamBody.tool_choice = {
1703
+ ...body.tool_choice,
1704
+ function: {
1705
+ ...body.tool_choice.function,
1706
+ name: originalToAlias.get(body.tool_choice.function.name),
1707
+ },
1708
+ };
1709
+ } else {
1710
+ upstreamBody.tool_choice = body.tool_choice;
1711
+ }
1712
+ }
1713
+
1714
+ return { upstreamBody, aliasToOriginal };
1715
+ }
1716
+
1717
+ /**
1718
+ * Mint a fresh session id after the identity changed.
1719
+ *
1720
+ * The id is derived from the recipe, so an id minted *before* a refresh encodes
1721
+ * the shape the gate just rejected. The self-heal path therefore has to replace
1722
+ * it — replaying the stale id would send the same rejected request and fail
1723
+ * identically. The cache entry is dropped for the same reason: otherwise the
1724
+ * next request from this client would get the stale id back.
1725
+ */
1726
+ function regenerateSessionId(req: IncomingRequestLike, body: Record<string, unknown>, staleId: string): string {
1727
+ for (const [key, entry] of sessionCache) {
1728
+ if (entry.sessionId === staleId) sessionCache.delete(key);
1729
+ }
1730
+ return getPersistentSessionId(req, body);
1731
+ }
1732
+
1733
+ /**
1734
+ * The project id the CLI would send from this checkout.
1735
+ *
1736
+ * Measured against a real CLI capture: the header equals
1737
+ * `sha1("git-remote:github.com/<owner>/<repo>")` — the remote URL with scheme
1738
+ * and `.git` stripped. With no remote the CLI hashes the directory path
1739
+ * (`sha1("directory:<abs path>")`), and an `opencode` file in the directory
1740
+ * overrides both. Derived once and cached: a checkout does not move.
1741
+ */
1742
+ let cachedProjectId: string | null = null;
1743
+ function getProjectId(): string {
1744
+ if (cachedProjectId) return cachedProjectId;
1745
+ try {
1746
+ const fs = require("fs");
1747
+ const path = require("path");
1748
+ const crypto = require("crypto");
1749
+ const cwd = process.cwd();
1750
+
1751
+ // An `opencode` file wins, exactly as it does in the CLI.
1752
+ const marker = path.join(cwd, "opencode");
1753
+ if (fs.existsSync(marker)) {
1754
+ const value = fs.readFileSync(marker, "utf8").trim();
1755
+ if (value) return (cachedProjectId = value);
1756
+ }
1757
+
1758
+ // Git remote, normalised the way the CLI's `url()` helper does it.
1759
+ let remote = "";
1760
+ try {
1761
+ const { execFileSync } = require("child_process");
1762
+ remote = execFileSync("git", ["remote", "get-url", "origin"], {
1763
+ cwd,
1764
+ encoding: "utf8",
1765
+ stdio: ["ignore", "pipe", "ignore"],
1766
+ timeout: 2000,
1767
+ }).trim();
1768
+ } catch {}
1769
+ if (remote) {
1770
+ const normalized = remote
1771
+ .replace(/^[a-z]+:\/\//i, "") // drop scheme
1772
+ .replace(/^git@([^:]+):/i, "$1/") // scp-style
1773
+ .replace(/\.git$/i, "")
1774
+ .replace(/\/+$/, "");
1775
+ if (normalized) {
1776
+ return (cachedProjectId = crypto
1777
+ .createHash("sha1")
1778
+ .update(`git-remote:${normalized}`)
1779
+ .digest("hex"));
1780
+ }
1781
+ }
1782
+
1783
+ return (cachedProjectId = crypto
1784
+ .createHash("sha1")
1785
+ .update(`directory:${cwd}`)
1786
+ .digest("hex"));
1787
+ } catch {
1788
+ return (cachedProjectId = "global");
1789
+ }
1790
+ }
1791
+
1792
+ function buildUpstreamHeaders(req: IncomingRequestLike, sessionId: string): Record<string, string> {
1793
+ const downstreamUa = req?.headers?.["user-agent"] || "";
1794
+ const ua = isValidV2UserAgent(downstreamUa) ? downstreamUa : gateSafeUserAgent();
1795
+ const client = req?.headers?.["x-opencode-client"];
1796
+ // `x-opencode-project` is not a constant: the CLI derives it as
1797
+ // `sha1("git-remote:" + host + path)` for a repo, `sha1("directory:" + path)`
1798
+ // otherwise, or the contents of an `opencode` file in the directory. Sending
1799
+ // the literal "global" is a shape the CLI never emits, so it is derived here
1800
+ // the same way — from this bridge's own checkout. A client that supplies the
1801
+ // header still wins.
1802
+ const project = req?.headers?.["x-opencode-project"] || getProjectId();
1803
+ // The gate header set is derived by identity.ts from upstream's own request
1804
+ // builder, so a header added upstream starts being sent on the next request
1805
+ // after a refresh. Values this bridge cannot derive are reported, not sent
1806
+ // empty: an empty required header is worse than an absent one.
1807
+ const { headers: gateHeaders } = identity.buildGateHeaders({
1808
+ userAgent: ua,
1809
+ client: client === "desktop" || client === "cli" ? client : "cli",
1810
+ project: String(project),
1811
+ sessionId,
1812
+ });
1813
+ return {
1814
+ "Authorization": "Bearer public",
1815
+ "Content-Type": "application/json",
1816
+ // The CLI sends `*/*` here (it always streams via the body, not the Accept
1817
+ // header). Matching it costs nothing and removes a difference the gate
1818
+ // could one day start looking at.
1819
+ "Accept": "*/*",
1820
+ // W3C trace context, which the CLI emits on every request. The values are
1821
+ // random per request — measured: they carry no relation to the session id —
1822
+ // so this generates them the same way rather than deriving them. Both
1823
+ // headers describe one 128-bit trace with a 64-bit span; `b3` adds the
1824
+ // parent span id.
1825
+ ...buildTraceHeaders(),
1826
+ ...gateHeaders,
1827
+ };
1828
+ }
1829
+
1830
+ /** A fresh W3C trace context, shaped like the CLI's. */
1831
+ function buildTraceHeaders(): Record<string, string> {
1832
+ const traceId = crypto.randomBytes(16).toString("hex");
1833
+ const spanId = crypto.randomBytes(8).toString("hex");
1834
+ const parentSpanId = crypto.randomBytes(8).toString("hex");
1835
+ return {
1836
+ b3: `${traceId}-${spanId}-1-${parentSpanId}`,
1837
+ traceparent: `00-${traceId}-${spanId}-01`,
1838
+ };
1839
+ }
1840
+
1841
+ /**
1842
+ * Upstream can answer HTTP 200 and then report a failure *inside* the stream
1843
+ * (`data: {"error":{...}}`, e.g. "Streaming response failed: [503] ...").
1844
+ * Left unhandled, a non-streaming client is handed a 200 with `content: null`
1845
+ * and `finish_reason: "stop"` — a fake success. Returns the error text when the
1846
+ * event is an error, otherwise null.
1847
+ */
1848
+ function extractStreamError(ev: unknown): string | null {
1849
+ const err = ev?.error;
1850
+ if (!err) return null;
1851
+ if (typeof err === "string") return err;
1852
+ return err.message || err.type || JSON.stringify(err);
1853
+ }
1854
+
1855
+ function extractResponsesFinishReason(ev: unknown, hasToolCalls: boolean): string {
1856
+ const status = ev?.response?.status;
1857
+ const reason = ev?.response?.incomplete_details?.reason;
1858
+ if (ev?.type === "response.incomplete" || status === "incomplete") {
1859
+ if (reason === "content_filter") return "content_filter";
1860
+ return "length";
1861
+ }
1862
+ if (hasToolCalls) return "tool_calls";
1863
+ return "stop";
1864
+ }
1865
+
1866
+ // Persistent session cache — preserves upstream prompt/KV cache across turns (LRU)
1867
+ const sessionCache = new Map<string, SessionCacheEntry>();
1868
+ const MAX_SESSIONS = 500;
1869
+ const SESSION_TTL_MS = 3 * 3600 * 1000;
1870
+ let lastFailedGateRetryTime = 0;
1871
+ let lastFailedGateRetryEpoch = -1;
1872
+ // Last IP-level abuse block seen from upstream, if any. Kept apart from the
1873
+ // retry cooldown because the two have different causes and different advice:
1874
+ // the cooldown is a per-IP allowance window, the block is the gateway refusing
1875
+ // this network outright.
1876
+ let lastIpAbuseAt = 0;
1877
+ // The last gate rejection's correlation id and the shape audit that was true
1878
+ // when it happened. `x-opencode-log-id` is the only handle upstream gives for
1879
+ // a rejected request, so it is recorded rather than discarded — it is what a
1880
+ // support request or a bug report needs to be actionable.
1881
+ let lastGateDiagnostic: GateDiagnostic | null = null;
1882
+ let lastUpstreamError: UpstreamErrorRecord | null = null;
1883
+
1884
+ /**
1885
+ * Which gate anchors the *actual* outgoing request carried.
1886
+ *
1887
+ * The gate requires a tool named `read` and an `opencode/*` User-Agent with a
1888
+ * session header (see GATE_ANCHOR_TOOL_NAMES / GATE_ANCHOR_HEADER_NAMES in
1889
+ * identity.ts). When a 403 comes back, these are what distinguishes "this
1890
+ * bridge sent an unacceptable shape" from "upstream refuses this egress".
1891
+ * Reporting the distinction is the whole point: both produce an identical
1892
+ * FreeTierError body.
1893
+ */
1894
+ function auditGateShape(upstreamBody: unknown, headers: Record<string, unknown>): GateShape {
1895
+ const tools = Array.isArray(upstreamBody?.tools) ? upstreamBody.tools : [];
1896
+ const toolNames = tools.map((t) => t?.function?.name || t?.name).filter(Boolean);
1897
+ // Header names are compared case-insensitively: the audit must not report a
1898
+ // missing anchor just because the same header arrived with different casing.
1899
+ const headerKey = (name) =>
1900
+ Object.keys(headers || {}).find((k) => k.toLowerCase() === name);
1901
+ const hasHeader = (name) => headerKey(name) !== undefined;
1902
+ const ua = String(headers?.[headerKey("user-agent")] || "");
1903
+ const sessionHeaders = ["x-opencode-session", "x-session-affinity", "x-session-id"].filter(
1904
+ hasHeader
1905
+ );
1906
+ return {
1907
+ hasReadTool: toolNames.includes("read"),
1908
+ toolCount: toolNames.length,
1909
+ userAgentOk: /^opencode\/[A-Za-z0-9-]+\/\d+\.\d+\.\d+\/[A-Za-z0-9-]+$/i.test(ua),
1910
+ userAgent: ua,
1911
+ sessionHeaders,
1912
+ };
1913
+ }
1914
+
1915
+ function upstreamLogIdOf(upstreamRes: FetchResponse | null): string | null {
1916
+ return typeof upstreamRes?.headers?.get === "function"
1917
+ ? upstreamRes.headers.get("x-opencode-log-id")
1918
+ : null;
1919
+ }
1920
+
1921
+ /**
1922
+ * Answer an upstream IP-level abuse block.
1923
+ *
1924
+ * Terminal by construction: the block is keyed to the egress network, so the
1925
+ * identity layer is not consulted, no session id is re-minted, and the request
1926
+ * is not replayed — measured (and confirmed by upstream's own issue tracker)
1927
+ * as a network flag that no client shape can clear. The refusal reaches the
1928
+ * client verbatim; `X-OpenCode-Gate: ip-abuse` lets callers and `verify.ts`
1929
+ * tell it apart from the shape gate without parsing the message.
1930
+ */
1931
+ function respondIpAbuse(res: ServerResponseLike, status: number, errType: unknown, errMsg: string, logId: string | null, model: string): void {
1932
+ lastIpAbuseAt = Date.now();
1933
+ lastGateDiagnostic = {
1934
+ at: lastIpAbuseAt,
1935
+ kind: "ip-abuse",
1936
+ status,
1937
+ logId: logId || null,
1938
+ message: errMsg,
1939
+ model,
1940
+ };
1941
+ console.warn(
1942
+ `[opencode-free-bridge] Upstream IP-abuse block (${status}): ${errMsg} — not refreshing or retrying; the gateway keys this to this network's IP, so no identity change can clear it` +
1943
+ (logId ? ` [x-opencode-log-id: ${logId}]` : "")
1944
+ );
1945
+ res.writeHead(status, {
1946
+ "Content-Type": "application/json",
1947
+ "X-OpenCode-Gate": "ip-abuse",
1948
+ ...(logId ? { "X-OpenCode-Log-Id": logId } : {}),
1949
+ });
1950
+ return res.end(
1951
+ JSON.stringify({
1952
+ error: {
1953
+ message: errMsg,
1954
+ type: errType || "FreeTierError",
1955
+ code: status,
1956
+ },
1957
+ })
1958
+ );
1959
+ }
1960
+
1961
+ const origSessionCacheClear = sessionCache.clear.bind(sessionCache);
1962
+ sessionCache.clear = () => {
1963
+ lastFailedGateRetryTime = 0;
1964
+ lastFailedGateRetryEpoch = -1;
1965
+ lastIpAbuseAt = 0;
1966
+ lastUpstreamError = null;
1967
+ return origSessionCacheClear();
1968
+ };
1969
+
1970
+ function getPersistentSessionId(req: IncomingRequestLike, body: Record<string, unknown>): string {
1971
+ const headers = req?.headers || {};
1972
+ const rawHeaderKey =
1973
+ headers["x-opencode-session"] ||
1974
+ headers["x-opencode-session-id"] ||
1975
+ headers["x-session-id"] ||
1976
+ headers["session-id"] ||
1977
+ headers["x-conversation-id"] ||
1978
+ headers["x-9r-session-id"];
1979
+ const headerKey = Array.isArray(rawHeaderKey)
1980
+ ? String(rawHeaderKey[0] || "").slice(0, 256)
1981
+ : rawHeaderKey
1982
+ ? String(rawHeaderKey).slice(0, 256)
1983
+ : "";
1984
+ // Fast path (common case): a session header is present, so no message
1985
+ // hashing is needed at all. The conv-signature hash below only runs for
1986
+ // headerless clients, and slices BEFORE stringify so a huge system prompt
1987
+ // never gets serialized just to take its first 1000 chars.
1988
+ let lookupKey = headerKey ? "hdr:" + headerKey : null;
1989
+ if (!lookupKey) {
1990
+ const msgs = body && Array.isArray(body.messages) ? body.messages : [];
1991
+ if (msgs.length > 0) {
1992
+ const sig =
1993
+ messageSignatureSample(msgs[0]?.content, 1000) +
1994
+ "::" +
1995
+ messageSignatureSample(msgs[1]?.content, 1000);
1996
+ if (sig !== "::") {
1997
+ lookupKey =
1998
+ "conv:" + crypto.createHash("sha256").update(sig).digest("hex").slice(0, 20);
1999
+ }
2000
+ }
2001
+ }
2002
+ const now = Date.now();
2003
+ if (lookupKey && sessionCache.has(lookupKey)) {
2004
+ const entry = sessionCache.get(lookupKey);
2005
+ if (now - entry.lastSeen < SESSION_TTL_MS) {
2006
+ // Re-insert to update Map insertion order for O(1) LRU eviction
2007
+ sessionCache.delete(lookupKey);
2008
+ entry.lastSeen = now;
2009
+ sessionCache.set(lookupKey, entry);
2010
+ return entry.sessionId;
2011
+ }
2012
+ sessionCache.delete(lookupKey);
2013
+ }
2014
+ const newSessionId = identity.createSessionId(true);
2015
+ if (lookupKey) {
2016
+ if (sessionCache.size >= MAX_SESSIONS) {
2017
+ for (const [k, v] of sessionCache) {
2018
+ if (now - v.lastSeen >= SESSION_TTL_MS) sessionCache.delete(k);
2019
+ }
2020
+ if (sessionCache.size >= MAX_SESSIONS) {
2021
+ const lruKey = sessionCache.keys().next().value;
2022
+ if (lruKey !== undefined) sessionCache.delete(lruKey);
2023
+ }
2024
+ }
2025
+ sessionCache.set(lookupKey, { sessionId: newSessionId, lastSeen: now });
2026
+ }
2027
+ return newSessionId;
2028
+ }
2029
+
2030
+ /**
2031
+ * `/api/proxy` — read and change the egress proxy; `/api/proxy/test` — prove a
2032
+ * candidate reaches upstream before it is trusted.
2033
+ *
2034
+ * The panel is the only caller, so the contract stays small: JSON in, JSON out,
2035
+ * one error field. Credentials are accepted on write and never echoed on read.
2036
+ */
2037
+ async function handleProxyApi(req: IncomingRequestLike, res: ServerResponseLike, pathname: string): Promise<unknown> {
2038
+ const send = (status: number, body: unknown) => {
2039
+ res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
2040
+ res.end(JSON.stringify(body));
2041
+ };
2042
+
2043
+ if (pathname === "/api/proxy" && (req.method === "GET" || req.method === "HEAD")) {
2044
+ return send(200, proxy.describe());
2045
+ }
2046
+ if (req.method !== "POST") {
2047
+ res.setHeader("Allow", "GET, POST");
2048
+ return send(405, { error: "Gunakan GET untuk status atau POST untuk mengubah." });
2049
+ }
2050
+
2051
+ let payload = {};
2052
+ try {
2053
+ const text = await readRequestBody(req, 128 * 1024);
2054
+ payload = text ? JSON.parse(text) : {};
2055
+ } catch (err) {
2056
+ return send(err.statusCode === 413 ? 413 : 400, { error: `Body tidak valid: ${err.message}` });
2057
+ }
2058
+ if (!payload || typeof payload !== "object") {
2059
+ return send(400, { error: "Body harus berupa objek JSON." });
2060
+ }
2061
+
2062
+ // Pool management. `entries` replaces the whole pool; `pool: []` clears it.
2063
+ // Kept apart from the single-proxy `url` field so one request cannot mean two
2064
+ // different things, and so an operator can keep a single proxy configured as a
2065
+ // fallback while experimenting with a pool.
2066
+ const hasPool = Object.prototype.hasOwnProperty.call(payload, "entries") ||
2067
+ Object.prototype.hasOwnProperty.call(payload, "pool");
2068
+ if (hasPool && pathname === "/api/proxy") {
2069
+ const spec = Object.prototype.hasOwnProperty.call(payload, "entries")
2070
+ ? { entries: payload.entries, strategy: payload.strategy, cooldownMs: payload.cooldownMs, maxCooldownMs: payload.maxCooldownMs }
2071
+ : payload.pool;
2072
+ const result = proxy.setPool(spec);
2073
+ if (!result.ok) return send(400, { error: result.error });
2074
+ console.log(
2075
+ `[opencode-free-bridge] Egress pool: ${result.pool.enabled}/${result.pool.size} aktif, strategi ${result.pool.strategy}`
2076
+ );
2077
+ return send(200, result);
2078
+ }
2079
+
2080
+ if (pathname === "/api/proxy/test" && Array.isArray(payload.entries)) {
2081
+ const { entries } = payload;
2082
+ if (entries.length === 0) return send(400, { error: "Daftar entries kosong." });
2083
+ // Probe without installing: the caller is evaluating candidates.
2084
+ const results = [];
2085
+ for (const [index, entry] of entries.entries()) {
2086
+ const parsed = proxy.parsePoolEntry(entry, index);
2087
+ if (!parsed.ok) {
2088
+ results.push({ id: `#${index + 1}`, host: null, ok: false, error: parsed.error });
2089
+ continue;
2090
+ }
2091
+ const verdict = await proxy.testProxy(parsed.entry.url, { probeUrl: resolveEndpoints().modelsUrl });
2092
+ results.push({
2093
+ id: parsed.entry.id,
2094
+ label: parsed.entry.label,
2095
+ host: proxy.displayHost(parsed.entry.url),
2096
+ ok: verdict.ok,
2097
+ apiStatus: verdict.apiStatus || null,
2098
+ exitIp: verdict.exitIp || null,
2099
+ latencyMs: verdict.latencyMs || null,
2100
+ error: verdict.error || null,
2101
+ });
2102
+ }
2103
+ const anyOk = results.some((r) => r.ok);
2104
+ return send(anyOk ? 200 : 502, { ok: anyOk, entries: results });
2105
+ }
2106
+
2107
+ if (pathname === "/api/proxy/test" && typeof payload.url === "string") {
2108
+ const result = await proxy.testProxy(payload.url, { probeUrl: resolveEndpoints().modelsUrl });
2109
+ return send(result.ok ? 200 : 502, result);
2110
+ }
2111
+
2112
+ if (typeof payload.url === "string") {
2113
+ const result = proxy.setProxyUrl(payload.url);
2114
+ if (!result.ok) return send(400, { error: result.error });
2115
+ console.log(
2116
+ `[opencode-free-bridge] Egress ${result.mode === "proxy" ? `via proxy ${result.proxy}` : "direct"}`
2117
+ );
2118
+ return send(200, result);
2119
+ }
2120
+
2121
+ return send(400, { error: "Body harus berisi 'url' (satu proxy) atau 'entries' (pool)." });
2122
+ }
2123
+
2124
+ function readRequestBody(req: IncomingRequestLike, maxBytes: number = MAX_BODY_BYTES): Promise<string> {
2125
+ // Early reject: if the client declares a huge body, refuse without reading
2126
+ // a single byte instead of buffering up to the limit first.
2127
+ const declared = parseInt(req?.headers?.["content-length"] || "", 10);
2128
+ if (Number.isFinite(declared) && declared > maxBytes) {
2129
+ const err = new Error(`Request body exceeds limit of ${maxBytes} bytes`);
2130
+ err.statusCode = 413;
2131
+ err.code = "payload_too_large";
2132
+ return Promise.reject(err);
2133
+ }
2134
+ return new Promise((resolve, reject) => {
2135
+ const chunks = [];
2136
+ let totalBytes = 0;
2137
+ let done = false;
2138
+ const cleanup = () => {
2139
+ if (typeof req.off === "function") {
2140
+ req.off("error", onError);
2141
+ req.off("data", onData);
2142
+ req.off("end", onEnd);
2143
+ } else if (typeof req.removeListener === "function") {
2144
+ req.removeListener("error", onError);
2145
+ req.removeListener("data", onData);
2146
+ req.removeListener("end", onEnd);
2147
+ }
2148
+ };
2149
+
2150
+ const onError = (err) => {
2151
+ if (done) return;
2152
+ done = true;
2153
+ cleanup();
2154
+ reject(err);
2155
+ };
2156
+
2157
+ const onData = (chunk) => {
2158
+ if (done) return;
2159
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
2160
+ totalBytes += buf.length;
2161
+ if (totalBytes > maxBytes) {
2162
+ done = true;
2163
+ chunks.length = 0;
2164
+ cleanup();
2165
+ if (typeof req.pause === "function") req.pause();
2166
+ const err = new Error(`Request body exceeds limit of ${maxBytes} bytes`);
2167
+ err.statusCode = 413;
2168
+ err.code = "payload_too_large";
2169
+ reject(err);
2170
+ return;
2171
+ }
2172
+ chunks.push(buf);
2173
+ };
2174
+
2175
+ const onEnd = () => {
2176
+ if (done) return;
2177
+ done = true;
2178
+ cleanup();
2179
+ resolve(Buffer.concat(chunks).toString("utf8"));
2180
+ };
2181
+
2182
+ req.on("error", onError);
2183
+ req.on("data", onData);
2184
+ req.on("end", onEnd);
2185
+ });
2186
+ }
2187
+
2188
+ // --- HTTP Server ---
2189
+ function handleRequest(req: IncomingRequestLike, res: ServerResponseLike): void {
2190
+ req.on("error", (err) => {
2191
+ console.warn("[opencode-free-bridge] request stream error:", err.message);
2192
+ });
2193
+ res.on("error", (err) => {
2194
+ console.warn("[opencode-free-bridge] response stream error:", err.message);
2195
+ });
2196
+
2197
+ const reqOrigin = req.headers?.origin || "";
2198
+ const configuredOrigin = process.env.CORS_ORIGIN !== undefined ? process.env.CORS_ORIGIN : CORS_ORIGIN;
2199
+ if (configuredOrigin === "*") {
2200
+ res.setHeader("Access-Control-Allow-Origin", "*");
2201
+ } else if (configuredOrigin) {
2202
+ const allowed = configuredOrigin.split(",").map((s) => s.trim()).filter(Boolean);
2203
+ if (allowed.includes(reqOrigin)) {
2204
+ res.setHeader("Access-Control-Allow-Origin", reqOrigin);
2205
+ res.setHeader("Vary", "Origin");
2206
+ }
2207
+ } else if (isLocalOrigin(reqOrigin)) {
2208
+ res.setHeader("Access-Control-Allow-Origin", reqOrigin);
2209
+ res.setHeader("Vary", "Origin");
2210
+ }
2211
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
2212
+ res.setHeader(
2213
+ "Access-Control-Allow-Headers",
2214
+ "Content-Type, Authorization, X-Requested-With, X-Session-Id, Session-Id, X-Conversation-Id, X-9r-Session-Id, X-OpenCode-Session, X-OpenCode-Session-Id, X-Session-Affinity, X-OpenCode-Client, X-OpenCode-Project"
2215
+ );
2216
+
2217
+ if (req.method === "OPTIONS") {
2218
+ res.writeHead(204);
2219
+ return res.end();
2220
+ }
2221
+
2222
+ const rawUrl = req.url || "/";
2223
+ const qIdx = rawUrl.indexOf("?");
2224
+ const rawPath = qIdx === -1 ? rawUrl : rawUrl.slice(0, qIdx);
2225
+ const pathname = rawPath.length > 1 && rawPath.endsWith("/") ? rawPath.replace(/\/+$/, "") : rawPath;
2226
+
2227
+ // Panel: the human-facing page. JSON consumers keep using /health, which is
2228
+ // why "/" is no longer an alias for the health document.
2229
+ if ((req.method === "GET" || req.method === "HEAD") && (pathname === "" || pathname === "/")) {
2230
+ const denied = adminRequestError(req);
2231
+ if (denied) {
2232
+ res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" });
2233
+ return res.end(req.method === "HEAD" ? undefined : denied);
2234
+ }
2235
+ const html = panel.renderPanel(proxy.describe(), { version: VERSION, port: PORT });
2236
+ res.writeHead(200, {
2237
+ "Content-Type": "text/html; charset=utf-8",
2238
+ "Cache-Control": "no-store",
2239
+ "Content-Length": Buffer.byteLength(html),
2240
+ "X-Frame-Options": "DENY",
2241
+ });
2242
+ return res.end(req.method === "HEAD" ? undefined : html);
2243
+ }
2244
+
2245
+ if (pathname === "/api/proxy" || pathname === "/api/proxy/test") {
2246
+ const denied = adminRequestError(req);
2247
+ if (denied) {
2248
+ res.writeHead(403, { "Content-Type": "application/json", "Cache-Control": "no-store" });
2249
+ return res.end(JSON.stringify({ error: denied }));
2250
+ }
2251
+ // Only JSON can change the setting. `text/plain` is a CORS "simple
2252
+ // request", so accepting it would let any page POST here without a
2253
+ // preflight; refusing it is the structural half of the CSRF defence.
2254
+ if (req.method === "POST") {
2255
+ const type = String(req.headers?.["content-type"] || "").split(";")[0].trim().toLowerCase();
2256
+ if (type !== "application/json") {
2257
+ res.writeHead(415, { "Content-Type": "application/json", "Cache-Control": "no-store" });
2258
+ return res.end(JSON.stringify({ error: "Content-Type harus application/json." }));
2259
+ }
2260
+ }
2261
+ // `handleProxyApi` is async; an unexpected throw must become a 500 instead
2262
+ // of an unhandled rejection that leaves the socket hanging.
2263
+ handleProxyApi(req, res, pathname).catch((err) => {
2264
+ if (res.headersSent) return res.destroy();
2265
+ res.writeHead(500, { "Content-Type": "application/json", "Cache-Control": "no-store" });
2266
+ res.end(JSON.stringify({ error: `Kesalahan internal: ${err.message}` }));
2267
+ });
2268
+ return;
2269
+ }
2270
+
2271
+ // Health check
2272
+ if (pathname === "/health") {
2273
+ res.writeHead(200, { "Content-Type": "application/json" });
2274
+ const idState = identity.getState();
2275
+ const proxyState = proxy.describe();
2276
+ let usageView = null;
2277
+ try {
2278
+ usageView = proxy.describeUsage();
2279
+ } catch {}
2280
+ const gateThrottled =
2281
+ lastFailedGateRetryTime > 0 &&
2282
+ Date.now() - lastFailedGateRetryTime < GATE_RETRY_COOLDOWN_MS &&
2283
+ lastFailedGateRetryEpoch === (idState.epoch || 0);
2284
+ return res.end(
2285
+ JSON.stringify({
2286
+ status: "ok",
2287
+ provider: "opencode-free-bridge",
2288
+ version: VERSION,
2289
+ runtime: typeof Bun !== "undefined" ? `bun/${Bun.version}` : `node/${process.versions.node}`,
2290
+ discoveredModels: activeModels.length,
2291
+ // Egress in force. `mode` is what actually carries the request: the
2292
+ // pool when one is configured, otherwise a single proxy, otherwise the
2293
+ // relay, otherwise direct. `proxy.mode` only reports the configured
2294
+ // shape, so a relay-only deployment still reads as `relay` here.
2295
+ // Credentials are never included; every host in `proxy` is host:port.
2296
+ egress: {
2297
+ mode:
2298
+ proxyState.mode === "pool"
2299
+ ? "pool"
2300
+ : proxyState.mode === "proxy"
2301
+ ? "proxy"
2302
+ : UPSTREAM_RELAY_URL
2303
+ ? "relay"
2304
+ : "direct",
2305
+ ...(UPSTREAM_RELAY_URL ? { relay: relayLabel(UPSTREAM_RELAY_URL) } : {}),
2306
+ proxy: proxyState,
2307
+ // Per-egress wire traffic and token accounting (usage.json). The
2308
+ // phone entry here is the mobile-data cost of the bridge today.
2309
+ ...(usageView ? { usage: usageView } : {}),
2310
+ },
2311
+ identity: {
2312
+ userAgent: idState.userAgent,
2313
+ updateMode: idState.updateMode,
2314
+ sourceTag: idState.lastSourceTag,
2315
+ versionFloor: idState.versionFloor,
2316
+ lastCheckAgeMs: idState.lastCheckTime ? Date.now() - idState.lastCheckTime : null,
2317
+ ttlMs: idState.ttlMs,
2318
+ lastError: idState.lastRefreshError,
2319
+ release: idState.release,
2320
+ // Set in reactive mode when a release exists that has not been adopted
2321
+ // because the gate has not moved. `null` once adopted.
2322
+ available: idState.available,
2323
+ // The header names in force, and any the recipe asks for that this
2324
+ // bridge cannot fill — a non-empty `unsentHeaders` means a manual
2325
+ // mapping is needed before the next gate move is followed.
2326
+ headers: idState.headers,
2327
+ unsentHeaders: idState.unsentHeaders,
2328
+ // The values derived from upstream sources: the wire endpoints (from
2329
+ // the provider catalog) and the tool allowlist (from the release's
2330
+ // tool plugin sources). Visible because they are the layers that
2331
+ // change without a bridge release.
2332
+ endpoints: idState.endpoints,
2333
+ toolNames: idState.toolNames,
2334
+ tools: idState.tools,
2335
+ gate: {
2336
+ status: lastIpAbuseAt > 0 ? "ip-blocked" : gateThrottled ? "throttled" : "open",
2337
+ // The gateway keys an abuse block to the egress network, so there is
2338
+ // no known expiry to advertise. `ipBlockedSince` is the last time
2339
+ // upstream returned that refusal.
2340
+ ipBlockedSince: lastIpAbuseAt || null,
2341
+ throttledUntil: gateThrottled
2342
+ ? lastFailedGateRetryTime + GATE_RETRY_COOLDOWN_MS
2343
+ : null,
2344
+ cooldownMs: GATE_RETRY_COOLDOWN_MS,
2345
+ // The shape anchors the gate checks. Reported so a deployment can
2346
+ // confirm it is sending them without waiting for a 403.
2347
+ anchors: {
2348
+ tools: identity.GATE_ANCHOR_TOOL_NAMES.slice(),
2349
+ headers: identity.GATE_ANCHOR_HEADER_NAMES.slice(),
2350
+ },
2351
+ // The most recent gate rejection: what was sent, what was missing,
2352
+ // and upstream's own correlation id. `shapeOk: false` means the
2353
+ // bridge produced a request the gate refuses — not an IP problem.
2354
+ lastRejection: lastGateDiagnostic,
2355
+ lastUpstreamError,
2356
+ },
2357
+ },
2358
+ })
2359
+ );
2360
+ }
2361
+
2362
+ // Model list (triggers async re-discovery when the hourly TTL expired)
2363
+ if (req.method === "GET" && (pathname === "/v1/models" || pathname === "/models")) {
2364
+ if (activeModels.length === 0) {
2365
+ discoverModels()
2366
+ .catch(() => {})
2367
+ .finally(() => {
2368
+ res.writeHead(200, { "Content-Type": "application/json" });
2369
+ res.end(cachedModelsPayload);
2370
+ });
2371
+ return;
2372
+ }
2373
+ if (Date.now() - lastDiscoveryTime > DISCOVERY_TTL_MS) {
2374
+ discoverModels().catch(() => {});
2375
+ }
2376
+ res.writeHead(200, { "Content-Type": "application/json" });
2377
+ return res.end(cachedModelsPayload);
2378
+ }
2379
+
2380
+ // Anthropic Messages API. Relays through this bridge's own chat route, so the
2381
+ // Anthropic path inherits the gate anchors, session minting, egress pool and
2382
+ // self-healing retries instead of duplicating them.
2383
+ if (req.method === "POST" && (pathname === "/v1/messages" || pathname === "/messages")) {
2384
+ handleAnthropicMessages(req, res).catch((err) => {
2385
+ if (res.headersSent) {
2386
+ res.destroy();
2387
+ return;
2388
+ }
2389
+ res.writeHead(500, { "Content-Type": "application/json" });
2390
+ res.end(JSON.stringify({ type: "error", error: { type: "api_error", message: err.message } }));
2391
+ });
2392
+ return;
2393
+ }
2394
+ if (
2395
+ req.method === "POST" &&
2396
+ (pathname === "/v1/messages/count_tokens" || pathname === "/messages/count_tokens")
2397
+ ) {
2398
+ handleCountTokens(req, res).catch((err) => {
2399
+ if (res.headersSent) {
2400
+ res.destroy();
2401
+ return;
2402
+ }
2403
+ res.writeHead(500, { "Content-Type": "application/json" });
2404
+ res.end(JSON.stringify({ type: "error", error: { type: "api_error", message: err.message } }));
2405
+ });
2406
+ return;
2407
+ }
2408
+ // Chat completions
2409
+ if (req.method === "POST" && (pathname === "/v1/chat/completions" || pathname === "/chat/completions")) {
2410
+ (async () => {
2411
+ let bodyText;
2412
+ try {
2413
+ bodyText = await readRequestBody(req);
2414
+ } catch (err) {
2415
+ if (err.statusCode === 413) {
2416
+ res.writeHead(413, { "Content-Type": "application/json", "Connection": "close" });
2417
+ res.end(
2418
+ JSON.stringify({
2419
+ error: {
2420
+ message: err.message,
2421
+ type: "invalid_request_error",
2422
+ code: "payload_too_large",
2423
+ },
2424
+ })
2425
+ );
2426
+ res.once("finish", () => {
2427
+ if (typeof req.destroy === "function") req.destroy();
2428
+ });
2429
+ return;
2430
+ }
2431
+ if (!res.headersSent && !res.writableEnded) {
2432
+ res.writeHead(400, { "Content-Type": "application/json" });
2433
+ res.end(
2434
+ JSON.stringify({
2435
+ error: { message: "Failed to read request body", type: "invalid_request_error" },
2436
+ })
2437
+ );
2438
+ }
2439
+ return;
2440
+ }
2441
+
2442
+ let body;
2443
+ try {
2444
+ body = JSON.parse(bodyText);
2445
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
2446
+ throw new Error("Request body must be a JSON object");
2447
+ }
2448
+ } catch (err) {
2449
+ res.writeHead(400, { "Content-Type": "application/json" });
2450
+ return res.end(
2451
+ JSON.stringify({
2452
+ error: {
2453
+ message: `Invalid JSON body: ${err.message}`,
2454
+ type: "invalid_request_error",
2455
+ code: "invalid_json",
2456
+ },
2457
+ })
2458
+ );
2459
+ }
2460
+
2461
+ const targetModel = normalizeModel(body.model);
2462
+ if (!targetModel) {
2463
+ res.writeHead(400, { "Content-Type": "application/json" });
2464
+ return res.end(
2465
+ JSON.stringify({
2466
+ error: {
2467
+ message: "Missing or empty required parameter: 'model'",
2468
+ type: "invalid_request_error",
2469
+ param: "model",
2470
+ code: "model_required",
2471
+ },
2472
+ })
2473
+ );
2474
+ }
2475
+
2476
+ // Free tier only: this bridge sends `Authorization: Bearer public` and
2477
+ // cannot authenticate anything else, so a model the catalog prices above
2478
+ // zero can only fail upstream. Say that here — an upstream 401 ("no
2479
+ // session") sends the user hunting for a login that does not exist.
2480
+ const modelVerdict = identity.getCatalogVerdict(targetModel);
2481
+ if (modelVerdict && modelVerdict !== "free") {
2482
+ const isRetired = modelVerdict === "deprecated";
2483
+ res.writeHead(404, { "Content-Type": "application/json" });
2484
+ return res.end(
2485
+ JSON.stringify({
2486
+ error: {
2487
+ message: isRetired
2488
+ ? `Model '${targetModel}' has been retired upstream. Free models are listed at /v1/models.`
2489
+ : `Model '${targetModel}' is not on the free tier, and this bridge has no account to run it with. Free models are listed at /v1/models.`,
2490
+ type: "invalid_request_error",
2491
+ param: "model",
2492
+ code: isRetired ? "model_deprecated" : "model_not_free",
2493
+ },
2494
+ })
2495
+ );
2496
+ }
2497
+
2498
+ if (!Array.isArray(body.messages)) {
2499
+ res.writeHead(400, { "Content-Type": "application/json" });
2500
+ return res.end(
2501
+ JSON.stringify({
2502
+ error: {
2503
+ message: "Missing or invalid required parameter: 'messages' must be an array",
2504
+ type: "invalid_request_error",
2505
+ param: "messages",
2506
+ code: "messages_required",
2507
+ },
2508
+ })
2509
+ );
2510
+ }
2511
+
2512
+ const clientStream = Boolean(body.stream);
2513
+
2514
+ // Lazy identity check: no timer runs in the background. The first request
2515
+ // after the TTL kicks off a refresh in the background and proceeds with
2516
+ // the current mask; the next request uses the refreshed one.
2517
+ identity.ensureFresh();
2518
+ syncUserAgent();
2519
+
2520
+ let useResponses = isResponsesModel(targetModel);
2521
+ const sessionId = getPersistentSessionId(req, body);
2522
+ let retryHeaders = null;
2523
+ const upstreamHeaders = buildUpstreamHeaders(req, sessionId);
2524
+
2525
+ const abortController = new AbortController();
2526
+ let timedOut = false;
2527
+ let clientDisconnected = false;
2528
+ const timeoutId = setTimeout(() => {
2529
+ timedOut = true;
2530
+ abortController.abort(new Error("Upstream request timed out"));
2531
+ }, UPSTREAM_TIMEOUT_MS);
2532
+
2533
+ const onClose = () => {
2534
+ if (!res.writableEnded) {
2535
+ clientDisconnected = true;
2536
+ abortController.abort(new Error("Client disconnected"));
2537
+ }
2538
+ };
2539
+ res.on("close", onClose);
2540
+
2541
+ let reader = null;
2542
+ try {
2543
+ let { upstreamBody, aliasToOriginal } = buildUpstreamPayload(body, targetModel, useResponses);
2544
+ let liveEndpoints = resolveEndpoints(targetModel);
2545
+ let upstreamUrl = useResponses ? liveEndpoints.responsesUrl : liveEndpoints.chatUrl;
2546
+
2547
+ // One egress per client request. Everything below — the protocol-lane
2548
+ // retry, the endpoint-migration retry, the 5xx retry, and the gate retry
2549
+ // — reuses it, because upstream ties a retry to the address that saw the
2550
+ // first attempt. Only two things move it: an unreachable proxy (the
2551
+ // request never left) and a gate rejection that names this egress as the
2552
+ // problem. Both are handled where they happen and update this state.
2553
+ const egressState = { egress: proxy.pick(), egressUrl: null, transportFailures: 0 };
2554
+ egressState.egressUrl = egressState.egress.url;
2555
+ const egressUrl = () => egressState.egressUrl;
2556
+
2557
+ let upstreamRes = await egressFetch(upstreamUrl, {
2558
+ method: "POST",
2559
+ headers: upstreamHeaders,
2560
+ body: JSON.stringify(upstreamBody),
2561
+ signal: abortController.signal,
2562
+ }, egressState);
2563
+
2564
+ // If a newly released model requires the opposite protocol lane, learn it
2565
+ // and transparently retry once on the matching lane.
2566
+ if (!upstreamRes.ok && upstreamRes.status === 400) {
2567
+ const errText = await upstreamRes.text();
2568
+ let errJson;
2569
+ try {
2570
+ errJson = JSON.parse(errText);
2571
+ } catch {
2572
+ errJson = { message: errText };
2573
+ }
2574
+ const errType = errJson.error?.type || "";
2575
+ const errMsg = errJson.error?.message || errJson.message || "";
2576
+ if (
2577
+ errType === "ModelProtocolUnsupported" ||
2578
+ errMsg.includes("ModelProtocolUnsupported") ||
2579
+ errMsg.includes("does not support this protocol")
2580
+ ) {
2581
+ useResponses = !useResponses;
2582
+ markProtocolSupport(targetModel, useResponses);
2583
+ ({ upstreamBody, aliasToOriginal } = buildUpstreamPayload(body, targetModel, useResponses));
2584
+ upstreamUrl = useResponses ? liveEndpoints.responsesUrl : liveEndpoints.chatUrl;
2585
+ upstreamRes = await upstreamFetch(upstreamUrl, {
2586
+ method: "POST",
2587
+ headers: upstreamHeaders,
2588
+ body: JSON.stringify(upstreamBody),
2589
+ signal: abortController.signal,
2590
+ }, egressUrl());
2591
+ } else {
2592
+ res.writeHead(400, { "Content-Type": "application/json" });
2593
+ return res.end(
2594
+ JSON.stringify({
2595
+ error: {
2596
+ message: errMsg || "Upstream error 400",
2597
+ type: errType || "upstream_error",
2598
+ code: 400,
2599
+ },
2600
+ })
2601
+ );
2602
+ }
2603
+ }
2604
+
2605
+ // Endpoint migration. The provider catalog is the authority for the wire
2606
+ // base URL, so an upstream path move (the /zen/v1 → /inference/v1 move)
2607
+ // shows up as a 404/410 at the old path — not as a gate rejection. A 404
2608
+ // is otherwise indistinguishable from "this route does not exist", so
2609
+ // re-derive from the catalog and retry once, but only when the derived
2610
+ // URL actually differs. Replaying the same URL on a 404 would loop.
2611
+ // A body can only be read once. When an earlier branch has already
2612
+ // consumed it, the generic error path below must reuse the text instead
2613
+ // of reading an empty stream and reporting "Upstream error <status>".
2614
+ let consumedErrorText = null;
2615
+ if (!upstreamRes.ok && (upstreamRes.status === 404 || upstreamRes.status === 410)) {
2616
+ const staleUrl = upstreamUrl;
2617
+ let moveText = "";
2618
+ try {
2619
+ moveText = await upstreamRes.text();
2620
+ } catch {}
2621
+ consumedErrorText = moveText;
2622
+ // A 410 can also be about the *model*, not the route
2623
+ // (`{"error":{"type":"ModelDeprecated"}}`). Retrying such a request at
2624
+ // another URL would just repeat the same model-level answer, so the
2625
+ // endpoint heal only applies when the error does not name a model.
2626
+ let moveErrType = "";
2627
+ try {
2628
+ const j = JSON.parse(moveText);
2629
+ moveErrType = j?.error?.type || j?.type || "";
2630
+ } catch {}
2631
+ const modelLevelError = /model(deprecated|unavailable|protocolunsupported)/i.test(
2632
+ moveErrType
2633
+ );
2634
+ if (!modelLevelError) {
2635
+ await identity.refresh({ force: true }).catch(() => null);
2636
+ liveEndpoints = resolveEndpoints(targetModel);
2637
+ const derivedUrl = useResponses ? liveEndpoints.responsesUrl : liveEndpoints.chatUrl;
2638
+ if (derivedUrl && derivedUrl !== staleUrl) {
2639
+ console.warn(
2640
+ `[opencode-free-bridge] Upstream endpoint moved (${upstreamRes.status}): ${staleUrl} → ${derivedUrl}; retrying once`
2641
+ );
2642
+ upstreamUrl = derivedUrl;
2643
+ upstreamRes = await upstreamFetch(upstreamUrl, {
2644
+ method: "POST",
2645
+ headers: upstreamHeaders,
2646
+ body: JSON.stringify(upstreamBody),
2647
+ signal: abortController.signal,
2648
+ }, egressUrl());
2649
+ // The text above belonged to the response we just replaced. Reading
2650
+ // it for the new response would report the old error verbatim.
2651
+ consumedErrorText = null;
2652
+ }
2653
+ }
2654
+ }
2655
+
2656
+ // Spent allowance on a pooled egress. A 429 means transport and request
2657
+ // shape were both accepted and only this IP's quota is gone, so the one
2658
+ // useful action is to spend the retry on a different IP instead of
2659
+ // replaying an identical request at an address upstream just refused.
2660
+ //
2661
+ // This walks the pool rather than failing over once. A single retry was
2662
+ // not enough: two spent IPs at the front handed the client a 429 while
2663
+ // the rest of the pool was healthy. The client should only see 429 when
2664
+ // every enabled member has been refused in this request — at that point
2665
+ // there is genuinely nothing left to try, and saying so is correct.
2666
+ if (!upstreamRes.ok && upstreamRes.status === 429) {
2667
+ const poolState = proxy.describe().pool;
2668
+ const canFailover = poolState && poolState.active && poolState.enabled > 1;
2669
+ recordEgressFailure(egressState, {
2670
+ reason: "allowance 429",
2671
+ cooldownMs: retryAfterMs(upstreamRes) ?? (poolState ? poolState.cooldownMs * 4 : null),
2672
+ });
2673
+
2674
+ if (canFailover) {
2675
+ // Every egress already refused for *this* request. `pick()` skips
2676
+ // cooling entries, but a just-recorded failure is cooling too, so
2677
+ // this also prevents revisiting one. The cap guards a pool whose
2678
+ // entries resolve to the same URL.
2679
+ const tried = new Set();
2680
+ if (egressState.egressUrl !== null && egressState.egressUrl !== undefined) {
2681
+ tried.add(egressState.egressUrl);
2682
+ }
2683
+ const MAX = Math.max(2, poolState.enabled);
2684
+
2685
+ for (let attempt = 0; attempt < MAX; attempt += 1) {
2686
+ // pick() excludes one entry, not a list. Pass the one we just
2687
+ // refused; it is also in cooldown now, so this is redundant
2688
+ // rather than load-bearing — which is the point.
2689
+ const next = proxy.pick({ exclude: egressState.egressUrl });
2690
+ // `cooling` means pick() found no ready candidate at all: every
2691
+ // member is already parked by an earlier request. Walking the pool
2692
+ // then spends one request per entry on an upstream that has
2693
+ // already refused each of them, which is exactly how an egress
2694
+ // that served nothing today still accumulates failures and gets
2695
+ // stamped with a fresh 429. Nothing healthy is left to try, so
2696
+ // fail fast and let Retry-After carry the wait instead.
2697
+ if (next.cooling) {
2698
+ console.warn(
2699
+ `[opencode-free-bridge] Pool has no ready egress (${poolState.enabled} enabled, all cooling); not walking it`
2700
+ );
2701
+ break;
2702
+ }
2703
+ const key = next.url === null || next.url === undefined ? "@direct" : next.url;
2704
+ if (tried.has(key)) break;
2705
+ tried.add(key);
2706
+
2707
+ console.warn(
2708
+ `[opencode-free-bridge] Egress ${
2709
+ proxy.displayHost(egressState.egressUrl) || "direct"
2710
+ } is out of allowance (429); trying ${
2711
+ proxy.displayHost(next.url) || "direct"
2712
+ } (${tried.size}/${poolState.enabled})`
2713
+ );
2714
+ egressState.egress = next;
2715
+ egressState.egressUrl = next.url;
2716
+ upstreamRes = await egressFetch(upstreamUrl, {
2717
+ method: "POST",
2718
+ headers: upstreamHeaders,
2719
+ body: JSON.stringify(upstreamBody),
2720
+ signal: abortController.signal,
2721
+ }, egressState);
2722
+ consumedErrorText = null;
2723
+
2724
+ if (upstreamRes.status !== 429) break;
2725
+
2726
+ // Still spent. Record with this response's own Retry-After so the
2727
+ // entry leaves rotation for the real reset window.
2728
+ recordEgressFailure(egressState, {
2729
+ reason: "allowance 429",
2730
+ cooldownMs: retryAfterMs(upstreamRes) ?? poolState.cooldownMs * 4,
2731
+ });
2732
+ }
2733
+
2734
+ if (upstreamRes.status === 429) {
2735
+ console.warn(
2736
+ `[opencode-free-bridge] All ${tried.size} pooled egress(es) refused this request; exhausted the pool, returning 429`
2737
+ );
2738
+ }
2739
+ }
2740
+ }
2741
+
2742
+ // Transient 5xx self-heal: upstream Workers intermittently drop empty-body
2743
+ // HTTP 500/502/503/504 responses (e.g. cf-placement: remote-IAD) during
2744
+ // free-inference degradation. Retry once with fresh trace/session headers.
2745
+ if (!upstreamRes.ok && upstreamRes.status >= 500 && upstreamRes.status < 600) {
2746
+ const first5xx = upstreamRes.status;
2747
+ const firstLogId =
2748
+ typeof upstreamRes.headers?.get === "function"
2749
+ ? upstreamRes.headers.get("x-opencode-log-id")
2750
+ : null;
2751
+ try {
2752
+ await upstreamRes.text();
2753
+ } catch {}
2754
+ const retry5xxSid = regenerateSessionId(req, body, sessionId);
2755
+ const retry5xxHeaders = buildUpstreamHeaders(req, retry5xxSid);
2756
+ console.warn(
2757
+ `[opencode-free-bridge] Upstream returned ${first5xx}` +
2758
+ (firstLogId ? ` [x-opencode-log-id: ${firstLogId}]` : "") +
2759
+ `; retrying once with fresh session`
2760
+ );
2761
+ upstreamRes = await upstreamFetch(upstreamUrl, {
2762
+ method: "POST",
2763
+ headers: retry5xxHeaders,
2764
+ body: JSON.stringify(upstreamBody),
2765
+ signal: abortController.signal,
2766
+ }, egressUrl());
2767
+ consumedErrorText = null;
2768
+ }
2769
+
2770
+ // Self-healing identity. A gate rejection is identified by the error
2771
+ // *body*, not the status line: a 403 is only the gate when its type or
2772
+ // message says so, while 426 is the version-floor handshake by itself.
2773
+ // The body must therefore be read before the decision — passing empty
2774
+ // strings here made this branch unreachable for 403.
2775
+ if (!upstreamRes.ok) {
2776
+ let errText = consumedErrorText ?? "";
2777
+ if (consumedErrorText === null) {
2778
+ try {
2779
+ errText = await upstreamRes.text();
2780
+ } catch {
2781
+ errText = "";
2782
+ }
2783
+ }
2784
+ let errJson = null;
2785
+ try {
2786
+ errJson = JSON.parse(errText);
2787
+ } catch {
2788
+ errJson = null;
2789
+ }
2790
+ const errType = errJson?.error?.type || errJson?.type || "";
2791
+ const rawMsg =
2792
+ errJson?.error?.message ||
2793
+ errJson?.message ||
2794
+ errText ||
2795
+ `Upstream error ${upstreamRes.status}`;
2796
+
2797
+ // Terminal branch. Upstream names an IP-level abuse block in the
2798
+ // message, and that is a different failure from the shape gate: the
2799
+ // gateway has flagged this network, so refreshing the recipe, minting
2800
+ // a new session id, or replaying the request cannot change the
2801
+ // answer. Measured against the gateway's own reports: the official
2802
+ // CLI gets the same refusal from the same IP. Return it verbatim and
2803
+ // leave the identity layer untouched.
2804
+ if (identity.isIpAbuseRejection(upstreamRes.status, rawMsg)) {
2805
+ // The block is keyed to this network's IP, so this egress is the
2806
+ // problem: park it so the next request leaves through another entry.
2807
+ recordEgressFailure(egressState, { reason: "ip-abuse block" });
2808
+ return respondIpAbuse(
2809
+ res,
2810
+ upstreamRes.status,
2811
+ errType,
2812
+ rawMsg,
2813
+ upstreamLogIdOf(upstreamRes),
2814
+ targetModel
2815
+ );
2816
+ }
2817
+
2818
+ if (!isFreeTierCliGateError(upstreamRes.status, errType, rawMsg)) {
2819
+ const upstreamLogId =
2820
+ typeof upstreamRes.headers?.get === "function"
2821
+ ? upstreamRes.headers.get("x-opencode-log-id")
2822
+ : null;
2823
+ const cfRay =
2824
+ typeof upstreamRes.headers?.get === "function"
2825
+ ? upstreamRes.headers.get("cf-ray")
2826
+ : null;
2827
+ const cfPlacement =
2828
+ typeof upstreamRes.headers?.get === "function"
2829
+ ? upstreamRes.headers.get("cf-placement")
2830
+ : null;
2831
+ if (upstreamRes.status >= 500) {
2832
+ lastUpstreamError = {
2833
+ at: Date.now(),
2834
+ status: upstreamRes.status,
2835
+ logId: upstreamLogId,
2836
+ cfRay,
2837
+ cfPlacement,
2838
+ message: rawMsg,
2839
+ model: targetModel,
2840
+ };
2841
+ console.warn(
2842
+ `[opencode-free-bridge] Upstream server error (${upstreamRes.status}) on model ${targetModel}: ${rawMsg}` +
2843
+ (upstreamLogId ? ` [x-opencode-log-id: ${upstreamLogId}]` : "") +
2844
+ (cfRay ? ` [cf-ray: ${cfRay}]` : "") +
2845
+ (cfPlacement ? ` [cf-placement: ${cfPlacement}]` : "")
2846
+ );
2847
+ }
2848
+ const errHeaders = { "Content-Type": "application/json" };
2849
+ if (upstreamLogId) errHeaders["X-OpenCode-Log-Id"] = upstreamLogId;
2850
+ if (upstreamRes.status >= 500) errHeaders["X-OpenCode-Gate"] = "upstream-error";
2851
+ // A capacity 429 reaches this passthrough, not the gate branch:
2852
+ // isFreeTierCliGateError() only claims 403/401/426, so FreeUsageLimitError
2853
+ // with status 429 falls through to here. Without the real Retry-After
2854
+ // the client retries immediately into a pool that is still spent, and
2855
+ // every retry re-stamps the entries. Upstream sends the free-allowance
2856
+ // reset as an absolute boundary (measured: ~46ks, i.e. next midnight
2857
+ // UTC), so passing it through is what makes the wait truthful.
2858
+ if (upstreamRes.status === 429) {
2859
+ const upstreamRetryAfter = retryAfterMs(upstreamRes);
2860
+ if (upstreamRetryAfter) {
2861
+ errHeaders["Retry-After"] = String(Math.max(1, Math.ceil(upstreamRetryAfter / 1000)));
2862
+ }
2863
+ errHeaders["X-OpenCode-Gate"] = "ip-throttled";
2864
+ }
2865
+ res.writeHead(upstreamRes.status, errHeaders);
2866
+ return res.end(
2867
+ JSON.stringify({
2868
+ error: {
2869
+ message: rawMsg,
2870
+ type: errType || "upstream_error",
2871
+ code: upstreamRes.status,
2872
+ ...(upstreamLogId ? { log_id: upstreamLogId } : {}),
2873
+ },
2874
+ })
2875
+ );
2876
+ }
2877
+
2878
+ const gateStatus = upstreamRes.status;
2879
+ const verdict = await identity
2880
+ .onGateRejection(gateStatus, errType, rawMsg, false)
2881
+ .catch(() => ({ retry: false, reason: "refresh-error" }));
2882
+
2883
+ // Always retry once on a gate rejection, even when the refresh learned
2884
+ // nothing new. Two inputs to the gate are *minted per request* rather
2885
+ // than read from the recipe — the session id and the tool set — so a
2886
+ // retry with fresh values is a genuinely different request. Measured
2887
+ // upstream behaviour: a session id this bridge did not mint (or one
2888
+ // minted by a rejected recipe) is refused with FreeTierError even
2889
+ // when every header matches, while the same request with a freshly
2890
+ // minted id is accepted.
2891
+ syncUserAgent();
2892
+ // Re-mint the session id. The one minted before this request was
2893
+ // produced by the recipe the gate just rejected; replaying it would
2894
+ // send the same rejected shape and fail identically. The cached
2895
+ // entry is dropped so the next request also gets a correct id.
2896
+ const retrySessionId = regenerateSessionId(req, body, sessionId);
2897
+ const currentEpoch = identity.getState().epoch || 0;
2898
+ const skipCooldownRetry =
2899
+ !verdict.retry &&
2900
+ lastFailedGateRetryTime > 0 &&
2901
+ Date.now() - lastFailedGateRetryTime < GATE_RETRY_COOLDOWN_MS &&
2902
+ lastFailedGateRetryEpoch === currentEpoch;
2903
+
2904
+ if (!skipCooldownRetry) {
2905
+ // A gate rejection on a pooled egress is the one case where the
2906
+ // bridge can act on it locally: the allowance is per IP, so a
2907
+ // different entry is a different allowance. Failed over before the
2908
+ // retry so the retry is a genuinely different request in both shape
2909
+ // and egress. The old entry is put in cooldown; with a single proxy
2910
+ // (or none) `pick()` hands back the same egress and this is a no-op.
2911
+ const pooled = proxy.describe().pool;
2912
+ const canFailover = pooled && pooled.active && pooled.enabled > 1;
2913
+ if (canFailover && egressState.egressUrl) {
2914
+ proxy.markFailure(egressState.egressUrl, {
2915
+ reason: `gate ${gateStatus}`,
2916
+ cooldownMs: gateStatus === 429 ? (retryAfterMs(upstreamRes) ?? pooled.cooldownMs * 4) : null,
2917
+ });
2918
+ const next = proxy.pick({ exclude: egressState.egressUrl });
2919
+ if (next.url && next.url !== egressState.egressUrl) {
2920
+ console.warn(
2921
+ `[opencode-free-bridge] Gate refused egress ${
2922
+ proxy.displayHost(egressState.egressUrl) || "direct"
2923
+ } (${gateStatus}); moving to ${proxy.displayHost(next.url) || "direct"} for the retry`
2924
+ );
2925
+ egressState.egress = next;
2926
+ egressState.egressUrl = next.url;
2927
+ }
2928
+ }
2929
+ console.warn(
2930
+ `[opencode-free-bridge] Upstream CLI gate rejected request (${gateStatus}, ${verdict.reason || "unknown"}); refreshing identity and retrying once with full tool set`
2931
+ );
2932
+ ({ upstreamBody, aliasToOriginal } = buildUpstreamPayload(
2933
+ body,
2934
+ targetModel,
2935
+ useResponses,
2936
+ "full"
2937
+ ));
2938
+ // Re-resolve the endpoint *after* the refresh: a catalog change is one
2939
+ // of the things the refresh can learn, and the retry must go to the
2940
+ // new URL — reusing the pre-refresh value would defeat the derivation.
2941
+ liveEndpoints = resolveEndpoints(targetModel);
2942
+ upstreamUrl = useResponses ? liveEndpoints.responsesUrl : liveEndpoints.chatUrl;
2943
+ retryHeaders = buildUpstreamHeaders(req, retrySessionId);
2944
+ upstreamRes = await upstreamFetch(upstreamUrl, {
2945
+ method: "POST",
2946
+ headers: retryHeaders,
2947
+ body: JSON.stringify(upstreamBody),
2948
+ signal: abortController.signal,
2949
+ }, egressUrl());
2950
+ } else {
2951
+ console.warn(
2952
+ `[opencode-free-bridge] Upstream CLI gate rejected request (${gateStatus}); skipping retry because a full-shape retry already failed <${Math.round(GATE_RETRY_COOLDOWN_MS / 1000)}s ago on the current identity (IP cooldown active)`
2953
+ );
2954
+ }
2955
+
2956
+ if (!upstreamRes.ok) {
2957
+ // The retry already used the freshest derived identity (endpoint,
2958
+ // session id, full tool set) — so a repeated FreeTierError is not a
2959
+ // shape problem this bridge can learn its way out of. Measured
2960
+ // 403 FreeTierError has more than one cause, and the message alone
2961
+ // cannot distinguish them:
2962
+ //
2963
+ // 1. transport fingerprint — measured: Node and curl are refused
2964
+ // 100% while Bun succeeds 100% from the same IP in the same
2965
+ // minute. The CLI ships as a Bun binary, so only Bun matches.
2966
+ // 2. per-IP allowance — also returned as 403. Measured: after a
2967
+ // few dozen probes the real CLI v2.0.32 gets the identical 403
2968
+ // from the same IP that answered 200 an hour earlier, and so
2969
+ // does the bridge. The transport had not changed.
2970
+ //
2971
+ // A 429 FreeUsageLimitError is unambiguous: transport passed and
2972
+ // the quota is spent. Observed on a fresh IP while 403 was being
2973
+ // returned elsewhere, which is how the two were told apart.
2974
+ //
2975
+ // Only the runtime can be checked locally, so report that and name
2976
+ // both possibilities instead of asserting the wrong one.
2977
+ // Read the retry's own body before logging. The first attempt's
2978
+ // message describes a shape this bridge has already replaced, so
2979
+ // reporting it here would describe a request nobody sent.
2980
+ let retryText = errText;
2981
+ let retryJson = errJson;
2982
+ if (!skipCooldownRetry) {
2983
+ retryText = "";
2984
+ try {
2985
+ retryText = await upstreamRes.text();
2986
+ } catch {}
2987
+ retryJson = null;
2988
+ try {
2989
+ retryJson = JSON.parse(retryText);
2990
+ } catch {}
2991
+ }
2992
+ const retryType = retryJson?.error?.type || retryJson?.type || errType || "upstream_error";
2993
+ const retryMsg =
2994
+ retryJson?.error?.message || retryJson?.message || retryText || rawMsg;
2995
+ // Report the *retry* status, not the first attempt's: they differ
2996
+ // whenever upstream answers the refreshed shape differently (a 426
2997
+ // floor handshake followed by a 429 capacity answer is common), and
2998
+ // logging the old status misattributes the final verdict.
2999
+ const retryStatus = upstreamRes.status;
3000
+ // The retry can reveal the block even when the first attempt still
3001
+ // carried the shape message (upstream mixes the two while a flag is
3002
+ // being applied). That is still terminal: answer it verbatim and do
3003
+ // not run the shape audit or append an update hint.
3004
+ if (identity.isIpAbuseRejection(retryStatus, retryMsg)) {
3005
+ if (!skipCooldownRetry) {
3006
+ lastFailedGateRetryTime = Date.now();
3007
+ lastFailedGateRetryEpoch = identity.getState().epoch || 0;
3008
+ }
3009
+ recordEgressFailure(egressState, { reason: "ip-abuse block" });
3010
+ return respondIpAbuse(
3011
+ res,
3012
+ retryStatus,
3013
+ retryType,
3014
+ retryMsg,
3015
+ upstreamLogIdOf(upstreamRes),
3016
+ targetModel
3017
+ );
3018
+ }
3019
+ const retryFreeTierMsg = /freetiererror|free tier|free models|only available in opencode/i.test(retryMsg);
3020
+ const onNode = typeof Bun === "undefined";
3021
+ // A 429 means transport and shape both passed and only capacity is
3022
+ // exhausted. Calling that a gate rejection would send the user to
3023
+ // re-check headers that upstream already accepted.
3024
+ const capacity = retryStatus === 429;
3025
+ if (capacity) {
3026
+ lastFailedGateRetryTime = 0;
3027
+ } else if (!skipCooldownRetry && isFreeTierCliGateError(retryStatus, retryType, retryMsg)) {
3028
+ lastFailedGateRetryTime = Date.now();
3029
+ lastFailedGateRetryEpoch = identity.getState().epoch || 0;
3030
+ }
3031
+ // The egress that produced *this* refusal is spent: record it so the
3032
+ // next request picks a different entry instead of relearning the
3033
+ // same throttle. A 429 is an unambiguous allowance answer, so it
3034
+ // earns a longer cooldown than a 403 whose cause the bridge cannot
3035
+ // fully separate from a shape problem.
3036
+ recordEgressFailure(egressState, {
3037
+ reason: capacity ? "allowance 429" : `gate ${retryStatus}`,
3038
+ cooldownMs: capacity ? (retryAfterMs(upstreamRes) ?? proxy.describe().pool.cooldownMs * 4) : null,
3039
+ });
3040
+
3041
+ // The gate answers the same `403 FreeTierError` for a blocked egress
3042
+ // and for a request whose shape it refuses, so the status line and
3043
+ // message cannot tell the two apart. What can: whether the request
3044
+ // that was actually sent carried the anchors the gate checks. Audit
3045
+ // that here instead of asserting a cause. Measured anchors: a tool
3046
+ // named `read`, and an `opencode/*` User-Agent with a session header.
3047
+ const shape = auditGateShape(upstreamBody, retryHeaders || upstreamHeaders);
3048
+ const shapeOk = shape.hasReadTool && shape.userAgentOk && shape.sessionHeaders.length > 0;
3049
+ const missing = [];
3050
+ if (!shape.hasReadTool) missing.push("tool `read`");
3051
+ if (!shape.userAgentOk) missing.push("an `opencode/*` User-Agent");
3052
+ if (shape.sessionHeaders.length === 0) missing.push("a session header");
3053
+ // Correlation id for this rejection. Upstream returns it on every
3054
+ // response, accepted or refused; it is the only handle a support
3055
+ // request or a bug report can quote.
3056
+ const upstreamLogId = upstreamLogIdOf(upstreamRes);
3057
+ lastGateDiagnostic = {
3058
+ at: Date.now(),
3059
+ kind: "free-tier-gate",
3060
+ status: retryStatus,
3061
+ logId: upstreamLogId,
3062
+ shape,
3063
+ shapeOk,
3064
+ missing,
3065
+ model: targetModel,
3066
+ };
3067
+
3068
+ const verdictText = capacity
3069
+ ? "upstream accepted the transport and the request shape and answered with capacity pressure; the free-tier allowance or the model's capacity is exhausted. Retry later or switch model"
3070
+ : retryFreeTierMsg
3071
+ ? onNode
3072
+ ? "this process is on Node, whose TLS ClientHello differs from the CLI's (measured: Node 0/6, Bun 6/6 from the same IP). Run the bridge with Bun — `bun server.js` — before suspecting an allowance limit"
3073
+ : shapeOk
3074
+ ? "the request carried every anchor the gate checks, so this is the egress: the per-IP free-tier allowance is spent or upstream refuses this network. The real CLI gets the same 403 from the same IP when it is"
3075
+ : `this bridge produced a shape the gate refuses — missing ${missing.join(", ")}. That is a bridge bug, not an IP allowance: the same 403 is returned for both, which is why it is audited here`
3076
+ : `no further identity change to apply; ${UPDATE_HINT}`;
3077
+ console.warn(
3078
+ `[opencode-free-bridge] Upstream CLI gate rejected ${
3079
+ skipCooldownRetry
3080
+ ? "the request (no retry: cooldown active)"
3081
+ : "the retry with the refreshed identity"
3082
+ } (${retryStatus}${
3083
+ retryStatus !== gateStatus ? `, first attempt ${gateStatus}` : ""
3084
+ }): ${retryMsg} — ${verdictText}` +
3085
+ (upstreamLogId ? ` [x-opencode-log-id: ${upstreamLogId}]` : "")
3086
+ );
3087
+ const outStatus = resolveIpThrottleStatus(upstreamRes.status, retryFreeTierMsg && !capacity);
3088
+ res.writeHead(
3089
+ outStatus,
3090
+ buildIpThrottleHeaders(retryFreeTierMsg && !capacity, {
3091
+ shapeOk,
3092
+ logId: upstreamLogId,
3093
+ })
3094
+ );
3095
+ return res.end(
3096
+ JSON.stringify({
3097
+ error: {
3098
+ // Point at an update only when the shape is plausibly stale.
3099
+ // A budget rejection already carries the newest identity, so
3100
+ // an "update the bridge" hint would send the user the wrong way.
3101
+ message: retryFreeTierMsg ? retryMsg : `${retryMsg} (${UPDATE_HINT})`,
3102
+ type: retryType,
3103
+ code: outStatus,
3104
+ },
3105
+ })
3106
+ );
3107
+ }
3108
+ }
3109
+
3110
+ lastFailedGateRetryTime = 0;
3111
+ lastIpAbuseAt = 0;
3112
+ // This egress carried a request upstream accepted, so its failure
3113
+ // history is stale: clear it so the next pick treats it as healthy.
3114
+ proxy.markSuccess(egressState.egressUrl);
3115
+ const completionId = `chatcmpl-${crypto.randomBytes(12).toString("hex")}`;
3116
+ const created = Math.floor(Date.now() / 1000);
3117
+ reader = upstreamRes.body.getReader();
3118
+ const decoder = new TextDecoder();
3119
+ let buffer = "";
3120
+
3121
+ // ==========================================
3122
+ // PATH A: Client requested streaming (SSE)
3123
+ // ==========================================
3124
+ if (clientStream) {
3125
+ let sseHeadersSent = false;
3126
+ const writeSse = (payload) => {
3127
+ if (!sseHeadersSent) {
3128
+ sseHeadersSent = true;
3129
+ res.writeHead(200, {
3130
+ "Content-Type": "text/event-stream; charset=utf-8",
3131
+ "Cache-Control": "no-cache",
3132
+ "Connection": "keep-alive",
3133
+ });
3134
+ }
3135
+ res.write(payload);
3136
+ };
3137
+ const emitStreamError = (errMessage, errType) => {
3138
+ console.warn(`[opencode-free-bridge] Upstream failed inside the stream: ${errMessage}`);
3139
+ reader.cancel().catch(() => {});
3140
+ if (!sseHeadersSent) {
3141
+ sseHeadersSent = true;
3142
+ res.writeHead(502, { "Content-Type": "application/json" });
3143
+ res.end(
3144
+ JSON.stringify({
3145
+ error: {
3146
+ message: errMessage,
3147
+ type: errType || "upstream_error",
3148
+ code: 502,
3149
+ },
3150
+ })
3151
+ );
3152
+ return;
3153
+ }
3154
+ writeSse(
3155
+ `data: ${JSON.stringify({
3156
+ error: {
3157
+ message: errMessage,
3158
+ type: errType || "upstream_error",
3159
+ code: 502,
3160
+ },
3161
+ })}\n\n`
3162
+ );
3163
+ writeSse("data: [DONE]\n\n");
3164
+ };
3165
+
3166
+ if (useResponses) {
3167
+ const toolIndexMap = new Map();
3168
+ let nextToolIndex = 0;
3169
+ let hasToolCalls = false;
3170
+ let upstreamFinishReason = null;
3171
+ let streamUsage = null;
3172
+ let streamAbortedByError = false;
3173
+
3174
+ const handleResponsesStreamLine = (line) => {
3175
+ if (streamAbortedByError) return;
3176
+ if (!line.startsWith("data: ")) return;
3177
+ const rawJson = line.slice(6).trim();
3178
+ if (!rawJson || rawJson === "[DONE]") return;
3179
+ try {
3180
+ const ev = JSON.parse(rawJson);
3181
+ const inStreamError = extractStreamError(ev);
3182
+ if (inStreamError) {
3183
+ streamAbortedByError = true;
3184
+ emitStreamError(inStreamError, ev?.error?.type);
3185
+ return;
3186
+ }
3187
+ if (ev.type === "response.output_text.delta" && ev.delta) {
3188
+ writeSse(
3189
+ `data: ${JSON.stringify({
3190
+ id: completionId,
3191
+ object: "chat.completion.chunk",
3192
+ created,
3193
+ model: targetModel,
3194
+ choices: [{ index: 0, delta: { content: ev.delta }, finish_reason: null }],
3195
+ })}\n\n`
3196
+ );
3197
+ } else if (
3198
+ (ev.type === "response.reasoning_summary_text.delta" ||
3199
+ ev.type === "response.reasoning_text.delta" ||
3200
+ ev.type === "response.reasoning.delta") &&
3201
+ ev.delta
3202
+ ) {
3203
+ writeSse(
3204
+ `data: ${JSON.stringify({
3205
+ id: completionId,
3206
+ object: "chat.completion.chunk",
3207
+ created,
3208
+ model: targetModel,
3209
+ choices: [{ index: 0, delta: { reasoning_content: ev.delta }, finish_reason: null }],
3210
+ })}\n\n`
3211
+ );
3212
+ } else if (ev.type === "response.output_item.added" && ev.item?.type === "function_call") {
3213
+ hasToolCalls = true;
3214
+ const key =
3215
+ ev.output_index !== undefined
3216
+ ? String(ev.output_index)
3217
+ : ev.item.call_id || ev.item.id || String(nextToolIndex);
3218
+ let toolIdx = toolIndexMap.get(key);
3219
+ if (toolIdx === undefined) {
3220
+ toolIdx = nextToolIndex++;
3221
+ toolIndexMap.set(key, toolIdx);
3222
+ if (ev.item.call_id) toolIndexMap.set(ev.item.call_id, toolIdx);
3223
+ if (ev.item.id) toolIndexMap.set(ev.item.id, toolIdx);
3224
+ if (ev.output_index !== undefined) toolIndexMap.set(String(ev.output_index), toolIdx);
3225
+ }
3226
+ const restoredName = restoreClientToolName(ev.item.name, aliasToOriginal);
3227
+ writeSse(
3228
+ `data: ${JSON.stringify({
3229
+ id: completionId,
3230
+ object: "chat.completion.chunk",
3231
+ created,
3232
+ model: targetModel,
3233
+ choices: [
3234
+ {
3235
+ index: 0,
3236
+ delta: {
3237
+ tool_calls: [
3238
+ {
3239
+ index: toolIdx,
3240
+ id: ev.item.call_id || ev.item.id || `call_${toolIdx}`,
3241
+ type: "function",
3242
+ function: { name: restoredName, arguments: "" },
3243
+ },
3244
+ ],
3245
+ },
3246
+ finish_reason: null,
3247
+ },
3248
+ ],
3249
+ })}\n\n`
3250
+ );
3251
+ } else if (ev.type === "response.function_call_arguments.delta" && ev.delta) {
3252
+ const key = ev.output_index !== undefined ? String(ev.output_index) : ev.item_id || ev.call_id;
3253
+ const toolIdx = key !== undefined && toolIndexMap.has(key) ? toolIndexMap.get(key) : 0;
3254
+ writeSse(
3255
+ `data: ${JSON.stringify({
3256
+ id: completionId,
3257
+ object: "chat.completion.chunk",
3258
+ created,
3259
+ model: targetModel,
3260
+ choices: [
3261
+ {
3262
+ index: 0,
3263
+ delta: {
3264
+ tool_calls: [{ index: toolIdx, function: { arguments: ev.delta } }],
3265
+ },
3266
+ finish_reason: null,
3267
+ },
3268
+ ],
3269
+ })}\n\n`
3270
+ );
3271
+ } else if (ev.type === "response.completed" || ev.type === "response.incomplete") {
3272
+ upstreamFinishReason = extractResponsesFinishReason(ev, hasToolCalls);
3273
+ if (ev.response?.usage) {
3274
+ streamUsage = {
3275
+ prompt_tokens: ev.response.usage.input_tokens || 0,
3276
+ completion_tokens: ev.response.usage.output_tokens || 0,
3277
+ total_tokens: ev.response.usage.total_tokens || 0,
3278
+ };
3279
+ }
3280
+ }
3281
+ } catch {}
3282
+ };
3283
+
3284
+ await consumeSseLines(reader, decoder, handleResponsesStreamLine);
3285
+ if (streamAbortedByError) {
3286
+ if (!res.writableEnded) res.end();
3287
+ return;
3288
+ }
3289
+
3290
+ const finalFinishReason = upstreamFinishReason || (hasToolCalls ? "tool_calls" : "stop");
3291
+ writeSse(
3292
+ `data: ${JSON.stringify({
3293
+ id: completionId,
3294
+ object: "chat.completion.chunk",
3295
+ created,
3296
+ model: targetModel,
3297
+ choices: [{ index: 0, delta: {}, finish_reason: finalFinishReason }],
3298
+ })}\n\n`
3299
+ );
3300
+ if (body.stream_options?.include_usage && streamUsage) {
3301
+ writeSse(
3302
+ `data: ${JSON.stringify({
3303
+ id: completionId,
3304
+ object: "chat.completion.chunk",
3305
+ created,
3306
+ model: targetModel,
3307
+ choices: [],
3308
+ usage: streamUsage,
3309
+ })}\n\n`
3310
+ );
3311
+ }
3312
+ writeSse("data: [DONE]\n\n");
3313
+ return res.end();
3314
+ } else {
3315
+ // Chat Completions API SSE stream
3316
+ const hasAliases = aliasToOriginal.size > 0;
3317
+ let streamAbortedByError = false;
3318
+ const handleChatStreamLine = (line) => {
3319
+ if (streamAbortedByError) return;
3320
+ if (!line.startsWith("data: ")) return;
3321
+ const raw = line.slice(6).trim();
3322
+ if (!raw) return;
3323
+ if (raw === "[DONE]") {
3324
+ writeSse("data: [DONE]\n\n");
3325
+ return;
3326
+ }
3327
+ // A failure inside the stream is not a completion. If no chunk has
3328
+ // been sent yet, return HTTP 502 JSON so any router or harness can
3329
+ // fail over; if chunks were already sent, emit an SSE error event.
3330
+ if (raw.includes('"error"')) try {
3331
+ const maybe = JSON.parse(raw);
3332
+ const streamErr = extractStreamError(maybe);
3333
+ if (streamErr) {
3334
+ streamAbortedByError = true;
3335
+ emitStreamError(streamErr, maybe?.error?.type);
3336
+ return;
3337
+ }
3338
+ } catch {}
3339
+ // Zero-parse fast path: when no client tools are aliased and the chunk
3340
+ // carries no `"reasoning":` field to normalize, forward raw SSE bytes directly.
3341
+ if (!hasAliases && !raw.includes('"reasoning"')) {
3342
+ writeSse(`data: ${raw}\n\n`);
3343
+ return;
3344
+ }
3345
+ try {
3346
+ const chunk = JSON.parse(raw);
3347
+ const delta = chunk.choices?.[0]?.delta;
3348
+ if (delta && delta.reasoning && !delta.reasoning_content) {
3349
+ delta.reasoning_content = delta.reasoning;
3350
+ }
3351
+ if (hasAliases && Array.isArray(delta?.tool_calls)) {
3352
+ for (const tc of delta.tool_calls) {
3353
+ if (tc.function?.name) {
3354
+ tc.function.name = restoreClientToolName(tc.function.name, aliasToOriginal);
3355
+ }
3356
+ }
3357
+ }
3358
+ writeSse(`data: ${JSON.stringify(chunk)}\n\n`);
3359
+ } catch {
3360
+ writeSse(`data: ${raw}\n\n`);
3361
+ }
3362
+ };
3363
+
3364
+ await consumeSseLines(reader, decoder, handleChatStreamLine);
3365
+ if (!res.writableEnded) {
3366
+ if (!sseHeadersSent) writeSse("data: [DONE]\n\n");
3367
+ res.end();
3368
+ }
3369
+ return;
3370
+ }
3371
+ }
3372
+
3373
+ // ==========================================
3374
+ // PATH B: Client requested non-streaming (JSON)
3375
+ // ==========================================
3376
+ let assistantText = "";
3377
+ let reasoningText = "";
3378
+ const toolCalls = [];
3379
+ const nonStreamToolMap = new Map();
3380
+ let usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
3381
+ let upstreamFinishReason = null;
3382
+ let streamError = null;
3383
+
3384
+ const handleNonStreamLine = (line) => {
3385
+ if (!line.startsWith("data: ")) return;
3386
+ const rawJson = line.slice(6).trim();
3387
+ if (!rawJson || rawJson === "[DONE]") return;
3388
+
3389
+ try {
3390
+ const ev = JSON.parse(rawJson);
3391
+
3392
+ // A 200 followed by an in-stream error is a failure, not an empty
3393
+ // completion. Without this the client would receive content: null
3394
+ // with finish_reason "stop".
3395
+ const inStreamError = extractStreamError(ev);
3396
+ if (inStreamError) {
3397
+ streamError = inStreamError;
3398
+ return;
3399
+ }
3400
+
3401
+ if (useResponses) {
3402
+ if (ev.type === "response.output_text.delta" && ev.delta) {
3403
+ assistantText += ev.delta;
3404
+ } else if (
3405
+ (ev.type === "response.reasoning_summary_text.delta" ||
3406
+ ev.type === "response.reasoning_text.delta" ||
3407
+ ev.type === "response.reasoning.delta") &&
3408
+ ev.delta
3409
+ ) {
3410
+ reasoningText += ev.delta;
3411
+ } else if (ev.type === "response.output_item.added" && ev.item?.type === "function_call") {
3412
+ const key =
3413
+ ev.output_index !== undefined
3414
+ ? String(ev.output_index)
3415
+ : ev.item.call_id || ev.item.id || String(toolCalls.length);
3416
+ const tc = {
3417
+ id: ev.item.call_id || ev.item.id || `call_${toolCalls.length}`,
3418
+ type: "function",
3419
+ function: {
3420
+ name: restoreClientToolName(ev.item.name, aliasToOriginal),
3421
+ arguments: "",
3422
+ },
3423
+ };
3424
+ toolCalls.push(tc);
3425
+ nonStreamToolMap.set(key, tc);
3426
+ if (ev.item.call_id) nonStreamToolMap.set(ev.item.call_id, tc);
3427
+ if (ev.item.id) nonStreamToolMap.set(ev.item.id, tc);
3428
+ if (ev.output_index !== undefined) nonStreamToolMap.set(String(ev.output_index), tc);
3429
+ } else if (ev.type === "response.function_call_arguments.delta" && ev.delta) {
3430
+ const key =
3431
+ ev.output_index !== undefined ? String(ev.output_index) : ev.item_id || ev.call_id;
3432
+ const targetTc =
3433
+ key !== undefined && nonStreamToolMap.has(key)
3434
+ ? nonStreamToolMap.get(key)
3435
+ : toolCalls[toolCalls.length - 1];
3436
+ if (targetTc) targetTc.function.arguments += ev.delta;
3437
+ } else if (ev.type === "response.completed" || ev.type === "response.incomplete") {
3438
+ upstreamFinishReason = extractResponsesFinishReason(ev, toolCalls.length > 0);
3439
+ if (ev.response?.usage) {
3440
+ usage = {
3441
+ prompt_tokens: ev.response.usage.input_tokens || 0,
3442
+ completion_tokens: ev.response.usage.output_tokens || 0,
3443
+ total_tokens: ev.response.usage.total_tokens || 0,
3444
+ };
3445
+ }
3446
+ }
3447
+ } else {
3448
+ // Chat completions format parsing
3449
+ const choice = ev.choices?.[0];
3450
+ if (choice?.finish_reason) {
3451
+ upstreamFinishReason = choice.finish_reason;
3452
+ }
3453
+ const delta = choice?.delta;
3454
+ if (delta?.content) assistantText += delta.content;
3455
+ if (delta?.reasoning) reasoningText += delta.reasoning;
3456
+ else if (delta?.reasoning_content) reasoningText += delta.reasoning_content;
3457
+ if (Array.isArray(delta?.tool_calls)) {
3458
+ for (const tc of delta.tool_calls) {
3459
+ const idx = tc.index ?? toolCalls.length;
3460
+ if (!toolCalls[idx]) {
3461
+ toolCalls[idx] = {
3462
+ id: tc.id || `call_${idx}`,
3463
+ type: "function",
3464
+ function: {
3465
+ name: restoreClientToolName(tc.function?.name || "", aliasToOriginal),
3466
+ arguments: "",
3467
+ },
3468
+ };
3469
+ } else {
3470
+ if (tc.id && toolCalls[idx].id.startsWith("call_")) {
3471
+ toolCalls[idx].id = tc.id;
3472
+ }
3473
+ if (tc.function?.name && !toolCalls[idx].function.name) {
3474
+ toolCalls[idx].function.name = restoreClientToolName(
3475
+ tc.function.name,
3476
+ aliasToOriginal
3477
+ );
3478
+ }
3479
+ }
3480
+ if (tc.function?.arguments) {
3481
+ toolCalls[idx].function.arguments += tc.function.arguments;
3482
+ }
3483
+ }
3484
+ }
3485
+ if (ev.usage && typeof ev.usage === "object") {
3486
+ usage = {
3487
+ prompt_tokens: ev.usage.prompt_tokens || 0,
3488
+ completion_tokens: ev.usage.completion_tokens || 0,
3489
+ total_tokens: ev.usage.total_tokens || 0,
3490
+ };
3491
+ }
3492
+ }
3493
+ } catch {}
3494
+ };
3495
+
3496
+ await consumeSseLines(reader, decoder, handleNonStreamLine);
3497
+
3498
+ if (streamError) {
3499
+ console.warn(`[opencode-free-bridge] Upstream failed inside the stream: ${streamError}`);
3500
+ res.writeHead(502, { "Content-Type": "application/json" });
3501
+ return res.end(
3502
+ JSON.stringify({
3503
+ error: { message: streamError, type: "upstream_error", code: 502 },
3504
+ })
3505
+ );
3506
+ }
3507
+
3508
+ const validToolCalls = toolCalls.filter(Boolean);
3509
+ const messageObj = { role: "assistant", content: assistantText || null };
3510
+ if (reasoningText) messageObj.reasoning_content = reasoningText;
3511
+ if (validToolCalls.length > 0) messageObj.tool_calls = validToolCalls;
3512
+
3513
+ let finishReason = upstreamFinishReason || "stop";
3514
+ if (
3515
+ validToolCalls.length > 0 &&
3516
+ finishReason !== "length" &&
3517
+ finishReason !== "content_filter"
3518
+ ) {
3519
+ finishReason = "tool_calls";
3520
+ }
3521
+
3522
+ res.writeHead(200, { "Content-Type": "application/json" });
3523
+ return res.end(
3524
+ JSON.stringify({
3525
+ id: completionId,
3526
+ object: "chat.completion",
3527
+ created,
3528
+ model: targetModel,
3529
+ choices: [
3530
+ {
3531
+ index: 0,
3532
+ message: messageObj,
3533
+ finish_reason: finishReason,
3534
+ },
3535
+ ],
3536
+ usage,
3537
+ })
3538
+ );
3539
+ } catch (err) {
3540
+ if (reader) {
3541
+ reader.cancel().catch(() => {});
3542
+ }
3543
+ if (clientDisconnected || res.writableEnded) {
3544
+ return;
3545
+ }
3546
+ if (timedOut) {
3547
+ if (!res.headersSent) {
3548
+ res.writeHead(504, { "Content-Type": "application/json" });
3549
+ return res.end(
3550
+ JSON.stringify({
3551
+ error: {
3552
+ message: `Upstream request timed out after ${UPSTREAM_TIMEOUT_MS}ms`,
3553
+ type: "timeout_error",
3554
+ code: 504,
3555
+ },
3556
+ })
3557
+ );
3558
+ }
3559
+ return res.end();
3560
+ }
3561
+ console.error("[opencode-free-bridge] exception:", err);
3562
+ if (!res.headersSent) {
3563
+ res.writeHead(500, { "Content-Type": "application/json" });
3564
+ return res.end(
3565
+ JSON.stringify({
3566
+ error: { message: err.message || "Internal server error", type: "server_error" },
3567
+ })
3568
+ );
3569
+ }
3570
+ return res.end();
3571
+ } finally {
3572
+ clearTimeout(timeoutId);
3573
+ res.off("close", onClose);
3574
+ }
3575
+ })();
3576
+ return;
3577
+ }
3578
+
3579
+ res.writeHead(404, { "Content-Type": "application/json" });
3580
+ res.end(JSON.stringify({ error: { message: "Not found", type: "invalid_request_error" } }));
3581
+ }
3582
+
3583
+ async function consumeSseLines(reader: StreamReader, decoder: TextDecoder, onLine: (line: string) => void): Promise<void> {
3584
+ let buffer = "";
3585
+ while (true) {
3586
+ const { done, value } = await reader.read();
3587
+ if (done) {
3588
+ buffer += decoder.decode();
3589
+ if (buffer.trim()) {
3590
+ let start = 0;
3591
+ for (let i = 0; i < buffer.length; i++) {
3592
+ if (buffer.charCodeAt(i) === 10) {
3593
+ const line =
3594
+ i > start && buffer.charCodeAt(i - 1) === 13
3595
+ ? buffer.slice(start, i - 1)
3596
+ : buffer.slice(start, i);
3597
+ onLine(line);
3598
+ start = i + 1;
3599
+ }
3600
+ }
3601
+ if (start < buffer.length) {
3602
+ const tail = buffer.endsWith("\r") ? buffer.slice(start, -1) : buffer.slice(start);
3603
+ onLine(tail);
3604
+ }
3605
+ }
3606
+ break;
3607
+ }
3608
+ buffer += decoder.decode(value, { stream: true });
3609
+ let start = 0;
3610
+ for (let i = 0; i < buffer.length; i++) {
3611
+ if (buffer.charCodeAt(i) === 10) {
3612
+ const line =
3613
+ i > start && buffer.charCodeAt(i - 1) === 13
3614
+ ? buffer.slice(start, i - 1)
3615
+ : buffer.slice(start, i);
3616
+ onLine(line);
3617
+ start = i + 1;
3618
+ }
3619
+ }
3620
+ buffer = start === 0 ? buffer : buffer.slice(start);
3621
+ }
3622
+ }
3623
+
3624
+ const server = http.createServer(handleRequest);
3625
+
3626
+ // Only auto-start when executed directly (`bun server.ts`), so unit tests can
3627
+ // require("./server") without binding the default port or starting timers.
3628
+ // The transport fingerprint is a property of the HTTP runtime, not of this code.
3629
+ // Measured from one IP in one minute with identical headers and body: the real
3630
+ // CLI and this bridge on Bun both answer 200, while this bridge on Node and curl
3631
+ // answer 403. The CLI ships as a Bun binary, and the gate inspects its
3632
+ // ClientHello. Node therefore cannot serve live traffic, so it is refused at
3633
+ // startup rather than left running and failing every request.
3634
+ const ON_BUN = typeof Bun !== "undefined";
3635
+ const ALLOW_NODE = process.env.ALLOW_NODE === "1";
3636
+
3637
+ function refuseNodeRuntime(): void {
3638
+ const lines = [
3639
+ "",
3640
+ " opencode-free-bridge requires Bun.",
3641
+ "",
3642
+ " This process is Node, whose TLS transport the free-tier gate refuses:",
3643
+ " measured 0/6 requests answered on Node vs 6/6 on Bun, from the same IP,",
3644
+ " in the same minute, with byte-identical headers and body.",
3645
+ "",
3646
+ " The CLI ships as a Bun binary, so only Bun reproduces its transport.",
3647
+ "",
3648
+ " Install Bun: curl -fsSL https://bun.sh/install | bash",
3649
+ " Then run: bun server.js",
3650
+ "",
3651
+ " For offline work (tests, drills, inspecting /v1/models) set ALLOW_NODE=1.",
3652
+ " Live chat requests will still be refused with 403 by upstream.",
3653
+ "",
3654
+ ];
3655
+ console.error(lines.join("\n"));
3656
+ }
3657
+
3658
+ if (require.main === module) {
3659
+ if (!ON_BUN && !ALLOW_NODE) {
3660
+ refuseNodeRuntime();
3661
+ process.exit(1);
3662
+ }
3663
+ server.listen(PORT, HOST, () => {
3664
+ console.log(`[opencode-free-bridge] v${VERSION} listening on http://${HOST}:${PORT}`);
3665
+ if (!ON_BUN) {
3666
+ console.log(
3667
+ "[opencode-free-bridge] WARNING: ALLOW_NODE=1 — running on Node. Real chat requests will " +
3668
+ "be refused by the free-tier gate with 403. This mode is for offline work against a " +
3669
+ "mocked upstream, not for live traffic."
3670
+ );
3671
+ }
3672
+ });
3673
+ // Repair a half-installed tree (an older self-updater that did not know about
3674
+ // proxy.ts/panel.ts) after the socket is open, so a slow or absent network
3675
+ // never delays startup. The panel reads the current binding per request, so
3676
+ // it starts working as soon as the repair lands.
3677
+ repairMissingModules().catch(() => {});
3678
+ // Discovery runs in background: /v1/models is live as soon as upstream
3679
+ // answers. Boot never blocks on network.
3680
+ discoverModels().catch(() => {});
3681
+ // Model list rotates on upstream's schedule, so it keeps a timer. The
3682
+ // IDENTITY does not: it is refreshed lazily from the request path (see
3683
+ // identity.ensureFresh), so an idle bridge makes no network calls at all.
3684
+ setInterval(discoverModels, DISCOVERY_TTL_MS).unref();
3685
+ // Priority-failover recovery: probe one cooling entry per minute so the
3686
+ // highest-priority egress (the renewable phone IP) returns to the top of the
3687
+ // pool as soon as it answers again, instead of only after its cooldown.
3688
+ setInterval(() => proxy.recoveryProbeTick().catch(() => {}), 60_000).unref();
3689
+ }
3690
+
3691
+ module.exports = {
3692
+ VERSION,
3693
+ // Kept for callers and tests written against the old frozen constants. These
3694
+ // are live views of the resolved profile, not snapshots.
3695
+ get FINGERPRINT_TOOL_NAMES() {
3696
+ return getFingerprintNames();
3697
+ },
3698
+ get FINGERPRINT_TOOL_DEFINITIONS() {
3699
+ return getFingerprintDefinitions();
3700
+ },
3701
+ get CANONICAL_TOOLS_CHAT() {
3702
+ return getCanonicalTools(false);
3703
+ },
3704
+ get CANONICAL_TOOLS_RESPONSES() {
3705
+ return getCanonicalTools(true);
3706
+ },
3707
+ MAX_SESSIONS,
3708
+ SESSION_TTL_MS,
3709
+ sessionCache,
3710
+ createId,
3711
+ isValidV2UserAgent,
3712
+ normalizeModel,
3713
+ isResponsesModel,
3714
+ markProtocolSupport,
3715
+ __resetProtocolLanes,
3716
+ extractContent,
3717
+ transformToResponsesInput,
3718
+ transformChatMessages,
3719
+ prepareToolsWithFingerprint,
3720
+ prepareResponsesTools,
3721
+ prepareChatTools,
3722
+ restoreClientToolName,
3723
+ buildUpstreamPayload,
3724
+ isNewerVersion,
3725
+ checkAndApplyUpdate,
3726
+ resolveEndpoints,
3727
+ buildUpstreamHeaders,
3728
+ getProjectId,
3729
+ extractResponsesFinishReason,
3730
+ extractStreamError,
3731
+ getPersistentSessionId,
3732
+ discoverModels,
3733
+ handleRequest,
3734
+ server,
3735
+ shortText,
3736
+ messageSignatureSample,
3737
+ transformResponsesContent,
3738
+ extractSystemInstructions,
3739
+ isLocalOrigin,
3740
+ isFreeTierCliGateError,
3741
+ consumeSseLines,
3742
+ readRequestBody,
3743
+ refreshCliVersion,
3744
+ identity,
3745
+ __getUserAgent: () => currentUserAgent,
3746
+ __syncUserAgent: syncUserAgent,
3747
+ __getGateDiagnostic: () => lastGateDiagnostic,
3748
+ __getLastUpstreamError: () => lastUpstreamError,
3749
+ __auditGateShape: auditGateShape,
3750
+ __retryAfterMs: retryAfterMs,
3751
+ gateSafeUserAgent,
3752
+ DISCOVERY_TTL_MS,
3753
+ CLI_VERSION_TTL_MS,
3754
+ __setLastDiscoveryTime: (v) => { lastDiscoveryTime = v; },
3755
+ __setActiveModels: (m) => {
3756
+ activeModels = Array.isArray(m) ? m : [];
3757
+ rebuildDiscoveryPayloads();
3758
+ },
3759
+ __getDiscoveryState: () => ({ inFlight: !!discoveryInFlight, lastDiscoveryTime, activeModels }),
3760
+ __setLastCliVersionCheckTime: (v) => { lastCliVersionCheckTime = v; },
3761
+ __getCliVersionState: () => ({ lastCliVersionCheckTime }),
3762
+ __setLastUpdateCheck: (v) => { lastUpdateCheck = v; },
3763
+ __localRequires: localRequires,
3764
+ __repairMissingModules: repairMissingModules,
3765
+ __adminRequestError: adminRequestError,
3766
+ };