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/identity.ts ADDED
@@ -0,0 +1,2841 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * identity.ts — adaptive OpenCode CLI identity & security-layer sync.
4
+ *
5
+ * Keeps the bridge aligned with the official OpenCode CLI when upstream adjusts
6
+ * its free-tier gate (User-Agent version floor, session ID format, headers, or
7
+ * core tool fingerprint definitions).
8
+ *
9
+ * How it works:
10
+ * 1. HANDSHAKE — Queries the same update endpoint the OpenCode CLI uses:
11
+ * GET https://opencode.ai/update/api/<channel>/cli/npm?current=<version>
12
+ * -> { version, minimum, metadata: { github: { sha } } }
13
+ * Falls back to GitHub's releases.atom feed if the update API is unreachable.
14
+ *
15
+ * 2. UPDATE MODES (`UPDATE_MODE`):
16
+ * - `reactive` (default): Uses the current identity until upstream rejects a
17
+ * request (403 FreeTierError / 426 UpgradeRequired) or flags `minimum: true`,
18
+ * then refreshes immediately and retries the request once.
19
+ * - `always`: Proactively adopts every new OpenCode release when the lazy
20
+ * TTL expires.
21
+ *
22
+ * 3. SOURCE SYNC — When moving to a new release (or forced by a gate error),
23
+ * fetches the lightweight source files at the release's exact commit SHA
24
+ * to update the session ID recipe, User-Agent template, and `read`/`shell`
25
+ * tool fingerprint schemas. Incomplete parses fall back safely to the last
26
+ * known-good values.
27
+ */
28
+
29
+ const crypto = require("crypto");
30
+ // Identity sync is egress too: the update handshake, GitHub source reads, and
31
+ // the provider catalog all travel through the same proxy the panel configures.
32
+ // `proxy.netFetch` is a thin wrapper over `fetch`, so tests that replace
33
+ // `global.fetch` keep intercepting every call.
34
+ //
35
+ // Loaded tolerantly: a 2.1.0 install updated by its own (older) updater can be
36
+ // missing `proxy.ts`, and identity sync must degrade to direct egress rather
37
+ // than crash the process that would otherwise repair itself.
38
+ let proxy: any;
39
+ try {
40
+ proxy = require("./proxy");
41
+ } catch (err) {
42
+ if (err.code !== "MODULE_NOT_FOUND" || !String(err.message).includes("'./proxy'")) throw err;
43
+ proxy = { netFetch: (url: any, init: any) => fetch(url, init) };
44
+ }
45
+
46
+ // --- Shape interfaces (erasable-only TS; upstream payloads stay `any`) --------
47
+
48
+ interface Recipe {
49
+ channel: string;
50
+ version: string;
51
+ client: string;
52
+ sessionPrefix: string;
53
+ sessionCharset: string;
54
+ sessionLength: number;
55
+ sessionMultiplier: number;
56
+ userAgentTemplate: string;
57
+ chatUrl: string;
58
+ responsesUrl: string;
59
+ modelsUrl: string;
60
+ catalogBase: string;
61
+ headers: string[];
62
+ }
63
+
64
+ interface ToolDef {
65
+ description: string | null;
66
+ parameters: any;
67
+ }
68
+ type ToolProfile = Record<string, ToolDef>;
69
+
70
+ interface ModelFacts {
71
+ reasoning: boolean;
72
+ maxOutput: number | null;
73
+ }
74
+
75
+ interface ExtractedTool {
76
+ name: string;
77
+ description: string | null;
78
+ descriptionFile?: string;
79
+ descriptionVar?: string;
80
+ parameters: any;
81
+ }
82
+
83
+ interface ReleaseInfo {
84
+ version: string | null;
85
+ sha: string | null;
86
+ minimum: boolean;
87
+ active: boolean;
88
+ channel: string;
89
+ source: string;
90
+ resolvedAt: number | null;
91
+ stale: boolean;
92
+ degraded?: string;
93
+ error?: string;
94
+ }
95
+
96
+ interface SourceCacheEntry {
97
+ ref: string;
98
+ extracted: Record<string, any>;
99
+ savedAt?: number;
100
+ }
101
+
102
+ interface ToolOverrides {
103
+ condition: string;
104
+ whenTrueRemove: string[];
105
+ whenTrueAdd: string[];
106
+ whenFalseRemove: string[];
107
+ whenFalseAdd: string[];
108
+ }
109
+
110
+ interface DynamicDescriptionSpec {
111
+ appendPrefix: string[];
112
+ joiner: string;
113
+ itemTemplate: string | null;
114
+ }
115
+
116
+ interface CatalogProjection {
117
+ catalogBase?: string;
118
+ chatUrl?: string;
119
+ responsesUrl?: string;
120
+ modelEndpoints?: Record<string, string>;
121
+ freeModels?: string[];
122
+ catalogVerdicts?: Record<string, string>;
123
+ modelFacts?: Record<string, ModelFacts>;
124
+ modelFamilies?: Record<string, string>;
125
+ fromCache?: boolean;
126
+ }
127
+
128
+ interface RecipeUpdate {
129
+ sessionCharset?: string;
130
+ sessionLength?: number;
131
+ sessionMultiplier?: number;
132
+ sessionPrefix?: string;
133
+ userAgentTemplate?: string;
134
+ headers?: string[];
135
+ optionalHeaders?: string[];
136
+ tools?: ToolProfile;
137
+ toolNames?: string[];
138
+ toolOverrides?: ToolOverrides;
139
+ dynamicDescriptions?: Record<string, DynamicDescriptionSpec>;
140
+ }
141
+
142
+ interface StructParse {
143
+ properties: Record<string, any>;
144
+ required: string[];
145
+ additionalProperties: boolean;
146
+ }
147
+
148
+ interface Endpoints {
149
+ chatUrl: string;
150
+ responsesUrl: string;
151
+ modelsUrl: string;
152
+ catalogBase: string;
153
+ }
154
+
155
+ interface GateContext {
156
+ userAgent?: string;
157
+ client?: string;
158
+ project?: string;
159
+ sessionId?: string;
160
+ }
161
+
162
+ interface GateRejectionResult {
163
+ retry: boolean;
164
+ reason: string;
165
+ status?: number;
166
+ errType?: any;
167
+ terminal?: boolean;
168
+ cooldown?: boolean;
169
+ }
170
+
171
+ const UPDATE_API_BASE =
172
+ process.env.OPENCODE_UPDATE_API_BASE || "https://opencode.ai/update/api";
173
+ const ATOM_URL =
174
+ process.env.OPENCODE_RELEASES_ATOM_URL ||
175
+ "https://github.com/anomalyco/opencode/releases.atom";
176
+ const SOURCE_BASE =
177
+ process.env.OPENCODE_SOURCE_BASE ||
178
+ "https://raw.githubusercontent.com/anomalyco/opencode";
179
+
180
+ const CHANNEL = process.env.OPENCODE_CHANNEL || "latest";
181
+ const ARTIFACT = "cli";
182
+ const DISTRIBUTION = process.env.OPENCODE_DISTRIBUTION || "npm";
183
+
184
+ const IDENTITY_TTL_MS = parseInt(
185
+ process.env.IDENTITY_TTL_MS || String(15 * 60 * 1000),
186
+ 10
187
+ );
188
+ const HANDSHAKE_TIMEOUT_MS = parseInt(
189
+ process.env.HANDSHAKE_TIMEOUT_MS || process.env.IDENTITY_FETCH_TIMEOUT_MS || "6000",
190
+ 10
191
+ );
192
+ const SOURCE_TIMEOUT_MS = parseInt(
193
+ process.env.IDENTITY_SOURCE_TIMEOUT_MS || "8000",
194
+ 10
195
+ );
196
+ const GATE_REFRESH_COOLDOWN_MS = parseInt(
197
+ process.env.GATE_REFRESH_COOLDOWN_MS || "30000",
198
+ 10
199
+ );
200
+
201
+ function getUpdateMode() {
202
+ const mode = (process.env.UPDATE_MODE || "reactive").toLowerCase().trim();
203
+ return mode === "always" ? "always" : "reactive";
204
+ }
205
+
206
+ // Non-tool sources. These are individual files with a stable role, so they are
207
+ // named. The *tool* sources are not: see PLUGIN_DIR below.
208
+ const SOURCE_FILES = Object.freeze({
209
+ identifier: "packages/schema/src/identifier.ts",
210
+ sessionId: "packages/schema/src/session-id.ts",
211
+ app: "packages/core/src/app.ts",
212
+ modelRequest: "packages/core/src/session/model-request.ts",
213
+ });
214
+
215
+ // Every tool the CLI ships is a file in this directory. The list is discovered
216
+ // from the release tree rather than enumerated here: when upstream added
217
+ // `patch.ts`, `mcp-resource.ts`, and `opencode.ts`, a hardcoded list would have
218
+ // kept reading the eleven names it already knew and silently missed the new
219
+ // ones — which is the failure mode this bridge exists to avoid.
220
+ const PLUGIN_DIR = "packages/core/src/tool/plugin";
221
+ // The one wire tool that is not a plugin file: code mode's dispatcher. It is
222
+ // always present when code mode is enabled, and it is the tool the other
223
+ // (codemode: true) tools are reached through.
224
+ const CODEMODE_TOOL_FILE = "packages/core/src/codemode/tool.ts";
225
+ const GITHUB_API = process.env.OPENCODE_GITHUB_API || "https://api.github.com";
226
+ const REPO = process.env.OPENCODE_REPO || "anomalyco/opencode";
227
+
228
+ // The provider/model catalog the real CLI consumes at boot. The `opencode`
229
+ // provider entry carries the inference endpoints (`api` field): today
230
+ // `https://opencode.ai/inference/openai/v1`, formerly `/zen/v1`. Deriving the
231
+ // wire URLs from here made the /zen → /inference migration detectable — the
232
+ // URL is no longer a hardcoded constant.
233
+ const CATALOG_URL = process.env.OPENCODE_CATALOG_URL || "https://models.opencode.ai/api.json";
234
+ // The catalog is what makes model aliases and the free list derivable. Fetching
235
+ // it on every boot would leave a cold-start window where a client's shorthand
236
+ // ("mimo", "deepseek") resolves to nothing. The cache closes that window with
237
+ // the last real catalog this process saw — not with a table of names written by
238
+ // hand, which is what it replaces.
239
+ function getCatalogCacheDir() {
240
+ const raw = process.env.OPENCODE_CACHE_DIR;
241
+ if (raw !== undefined) {
242
+ const trimmed = String(raw).trim();
243
+ if (!trimmed || /^(off|0|false|none)$/i.test(trimmed)) return null;
244
+ return trimmed;
245
+ }
246
+ return require("path").join(require("os").homedir(), ".opencode-free-bridge", "cache");
247
+ }
248
+ function getCatalogCacheFile() {
249
+ const dir = getCatalogCacheDir();
250
+ return dir ? require("path").join(dir, "catalog.json") : null;
251
+ }
252
+ function getSourceCacheFile() {
253
+ const dir = getCatalogCacheDir();
254
+ return dir ? require("path").join(dir, "source-recipe.json") : null;
255
+ }
256
+ const BOOT_FETCH = global.fetch;
257
+ const CATALOG_CACHE_DIR = getCatalogCacheDir();
258
+ const CATALOG_CACHE_FILE = getCatalogCacheFile();
259
+
260
+ const DEFAULT_RECIPE = Object.freeze({
261
+ channel: "latest",
262
+ version: "2.0.32",
263
+ client: "cli",
264
+ sessionPrefix: "ses_",
265
+ sessionCharset: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
266
+ sessionLength: 26,
267
+ sessionMultiplier: 0x1000,
268
+ userAgentTemplate: "opencode/${app.channel}/${app.version}/${app.name}",
269
+ // Wire endpoints, resolved from the upstream model catalog (field `api` of
270
+ // the `opencode` provider). The fallback here matches today's gate; a catalog
271
+ // read at refresh time replaces them, so a path migration upstream is picked
272
+ // up without a bridge release.
273
+ chatUrl: "https://opencode.ai/inference/v1/chat/completions",
274
+ responsesUrl: "https://opencode.ai/inference/v1/responses",
275
+ modelsUrl: "https://opencode.ai/inference/v1/models",
276
+ catalogBase: "https://opencode.ai",
277
+ // The header names upstream's own request builder sets, in its order. This is
278
+ // the fallback when the source read fails, so it must be the complete set —
279
+ // a partial list would silently stop sending a header the gate checks.
280
+ headers: Object.freeze([
281
+ "x-opencode-session-id",
282
+ "x-session-affinity",
283
+ "X-Session-Id",
284
+ "User-Agent",
285
+ "x-opencode-project",
286
+ "x-opencode-session",
287
+ "x-opencode-client",
288
+ ]),
289
+ });
290
+
291
+ const DEFAULT_TOOLS = Object.freeze({
292
+ read: {
293
+ description:
294
+ "Read the contents of a file or directory. Supports text files, images, and PDFs. Images and PDFs are presented directly to the model. Each text line is prefixed by its 1-based line number as <line>: <content>. The prefix is for reference and is not part of the file content. Directory entries are returned one per line. Use offset and limit to read large files or directories in sections. Prefer one larger read over many small slices, and use grep to find specific content in large files.",
295
+ parameters: {
296
+ type: "object",
297
+ properties: {
298
+ path: { type: "string", description: "File or directory to read" },
299
+ offset: {
300
+ type: "integer",
301
+ minimum: 0,
302
+ description: "The line or directory entry to start reading from (1-based)",
303
+ },
304
+ limit: {
305
+ type: "integer",
306
+ minimum: 0,
307
+ description:
308
+ "The maximum number of lines or directory entries to read (defaults to and capped at 2000)",
309
+ },
310
+ },
311
+ required: ["path"],
312
+ additionalProperties: false,
313
+ },
314
+ },
315
+ shell: {
316
+ description:
317
+ "Execute a shell command and return its output. Commands run on Linux using bash. Quote file paths containing spaces or special characters. Prefer dedicated tools over shell commands when possible. When output is large, the full result is saved to a file and a truncated preview is returned. Rely on automatic truncation unless filtering the output is more useful. Commands accept an optional timeout, background commands have no timeout by default. Background commands return immediately, and you will be notified when they complete.",
318
+ parameters: {
319
+ type: "object",
320
+ properties: {
321
+ command: { type: "string", description: "Shell command string to execute" },
322
+ workdir: {
323
+ type: "string",
324
+ description:
325
+ "Working directory to execute the command in. Defaults to the current working directory. When possible, avoid changing directories in the command and set the working directory here instead.",
326
+ },
327
+ timeout: {
328
+ type: "integer",
329
+ minimum: 0,
330
+ description:
331
+ "Timeout in milliseconds. Set to 0 to disable the timeout. Defaults to 120000 for foreground commands. Background commands have no timeout by default.",
332
+ },
333
+ background: {
334
+ type: "boolean",
335
+ description:
336
+ "Run the command in the background and return immediately (useful for dev servers and long-running builds). You do not need to use '&' at the end of the command when using this parameter. You will be notified when it completes. DO NOT poll for completion.",
337
+ },
338
+ },
339
+ required: ["command"],
340
+ additionalProperties: false,
341
+ },
342
+ },
343
+ });
344
+
345
+ const CORE_TOOL_NAMES = ["read", "shell", "bash"];
346
+
347
+ /**
348
+ * Tool names the free-tier gate requires *by name*, independent of what the
349
+ * derived profile happens to contain.
350
+ *
351
+ * Measured against upstream on 2026-10-18 by replaying byte-identical requests
352
+ * from a blocked egress and a clean one, varying one field at a time:
353
+ *
354
+ * - 12 real tools -> 200
355
+ * - the same 12 minus `read` -> 403 FreeTierError
356
+ * - the same 12 minus any other tool -> 200
357
+ * - `read` alone -> 200
358
+ * - `read` + 11 fabricated tools -> 200
359
+ * - a fabricated tool *named* `read` -> 200
360
+ * - the real `read` renamed `read_file` -> 403
361
+ *
362
+ * So the check is the name, not the description or the schema: a made-up
363
+ * `read` with an empty schema passes, a renamed real one fails. That matters
364
+ * here because the profile is derived from upstream's own plugin sources — if
365
+ * upstream renames `read.ts` (or drops it), the derived wire shape loses the
366
+ * anchor and the gate answers with the *same* 403 it uses for an exhausted IP.
367
+ * Without this anchor the bridge would report a per-IP allowance problem while
368
+ * the actual cause is a shape this bridge produced.
369
+ *
370
+ * The shipped definition is used as the fallback, so the anchor survives a
371
+ * profile that no longer carries the name.
372
+ */
373
+ const GATE_ANCHOR_TOOL_NAMES = ["read"];
374
+
375
+ /**
376
+ * Header names the gate requires, independent of what the recipe lists.
377
+ *
378
+ * Measured the same way (clean egress, `read` tool present):
379
+ *
380
+ * - no User-Agent -> 403
381
+ * - `opencode` (no version) -> 403
382
+ * - `Mozilla/5.0 …`, `curl/8.18.0` -> 403
383
+ * - `opencode/9.9.9`, `OpenCode/2.0.32` -> 200
384
+ * - `x-opencode-session` alone -> 200
385
+ * - `x-session-affinity` alone -> 200
386
+ * - `x-opencode-session-id` alone -> 403
387
+ * - no `x-opencode-client`/`-project` -> 200
388
+ *
389
+ * The recipe is derived from upstream's request builder, so it normally lists
390
+ * these. They are pinned anyway because a recipe change that drops one would
391
+ * produce a 403 indistinguishable from a blocked IP.
392
+ */
393
+ const GATE_ANCHOR_HEADER_NAMES = ["user-agent", "x-opencode-session", "x-session-affinity"];
394
+
395
+ let recipe: Recipe = { ...DEFAULT_RECIPE };
396
+ let toolProfile: ToolProfile | null = null;
397
+ let toolProfileSource: string = "default";
398
+ let toolProfileVersion: string = DEFAULT_RECIPE.version;
399
+ // The gate allowlist: tool names upstream accepts. Derived from the tool plugin
400
+ // sources at the release SHA; the wire sends these names (schema is not
401
+ // fingerprinted). Empty = fall back to the tool profile's own key order.
402
+ let toolNames: string[] = [];
403
+ // Per-model route overrides from the provider catalog (model id -> base URL).
404
+ let modelEndpoints: Record<string, string> = {};
405
+ // Free-tier model ids derived from the provider catalog (zero cost, not
406
+ // deprecated). Empty until the first successful catalog read.
407
+ let freeModels: string[] = [];
408
+ // id → "free" | "paid" | "deprecated", straight from the provider catalog.
409
+ let catalogVerdicts: Record<string, string> = {};
410
+ // Kee 2026-11-10: upstream still serves these ids on the free tier while the
411
+ // catalog marks them deprecated. Keep them exposed; a priced entry stays out.
412
+ const FREE_VERDICT_OVERRIDES = Object.freeze(["minimax-m3.1-flash-free"]);
413
+ // catalog family → a free model id in that family (e.g. "nemotron-free").
414
+ let modelFamilies: Record<string, string> = {};
415
+ // id → { reasoning: boolean, maxOutput: number|null } from the catalog.
416
+ let modelFacts: Record<string, ModelFacts> = {};
417
+ // Model-conditional tool swaps read from the release (see extractToolOverrides).
418
+ let toolOverrides: ToolOverrides | null = null;
419
+ // Tool descriptions the CLI extends at request time (see extractDynamicDescriptions).
420
+ let dynamicDescriptions: Record<string, DynamicDescriptionSpec> | null = null;
421
+ // Tool plugin basenames last seen in the release tree. Seeded with the current
422
+ // set so the first refresh works even if the directory listing fails.
423
+ let knownPlugins = [
424
+ "edit",
425
+ "glob",
426
+ "grep",
427
+ "mcp-resource",
428
+ "opencode",
429
+ "patch",
430
+ "question",
431
+ "read",
432
+ "shell",
433
+ "skill",
434
+ "subagent",
435
+ "webfetch",
436
+ "websearch",
437
+ "write",
438
+ ];
439
+ let lastRelease: ReleaseInfo | null = null;
440
+ let lastAvailable: string | null = null;
441
+ let lastCheckTime: number = 0;
442
+ let refreshInFlight: Promise<any> | null = null;
443
+ let refreshInFlightForced: boolean = false;
444
+ let versionFloor: string | null = null;
445
+ let lastRefreshError: string | null = null;
446
+ let lastSourceTag: string | null = null;
447
+ let optionalHeaders: string[] = [];
448
+ let lastForcedRefreshTime: number = 0;
449
+ let stateEpoch: number = 0;
450
+ let refreshGen: number = 0;
451
+ let lastSyncedSource: { ref: string; extracted: Record<string, any>; fetchRef: any } | null = null;
452
+
453
+ function stableStringify(val: any): string {
454
+ if (!val || typeof val !== "object") return JSON.stringify(val);
455
+ if (Array.isArray(val)) return "[" + val.map(stableStringify).join(",") + "]";
456
+ const keys = Object.keys(val).sort();
457
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + stableStringify(val[k])).join(",") + "}";
458
+ }
459
+
460
+ function clampString(value: any, max: number): string | null {
461
+ return typeof value === "string" && value.length > 0 && value.length <= max ? value : null;
462
+ }
463
+
464
+ // --- Version & Handshake Helpers ---------------------------------------------
465
+
466
+ function sortVersions(list: any[]): string[] {
467
+ const seen = new Set();
468
+ return list
469
+ .filter((v) => typeof v === "string" && /^\d+\.\d+\.\d+$/.test(v))
470
+ .filter((v) => (seen.has(v) ? false : (seen.add(v), true)))
471
+ .sort((a, b) => {
472
+ const [a1, a2, a3] = a.split(".").map(Number);
473
+ const [b1, b2, b3] = b.split(".").map(Number);
474
+ return b1 - a1 || b2 - a2 || b3 - a3;
475
+ });
476
+ }
477
+
478
+ function parseVersions(text: any): string[] {
479
+ const found = [];
480
+ const re = /<title>v?(\d+\.\d+\.\d+)<\/title>/gi;
481
+ let m;
482
+ while ((m = re.exec(String(text || ""))) !== null) found.push(m[1]);
483
+ return sortVersions(found);
484
+ }
485
+
486
+ function selectVersion(versions: any): string | null {
487
+ if (!Array.isArray(versions) || versions.length === 0) return null;
488
+ const pinned = process.env.OPENCODE_MAJOR;
489
+ if (pinned && /^\d+$/.test(pinned)) {
490
+ return versions.find((v) => v.split(".")[0] === pinned) || null;
491
+ }
492
+ return versions[0];
493
+ }
494
+
495
+ function compareVersions(a: any, b: any): number {
496
+ const [a1, a2, a3] = String(a).split(".").map(Number);
497
+ const [b1, b2, b3] = String(b).split(".").map(Number);
498
+ if (a1 !== b1) return a1 - b1;
499
+ if (a2 !== b2) return a2 - b2;
500
+ return a3 - b3;
501
+ }
502
+
503
+ function parseVersionFloor(message: any): string | null {
504
+ const m = String(message || "").match(/(\d+\.\d+\.\d+)\s+or newer/i);
505
+ return m ? m[1] : null;
506
+ }
507
+
508
+ function sourceRef(release: any): string {
509
+ if (release && release.sha) return release.sha;
510
+ if (release && release.version) return `v${release.version}`;
511
+ return process.env.OPENCODE_SOURCE_REF || "dev";
512
+ }
513
+
514
+ async function fetchJson(url: string, timeoutMs: number = HANDSHAKE_TIMEOUT_MS): Promise<any> {
515
+ const res = await proxy.netFetch(url, {
516
+ signal: AbortSignal.timeout(timeoutMs),
517
+ headers: { accept: "application/json" },
518
+ });
519
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
520
+ return res.json();
521
+ }
522
+
523
+ async function fetchText(url: string, timeoutMs: number = SOURCE_TIMEOUT_MS): Promise<string> {
524
+ const res = await proxy.netFetch(url, { signal: AbortSignal.timeout(timeoutMs) });
525
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
526
+ return res.text();
527
+ }
528
+
529
+ /**
530
+ * List the `.ts` files in a release directory.
531
+ *
532
+ * The tool plugins are discovered, not enumerated: a hardcoded list keeps
533
+ * working after upstream adds a tool, which means it silently stops covering
534
+ * the release. `raw.githubusercontent.com` cannot list a directory, so this
535
+ * uses the contents API once per refresh; a failure returns an empty list and
536
+ * the caller falls back to the previously known set.
537
+ */
538
+ async function listSourceDir(dir: string, ref: string, timeoutMs: number = SOURCE_TIMEOUT_MS): Promise<string[]> {
539
+ try {
540
+ const res = await proxy.netFetch(
541
+ `${GITHUB_API}/repos/${REPO}/contents/${dir}?ref=${encodeURIComponent(ref)}`,
542
+ { signal: AbortSignal.timeout(timeoutMs), headers: { accept: "application/vnd.github+json" } }
543
+ );
544
+ if (!res.ok) return [];
545
+ const json = await res.json();
546
+ if (!Array.isArray(json)) return [];
547
+ return json
548
+ .filter((e) => e && e.type === "file" && /^[a-z0-9-]+\.ts$/i.test(e.name))
549
+ .map((e) => e.name.replace(/\.ts$/, ""));
550
+ } catch {
551
+ return [];
552
+ }
553
+ }
554
+
555
+ /**
556
+ * Resolve the current authoritative CLI release via OpenCode's update handshake,
557
+ * falling back to the GitHub Atom feed when the update API is unreachable.
558
+ */
559
+ async function resolveRelease(currentVersion: string = recipe.version): Promise<ReleaseInfo> {
560
+ const channel = process.env.OPENCODE_CHANNEL || CHANNEL;
561
+ const url =
562
+ `${UPDATE_API_BASE}/${encodeURIComponent(channel)}/${encodeURIComponent(ARTIFACT)}` +
563
+ `/${encodeURIComponent(DISTRIBUTION)}?current=${encodeURIComponent(currentVersion || "0.0.0")}`;
564
+ try {
565
+ const data = await fetchJson(url, HANDSHAKE_TIMEOUT_MS);
566
+ const version = typeof data?.version === "string" ? data.version : null;
567
+ if (!version) throw new Error("update service returned no version");
568
+ const github = data?.metadata?.github || {};
569
+ const sha =
570
+ typeof github.sha === "string" && /^[0-9a-f]{7,40}$/i.test(github.sha)
571
+ ? github.sha
572
+ : null;
573
+ lastRelease = {
574
+ version,
575
+ sha,
576
+ minimum: data.minimum === true,
577
+ active: data.active !== false,
578
+ channel: data.channel || channel,
579
+ source: "update-api",
580
+ resolvedAt: Date.now(),
581
+ stale: false,
582
+ };
583
+ return lastRelease;
584
+ } catch (primaryErr) {
585
+ try {
586
+ const text = await fetchText(ATOM_URL, HANDSHAKE_TIMEOUT_MS);
587
+ const version = selectVersion(parseVersions(text));
588
+ if (!version) throw new Error("no version found in release feed");
589
+ lastRelease = {
590
+ version,
591
+ sha: null,
592
+ minimum: false,
593
+ active: true,
594
+ channel,
595
+ source: "atom-feed",
596
+ resolvedAt: Date.now(),
597
+ stale: false,
598
+ degraded: `update-api: ${primaryErr.message}`,
599
+ };
600
+ return lastRelease;
601
+ } catch (feedErr) {
602
+ const error = `update-api: ${primaryErr.message}; atom-feed: ${feedErr.message}`;
603
+ if (lastRelease) return { ...lastRelease, stale: true, error };
604
+ return {
605
+ version: null,
606
+ sha: null,
607
+ minimum: false,
608
+ active: true,
609
+ channel,
610
+ source: "none",
611
+ resolvedAt: null,
612
+ stale: true,
613
+ error,
614
+ };
615
+ }
616
+ }
617
+ }
618
+
619
+ // --- Source Extraction (Recipe + Tool Definitions) ---------------------------
620
+
621
+ function interpolateTemplate(str: string, vars: Record<string, any>): string {
622
+ return str.replace(/\$\{([^}]+)\}/g, (_, expr) => {
623
+ const key = expr.trim();
624
+ if (vars[key] !== undefined) return String(vars[key]);
625
+ // `FileSystem.DEFAULT_SEARCH_LIMIT` and friends: take the last segment and
626
+ // look it up in the numeric constants harvested from the source. An
627
+ // expression that still cannot be resolved is left as its own text rather
628
+ // than being turned into a newline — a description that differs from the
629
+ // CLI's by a stray line break is a wire mismatch.
630
+ const tail = key.split(".").pop();
631
+ if (vars[tail] !== undefined) return String(vars[tail]);
632
+ // A date expression is evaluated, not emitted: the CLI sends the current
633
+ // year, so a literal `${new Date().getFullYear()}` would differ from it.
634
+ if (/new Date\(\)\.getFullYear\(\)/.test(key)) return String(new Date().getFullYear());
635
+ return `\${${key}}`;
636
+ });
637
+ }
638
+
639
+ /**
640
+ * Read a balanced `{...}` / `(...)` / `[...]` region starting at `open`.
641
+ * Regexes with lazy quantifiers stop at the first `\n})`, which is how a struct
642
+ * with a multi-line `.annotate({...})` lost the fields after it.
643
+ */
644
+ function readBalanced(source: string, openIndex: number): string | null {
645
+ const open = source[openIndex];
646
+ const close = open === "{" ? "}" : open === "(" ? ")" : "]";
647
+ let depth = 0;
648
+ let quote = null;
649
+ for (let i = openIndex; i < source.length; i++) {
650
+ const ch = source[i];
651
+ if (quote) {
652
+ if (ch === "\\") { i++; continue; }
653
+ if (ch === quote) quote = null;
654
+ continue;
655
+ }
656
+ if (ch === '"' || ch === "'" || ch === "`") { quote = ch; continue; }
657
+ if (ch === open) depth++;
658
+ else if (ch === close) {
659
+ depth--;
660
+ if (depth === 0) return source.slice(openIndex, i + 1);
661
+ }
662
+ }
663
+ return null;
664
+ }
665
+
666
+ // Every source file fetched for the current release, joined. Cross-file schema
667
+ // references are resolved against this when a plugin imports a struct or class
668
+ // from a sibling module.
669
+ let schemaCorpus: string | null = null;
670
+ // Numeric/constant bindings harvested from the corpus, used to interpolate
671
+ // `${...}` inside descriptions.
672
+ let schemaVars: Record<string, any> | null = null;
673
+ // basename → source text, for resolving `Namespace.Struct` references.
674
+ let schemaModules: Map<string, string> | null = null;
675
+
676
+ /** `Schema.Struct({...})` → the full call text, matched by braces. */
677
+ function readStructAt(source: string, indexOfStruct: number): string | null {
678
+ const paren = source.indexOf("(", indexOfStruct);
679
+ if (paren < 0) return null;
680
+ const args = readBalanced(source, paren);
681
+ if (!args) return null;
682
+ return `Schema.Struct${args}`;
683
+ }
684
+
685
+ /**
686
+ * Locate the tool's input schema expression.
687
+ *
688
+ * Three forms upstream uses:
689
+ * 1. `export const Input = Schema.Struct({ ... })`
690
+ * 2. `input: LocationInput` inside `editor.add({...})`, defined above
691
+ * 3. an inline `Schema.Struct({...})` passed as `input:`
692
+ */
693
+ function findInputSchema(source: string): string | null {
694
+ const inlineAt = source.search(/input:\s*Schema\.Struct\s*\(/);
695
+ if (inlineAt >= 0) {
696
+ const structAt = source.indexOf("Schema.Struct", inlineAt);
697
+ const full = readStructAt(source, structAt);
698
+ if (full) return full;
699
+ }
700
+
701
+ const named = source.match(/input:\s*([A-Z][A-Za-z0-9_]*)\b/);
702
+ if (named) {
703
+ // Follow aliasing: `export const Input = LocationInput` where
704
+ // `LocationInput` holds the Struct (read.ts does this).
705
+ let varName = named[1];
706
+ for (let hop = 0; hop < 3; hop++) {
707
+ const decl = source.match(
708
+ new RegExp(`(?:const|export\\s+const)\\s+${varName}\\s*=\\s*(Schema\\.Struct\\s*\\()`)
709
+ );
710
+ if (decl) {
711
+ const structAt = source.indexOf("Schema.Struct", decl.index);
712
+ const full = readStructAt(source, structAt);
713
+ if (full) return full;
714
+ }
715
+ const alias = source.match(
716
+ new RegExp(`(?:const|export\\s+const)\\s+${varName}\\s*=\\s*([A-Z][A-Za-z0-9_]*)\\b`)
717
+ );
718
+ if (!alias) break;
719
+ varName = alias[1];
720
+ }
721
+ }
722
+
723
+ const exportedAt = source.search(/export\s+const\s+Input\s*=\s*Schema\.Struct\s*\(/);
724
+ if (exportedAt >= 0) {
725
+ const structAt = source.indexOf("Schema.Struct", exportedAt);
726
+ return readStructAt(source, structAt);
727
+ }
728
+ return null;
729
+ }
730
+
731
+ /** Split a `{ a: x, b: y }` body at top-level commas (ignores nested braces,
732
+ * brackets, parens, strings, and template literals). */
733
+ function splitTopLevel(body: string): string[] {
734
+ const parts = [];
735
+ let depth = 0;
736
+ let start = 0;
737
+ let quote = null;
738
+ for (let i = 0; i < body.length; i++) {
739
+ const ch = body[i];
740
+ if (quote) {
741
+ if (ch === "\\") { i++; continue; }
742
+ if (ch === quote) quote = null;
743
+ continue;
744
+ }
745
+ if (ch === '"' || ch === "'" || ch === "`") { quote = ch; continue; }
746
+ if (ch === "{" || ch === "[" || ch === "(") depth++;
747
+ else if (ch === "}" || ch === "]" || ch === ")") depth--;
748
+ else if (ch === "," && depth === 0) {
749
+ parts.push(body.slice(start, i));
750
+ start = i + 1;
751
+ }
752
+ }
753
+ if (start < body.length) parts.push(body.slice(start));
754
+ return parts.map((p) => p.trim()).filter(Boolean);
755
+ }
756
+
757
+ /** Undo the escapes that carry meaning in a description string. */
758
+ function unescapeLiteral(text: any): any {
759
+ if (typeof text !== "string") return text;
760
+ // A single left-to-right pass, so each escape is consumed exactly once.
761
+ // Doing the replacements sequentially mangled `\\n` (an escaped backslash
762
+ // followed by `n`, i.e. the two characters `\n`) into backslash + newline.
763
+ return text.replace(/\\(r\\n|n|t|"|'|`|\\)/g, (_, seq) => {
764
+ switch (seq) {
765
+ case "r\n":
766
+ case "n":
767
+ return "\n";
768
+ case "t":
769
+ return "\t";
770
+ case '"':
771
+ return '"';
772
+ case "'":
773
+ return "'";
774
+ case "`":
775
+ return "`";
776
+ case "\\":
777
+ return "\\";
778
+ default:
779
+ return seq;
780
+ }
781
+ });
782
+ }
783
+
784
+ /** Read a JS string/template literal body and unescape it. */
785
+ function readStringLiteral(raw: any): string | null {
786
+ if (typeof raw !== "string") return null;
787
+ const m = raw.match(/^\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|`((?:[^`\\]|\\.)*)`)/s);
788
+ if (!m) return null;
789
+ const text = m[1] !== undefined ? m[1] : m[2] !== undefined ? m[2] : m[3];
790
+ return unescapeLiteral(text);
791
+ }
792
+
793
+ /**
794
+ * Evaluate one field's schema expression into a JSON Schema fragment plus its
795
+ * requiredness. This understands the constructors upstream uses and nothing
796
+ * else; anything unrecognised degrades to `{ type: "string" }`.
797
+ */
798
+ function parseFieldSchema(expr: string, source: string): { required: boolean; schema: any } {
799
+ let required = true;
800
+ let schema = {};
801
+
802
+ // Unwrap modifiers, outermost first.
803
+ let working = expr.trim();
804
+ const optional =
805
+ /Schema\.optionalKey\(/.test(working) ||
806
+ /Schema\.optional\(/.test(working) ||
807
+ // A decoding default makes the field omittable on the wire even though the
808
+ // schema itself is not wrapped in optionalKey (webfetch's `format`).
809
+ /withDecodingDefault(Key)?\(/.test(working) ||
810
+ // `.pipe(optional)` / `.pipe(Schema.optional)` — the shared `optional`
811
+ // helper in packages/schema/src/schema.ts.
812
+ /\.pipe\(\s*(?:Schema\.)?optional\b/.test(working);
813
+ if (optional) required = false;
814
+
815
+ // Description and constraints are collected first, then applied in the order
816
+ // the CLI emits them (`type`, bounds, `description`) — the wire body is
817
+ // compared by upstream, so key order is part of matching it exactly.
818
+ let description = null;
819
+ const annotate = working.match(/\.annotate\(\{\s*description:\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)/s);
820
+ if (annotate) {
821
+ description = readStringLiteral(annotate[1]);
822
+ if (description && schemaVars) description = interpolateTemplate(description, schemaVars);
823
+ // Where the annotation sits relative to `.pipe(...)` decides whether it
824
+ // reaches the wire: `Schema.X.annotate({...}).pipe(...)` keeps it (webfetch's
825
+ // `format`), while `Schema.X.pipe(...).annotate({...})` does not (question's
826
+ // `multiple`). Compare positions rather than the mere presence of a pipe.
827
+ const pipeAt = working.indexOf(".pipe(");
828
+ const annotateAt = working.indexOf(".annotate(");
829
+ if (pipeAt >= 0 && annotateAt > pipeAt) description = null;
830
+ }
831
+
832
+ // Base type, from the innermost constructor. A local alias
833
+ // (`const Timeout = Schema.Finite.check(...)`) is expanded first so both the
834
+ // type and the constraints can be read from what it actually is.
835
+ let core = working
836
+ .replace(/Schema\.optionalKey\(/g, "(")
837
+ .replace(/Schema\.optional\(/g, "(");
838
+ let expanded = core;
839
+ const aliasMatch = core.match(/^\s*\(?\s*([A-Z][A-Za-z0-9_]*)\b/);
840
+ // Only a *local* alias is expanded: not `Schema` itself, and not a name that
841
+ // is a struct/class reference (`Question.Prompt`, `FileSystem.GlobInput`).
842
+ const isLocalAlias =
843
+ aliasMatch &&
844
+ aliasMatch[1] !== "Schema" &&
845
+ !/\./.test(core.slice(aliasMatch.index + aliasMatch[0].length).trim().slice(0, 1)) &&
846
+ schemaCorpus &&
847
+ new RegExp(`const\\s+${aliasMatch[1]}\\s*=\\s*Schema\\.`).test(schemaCorpus);
848
+ if (isLocalAlias) {
849
+ const decl = schemaCorpus.match(new RegExp(`const\\s+${aliasMatch[1]}\\s*=\\s*([^\\n]+)`));
850
+ if (decl) {
851
+ expanded = `${decl[1]} ${core}`;
852
+ core = expanded;
853
+ }
854
+ }
855
+
856
+ const constraints = {};
857
+ const minLength = working.match(/\.check\(\s*Schema\.isMinLength\(\s*(\d+)/);
858
+ if (minLength) constraints.minLength = Number(minLength[1]);
859
+ const maxLength = working.match(/\.check\(\s*Schema\.isMaxLength\(\s*(\d+)/);
860
+ if (maxLength) constraints.maxLength = Number(maxLength[1]);
861
+ if (/\.check\(\s*Schema\.isNonEmpty\(\)/.test(expanded)) constraints.minItems = 1;
862
+ if (/\.check\([^)]*Schema\.isGreaterThan\(\s*0\s*\)/.test(expanded)) constraints.exclusiveMinimum = 0;
863
+ const maxValue = expanded.match(/\.check\(\s*Schema\.isLessThanOrEqualTo\(\s*(\d+)/);
864
+ if (maxValue) constraints.maximum = Number(maxValue[1]);
865
+ // `Timeout` carries its ceiling in a named constant.
866
+ if (/^\s*(?:Schema\.optionalKey\()?\s*Timeout\b/.test(working) && schemaVars && Number.isFinite(schemaVars.MAX_TIMEOUT_SECONDS)) {
867
+ constraints.maximum = schemaVars.MAX_TIMEOUT_SECONDS;
868
+ }
869
+
870
+ if (/Schema\.Literals\(\s*\[([^\]]*)\]/.test(core)) {
871
+ const list = core.match(/Schema\.Literals\(\s*\[([^\]]*)\]/)[1];
872
+ const values = [...list.matchAll(/("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g)].map((m) =>
873
+ readStringLiteral(m[1])
874
+ );
875
+ schema = { ...schema, type: "string", enum: values };
876
+ } else if (/Schema\.Array\(/.test(core)) {
877
+ const inner = core.match(/Schema\.Array\(([\s\S]*)\)/);
878
+ const itemExpr = inner ? inner[1] : "";
879
+ // A nested Struct becomes an object schema with its own fields.
880
+ const struct = itemExpr.match(/Schema\.Struct\(\{([\s\S]*)\n\s*\}\)/);
881
+ if (struct) {
882
+ const nested = parseStructBody(struct[1], source);
883
+ schema = { ...schema, type: "array", items: { type: "object", ...nested } };
884
+ } else if (/\.fields\.[a-zA-Z]/.test(itemExpr)) {
885
+ // `SomeClass.fields.x` — a single field, not a struct.
886
+ const ref = itemExpr.match(/^\s*([A-Za-z][A-Za-z0-9_.]*)/);
887
+ const resolved = ref ? resolveStructRef(ref[1], source) : null;
888
+ schema = { ...schema, type: "array", items: resolved || { type: "string" } };
889
+ } else {
890
+ // `Schema.Array(Question.Prompt)` — a named struct/class.
891
+ const ref = itemExpr.match(/^\s*([A-Za-z][A-Za-z0-9_.]*)/);
892
+ const resolved = ref ? resolveStructRef(ref[1], source) : null;
893
+ schema = { ...schema, type: "array", items: resolved || { type: "string" } };
894
+ }
895
+ } else if (/\bBoolean\b/.test(core)) {
896
+ schema = { ...schema, type: "boolean" };
897
+ } else if (/\bPositiveInt\b/.test(core)) {
898
+ schema = { ...schema, type: "integer", exclusiveMinimum: 0 };
899
+ } else if (/\bNonNegativeInt\b/.test(core)) {
900
+ schema = { ...schema, type: "integer", minimum: 0 };
901
+ } else if (/Schema\.(?:Int|Number|Finite)\b/.test(core)) {
902
+ schema = { ...schema, type: "number" };
903
+ } else if (/\bSession[A-Za-z]*\.ID\b/.test(core) || /\bSessionID\b/.test(core)) {
904
+ schema = { ...schema, type: "string", pattern: "^ses" };
905
+ } else if (/\.fields\.[A-Za-z0-9_]+/.test(core)) {
906
+ // A field borrowed from a shared struct: `PageInput.fields.offset`,
907
+ // `ReadToolFileSystem.PageInput.fields.limit`, `GlobInput.fields.hidden`.
908
+ // The field's type AND optionality live on the source struct, so resolve it
909
+ // there rather than inferring from the name. `ReadToolFileSystem` is a
910
+ // namespace import, so the struct is the segment right before `.fields`.
911
+ const ref = core.match(/([A-Z][A-Za-z0-9_]*)\.fields\.([A-Za-z0-9_]+)/);
912
+ const resolved = ref ? resolveStructField(ref[1], ref[2], source) : null;
913
+ if (resolved) {
914
+ schema = { ...resolved.schema, ...schema };
915
+ if (resolved.optional) required = false;
916
+ } else {
917
+ // Unresolvable (no corpus for this reference). The page fields are the
918
+ // common case: offset/limit on read. Guessing their real shape is better
919
+ // than emitting `string` + required, which would be a worse wire match
920
+ // than the previous behaviour and would also mark them mandatory.
921
+ const field = ref ? ref[2] : "";
922
+ if (/^(offset|limit)$/.test(field)) {
923
+ schema = { ...schema, type: "integer", minimum: 0 };
924
+ required = false;
925
+ } else if (/^(hidden|literal|caseSensitive|background)$/.test(field)) {
926
+ schema = { ...schema, type: "boolean" };
927
+ } else {
928
+ schema = { ...schema, type: "string" };
929
+ }
930
+ }
931
+ } else {
932
+ schema = { ...schema, type: "string" };
933
+ }
934
+
935
+ // `Timeout` is a branded number with a maximum, used by webfetch. Only apply
936
+ // it when the expression IS that brand — `NonNegativeInt` also appears in
937
+ // shell's timeout field, and matching any occurrence changed its type.
938
+ if (/^\s*(?:Schema\.optionalKey\()?\s*Timeout\b/.test(core)) {
939
+ schema = { ...schema, type: "number", exclusiveMinimum: 0 };
940
+ }
941
+
942
+ // Assemble in wire order: type → constraints → description. `description`
943
+ // first would emit a different key order than the CLI's own JSON Schema.
944
+ const merged = { ...schema, ...constraints };
945
+ const ordered = {};
946
+ for (const k of ["type", "minLength", "maxLength", "minimum", "exclusiveMinimum", "maximum", "pattern", "enum", "items", "minItems"]) {
947
+ if (merged[k] !== undefined) ordered[k] = merged[k];
948
+ }
949
+ if (description) ordered.description = description;
950
+
951
+ return { required, schema: ordered };
952
+ }
953
+
954
+ /** `Schema.Struct({...})` body → { properties, required, additionalProperties }. */
955
+ function parseStructBody(body: string, source: string): StructParse {
956
+ const properties = {};
957
+ const required = [];
958
+ for (const part of splitTopLevel(body)) {
959
+ const m = part.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*([\s\S]+)$/);
960
+ if (!m) continue;
961
+ const [, key, expr] = m;
962
+ const { required: isRequired, schema } = parseFieldSchema(expr, source);
963
+ properties[key] = schema;
964
+ if (isRequired) required.push(key);
965
+ }
966
+ return { properties, required, additionalProperties: false };
967
+ }
968
+
969
+ function parseSchemaExpr(expr: any, source: string): StructParse | null {
970
+ const text = String(expr);
971
+ const structAt = text.indexOf("Schema.Struct");
972
+ if (structAt < 0) return null;
973
+ const paren = text.indexOf("(", structAt);
974
+ const args = readBalanced(text, paren);
975
+ if (!args) return null;
976
+
977
+ // `Schema.Struct({ ... })` — literal fields.
978
+ const brace = args.indexOf("{");
979
+ if (brace >= 0) {
980
+ const body = readBalanced(args, brace);
981
+ if (body) return parseStructBody(body.slice(1, -1), source);
982
+ }
983
+
984
+ // `Schema.Struct(base)` — the fields live in a named object literal declared
985
+ // above (`const base = { ... }`), which is how Question.Prompt is written.
986
+ const ref = args.slice(1, -1).trim().match(/^([A-Za-z_$][\w$]*)$/);
987
+ if (ref) {
988
+ const at = source.search(new RegExp(`const\\s+${ref[1]}\\s*=\\s*\\{`));
989
+ if (at >= 0) {
990
+ const objBrace = source.indexOf("{", at);
991
+ const body = readBalanced(source, objBrace);
992
+ if (body) return parseStructBody(body.slice(1, -1), source);
993
+ }
994
+ }
995
+ return null;
996
+ }
997
+
998
+ /** Resolve `Question.Prompt` to the `Prompt` struct declared in the same file. */
999
+ function resolveStructRef(name: string, source: string): any {
1000
+ const parts = String(name).split(".");
1001
+ const short = parts.pop();
1002
+ // For `Question.Prompt`, prefer the file that defines the `Question` module:
1003
+ // the joined corpus contains many unrelated `Prompt` declarations, and taking
1004
+ // the first match resolved to a different struct entirely.
1005
+ if (parts.length > 0 && schemaModules) {
1006
+ const namespace = parts[parts.length - 1];
1007
+ const mod = schemaModules.get(namespace);
1008
+ if (mod) {
1009
+ // Resolve the struct inside that module only. Recursing with `short`
1010
+ // would re-enter this function with no namespace and fall back to the
1011
+ // joined corpus, which is what produced the wrong struct.
1012
+ const at = mod.search(
1013
+ new RegExp(`(?:const|export\\s+const)\\s+${short}\\s*=\\s*Schema\\.Struct\\s*\\(`)
1014
+ );
1015
+ if (at >= 0) {
1016
+ const structAt = mod.indexOf("Schema.Struct", at);
1017
+ const parsed = parseSchemaExpr(mod.slice(structAt, structAt + 6000), mod);
1018
+ if (parsed) return { type: "object", ...parsed };
1019
+ }
1020
+ }
1021
+ }
1022
+ const at = source.search(new RegExp(`(?:const|export\\s+const)\\s+${short}\\s*=\\s*Schema\\.Struct\\s*\\(`));
1023
+ if (at < 0 && typeof schemaCorpus === "string" && schemaCorpus !== source) {
1024
+ return resolveStructRef(short, schemaCorpus);
1025
+ }
1026
+ if (at < 0) return null;
1027
+ const structAt = source.indexOf("Schema.Struct", at);
1028
+ const parsed = parseSchemaExpr(source.slice(structAt, structAt + 4000), source);
1029
+ if (!parsed) return null;
1030
+ return { type: "object", ...parsed };
1031
+ }
1032
+
1033
+ /**
1034
+ * Resolve `SomeStruct.fields.name` from the struct that declares it.
1035
+ *
1036
+ * The struct may be a `const X = Schema.Struct({...})` or a
1037
+ * `class X extends Schema.Class<X>(...)({...})`, and it may live in a module the
1038
+ * plugin imports rather than in the plugin itself — `read.ts` refers to
1039
+ * `ReadToolFileSystem.PageInput`, declared in `read-filesystem.ts`.
1040
+ */
1041
+ function resolveStructField(structName: string, field: string, source: string): { schema: any; optional: boolean } | null {
1042
+ for (const corpus of [source, typeof schemaCorpus === "string" ? schemaCorpus : null]) {
1043
+ if (!corpus) continue;
1044
+ for (const part of structFields(structName, corpus)) {
1045
+ const m = part.match(new RegExp(`^${field}\\s*:\\s*([\\s\\S]+)$`));
1046
+ if (!m) continue;
1047
+ const parsed = parseFieldSchema(m[1], corpus);
1048
+ return { schema: parsed.schema, optional: !parsed.required };
1049
+ }
1050
+ }
1051
+ return null;
1052
+ }
1053
+
1054
+ /** The field list of a struct/class declaration, wherever it appears. */
1055
+ function structFields(structName: string, corpus: string): string[] {
1056
+ const out = [];
1057
+ // const X = Schema.Struct({ ... })
1058
+ const constAt = corpus.search(
1059
+ new RegExp(`(?:const|export\\s+const)\\s+${structName}\\s*=\\s*Schema\\.Struct\\s*\\(`)
1060
+ );
1061
+ if (constAt >= 0) {
1062
+ const structAt = corpus.indexOf("Schema.Struct", constAt);
1063
+ const args = readBalanced(corpus, corpus.indexOf("(", structAt));
1064
+ const brace = args ? args.indexOf("{") : -1;
1065
+ const body = brace >= 0 ? readBalanced(args, brace) : null;
1066
+ if (body) out.push(...splitTopLevel(body.slice(1, -1)));
1067
+ }
1068
+ // class X extends Schema.Class<X>("...")({ ... })
1069
+ const classAt = corpus.search(new RegExp(`class\\s+${structName}\\b`));
1070
+ if (classAt >= 0) {
1071
+ const paren = corpus.indexOf("(", classAt);
1072
+ const first = paren >= 0 ? readBalanced(corpus, paren) : null;
1073
+ if (first) {
1074
+ const after = corpus.indexOf("(", paren + first.length);
1075
+ const second = after >= 0 ? readBalanced(corpus, after) : null;
1076
+ const brace = second ? second.indexOf("{") : -1;
1077
+ const body = brace >= 0 ? readBalanced(second, brace) : null;
1078
+ if (body) out.push(...splitTopLevel(body.slice(1, -1)));
1079
+ }
1080
+ }
1081
+ return out;
1082
+ }
1083
+
1084
+ /**
1085
+ * Extract a single tool's wire definition (`description` + JSON Schema `parameters`)
1086
+ * directly from its TypeScript plugin source (`read.ts` or `shell.ts`).
1087
+ */
1088
+ function extractToolFromSource(source: any, fallbackName: string | null): ExtractedTool | null {
1089
+ if (typeof source !== "string" || !source.trim()) return null;
1090
+
1091
+ const nameMatch = source.match(/export\s+const\s+name\s*=\s*"([a-z][a-z0-9_-]*)"/i);
1092
+ const name = nameMatch ? nameMatch[1] : fallbackName;
1093
+ if (!name) return null;
1094
+
1095
+ const vars = { OS: "Linux", shell: "bash" };
1096
+ // Constants declared in the corpus (including imported modules) so template
1097
+ // interpolation can resolve `FileSystem.DEFAULT_SEARCH_LIMIT`.
1098
+ const corpusForVars = typeof schemaCorpus === "string" ? `${source}\n${schemaCorpus}` : source;
1099
+ for (const m of corpusForVars.matchAll(/const\s+([A-Z][A-Z0-9_]*)\s*=\s*([0-9][0-9_*\s+]*)/g)) {
1100
+ const clean = m[2].replace(/_/g, "").trim();
1101
+ if (/^[0-9*\s+]+$/.test(clean)) {
1102
+ const val = clean
1103
+ .split("+")
1104
+ .map((part) => part.split("*").reduce((acc, n) => acc * Number(n.trim()), 1))
1105
+ .reduce((a, b) => a + b, 0);
1106
+ if (Number.isFinite(val)) vars[m[1]] = val;
1107
+ }
1108
+ }
1109
+
1110
+ // A description can live in a sibling `.txt` file (`patch.ts` does this:
1111
+ // `import DESCRIPTION from "../patch.txt"`). The extractor cannot read a file
1112
+ // it was not given, so it reports the reference and the refresh fetches it.
1113
+ const txtImport = source.match(/import\s+([A-Za-z_$][\w$]*)\s+from\s+"(\.\.?\/[^"]+\.txt)"/);
1114
+
1115
+ // 1. Tool description. Three upstream forms:
1116
+ // (a) array literal (optionally inside an arrow fn) joined with " " or "\n"
1117
+ // (b) exported template/string literal
1118
+ // (c) a `description` key inside `editor.add({ ... })`
1119
+ let description = null;
1120
+ const builderMatch = source.match(
1121
+ /const\s+description\s*=\s*(?:\([^)]*\)\s*=>\s*)?\[([\s\S]*?)\]\.join\(\s*(?:"([^"]*)"|'([^']*)')\s*\)/m
1122
+ );
1123
+ const litRe = /"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|`((?:[^`\\]|\\.)*)`/g;
1124
+ if (builderMatch) {
1125
+ // Groups are the joiner's *contents* (`" "` gives ` `, `"\n"` gives `\n`).
1126
+ const rawJoiner = builderMatch[2] !== undefined ? builderMatch[2] : builderMatch[3];
1127
+ const joiner = String(rawJoiner === undefined ? " " : rawJoiner).replace(/\\n/g, "\n");
1128
+ const parts = [];
1129
+ let lm;
1130
+ while ((lm = litRe.exec(builderMatch[1])) !== null) {
1131
+ const raw =
1132
+ lm[1] !== undefined
1133
+ ? unescapeLiteral(lm[1])
1134
+ : interpolateTemplate(unescapeLiteral(lm[2] !== undefined ? lm[2] : lm[3] || ""), vars);
1135
+ // An empty literal is a deliberate blank line in the joined description
1136
+ // (`skill` separates its paragraphs that way); dropping it shortened the
1137
+ // text by one newline against the CLI's.
1138
+ parts.push(raw);
1139
+ }
1140
+ if (parts.length > 0) description = parts.join(joiner);
1141
+ } else {
1142
+ // Multi-line template literal. The closing backtick must be an *unescaped*
1143
+ // one: a description that quotes code (`` \`multiple: true\` ``) contains
1144
+ // escaped backticks, and a lazy match stopped at the first of those.
1145
+ const tpl = source.match(/export\s+const\s+description\s*=\s*`((?:[^`\\]|\\.)*)`/s);
1146
+ if (tpl) description = interpolateTemplate(unescapeLiteral(tpl[1]), vars);
1147
+ else {
1148
+ const dq = source.match(/export\s+const\s+description\s*=\s*"((?:[^"\\]|\\.)*)"/m);
1149
+ const sq = source.match(/export\s+const\s+description\s*=\s*'((?:[^'\\]|\\.)*)'/m);
1150
+ if (dq) description = unescapeLiteral(dq[1]);
1151
+ else if (sq) description = interpolateTemplate(unescapeLiteral(sq[1]), vars);
1152
+ }
1153
+ }
1154
+ if (!description || description.length < 20) {
1155
+ const addBlock0 = source.match(/editor\.add\(\{([\s\S]*?)\binput\s*:/);
1156
+ if (addBlock0) {
1157
+ const descMatch0 = addBlock0[1].match(
1158
+ /description\s*:\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|`((?:[^`\\]|\\.)*)`)/
1159
+ );
1160
+ if (descMatch0) {
1161
+ description =
1162
+ descMatch0[1] !== undefined
1163
+ ? unescapeLiteral(descMatch0[1])
1164
+ : interpolateTemplate(
1165
+ unescapeLiteral(descMatch0[2] !== undefined ? descMatch0[2] : descMatch0[3] || ""),
1166
+ vars
1167
+ );
1168
+ }
1169
+ }
1170
+ }
1171
+ if ((!description || description.length < 20) && txtImport) {
1172
+ return {
1173
+ name,
1174
+ description: null,
1175
+ descriptionFile: txtImport[2],
1176
+ descriptionVar: txtImport[1],
1177
+ parameters: null,
1178
+ };
1179
+ }
1180
+ if (!description || description.length < 20) {
1181
+ // A substituted literal from the sibling `.txt` is a plain string, not an
1182
+ // `export const description = ...`, so read it from the add block.
1183
+ const fromAdd = source.match(/description\s*:\s*"((?:[^"\\]|\\.){20,})"/);
1184
+ if (fromAdd) description = fromAdd[1].replace(/\\n/g, "\n");
1185
+ }
1186
+ if (!description || description.length < 20) return null;
1187
+
1188
+ // 2. The input schema. Upstream writes these as Effect Schema expressions,
1189
+ // and the shape that reaches the wire is the JSON Schema derived from
1190
+ // them. Rather than pattern-match each form, this parses the field list and
1191
+ // evaluates the small, closed set of constructors upstream actually uses:
1192
+ // Schema.String / Number / Int / Boolean / Array / Literals / Struct,
1193
+ // optionalKey, annotate (description), check (minLength), and the shared
1194
+ // class fields (`FileSystem.GlobInput.fields.hidden`). A construct it does
1195
+ // not recognise becomes a plain string — the previous behaviour — but the
1196
+ // recognised ones now carry their real type, enum, bounds, and requiredness.
1197
+ const inputExpr = findInputSchema(source);
1198
+ if (!inputExpr) return null;
1199
+ const parsed = parseSchemaExpr(inputExpr, source);
1200
+ if (!parsed || Object.keys(parsed.properties).length === 0) return null;
1201
+ const { properties, required } = parsed;
1202
+
1203
+ return {
1204
+ name,
1205
+ description,
1206
+ parameters: {
1207
+ type: "object",
1208
+ properties,
1209
+ required,
1210
+ additionalProperties: false,
1211
+ },
1212
+ };
1213
+ }
1214
+
1215
+ /**
1216
+ * Resolve wire endpoints from the upstream provider catalog.
1217
+ *
1218
+ * The catalog is the same file the real CLI reads at boot
1219
+ * (`models.opencode.ai/api.json`). Its `opencode` provider entry carries the
1220
+ * live inference base URLs — this is how the /zen/v1 → /inference/v1 migration
1221
+ * would have been surfaced without a bridge release. Every resolved URL is
1222
+ * sanity-checked before adoption; a malformed catalog changes nothing.
1223
+ */
1224
+ function readCachedCatalog(): any {
1225
+ try {
1226
+ const file = getCatalogCacheFile();
1227
+ if (!file) return null;
1228
+ const fs = require("fs");
1229
+ const raw = fs.readFileSync(file, "utf8");
1230
+ const parsed = JSON.parse(raw);
1231
+ // A cached catalog is only useful if it is structurally a catalog.
1232
+ if (parsed && typeof parsed === "object" && parsed.opencode) return parsed;
1233
+ } catch {}
1234
+ return null;
1235
+ }
1236
+
1237
+ /**
1238
+ * The catalog fields this bridge actually reads.
1239
+ *
1240
+ * Upstream's `api.json` is ~6.5 MB, nearly all of it pricing tables, modalities
1241
+ * and release metadata no code path here touches. Parsing it at every boot cost
1242
+ * ~40 ms of the ~80 ms cold start, so the disk cache keeps only the projection
1243
+ * `parseCatalogData` consumes — still shaped like a catalog (`opencode.models`)
1244
+ * so `readCachedCatalog`/`parseCatalogData` need no second format, and a cache
1245
+ * written by an older build (the full document) still loads unchanged.
1246
+ */
1247
+ function compactCatalog(json: any): any {
1248
+ const oc = json?.opencode;
1249
+ if (!oc || typeof oc !== "object" || !oc.models || typeof oc.models !== "object") return json;
1250
+ const models = {};
1251
+ for (const [id, m] of Object.entries(oc.models)) {
1252
+ models[id] = {
1253
+ cost: { input: m?.cost?.input, output: m?.cost?.output },
1254
+ status: m?.status,
1255
+ tool_call: m?.tool_call,
1256
+ reasoning: m?.reasoning,
1257
+ limit: { output: m?.limit?.output },
1258
+ family: m?.family,
1259
+ provider: { api: m?.provider?.api, npm: m?.provider?.npm },
1260
+ };
1261
+ }
1262
+ return { opencode: { api: oc.api, npm: oc.npm, models } };
1263
+ }
1264
+
1265
+ function writeCachedCatalog(json: any): void {
1266
+ try {
1267
+ const dir = getCatalogCacheDir();
1268
+ const file = getCatalogCacheFile();
1269
+ if (!dir || !file) return;
1270
+ const fs = require("fs");
1271
+ fs.mkdirSync(dir, { recursive: true });
1272
+ const tmp = `${file}.tmp.${process.pid}`;
1273
+ fs.writeFileSync(tmp, JSON.stringify(compactCatalog(json)));
1274
+ fs.renameSync(tmp, file);
1275
+ } catch {
1276
+ // A read-only home directory must not break the bridge; the fetch still
1277
+ // worked, this process just will not have a warm start next time.
1278
+ }
1279
+ }
1280
+
1281
+ function readCachedSource(expectedRef: string | null = null): SourceCacheEntry | null {
1282
+ try {
1283
+ const file = getSourceCacheFile();
1284
+ if (!file) return null;
1285
+ const fs = require("fs");
1286
+ const raw = fs.readFileSync(file, "utf8");
1287
+ const parsed = JSON.parse(raw);
1288
+ if (
1289
+ parsed &&
1290
+ typeof parsed === "object" &&
1291
+ typeof parsed.ref === "string" &&
1292
+ parsed.extracted &&
1293
+ typeof parsed.extracted === "object"
1294
+ ) {
1295
+ if (expectedRef && parsed.ref !== expectedRef) return null;
1296
+ return parsed;
1297
+ }
1298
+ } catch {}
1299
+ return null;
1300
+ }
1301
+
1302
+ function writeCachedSource(ref: string, extracted: any): void {
1303
+ if (!ref || !extracted || typeof extracted !== "object") return;
1304
+ try {
1305
+ const dir = getCatalogCacheDir();
1306
+ const file = getSourceCacheFile();
1307
+ if (!dir || !file) return;
1308
+ const fs = require("fs");
1309
+ fs.mkdirSync(dir, { recursive: true });
1310
+ const tmp = `${file}.tmp.${process.pid}`;
1311
+ fs.writeFileSync(tmp, JSON.stringify({ ref, extracted, savedAt: Date.now() }));
1312
+ fs.renameSync(tmp, file);
1313
+ } catch {}
1314
+ }
1315
+
1316
+ function isTrustedCatalogBaseUrl(url: any): boolean {
1317
+ return typeof url === "string" && /^https:\/\/([a-z0-9-]+\.)*opencode\.ai(\/|$)/i.test(url);
1318
+ }
1319
+
1320
+ function parseCatalogData(json: any): CatalogProjection {
1321
+ const out: CatalogProjection = {};
1322
+ const oc = json?.opencode;
1323
+ if (!oc || typeof oc !== "object") return out;
1324
+ const api = typeof oc.api === "string" ? oc.api.replace(/\/+$/, "") : null;
1325
+ if (api && isTrustedCatalogBaseUrl(api)) {
1326
+ out.catalogBase = api;
1327
+ out.chatUrl = `${api}/chat/completions`;
1328
+ // The Responses lane is the same base with /responses — that is how the
1329
+ // real CLI's @ai-sdk/openai route is built. Keep the current value if the
1330
+ // derived URL would be identical to the chat URL (malformed catalog).
1331
+ if (api.endsWith("/v1")) out.responsesUrl = `${api}/responses`;
1332
+ }
1333
+ // Per-model route overrides. The catalog lets a single model pin a different
1334
+ // base (e.g. the anthropic-protocol models under /inference/anthropic/v1).
1335
+ // This bridge speaks the OpenAI protocols only, so an override is adopted
1336
+ // only when the model's SDK is OpenAI-compatible; an anthropic-only route is
1337
+ // left alone rather than silently misrouted.
1338
+ const overrides = {};
1339
+ for (const [id, m] of Object.entries(oc.models || {})) {
1340
+ const mp = m?.provider?.api;
1341
+ if (typeof mp !== "string" || !isTrustedCatalogBaseUrl(mp)) continue;
1342
+ const npm = String(m?.provider?.npm || oc.npm || "");
1343
+ if (!npm.startsWith("@ai-sdk/openai")) continue;
1344
+ const base = mp.replace(/\/+$/, "");
1345
+ if (base !== api) overrides[id.toLowerCase()] = base;
1346
+ }
1347
+ if (Object.keys(overrides).length > 0) out.modelEndpoints = overrides;
1348
+ // The free-tier list is a catalog fact, not a naming convention. Deriving it
1349
+ // from `cost` + `status` is what the CLI itself does (models-dev.ts maps
1350
+ // `status ?? "active"` and keeps zero-cost models), so a model that stops
1351
+ // being free or gets deprecated drops out without a bridge release — and one
1352
+ // that is free but missing from the gateway's /models is not lost.
1353
+ //
1354
+ // `catalogVerdicts` records every model the catalog describes, so a caller
1355
+ // can tell "the catalog says this one is paid/deprecated" apart from "the
1356
+ // catalog does not know this id at all" (the gateway lists a few evaluator
1357
+ // models the catalog omits).
1358
+ const freeModels = [];
1359
+ const verdicts = {};
1360
+ const modelFacts = {};
1361
+ for (const [id, m] of Object.entries(oc?.models || {})) {
1362
+ const zeroCost = Number(m?.cost?.input) === 0 && Number(m?.cost?.output) === 0;
1363
+ const deprecated = m?.status === "deprecated";
1364
+ const usable = m?.tool_call !== false;
1365
+ const key = id.toLowerCase();
1366
+ verdicts[key] = deprecated ? "deprecated" : zeroCost && usable ? "free" : "paid";
1367
+ if (verdicts[key] === "free") freeModels.push(id);
1368
+ // Model facts the wire depends on. `reasoning` decides whether the client's
1369
+ // token budget needs thinking headroom (token-budget.ts used to guess this
1370
+ // from substrings of the name), and `limit.output` caps a request.
1371
+ if (typeof m?.reasoning === "boolean") {
1372
+ modelFacts[key] = {
1373
+ reasoning: m.reasoning,
1374
+ maxOutput: Number(m?.limit?.output) > 0 ? Number(m.limit.output) : null,
1375
+ };
1376
+ }
1377
+ }
1378
+ for (const id of FREE_VERDICT_OVERRIDES) {
1379
+ const key = id.toLowerCase();
1380
+ if (verdicts[key] === "deprecated") {
1381
+ verdicts[key] = "free";
1382
+ if (!freeModels.includes(id)) freeModels.push(id);
1383
+ }
1384
+ }
1385
+ if (freeModels.length > 0) out.freeModels = freeModels;
1386
+ if (Object.keys(verdicts).length > 0) out.catalogVerdicts = verdicts;
1387
+ if (Object.keys(modelFacts).length > 0) out.modelFacts = modelFacts;
1388
+
1389
+ // Shorthand aliases, derived from the catalog's own `family` field instead of
1390
+ // a hand-maintained table. `family` groups revisions of one model
1391
+ // (`nemotron-free`, `deepseek-flash`), so the newest non-deprecated free
1392
+ // member answers the family name — and when a revision is retired the alias
1393
+ // follows automatically.
1394
+ const families = {};
1395
+ for (const [id, m] of Object.entries(oc.models || {})) {
1396
+ if (verdicts[id.toLowerCase()] !== "free") continue;
1397
+ const family = typeof m?.family === "string" ? m.family.trim().toLowerCase() : "";
1398
+ if (!family) continue;
1399
+ if (!families[family]) families[family] = id;
1400
+ }
1401
+ if (Object.keys(families).length > 0) out.modelFamilies = families;
1402
+
1403
+ return out;
1404
+ }
1405
+
1406
+ async function extractCatalog(): Promise<CatalogProjection> {
1407
+ let json;
1408
+ let fromCache = false;
1409
+ try {
1410
+ json = await fetchJson(CATALOG_URL, SOURCE_TIMEOUT_MS);
1411
+ writeCachedCatalog(json);
1412
+ } catch {
1413
+ // Network unavailable: fall back to the last catalog this machine saw, so
1414
+ // aliases and the free list keep working offline instead of going empty.
1415
+ json = readCachedCatalog();
1416
+ if (!json) return {};
1417
+ fromCache = true;
1418
+ }
1419
+ const out = parseCatalogData(json);
1420
+ if (fromCache) out.fromCache = true;
1421
+ return out;
1422
+ }
1423
+
1424
+ /**
1425
+ * Extract the tool *name list* (the gate's allowlist) from all fetched tool
1426
+ * source files. Schema details are secondary — the upstream gate validates the
1427
+ * tool name against its list (schema content is not fingerprinted), so the
1428
+ * wire needs correct names, not byte-identical schemas.
1429
+ */
1430
+ /**
1431
+ * Which tools appear in the model's tool list.
1432
+ *
1433
+ * Upstream decides this per tool with `options: { codemode: false }` in the
1434
+ * registration block: those are sent on the wire, while everything else is
1435
+ * reached through the `execute` tool. Measured against the real CLI's request,
1436
+ * the wire carries exactly the `codemode: false` set (plus `execute`). Deriving
1437
+ * the list from that flag means a tool that moves into code mode drops out and
1438
+ * a new direct tool appears, without either being named here.
1439
+ */
1440
+ function extractToolNames(files: Record<string, any> = {}): string[] {
1441
+ const names = [];
1442
+ const seen = new Set();
1443
+ for (const key of Object.keys(files)) {
1444
+ if (!key.startsWith("tool:")) continue;
1445
+ const source = files[key];
1446
+ if (typeof source !== "string" || !source.trim()) continue;
1447
+
1448
+ const exported = (source.match(/export\s+const\s+name\s*=\s*"([a-z][a-z0-9_-]*)"/i) || [])[1];
1449
+ const fallback = key.replace(/^tool:/, "").replace(/[^a-z0-9_-]/gi, "");
1450
+
1451
+ for (const block of registrationBlocks(source)) {
1452
+ if (!/codemode:\s*false/.test(block.body)) continue;
1453
+ const literal = (block.body.match(/name:\s*"([a-z][a-z0-9_-]*)"/i) || [])[1];
1454
+ // `name,` (shorthand for the exported constant) or `name:` with no literal.
1455
+ const shorthand = /^\s*name\s*,/m.test(block.body) || /name:\s*name\b/.test(block.body);
1456
+ const name = literal || (shorthand ? exported || fallback : null);
1457
+ if (!name || seen.has(name)) continue;
1458
+ seen.add(name);
1459
+ names.push(name);
1460
+ }
1461
+ }
1462
+ return names;
1463
+ }
1464
+
1465
+ /**
1466
+ * Every `editor.add({ ... })` / `draft.add({ ... })` registration in a source
1467
+ * file, with its argument text. Braces are matched by counting, so a nested
1468
+ * `execute:` closure does not truncate the block the way a regex would.
1469
+ */
1470
+ function registrationBlocks(source: string): Array<{ body: string; index: number }> {
1471
+ const blocks = [];
1472
+ const re = /(?:editor|draft)\.add\(/g;
1473
+ let m;
1474
+ while ((m = re.exec(source))) {
1475
+ let i = m.index + m[0].length;
1476
+ let depth = 1;
1477
+ const start = i;
1478
+ for (; i < source.length && depth > 0; i++) {
1479
+ const ch = source[i];
1480
+ if (ch === "{") depth++;
1481
+ else if (ch === "}") depth--;
1482
+ }
1483
+ if (depth === 0) blocks.push({ body: source.slice(start, i), index: m.index });
1484
+ }
1485
+ return blocks;
1486
+ }
1487
+
1488
+ /**
1489
+ * Tool-set overrides that depend on the model, extracted from the sources.
1490
+ *
1491
+ * `patch.ts` installs a session hook that swaps the editing tools per model:
1492
+ * GPT models (excluding `oss` and `gpt-4`) get `patch` and lose `edit`/`write`;
1493
+ * everything else keeps `edit`/`write` and loses `patch`. That is why the real
1494
+ * CLI's request for a non-GPT model carries eleven tools and no `patch`, while
1495
+ * a GPT model carries `patch` instead of `edit`+`write`. A fixed list cannot
1496
+ * express this, so the rule is read from the release and applied per request.
1497
+ */
1498
+ /**
1499
+ * Descriptions upstream extends at request time.
1500
+ *
1501
+ * `subagent.ts` rewrites its description on every request to append the agents
1502
+ * the caller may use. The list itself is session state, not something a release
1503
+ * source can supply, but the *shape* is: a blank line, a heading, and one
1504
+ * `- <id>: <description>` line per agent. Extracting the shape keeps the static
1505
+ * prefix identical to the CLI's and marks the dynamic tail so it is not silently
1506
+ * missing.
1507
+ */
1508
+ function extractDynamicDescriptions(files: Record<string, any> = {}): Record<string, DynamicDescriptionSpec> | null {
1509
+ const out = {};
1510
+ for (const key of Object.keys(files)) {
1511
+ if (!key.startsWith("tool:")) continue;
1512
+ const source = files[key];
1513
+ if (typeof source !== "string") continue;
1514
+ if (!/tool\.description\s*=\s*\[/.test(source)) continue;
1515
+ const exported = source.match(/export\s+const\s+name\s*=\s*"([a-z][a-z0-9_-]*)"/i);
1516
+ const block = source.match(/tool\.description\s*=\s*\[([\s\S]*?)\]\.join\(\s*"([^"]*)"\s*\)/);
1517
+ if (!exported || !block) continue;
1518
+ const literals = [...block[1].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => unescapeLiteral(m[1]));
1519
+ out[exported[1]] = {
1520
+ appendPrefix: literals,
1521
+ joiner: block[2] === "\n" ? "\n" : block[2],
1522
+ itemTemplate: (block[1].match(/`([^`]*\$\{[^}]*\}[^`]*)`/) || [])[1] || null,
1523
+ };
1524
+ }
1525
+ return Object.keys(out).length > 0 ? out : null;
1526
+ }
1527
+
1528
+ function extractToolOverrides(files: Record<string, any> = {}): ToolOverrides | null {
1529
+ for (const key of Object.keys(files)) {
1530
+ if (!key.startsWith("tool:")) continue;
1531
+ const source = files[key];
1532
+ if (typeof source !== "string") continue;
1533
+ const usesPatch = source.match(
1534
+ /const\s+usePatch\s*=\s*([^\n]+)\n([\s\S]{0,400}?)(?=\n\s*\}\s*\n)/
1535
+ );
1536
+ if (!usesPatch) continue;
1537
+ const condition = usesPatch[1].trim();
1538
+ const body = usesPatch[2];
1539
+ const removedForPatch = [...body.matchAll(/delete\s+event\.tools\.([a-z_]+)/g)].map((m) => m[1]);
1540
+ // The `else` branch removes the other side; read the second delete block.
1541
+ const allRemoved = [...source.matchAll(/delete\s+event\.tools\.([a-z_]+)/g)].map((m) => m[1]);
1542
+ const addedForPatch = allRemoved.filter((n) => !removedForPatch.includes(n));
1543
+ if (removedForPatch.length === 0) continue;
1544
+ return {
1545
+ // The condition is kept verbatim and evaluated by the bridge against the
1546
+ // model id, so a change of the rule upstream travels with the release.
1547
+ condition,
1548
+ whenTrueRemove: removedForPatch,
1549
+ whenTrueAdd: addedForPatch,
1550
+ whenFalseRemove: addedForPatch,
1551
+ whenFalseAdd: removedForPatch,
1552
+ };
1553
+ }
1554
+ return null;
1555
+ }
1556
+
1557
+ /**
1558
+ * Extract session ID, User-Agent template, headers, and tool schemas from
1559
+ * upstream source files.
1560
+ */
1561
+ function extractRecipe(files: Record<string, any> = {}): RecipeUpdate {
1562
+ const out: RecipeUpdate = {};
1563
+
1564
+ const identifier = files.identifier;
1565
+ if (typeof identifier === "string") {
1566
+ const charset = identifier.match(/const\s+chars\s*=\s*"([^"]+)"/);
1567
+ if (charset && charset[1].length >= 2) out.sessionCharset = charset[1];
1568
+
1569
+ const length = identifier.match(/const\s+length\s*=\s*(\d+)/);
1570
+ if (length) {
1571
+ const n = parseInt(length[1], 10);
1572
+ if (n >= 16 && n <= 64) out.sessionLength = n;
1573
+ }
1574
+
1575
+ const multiplier = identifier.match(
1576
+ /BigInt\(timestamp\)\s*\*\s*0x([0-9a-fA-F]+)n/
1577
+ );
1578
+ if (multiplier) {
1579
+ const n = parseInt(multiplier[1], 16);
1580
+ if (Number.isSafeInteger(n) && n > 0) out.sessionMultiplier = n;
1581
+ }
1582
+ }
1583
+
1584
+ const sessionId = files.sessionId;
1585
+ if (typeof sessionId === "string") {
1586
+ const prefix = sessionId.match(/make\(\s*"([a-z]+_)"\s*\+\s*descending/);
1587
+ if (prefix) out.sessionPrefix = prefix[1];
1588
+ }
1589
+
1590
+ const app = files.app;
1591
+ if (typeof app === "string") {
1592
+ const tpl = app.match(/return\s+`(opencode\/[^`]+)`/);
1593
+ if (tpl) out.userAgentTemplate = tpl[1];
1594
+ }
1595
+
1596
+ const modelRequest = files.modelRequest;
1597
+ if (typeof modelRequest === "string") {
1598
+ const block = modelRequest.match(/headers:\s*\{([\s\S]{0,2000}?)\n\s{8}\}/);
1599
+ if (block) {
1600
+ // Split by line so a conditional spread can be told apart from a header
1601
+ // that is always sent. Upstream writes parent-session headers as
1602
+ // `...(session.parentID ? { "x-parent": ... } : {})`, which this bridge
1603
+ // has no value for — reporting those as missing would be a false alarm.
1604
+ const required = [];
1605
+ const optional = [];
1606
+ const seen = new Set();
1607
+ for (const line of block[1].split("\n")) {
1608
+ const nameMatch = line.match(/"([A-Za-z][A-Za-z0-9-]*)":/);
1609
+ if (!nameMatch) continue;
1610
+ const name = nameMatch[1];
1611
+ const key = name.toLowerCase();
1612
+ if (key.length === 0 || key.length >= 64 || seen.has(key)) continue;
1613
+ seen.add(key);
1614
+ // A spread guarded by a ternary is conditional.
1615
+ if (line.trim().startsWith("...") && line.includes("?")) optional.push(name);
1616
+ else required.push(name);
1617
+ }
1618
+ if (required.length > 0) out.headers = required;
1619
+ if (optional.length > 0) out.optionalHeaders = optional;
1620
+ }
1621
+ }
1622
+
1623
+ const extractedTools = {};
1624
+ // Build the cross-file corpus once per extraction so `PageInput`-style
1625
+ // references resolve regardless of which file declares them.
1626
+ const corpusParts = Object.entries(files)
1627
+ .filter(([k]) => k.startsWith("tool:") || k.startsWith("ref:"))
1628
+ .map(([, v]) => (typeof v === "string" ? v : ""))
1629
+ .filter(Boolean);
1630
+ schemaCorpus = corpusParts.length > 0 ? corpusParts.join("\n\n") : null;
1631
+ schemaVars = null;
1632
+ schemaModules = new Map();
1633
+ for (const [k, v] of Object.entries(files)) {
1634
+ if ((k.startsWith("ref:") || k.startsWith("tool:")) && typeof v === "string") {
1635
+ const stripped = k.replace(/^(ref:|tool:)/, "");
1636
+ const base = stripped.split("-").pop();
1637
+ // Namespace lookups use the capitalised module name (`Question`), while
1638
+ // the file basename is lowercase (`question`).
1639
+ schemaModules.set(base, v);
1640
+ schemaModules.set(base.charAt(0).toUpperCase() + base.slice(1), v);
1641
+ schemaModules.set(stripped, v);
1642
+ }
1643
+ }
1644
+
1645
+ // Harvest constants from the whole corpus once, so a field description that
1646
+ // interpolates an imported constant can be resolved.
1647
+ {
1648
+ const parts = Object.entries(files)
1649
+ .filter(([k]) => k.startsWith("tool:") || k.startsWith("ref:"))
1650
+ .map(([, v]) => (typeof v === "string" ? v : ""));
1651
+ const all = parts.join("\n");
1652
+ const vars = { OS: "Linux", shell: "bash" };
1653
+ for (const m of all.matchAll(/const\s+([A-Z][A-Z0-9_]*)\s*=\s*([0-9][0-9_*\s+]*)/g)) {
1654
+ const clean = m[2].replace(/_/g, "").trim();
1655
+ if (/^[0-9*\s+]+$/.test(clean)) {
1656
+ const val = clean
1657
+ .split("+")
1658
+ .map((part) => part.split("*").reduce((acc, n) => acc * Number(n.trim()), 1))
1659
+ .reduce((a, b) => a + b, 0);
1660
+ if (Number.isFinite(val)) vars[m[1]] = val;
1661
+ }
1662
+ }
1663
+ schemaVars = vars;
1664
+ }
1665
+
1666
+ const toolKeys = Object.keys(files).filter((k) => k.startsWith("tool:"));
1667
+ // Code mode's `execute` is registered in its own file with an inline object,
1668
+ // so the plugin parser would miss it. Read it here.
1669
+ if (typeof files.codemode === "string") {
1670
+ const cm = files.codemode.match(/name:\s*"(execute)"[\s\S]{0,200}?input:\s*([A-Za-z0-9_.]+)/);
1671
+ if (cm) {
1672
+ const cmDesc = files.codemode.match(/const\s+description\s*=\s*\[([\s\S]*?)\]\.join\(\s*"([^"]*)"\s*\)/);
1673
+ let description = "Call tools through `tools` using exact paths and signatures from the catalog.";
1674
+ if (cmDesc) {
1675
+ const parts = [];
1676
+ for (const m of cmDesc[1].matchAll(/'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)"/g)) {
1677
+ parts.push(unescapeLiteral(m[1] !== undefined ? m[1] : m[2]));
1678
+ }
1679
+ // `cmDesc[2]` is the join argument's contents, already without the
1680
+ // surrounding quotes (`[^"]*`), so it is unescaped as-is.
1681
+ const joiner = unescapeLiteral(cmDesc[2]);
1682
+ if (parts.length > 0) description = parts.join(joiner);
1683
+ }
1684
+ // `{ code: string }` with no field description: the guidance lives in the
1685
+ // tool description, and the CLI does not annotate the field.
1686
+ extractedTools.execute = {
1687
+ description,
1688
+ parameters: {
1689
+ type: "object",
1690
+ properties: { code: { type: "string" } },
1691
+ required: ["code"],
1692
+ additionalProperties: false,
1693
+ },
1694
+ };
1695
+ }
1696
+ }
1697
+ for (const key of toolKeys) {
1698
+ // No filename fallback: a file that registers its tools by literal (or that
1699
+ // exposes none at all) must not be recorded under its own filename. That is
1700
+ // how `mcp-resource` used to end up in the profile as a tool name.
1701
+ const def = extractToolFromSource(files[key], null);
1702
+ if (def) {
1703
+ extractedTools[def.name] = {
1704
+ description: def.description,
1705
+ parameters: def.parameters,
1706
+ };
1707
+ }
1708
+ }
1709
+ if (Object.keys(extractedTools).length > 0) {
1710
+ out.tools = extractedTools;
1711
+ }
1712
+ const toolNames = extractToolNames(files);
1713
+ // `execute` is the code-mode dispatcher itself: always on the wire when code
1714
+ // mode is enabled, even though it carries no `codemode: false` flag.
1715
+ if (Object.keys(extractedTools).includes("execute") && !toolNames.includes("execute")) {
1716
+ toolNames.push("execute");
1717
+ }
1718
+ if (toolNames.length > 0) {
1719
+ out.toolNames = toolNames;
1720
+ }
1721
+ const overrides = extractToolOverrides(files);
1722
+ if (overrides) {
1723
+ out.toolOverrides = overrides;
1724
+ }
1725
+ const dynamicDescriptions = extractDynamicDescriptions(files);
1726
+ if (dynamicDescriptions) {
1727
+ out.dynamicDescriptions = dynamicDescriptions;
1728
+ }
1729
+
1730
+ return out;
1731
+ }
1732
+
1733
+ function buildUserAgent(next: Recipe = recipe): string {
1734
+ const tpl = next.userAgentTemplate;
1735
+ if (typeof tpl === "string") {
1736
+ return tpl
1737
+ .replace("${app.channel}", next.channel)
1738
+ .replace("${app.version}", next.version)
1739
+ .replace("${app.name}", next.client);
1740
+ }
1741
+ return `opencode/${next.channel}/${next.version}/${next.client}`;
1742
+ }
1743
+
1744
+ function getUserAgent(): string {
1745
+ return buildUserAgent(recipe);
1746
+ }
1747
+
1748
+ function applyRecipe(update: any = {}, tag: string | null = null): string[] {
1749
+ const next: Recipe = { ...recipe };
1750
+ const changed: string[] = [];
1751
+
1752
+ const version = clampString(update.version, 32);
1753
+ if (version && /^\d+\.\d+\.\d+$/.test(version) && version !== next.version) {
1754
+ next.version = version;
1755
+ changed.push("version");
1756
+ }
1757
+
1758
+ const charset = clampString(update.sessionCharset, 128);
1759
+ if (charset && charset.length >= 2 && charset !== next.sessionCharset) {
1760
+ next.sessionCharset = charset;
1761
+ changed.push("sessionCharset");
1762
+ }
1763
+
1764
+ if (
1765
+ Number.isInteger(update.sessionLength) &&
1766
+ update.sessionLength >= 16 &&
1767
+ update.sessionLength <= 64 &&
1768
+ update.sessionLength !== next.sessionLength
1769
+ ) {
1770
+ next.sessionLength = update.sessionLength;
1771
+ changed.push("sessionLength");
1772
+ }
1773
+
1774
+ if (
1775
+ Number.isInteger(update.sessionMultiplier) &&
1776
+ update.sessionMultiplier > 0 &&
1777
+ update.sessionMultiplier !== next.sessionMultiplier
1778
+ ) {
1779
+ next.sessionMultiplier = update.sessionMultiplier;
1780
+ changed.push("sessionMultiplier");
1781
+ }
1782
+
1783
+ const prefix = clampString(update.sessionPrefix, 16);
1784
+ if (prefix && prefix !== next.sessionPrefix) {
1785
+ next.sessionPrefix = prefix;
1786
+ changed.push("sessionPrefix");
1787
+ }
1788
+
1789
+ for (const k of ["chatUrl", "responsesUrl", "modelsUrl", "catalogBase"]) {
1790
+ const v = clampString(update[k], 256);
1791
+ if (v && /^https?:\/\/[a-z0-9.:-]+/i.test(v) && v !== next[k]) {
1792
+ next[k] = v;
1793
+ changed.push(k);
1794
+ }
1795
+ }
1796
+
1797
+ if (typeof update.userAgentTemplate === "string") {
1798
+ const probe = buildUserAgent({ ...next, userAgentTemplate: update.userAgentTemplate });
1799
+ if (/^opencode\/[A-Za-z0-9-]+\/\d+\.\d+\.\d+\/[A-Za-z0-9-]+$/.test(probe)) {
1800
+ if (probe !== buildUserAgent(recipe)) changed.push("userAgentTemplate");
1801
+ next.userAgentTemplate = update.userAgentTemplate;
1802
+ }
1803
+ }
1804
+
1805
+ if (Array.isArray(update.headers) && update.headers.length > 0) {
1806
+ const incoming = update.headers.map(String);
1807
+ const same =
1808
+ incoming.length === next.headers.length &&
1809
+ incoming.every((h, i) => h.toLowerCase() === next.headers[i].toLowerCase());
1810
+ if (!same) {
1811
+ next.headers = incoming;
1812
+ changed.push("headers");
1813
+ }
1814
+ }
1815
+
1816
+ if (Array.isArray(update.optionalHeaders)) {
1817
+ optionalHeaders = update.optionalHeaders.map(String);
1818
+ }
1819
+
1820
+ if (Array.isArray(update.freeModels) && update.freeModels.length > 0) {
1821
+ const incoming = update.freeModels.map(String).filter((n) => /^[A-Za-z0-9._:-]+$/.test(n));
1822
+ if (incoming.length > 0 && stableStringify(incoming) !== stableStringify(freeModels)) {
1823
+ freeModels = incoming;
1824
+ changed.push("freeModels");
1825
+ }
1826
+ }
1827
+
1828
+ if (update.dynamicDescriptions && typeof update.dynamicDescriptions === "object") {
1829
+ if (stableStringify(update.dynamicDescriptions) !== stableStringify(dynamicDescriptions)) {
1830
+ dynamicDescriptions = update.dynamicDescriptions;
1831
+ changed.push("dynamicDescriptions");
1832
+ }
1833
+ }
1834
+
1835
+ if (update.toolOverrides && typeof update.toolOverrides === "object") {
1836
+ if (stableStringify(update.toolOverrides) !== stableStringify(toolOverrides)) {
1837
+ toolOverrides = update.toolOverrides;
1838
+ changed.push("toolOverrides");
1839
+ }
1840
+ }
1841
+
1842
+ if (update.modelFacts && typeof update.modelFacts === "object") {
1843
+ const next = {};
1844
+ for (const [id, f] of Object.entries(update.modelFacts)) {
1845
+ if (typeof f?.reasoning !== "boolean") continue;
1846
+ next[String(id).toLowerCase()] = {
1847
+ reasoning: f.reasoning,
1848
+ maxOutput: Number(f.maxOutput) > 0 ? Number(f.maxOutput) : null,
1849
+ };
1850
+ }
1851
+ if (Object.keys(next).length > 0 && stableStringify(next) !== stableStringify(modelFacts)) {
1852
+ modelFacts = next;
1853
+ changed.push("modelFacts");
1854
+ }
1855
+ }
1856
+
1857
+ if (update.modelFamilies && typeof update.modelFamilies === "object") {
1858
+ const next = {};
1859
+ for (const [family, id] of Object.entries(update.modelFamilies)) {
1860
+ if (typeof id === "string" && /^[A-Za-z0-9._:-]+$/.test(id)) {
1861
+ next[String(family).toLowerCase()] = id;
1862
+ }
1863
+ }
1864
+ if (Object.keys(next).length > 0 && stableStringify(next) !== stableStringify(modelFamilies)) {
1865
+ modelFamilies = next;
1866
+ changed.push("modelFamilies");
1867
+ }
1868
+ }
1869
+
1870
+ if (update.catalogVerdicts && typeof update.catalogVerdicts === "object") {
1871
+ const next = {};
1872
+ for (const [id, v] of Object.entries(update.catalogVerdicts)) {
1873
+ if (v === "free" || v === "paid" || v === "deprecated") next[String(id).toLowerCase()] = v;
1874
+ }
1875
+ if (Object.keys(next).length > 0 && stableStringify(next) !== stableStringify(catalogVerdicts)) {
1876
+ catalogVerdicts = next;
1877
+ changed.push("catalogVerdicts");
1878
+ }
1879
+ }
1880
+
1881
+ if (update.modelEndpoints && typeof update.modelEndpoints === "object") {
1882
+ const nextMap = {};
1883
+ for (const [id, base] of Object.entries(update.modelEndpoints)) {
1884
+ if (typeof base === "string" && /^https:\/\/[a-z0-9.-]+/i.test(base)) {
1885
+ nextMap[String(id).toLowerCase()] = base;
1886
+ }
1887
+ }
1888
+ if (Object.keys(nextMap).length > 0) {
1889
+ if (stableStringify(nextMap) !== stableStringify(modelEndpoints)) {
1890
+ modelEndpoints = nextMap;
1891
+ changed.push("modelEndpoints");
1892
+ }
1893
+ }
1894
+ }
1895
+
1896
+ if (Array.isArray(update.toolNames) && update.toolNames.length > 0) {
1897
+ const incoming = update.toolNames.map(String).filter((n) => /^[a-z][a-z0-9_-]*$/i.test(n));
1898
+ if (incoming.length > 0) {
1899
+ const same =
1900
+ incoming.length === toolNames.length &&
1901
+ incoming.every((n, i) => n === toolNames[i]);
1902
+ if (!same) {
1903
+ toolNames = incoming;
1904
+ changed.push("toolNames");
1905
+ }
1906
+ }
1907
+ }
1908
+
1909
+ if (update.tools && typeof update.tools === "object") {
1910
+ // The extracted set *replaces* the previous one rather than merging into
1911
+ // it. Merging would keep a tool upstream has renamed or removed forever,
1912
+ // so the wire shape could never converge on what the release actually
1913
+ // ships — the opposite of adapting.
1914
+ const nextTools = { ...update.tools };
1915
+ if (Object.keys(nextTools).length > 0) {
1916
+ if (stableStringify(nextTools) !== stableStringify(getTools())) {
1917
+ changed.push("tools");
1918
+ }
1919
+ toolProfile = nextTools;
1920
+ toolProfileSource = "source";
1921
+ toolProfileVersion = next.version;
1922
+ }
1923
+ }
1924
+
1925
+ if (changed.length > 0) {
1926
+ recipe = next;
1927
+ stateEpoch++;
1928
+ lastForcedRefreshTime = 0;
1929
+ }
1930
+ if (tag) lastSourceTag = tag;
1931
+ return changed;
1932
+ }
1933
+
1934
+ // --- Refresh & Reactive Self-Heal --------------------------------------------
1935
+
1936
+ /**
1937
+ * @param {object} [opts]
1938
+ * @param {boolean} [opts.force] Adopt whatever the handshake reports, even in
1939
+ * reactive mode and even when the version has
1940
+ * not moved (the gate can move without a bump).
1941
+ * Used by the gate-rejection self-heal.
1942
+ * @param {boolean} [opts.recheck] Skip the freshness guard and consult the
1943
+ * handshake now, but still respect UPDATE_MODE
1944
+ * when deciding whether to adopt. Used by the
1945
+ * periodic CLI-version poll.
1946
+ */
1947
+ async function refresh(opts: { force?: boolean; recheck?: boolean } = {}): Promise<any> {
1948
+ const { force = false, recheck = false } = opts;
1949
+ if (process.env.OPENCODE_USER_AGENT) {
1950
+ return { updated: false, reason: "pinned" };
1951
+ }
1952
+ if (!force && !recheck && Date.now() - lastCheckTime < IDENTITY_TTL_MS) {
1953
+ return { updated: false, reason: "fresh" };
1954
+ }
1955
+ if (refreshInFlight) {
1956
+ if (!force) return refreshInFlight;
1957
+ refreshInFlightForced = true;
1958
+ const pending = await refreshInFlight;
1959
+ if (pending && (pending.updated || pending.sourceRead)) return pending;
1960
+ }
1961
+
1962
+ refreshInFlightForced = Boolean(force);
1963
+ const myGen = ++refreshGen;
1964
+ refreshInFlight = (async () => {
1965
+ try {
1966
+ const release = await resolveRelease(recipe.version);
1967
+ const latest = release.version;
1968
+ if (!latest) throw new Error(release.error || "handshake resolved no version");
1969
+
1970
+ if (myGen !== refreshGen) return { updated: false, reason: "reset" };
1971
+ lastCheckTime = Date.now();
1972
+ lastRefreshError = release.stale ? release.error || "handshake stale" : null;
1973
+
1974
+ const cmp = compareVersions(latest, recipe.version);
1975
+ if (cmp < 0) {
1976
+ return {
1977
+ updated: false,
1978
+ version: recipe.version,
1979
+ reason: `newer-local:${recipe.version}`,
1980
+ };
1981
+ }
1982
+
1983
+ const updateMode = getUpdateMode();
1984
+ const forcedByUpstream = release.minimum === true;
1985
+ const isForced = force || refreshInFlightForced;
1986
+ const shouldAdopt = cmp > 0 && (isForced || updateMode === "always" || forcedByUpstream);
1987
+
1988
+ if (cmp === 0 && !isForced) {
1989
+ // Even when the CLI version has not moved, keep the catalog current.
1990
+ // Warm-starting from the disk cache fills `freeModels`, which used to
1991
+ // gate this call — so a cached list was a permanent snapshot and
1992
+ // deprecated models kept being advertised (measured: retired
1993
+ // minimax-m3.1-flash-free stayed in /v1/models). Clients probing
1994
+ // retired ids burn the per-IP burst quota for nothing. refresh() is
1995
+ // TTL-gated by ensureFresh, so re-reading the catalog costs at most
1996
+ // one request per refresh interval.
1997
+ const catalog = await extractCatalog();
1998
+ applyRecipe(catalog);
1999
+ return {
2000
+ updated: false,
2001
+ version: recipe.version,
2002
+ reason: "up-to-date",
2003
+ };
2004
+ }
2005
+ if (cmp > 0 && !shouldAdopt) {
2006
+ // Reactive mode: remember that a release exists without adopting it.
2007
+ // The next gate rejection forces a refresh, which flips shouldAdopt.
2008
+ // Refresh the catalog here too — the not-adopted branch is the
2009
+ // default-mode path and used to freeze the same stale list.
2010
+ {
2011
+ const catalog = await extractCatalog();
2012
+ applyRecipe(catalog);
2013
+ }
2014
+ lastAvailable = latest;
2015
+ return {
2016
+ updated: false,
2017
+ version: recipe.version,
2018
+ available: latest,
2019
+ reason: `available-not-adopted:${updateMode}`,
2020
+ };
2021
+ }
2022
+ lastAvailable = null;
2023
+
2024
+ const ref = sourceRef(release);
2025
+ const update = { version: latest };
2026
+ let sourceRead = false;
2027
+
2028
+ const diskCachedSource =
2029
+ (global.fetch === BOOT_FETCH || process.env.OPENCODE_CACHE_DIR)
2030
+ ? readCachedSource(ref)
2031
+ : null;
2032
+ if (
2033
+ lastSyncedSource &&
2034
+ lastSyncedSource.ref === ref &&
2035
+ lastSyncedSource.fetchRef === global.fetch
2036
+ ) {
2037
+ Object.assign(update, lastSyncedSource.extracted);
2038
+ sourceRead = true;
2039
+ } else if (diskCachedSource && diskCachedSource.extracted) {
2040
+ Object.assign(update, diskCachedSource.extracted);
2041
+ lastSyncedSource = { ref, extracted: diskCachedSource.extracted, fetchRef: global.fetch };
2042
+ sourceRead = true;
2043
+ } else {
2044
+ // Discover the release's tool plugins, falling back to the ones already
2045
+ // known when the directory listing is unavailable (API outage / rate
2046
+ // limit). The known set is kept in `knownPlugins`, so a transient failure
2047
+ // narrows coverage for one refresh instead of erasing it.
2048
+ const discovered = await listSourceDir(PLUGIN_DIR, ref);
2049
+ if (discovered.length > 0) knownPlugins = discovered;
2050
+ const pluginFiles = { codemode: CODEMODE_TOOL_FILE };
2051
+ for (const name of knownPlugins) {
2052
+ pluginFiles[`tool:${name}`] = `${PLUGIN_DIR}/${name}.ts`;
2053
+ }
2054
+
2055
+ const settled = await Promise.allSettled(
2056
+ Object.entries({ ...SOURCE_FILES, ...pluginFiles }).map(async ([key, filePath]) => [
2057
+ key,
2058
+ await fetchText(`${SOURCE_BASE}/${ref}/${filePath}`, SOURCE_TIMEOUT_MS),
2059
+ ])
2060
+ );
2061
+ const fetchedFiles = {};
2062
+ for (const item of settled) {
2063
+ if (item.status === "fulfilled") {
2064
+ fetchedFiles[item.value[0]] = item.value[1];
2065
+ sourceRead = true;
2066
+ }
2067
+ }
2068
+ // Cross-file schema references. `read.ts` writes
2069
+ // `ReadToolFileSystem.PageInput.fields.offset`, and `PageInput` lives in
2070
+ // `../read-filesystem.ts`. Fetch the local modules each plugin imports so
2071
+ // the field's real optionality/type can be resolved instead of guessed.
2072
+ const refFiles = new Map();
2073
+ for (const [key, source] of Object.entries(fetchedFiles)) {
2074
+ if (!key.startsWith("tool:") || typeof source !== "string") continue;
2075
+ // Relative imports: `../read-filesystem.js` → packages/core/src/read-filesystem.ts
2076
+ for (const m of source.matchAll(/import\s+\{([^}]+)\}\s+from\s+"(\.\.?\/[^"]+)\.js"/g)) {
2077
+ const rel = m[2].replace(/^\.\.?\//, "");
2078
+ const resolved = new URL(m[2] + ".ts", `https://x/${PLUGIN_DIR}/`).pathname.replace(/^\//, "");
2079
+ refFiles.set(`ref:${rel.replace(/\//g, "-")}`, resolved);
2080
+ }
2081
+ // Workspace imports: `@opencode/schema/question` → packages/schema/src/question.ts.
2082
+ // This is how a plugin refers to a struct it does not declare itself
2083
+ // (`Question.Prompt`).
2084
+ for (const m of source.matchAll(/from\s+"@opencode\/([a-z-]+)\/([a-z0-9-]+)"/g)) {
2085
+ const pkg = m[1];
2086
+ const mod = m[2];
2087
+ refFiles.set(`ref:${pkg}-${mod}`, `packages/${pkg}/src/${mod}.ts`);
2088
+ }
2089
+ }
2090
+ if (refFiles.size > 0) {
2091
+ const refSettled = await Promise.allSettled(
2092
+ [...refFiles.entries()].map(async ([key, filePath]) => [
2093
+ key,
2094
+ await fetchText(`${SOURCE_BASE}/${ref}/${filePath}`, SOURCE_TIMEOUT_MS),
2095
+ ])
2096
+ );
2097
+ for (const item of refSettled) {
2098
+ if (item.status === "fulfilled") fetchedFiles[item.value[0]] = item.value[1];
2099
+ }
2100
+ }
2101
+
2102
+ // Some tools keep their description in a sibling `.txt` (patch.ts). Fetch
2103
+ // those too: the description is part of the wire schema, and a tool whose
2104
+ // schema cannot be built is dropped from the profile.
2105
+ const txtRefs = [];
2106
+ for (const [key, source] of Object.entries(fetchedFiles)) {
2107
+ if (!key.startsWith("tool:")) continue;
2108
+ const probe = extractToolFromSource(source, key.replace(/^tool:/, ""));
2109
+ if (probe && probe.descriptionFile) {
2110
+ txtRefs.push({ key, file: probe.descriptionFile, varName: probe.descriptionVar });
2111
+ }
2112
+ }
2113
+ if (txtRefs.length > 0) {
2114
+ const txtSettled = await Promise.allSettled(
2115
+ txtRefs.map(async (t) => {
2116
+ const dir = PLUGIN_DIR;
2117
+ // `../patch.txt` is relative to the plugin directory.
2118
+ const resolved = new URL(t.file, `https://x/${dir}/`).pathname.replace(/^\//, "");
2119
+ return [t, await fetchText(`${SOURCE_BASE}/${ref}/${resolved}`, SOURCE_TIMEOUT_MS)];
2120
+ })
2121
+ );
2122
+ for (const item of txtSettled) {
2123
+ if (item.status !== "fulfilled") continue;
2124
+ const [t, text] = item.value;
2125
+ const src = fetchedFiles[t.key];
2126
+ if (typeof src !== "string") continue;
2127
+ // Replace the identifier with a string literal so the existing
2128
+ // description parser can read it.
2129
+ fetchedFiles[t.key] = src.replace(
2130
+ new RegExp(`\\b${t.varName}\\b(?!\\s+from)`),
2131
+ JSON.stringify(text.trim())
2132
+ );
2133
+ }
2134
+ }
2135
+
2136
+ if (sourceRead) {
2137
+ const extracted = extractRecipe(fetchedFiles);
2138
+ Object.assign(update, extracted);
2139
+ const allCoreFetched = Object.keys(SOURCE_FILES).every(
2140
+ (k) => typeof fetchedFiles[k] === "string" && fetchedFiles[k].length > 0
2141
+ );
2142
+ const allSettledOk = settled.every((item) => item.status === "fulfilled");
2143
+ if (allCoreFetched && allSettledOk) {
2144
+ lastSyncedSource = { ref, extracted, fetchRef: global.fetch };
2145
+ if (extracted.tools && Object.keys(extracted.tools).length > 0) {
2146
+ writeCachedSource(ref, extracted);
2147
+ }
2148
+ }
2149
+ } else {
2150
+ const fallbackSource = readCachedSource(ref) || readCachedSource();
2151
+ if (fallbackSource && fallbackSource.extracted) {
2152
+ Object.assign(update, fallbackSource.extracted);
2153
+ }
2154
+ }
2155
+ }
2156
+
2157
+ // Endpoints live in the provider catalog, not in the git source tree.
2158
+ // Missing catalog or missing `opencode` entry leaves the endpoints at
2159
+ // their current values — a catalog outage must not blank the wire URLs.
2160
+ const catalog = await extractCatalog();
2161
+ Object.assign(update, catalog);
2162
+
2163
+ if (myGen !== refreshGen) return { updated: false, reason: "reset" };
2164
+ const changed = applyRecipe(update, ref);
2165
+ if (isForced && sourceRead && !release.stale) {
2166
+ lastForcedRefreshTime = Date.now();
2167
+ }
2168
+ return {
2169
+ updated: changed.length > 0,
2170
+ changed,
2171
+ version: recipe.version,
2172
+ tag: ref,
2173
+ sourceRead,
2174
+ release: {
2175
+ version: release.version,
2176
+ sha: release.sha,
2177
+ source: release.source,
2178
+ minimum: release.minimum,
2179
+ },
2180
+ };
2181
+ } catch (err) {
2182
+ if (myGen === refreshGen) {
2183
+ lastRefreshError = err.message || String(err);
2184
+ }
2185
+ return { updated: false, error: err.message || String(err) };
2186
+ } finally {
2187
+ if (myGen === refreshGen) {
2188
+ refreshInFlight = null;
2189
+ refreshInFlightForced = false;
2190
+ }
2191
+ }
2192
+ })();
2193
+
2194
+ return refreshInFlight;
2195
+ }
2196
+
2197
+ /**
2198
+ * Non-blocking freshness check on the request path.
2199
+ * - In `always` mode: kicks off a background handshake check after TTL expiry.
2200
+ * - In `reactive` mode: stays silent after initial check until a gate error occurs.
2201
+ */
2202
+ function ensureFresh(): { updated: boolean; reason: string } {
2203
+ if (Date.now() - lastCheckTime < IDENTITY_TTL_MS) {
2204
+ return { updated: false, reason: "fresh" };
2205
+ }
2206
+ if (getUpdateMode() === "reactive" && lastCheckTime > 0) {
2207
+ return { updated: false, reason: "reactive-idle" };
2208
+ }
2209
+ refresh().catch(() => {});
2210
+ return { updated: false, reason: "refreshing-in-background" };
2211
+ }
2212
+
2213
+ /**
2214
+ * Upstream's IP-level abuse block.
2215
+ *
2216
+ * Known variants (all HTTP 403, `error.type: FreeTierError`):
2217
+ *
2218
+ * - "OpenCode's free models aren't available from your current network
2219
+ * because we've detected abusive traffic from this IP address. ..."
2220
+ * - "Forbidden, OpenCode Free Model Gateway Detect Abuse Traffic"
2221
+ * - "Abuse of traffic" (short form)
2222
+ *
2223
+ * Unlike the shape gate ("OpenCode's free tier can only be used from within
2224
+ * OpenCode"), no identity change can clear this: the gateway keys it to the
2225
+ * egress network, and the official CLI gets the same answer from the same IP.
2226
+ * Retrying only extends the penalty, so callers must not refresh or replay.
2227
+ */
2228
+ function isIpAbuseRejection(status: number, errMsg: any): boolean {
2229
+ if (status !== 403) return false;
2230
+ const m = String(errMsg || "").toLowerCase();
2231
+ return (
2232
+ m.includes("abusive traffic") ||
2233
+ m.includes("abuse traffic") ||
2234
+ m.includes("abuse of traffic")
2235
+ );
2236
+ }
2237
+
2238
+ /**
2239
+ * Reactive self-heal when upstream rejects our request with a CLI gate error
2240
+ * (403 FreeTierError or 426 UpgradeRequired).
2241
+ */
2242
+ async function onGateRejection(status: number, errType: any, errMsg: any, attempted: boolean = false): Promise<GateRejectionResult> {
2243
+ if (attempted) return { retry: false, reason: "already-retried" };
2244
+ // A network-level block is terminal: refreshing the recipe cannot change
2245
+ // which IP the request leaves from, so skip the GitHub/catalog fetch.
2246
+ if (isIpAbuseRejection(status, errMsg)) {
2247
+ return { retry: false, reason: "ip-abuse", terminal: true };
2248
+ }
2249
+
2250
+ const versionBefore = recipe.version;
2251
+ const toolsBefore = stableStringify(getTools());
2252
+
2253
+ const floor = parseVersionFloor(errMsg);
2254
+ if (floor) {
2255
+ versionFloor = floor;
2256
+ if (compareVersions(recipe.version, floor) < 0) {
2257
+ applyRecipe({ version: floor }, lastSourceTag);
2258
+ }
2259
+ }
2260
+
2261
+ // Avoid hammering GitHub's API (60 req/hr unauthenticated) and the catalog on
2262
+ // every request during a per-IP 403 cooldown burst: if a forced refresh
2263
+ // already succeeded within GATE_REFRESH_COOLDOWN_MS and no version floor was
2264
+ // reported, reuse the current state.
2265
+ if (
2266
+ !floor &&
2267
+ lastForcedRefreshTime > 0 &&
2268
+ Date.now() - lastForcedRefreshTime < GATE_REFRESH_COOLDOWN_MS
2269
+ ) {
2270
+ return {
2271
+ retry: false,
2272
+ reason: "no-change",
2273
+ cooldown: true,
2274
+ status,
2275
+ errType,
2276
+ };
2277
+ }
2278
+
2279
+ const result = await refresh({ force: true });
2280
+ const toolsAfter = stableStringify(getTools());
2281
+
2282
+ const learned =
2283
+ recipe.version !== versionBefore ||
2284
+ toolsAfter !== toolsBefore ||
2285
+ (result && Array.isArray(result.changed) && result.changed.length > 0);
2286
+
2287
+ return {
2288
+ retry: learned,
2289
+ reason: floor
2290
+ ? `version-floor:${floor}`
2291
+ : learned
2292
+ ? `updated:${result?.version || recipe.version}`
2293
+ : "no-change",
2294
+ status,
2295
+ errType,
2296
+ };
2297
+ }
2298
+
2299
+ // --- Fast Session ID Generator (Pooled CSPRNG) -------------------------------
2300
+
2301
+ let lastTimestamp: number = 0;
2302
+ let counter: number = 0;
2303
+ const MAX_COUNTER_PER_MS = 16;
2304
+ const RAND_POOL_SIZE = 14 * 256;
2305
+ const randPool = Buffer.allocUnsafe(RAND_POOL_SIZE);
2306
+ let randPoolOffset: number = RAND_POOL_SIZE;
2307
+
2308
+ function nextRandomChars(chars: string, count: number): string {
2309
+ if (randPoolOffset + count > RAND_POOL_SIZE) {
2310
+ crypto.randomFillSync(randPool);
2311
+ randPoolOffset = 0;
2312
+ }
2313
+ const len = chars.length;
2314
+ let out = "";
2315
+ for (let i = 0; i < count; i++) {
2316
+ out += chars[randPool[randPoolOffset + i] % len];
2317
+ }
2318
+ randPoolOffset += count;
2319
+ return out;
2320
+ }
2321
+
2322
+ function createId(descending: boolean = true, timestamp: number = Date.now()): string {
2323
+ const {
2324
+ sessionCharset: chars,
2325
+ sessionLength: length,
2326
+ sessionMultiplier: mult,
2327
+ } = recipe;
2328
+
2329
+ if (timestamp !== lastTimestamp) {
2330
+ lastTimestamp = timestamp;
2331
+ counter = 0;
2332
+ }
2333
+ counter++;
2334
+ const extraMs = Math.floor((counter - 1) / MAX_COUNTER_PER_MS);
2335
+ const effectiveCounter = ((counter - 1) % MAX_COUNTER_PER_MS) + 1;
2336
+
2337
+ const current = BigInt(timestamp + extraMs) * BigInt(mult) + BigInt(effectiveCounter);
2338
+ const value = descending ? ~current : current;
2339
+ const mask = (1n << 48n) - 1n;
2340
+
2341
+ const hexChars = 12;
2342
+ const hex = (value & mask).toString(16).padStart(hexChars, "0");
2343
+ const randomChars = Math.max(0, length - hexChars);
2344
+ return hex + nextRandomChars(chars, randomChars);
2345
+ }
2346
+
2347
+ // --- Accessors & Tool Formatting ---------------------------------------------
2348
+
2349
+ /**
2350
+ * The gate's tool-name allowlist, in upstream's own order. Falls back to the
2351
+ * tool profile's key order when the source read has not produced a list yet.
2352
+ */
2353
+ function getToolNames(): string[] {
2354
+ if (toolNames.length > 0) return toolNames.slice();
2355
+ return Object.keys(getTools());
2356
+ }
2357
+
2358
+ /**
2359
+ * Current wire endpoints. `chatUrl` / `responsesUrl` are resolved from the
2360
+ * upstream provider catalog at refresh time; `server.ts` reads these per
2361
+ * request, so an endpoint migration applies without a restart.
2362
+ */
2363
+ /**
2364
+ * Free-tier model ids derived from the provider catalog. Empty means the
2365
+ * catalog has not been read yet — callers keep their own list in that case
2366
+ * rather than treating "unknown" as "none are free".
2367
+ */
2368
+ function getFreeModels(): string[] {
2369
+ return freeModels.slice();
2370
+ }
2371
+
2372
+ /** Catalog-derived shorthand: a family name (or a prefix of a free model id)
2373
+ * mapped to a live free model. Returns undefined when nothing matches. */
2374
+ function resolveModelAlias(name: any): string | undefined {
2375
+ const key = String(name || "").toLowerCase().trim();
2376
+ if (!key) return undefined;
2377
+ if (modelFamilies[key]) return modelFamilies[key];
2378
+ // Prefix form: "nemotron" for family "nemotron-free", "nemotron-3" for the
2379
+ // model id `nemotron-3-ultra-free`. Longest match wins so a short prefix does
2380
+ // not shadow a more specific one.
2381
+ let best;
2382
+ for (const [family, id] of Object.entries(modelFamilies)) {
2383
+ const matches =
2384
+ key === family ||
2385
+ key === family.replace(/-free$/, "") ||
2386
+ family.startsWith(`${key}-`) ||
2387
+ id.toLowerCase().startsWith(`${key}-`) ||
2388
+ id.toLowerCase().startsWith(key);
2389
+ if (!matches) continue;
2390
+ if (!best || family.length > best.family.length) best = { family, id };
2391
+ }
2392
+ if (best) return best.id;
2393
+ // Revision-prefix form ("nemotron-3.5" for `nemotron-3.5-lightning-free`):
2394
+ // the family map keeps one representative, so fall back to the free list and
2395
+ // take the most specific (longest) prefix match, ties broken lexicographically
2396
+ // so the choice is stable across runs.
2397
+ const candidates = freeModels
2398
+ .filter((id) => id.toLowerCase().startsWith(`${key}-`) || id.toLowerCase().startsWith(key))
2399
+ .sort((a, b) => a.length - b.length || a.localeCompare(b));
2400
+ return candidates[0];
2401
+ }
2402
+
2403
+ /**
2404
+ * Apply the release's model-conditional tool rule to a name list.
2405
+ *
2406
+ * The rule is stored as its upstream condition plus the names it removes and
2407
+ * restores on each branch. The condition is evaluated here against the model id
2408
+ * (only the `event.model.id.includes(...)` form upstream uses is supported; an
2409
+ * unrecognised condition leaves the list untouched rather than guessing).
2410
+ */
2411
+ function applyToolOverrides(names: any, modelId: any): string[] {
2412
+ const rule = toolOverrides;
2413
+ if (!rule || !Array.isArray(names)) return names.slice();
2414
+ const id = String(modelId || "");
2415
+ const cond = String(rule.condition || "");
2416
+ const tests = [...cond.matchAll(/(!?)\s*event\.model\.id\.includes\(\s*"([^"]+)"\s*\)/g)];
2417
+ if (tests.length === 0) return names.slice();
2418
+ let matches = true;
2419
+ for (const [, negated, needle] of tests) {
2420
+ const hit = id.includes(needle);
2421
+ if (negated && hit) matches = false;
2422
+ if (!negated && !hit) matches = false;
2423
+ }
2424
+ const remove = matches ? rule.whenTrueRemove || [] : rule.whenFalseRemove || [];
2425
+ const add = matches ? rule.whenTrueAdd || [] : rule.whenFalseAdd || [];
2426
+ const out = names.filter((n) => !remove.includes(n));
2427
+ for (const n of add) if (!out.includes(n)) out.push(n);
2428
+ return out;
2429
+ }
2430
+
2431
+ /** Catalog facts for one model id: `{ reasoning, maxOutput }`, or undefined
2432
+ * when the catalog does not describe it. */
2433
+ function getModelFacts(modelId: any): ModelFacts | undefined {
2434
+ return modelFacts[String(modelId || "").toLowerCase()];
2435
+ }
2436
+
2437
+ /** The catalog's verdict for one model id: "free", "paid", "deprecated", or
2438
+ * undefined when the catalog does not describe it. */
2439
+ function getCatalogVerdict(modelId: any): string | undefined {
2440
+ return catalogVerdicts[String(modelId || "").toLowerCase()];
2441
+ }
2442
+
2443
+ /**
2444
+ * Reconcile the verdicts with the gateway's own price list.
2445
+ *
2446
+ * The provider catalog lags the serving side: it kept
2447
+ * `minimax-m3.1-flash-free` marked `deprecated` after upstream had already
2448
+ * started serving it, which needed a hand-written override to undo. The
2449
+ * gateway's `/models` entries carry `cost.text.input.price` and
2450
+ * `cost.text.output.price` — the price applied to a request right now — and
2451
+ * retired ids disappear from that list entirely. So a zero price there wins
2452
+ * over a stale catalog verdict in both directions: a deprecated-but-zero id
2453
+ * becomes free, and a catalog-free id the gateway now prices above zero stops
2454
+ * being advertised instead of failing upstream.
2455
+ *
2456
+ * An entry without a text price block (image/video-only model) changes nothing;
2457
+ * its catalog verdict stands rather than guessing a price from its name.
2458
+ * Returns the ids whose verdict moved, for logging.
2459
+ */
2460
+ function applyGatewayPricing(models: any): string[] {
2461
+ if (!Array.isArray(models)) return [];
2462
+ const changed: string[] = [];
2463
+ for (const m of models) {
2464
+ const id = String(m?.id || "").trim();
2465
+ const key = id.toLowerCase();
2466
+ if (!key) continue;
2467
+ const text = m?.cost?.text;
2468
+ const inPrice = Number(text?.input?.price);
2469
+ const outPrice = Number(text?.output?.price);
2470
+ if (!Number.isFinite(inPrice) || !Number.isFinite(outPrice)) continue;
2471
+ const free = inPrice === 0 && outPrice === 0;
2472
+ if (free) {
2473
+ if (catalogVerdicts[key] !== "free") {
2474
+ catalogVerdicts[key] = "free";
2475
+ changed.push(key);
2476
+ }
2477
+ if (!freeModels.some((n) => String(n).toLowerCase() === key)) freeModels.push(id);
2478
+ } else if (catalogVerdicts[key] === "free") {
2479
+ catalogVerdicts[key] = "paid";
2480
+ freeModels = freeModels.filter((n) => String(n).toLowerCase() !== key);
2481
+ changed.push(key);
2482
+ }
2483
+ }
2484
+ if (changed.length > 0) {
2485
+ // Keep the derived aliases honest for the ids that moved.
2486
+ for (const [family, id] of Object.entries(modelFamilies)) {
2487
+ if (catalogVerdicts[String(id).toLowerCase()] !== "free") delete modelFamilies[family];
2488
+ }
2489
+ }
2490
+ return changed;
2491
+ }
2492
+
2493
+ function getEndpoints(modelId: string | null = null): Endpoints {
2494
+ const base = {
2495
+ chatUrl: recipe.chatUrl,
2496
+ responsesUrl: recipe.responsesUrl,
2497
+ modelsUrl: recipe.modelsUrl,
2498
+ catalogBase: recipe.catalogBase,
2499
+ };
2500
+ // A model can pin its own base in the catalog (anthropic-protocol models).
2501
+ // The wire path is derived the same way: <base>/chat/completions.
2502
+ if (modelId) {
2503
+ const override = modelEndpoints[String(modelId).toLowerCase()];
2504
+ if (override) {
2505
+ base.catalogBase = override;
2506
+ base.chatUrl = `${override}/chat/completions`;
2507
+ base.responsesUrl = `${override}/responses`;
2508
+ }
2509
+ }
2510
+ return base;
2511
+ }
2512
+
2513
+ function getRecipe(): Recipe {
2514
+ return { ...recipe };
2515
+ }
2516
+
2517
+ function getTools(): ToolProfile {
2518
+ // An empty profile is not a profile. Without this guard `toolProfile || ...`
2519
+ // lets `{}` win (objects are truthy) and the bridge sends `tools: []`, which
2520
+ // upstream rejects with 403 — the exact failure the fingerprint exists to
2521
+ // avoid. An empty or malformed profile falls back to the shipped set.
2522
+ if (toolProfile && Object.keys(toolProfile).length > 0) return toolProfile;
2523
+ return DEFAULT_TOOLS;
2524
+ }
2525
+
2526
+ /**
2527
+ * The upstream header names currently in force, in upstream's own order.
2528
+ * `server.ts` builds its header object from this, so a header added upstream
2529
+ * starts being sent on the next request after a refresh.
2530
+ */
2531
+ function getHeaderNames(): string[] {
2532
+ return Array.isArray(recipe.headers) ? recipe.headers.slice() : DEFAULT_RECIPE.headers.slice();
2533
+ }
2534
+
2535
+ /**
2536
+ * Append the part of a tool's description that upstream builds at request time.
2537
+ *
2538
+ * The static prefix and the heading come from the release source; the entries
2539
+ * under it are the caller's available agents, which this bridge does not have.
2540
+ * Emitting the heading with no entries is the truthful rendering of "none
2541
+ * available" and keeps the static text byte-identical to the CLI's.
2542
+ */
2543
+ function withDynamicDescription(name: string, description: string): string {
2544
+ const spec = dynamicDescriptions && dynamicDescriptions[name];
2545
+ if (!spec || !Array.isArray(spec.appendPrefix) || spec.appendPrefix.length === 0) return description;
2546
+ const joiner = spec.joiner || "\n";
2547
+ // The extracted literals are [separator, heading, fallbackText]. Only the
2548
+ // heading belongs in the static description: `fallbackText` is what upstream
2549
+ // prints for an agent that has no description, not a heading of its own.
2550
+ const heading = spec.appendPrefix.filter((p) => p !== "").slice(0, 1);
2551
+ if (heading.length === 0) return description;
2552
+ return [description, "", ...heading].join(joiner);
2553
+ }
2554
+
2555
+ function getToolList(flat: boolean = false, scope: string | null = null, modelId: string | null = null): any[] {
2556
+ const profile = getTools();
2557
+ const available = Object.keys(profile);
2558
+ const mode = scope || process.env.TOOL_PROFILE_SCOPE || "core";
2559
+
2560
+ // `core` sends the minimum proven set. `full` sends every name derived from
2561
+ // the release's tool plugin sources — the shape the real CLI uses. The
2562
+ // reactive self-heal retries with `full` so a renamed/added upstream tool is
2563
+ // picked up without a bridge release.
2564
+ let ordered;
2565
+ if (mode === "full") {
2566
+ ordered = applyToolOverrides(getToolNames(), modelId).filter((n) => profile[n]);
2567
+ if (ordered.length === 0) ordered = available;
2568
+ } else {
2569
+ const coreNames = CORE_TOOL_NAMES.filter((n) => profile[n]);
2570
+ ordered = coreNames.length > 0 ? coreNames : available;
2571
+ }
2572
+
2573
+ // Pin the gate anchors last, so the derived order is otherwise untouched.
2574
+ // `profile[name]` may be missing when upstream renamed or dropped the tool:
2575
+ // the shipped definition is then the only thing that keeps the wire shape
2576
+ // acceptable. See GATE_ANCHOR_TOOL_NAMES for the measurements.
2577
+ for (const name of GATE_ANCHOR_TOOL_NAMES) {
2578
+ if (!ordered.includes(name)) ordered = [...ordered, name];
2579
+ }
2580
+
2581
+ return ordered.map((name) => {
2582
+ const def = profile[name] || DEFAULT_TOOLS[name];
2583
+ const description = withDynamicDescription(name, def.description);
2584
+ return flat
2585
+ ? {
2586
+ type: "function",
2587
+ name,
2588
+ description,
2589
+ parameters: def.parameters,
2590
+ strict: false,
2591
+ }
2592
+ : {
2593
+ type: "function",
2594
+ function: {
2595
+ name,
2596
+ description,
2597
+ parameters: def.parameters,
2598
+ // The CLI includes `strict: false` on every tool it sends. It is a
2599
+ // no-op today, but it is part of the shape the wire carries.
2600
+ strict: false,
2601
+ },
2602
+ };
2603
+ });
2604
+ }
2605
+
2606
+ /**
2607
+ * Resolve the header names upstream's client sends to concrete values.
2608
+ *
2609
+ * Returns `{ headers, unsent }`. `unsent` lists names we know upstream sends
2610
+ * but whose value this bridge cannot derive — reported in `/health` instead of
2611
+ * being sent empty, because an empty required header is worse than a missing
2612
+ * one.
2613
+ */
2614
+ const GATE_HEADER_VALUES: string[] = [
2615
+ "user-agent",
2616
+ "x-opencode-client",
2617
+ "x-opencode-project",
2618
+ "x-opencode-session",
2619
+ "x-opencode-session-id",
2620
+ "x-session-affinity",
2621
+ "x-session-id",
2622
+ ];
2623
+
2624
+ function buildGateHeaders(ctx: GateContext = {}): { headers: Record<string, string>; unsent: string[] } {
2625
+ const values = {
2626
+ "user-agent": ctx.userAgent,
2627
+ "x-opencode-client": ctx.client,
2628
+ "x-opencode-project": ctx.project,
2629
+ "x-opencode-session": ctx.sessionId,
2630
+ "x-opencode-session-id": ctx.sessionId,
2631
+ "x-session-affinity": ctx.sessionId,
2632
+ "x-session-id": ctx.sessionId,
2633
+ };
2634
+ const headers = {};
2635
+ const unsent = [];
2636
+ const names = getHeaderNames().slice();
2637
+ // Pin the anchors even when the recipe stops listing them: the gate rejects
2638
+ // a request without these with the same 403 it uses for a blocked IP, so a
2639
+ // recipe regression would be indistinguishable from an exhausted allowance.
2640
+ for (const anchor of GATE_ANCHOR_HEADER_NAMES) {
2641
+ if (!names.some((n) => String(n).toLowerCase() === anchor)) names.push(anchor);
2642
+ }
2643
+ for (const name of names) {
2644
+ const lower = String(name).toLowerCase();
2645
+ const value = values[lower];
2646
+ // Header names are case-insensitive. Emit one canonical spelling per name
2647
+ // so a change of case upstream cannot produce a duplicate key: `User-Agent`
2648
+ // keeps its conventional form, every `x-opencode-*` header stays lowercase.
2649
+ if (value === undefined) unsent.push(name);
2650
+ else headers[lower === "user-agent" ? "User-Agent" : lower] = value;
2651
+ }
2652
+ return { headers, unsent };
2653
+ }
2654
+
2655
+ /**
2656
+ * Header names the current recipe asks for that this bridge has no value for.
2657
+ * Non-empty means upstream added a header whose value is not derivable from
2658
+ * the release source — the alert that a manual mapping is needed, since the
2659
+ * request will be sent without it.
2660
+ */
2661
+ function getUnsentHeaders(): string[] {
2662
+ const known = new Set(GATE_HEADER_VALUES);
2663
+ const conditional = new Set(optionalHeaders.map((n) => String(n).toLowerCase()));
2664
+ return getHeaderNames().filter((n) => {
2665
+ const key = String(n).toLowerCase();
2666
+ // Conditional headers (parent-session lineage) are only sent by the CLI
2667
+ // when the session has a parent. This bridge never creates nested
2668
+ // sessions, so their absence is expected, not a gap to report.
2669
+ return !known.has(key) && !conditional.has(key);
2670
+ });
2671
+ }
2672
+
2673
+ function getSessionPrefix(): string {
2674
+ return recipe.sessionPrefix || DEFAULT_RECIPE.sessionPrefix;
2675
+ }
2676
+
2677
+ /** Session id with upstream's prefix, e.g. `ses_<12 hex><14 base62>`. */
2678
+ function createSessionId(descending: boolean = true, timestamp: number = Date.now()): string {
2679
+ return getSessionPrefix() + createId(descending, timestamp);
2680
+ }
2681
+
2682
+ function getState(): any {
2683
+ return {
2684
+ recipe: getRecipe(),
2685
+ userAgent: getUserAgent(),
2686
+ updateMode: getUpdateMode(),
2687
+ lastCheckTime,
2688
+ lastForcedRefreshTime,
2689
+ epoch: stateEpoch,
2690
+ ttlMs: IDENTITY_TTL_MS,
2691
+ versionFloor,
2692
+ lastRefreshError,
2693
+ lastSourceTag,
2694
+ release: lastRelease,
2695
+ available: lastAvailable,
2696
+ headers: getHeaderNames(),
2697
+ optionalHeaders: optionalHeaders.slice(),
2698
+ unsentHeaders: getUnsentHeaders(),
2699
+ toolNames: getToolNames(),
2700
+ freeModels: freeModels.slice(),
2701
+ catalogVerdicts: { ...catalogVerdicts },
2702
+ modelFamilies: { ...modelFamilies },
2703
+ modelFacts: { ...modelFacts },
2704
+ toolOverrides: toolOverrides ? { ...toolOverrides } : null,
2705
+ dynamicDescriptions: dynamicDescriptions ? { ...dynamicDescriptions } : null,
2706
+ endpoints: getEndpoints(),
2707
+ inFlight: Boolean(refreshInFlight),
2708
+ tools: {
2709
+ source: toolProfileSource,
2710
+ version: toolProfileVersion,
2711
+ toolNames: Object.keys(getTools()),
2712
+ },
2713
+ };
2714
+ }
2715
+
2716
+ function __reset(): void {
2717
+ recipe = { ...DEFAULT_RECIPE };
2718
+ toolProfile = null;
2719
+ toolProfileSource = "default";
2720
+ toolProfileVersion = DEFAULT_RECIPE.version;
2721
+ toolNames = [];
2722
+ modelEndpoints = {};
2723
+ freeModels = [];
2724
+ catalogVerdicts = {};
2725
+ modelFamilies = {};
2726
+ modelFacts = {};
2727
+ toolOverrides = null;
2728
+ dynamicDescriptions = null;
2729
+ lastRelease = null;
2730
+ lastAvailable = null;
2731
+ lastCheckTime = 0;
2732
+ lastForcedRefreshTime = 0;
2733
+ stateEpoch++;
2734
+ refreshInFlight = null;
2735
+ refreshInFlightForced = false;
2736
+ refreshGen++;
2737
+ lastSyncedSource = null;
2738
+ versionFloor = null;
2739
+ lastRefreshError = null;
2740
+ lastSourceTag = null;
2741
+ optionalHeaders = [];
2742
+ lastTimestamp = 0;
2743
+ counter = 0;
2744
+ }
2745
+
2746
+ function __setLastCheckTime(v: number): void {
2747
+ lastCheckTime = v;
2748
+ lastForcedRefreshTime = 0;
2749
+ stateEpoch++;
2750
+ }
2751
+
2752
+ /** Test hook: stage a session prefix without going through recipe validation. */
2753
+ function __setSessionPrefix(prefix: any): void {
2754
+ recipe = { ...recipe, sessionPrefix: String(prefix) };
2755
+ lastForcedRefreshTime = 0;
2756
+ stateEpoch++;
2757
+ }
2758
+
2759
+ function __setToolProfile(tools: any, source: string = "test"): void {
2760
+ toolProfile = tools;
2761
+ toolProfileSource = source;
2762
+ toolProfileVersion = recipe.version;
2763
+ lastForcedRefreshTime = 0;
2764
+ stateEpoch++;
2765
+ }
2766
+
2767
+ // Warm-start from the on-disk catalog cache at module load so shorthand aliases,
2768
+ // model verdicts, and token-budget facts work on the very first request.
2769
+ {
2770
+ const bootCatalog = readCachedCatalog();
2771
+ if (bootCatalog) applyRecipe(parseCatalogData(bootCatalog));
2772
+ const bootSource = readCachedSource();
2773
+ if (bootSource && bootSource.extracted) {
2774
+ applyRecipe(bootSource.extracted, bootSource.ref);
2775
+ lastSyncedSource = {
2776
+ ref: bootSource.ref,
2777
+ extracted: bootSource.extracted,
2778
+ fetchRef: global.fetch,
2779
+ };
2780
+ }
2781
+ }
2782
+ module.exports = {
2783
+ IDENTITY_TTL_MS,
2784
+ GATE_REFRESH_COOLDOWN_MS,
2785
+ get UPDATE_MODE() {
2786
+ return getUpdateMode();
2787
+ },
2788
+ DEFAULT_RECIPE,
2789
+ DEFAULT_TOOLS,
2790
+ SOURCE_FILES,
2791
+ parseVersions,
2792
+ sortVersions,
2793
+ selectVersion,
2794
+ compareVersions,
2795
+ parseVersionFloor,
2796
+ sourceRef,
2797
+ resolveRelease,
2798
+ parseCatalogData,
2799
+ compactCatalog,
2800
+ writeCachedCatalog,
2801
+ extractCatalog,
2802
+ readCachedSource,
2803
+ writeCachedSource,
2804
+ extractToolFromSource,
2805
+ extractToolNames,
2806
+ extractToolOverrides,
2807
+ parseSchemaExpr,
2808
+ parseFieldSchema,
2809
+ extractRecipe,
2810
+ buildUserAgent,
2811
+ applyRecipe,
2812
+ refresh,
2813
+ ensureFresh,
2814
+ onGateRejection,
2815
+ isIpAbuseRejection,
2816
+ createId,
2817
+ getUserAgent,
2818
+ getRecipe,
2819
+ getTools,
2820
+ getHeaderNames,
2821
+ getUnsentHeaders,
2822
+ getToolNames,
2823
+ getFreeModels,
2824
+ getCatalogVerdict,
2825
+ applyGatewayPricing,
2826
+ getModelFacts,
2827
+ applyToolOverrides,
2828
+ resolveModelAlias,
2829
+ getEndpoints,
2830
+ buildGateHeaders,
2831
+ GATE_ANCHOR_TOOL_NAMES,
2832
+ GATE_ANCHOR_HEADER_NAMES,
2833
+ getSessionPrefix,
2834
+ createSessionId,
2835
+ getToolList,
2836
+ getState,
2837
+ __reset,
2838
+ __setLastCheckTime,
2839
+ __setSessionPrefix,
2840
+ __setToolProfile,
2841
+ };