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/gate-drill.ts ADDED
@@ -0,0 +1,1096 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * gate-drill.ts — prove the reactive self-heal against the *real* upstream gate.
4
+ *
5
+ * This is not a unit test. It deliberately starts the bridge in a state that
6
+ * upstream rejects, sends one client request, and checks that the bridge heals
7
+ * itself and the client still gets an answer. Nothing is mocked.
8
+ *
9
+ * Two drills, each mapped to a gate layer that was measured live:
10
+ *
11
+ * version-floor A User-Agent below the floor upstream advertises gets
12
+ * `426 UpgradeRequired` naming the minimum version. The
13
+ * bridge adopts that floor, refreshes from the handshake, and
14
+ * replays the request.
15
+ *
16
+ * endpoint-move A path migration upstream (the /zen/v1 → /inference/v1
17
+ * move) surfaces as a 404 at the old URL. The provider
18
+ * catalog is the authority for the base URL, so the bridge
19
+ * must re-derive and retry instead of handing the 404 to the
20
+ * client. This drill uses two local servers so it never
21
+ * depends on which path upstream currently serves.
22
+ *
23
+ * legacy-shape The v1.5.0 fingerprint — old ai-sdk User-Agent, old tool
24
+ * names, old session prefix — is replayed through the current
25
+ * bridge to confirm the access pattern is *not* what gates
26
+ * the free tier. It is kept as the control: it proves the
27
+ * bridge did not "fix" something that was never broken.
28
+ *
29
+ * empty-tools A profile that resolves to no tools makes upstream answer
30
+ * `403 FreeTierError`. The bridge must fall back to the
31
+ * shipped fingerprint instead of sending `tools: []`.
32
+ *
33
+ * session-shape The error this drill exists for:
34
+ * `403 {"type":"error","error":{"type":"FreeTierError",
35
+ * "message":"OpenCode's free tier can only be used from
36
+ * within OpenCode. Download it at https://opencode.ai ..."}}`
37
+ * Upstream reads that as "this is not the OpenCode client".
38
+ * Measured cause: the session id's shape. `ses_` + 12 lowercase
39
+ * hex + 14 base62 (exactly 30 chars) is accepted; a different
40
+ * prefix, length, or case is not. A stale recipe mints the
41
+ * wrong shape, so the bridge must re-mint after refreshing —
42
+ * replaying the stale id fails identically.
43
+ *
44
+ * What this drill does NOT do: fuzz the gate. Every failing request is one the
45
+ * bridge is about to heal, and the drills run sequentially with a small pause,
46
+ * because upstream applies a per-IP cooldown after a burst of failures.
47
+ *
48
+ * Usage:
49
+ * bun gate-drill.ts # all drills
50
+ * bun gate-drill.ts full-corrupt # one drill
51
+ */
52
+
53
+ const http = require("http");
54
+
55
+ const DRILLS: string[] = [
56
+ "version-floor",
57
+ "legacy-shape",
58
+ "empty-tools",
59
+ "session-shape",
60
+ "routing",
61
+ "allowlist",
62
+ "retry-endpoint",
63
+ "endpoint-move",
64
+ "gate-heal",
65
+ "full-corrupt",
66
+ ];
67
+
68
+ /** Token usage as the bridge reports it. */
69
+ interface Usage {
70
+ completion_tokens?: number;
71
+ }
72
+
73
+ /** One completion, SSE chunk, or error envelope — only the fields read here. */
74
+ interface CompletionBody {
75
+ choices?: Array<{
76
+ message?: { role?: string; content?: string; reasoning_content?: string };
77
+ delta?: { content?: string; reasoning_content?: string };
78
+ finish_reason?: string | null;
79
+ }>;
80
+ usage?: Usage | null;
81
+ error?: { message?: string };
82
+ tools?: unknown[];
83
+ }
84
+
85
+ /** One answer from the bridge, already folded back to a completion. */
86
+ interface DrillResponse {
87
+ status: number;
88
+ json: CompletionBody | null;
89
+ text: string;
90
+ }
91
+
92
+ /**
93
+ * The identity module surface the drills stage state through. Declared here
94
+ * rather than imported: identity is CommonJS, so its shape is the exported
95
+ * object, and this is the only slice a drill touches.
96
+ */
97
+ interface IdentityModule {
98
+ getState(): { versionFloor?: string | null; toolNames?: string[] };
99
+ getRecipe(): { version: string; sessionPrefix: string; sessionLength: number; sessionCharset: string };
100
+ getTools(): Record<string, unknown>;
101
+ getToolList(core: boolean, scope?: string): Array<{ function: { name: string } }>;
102
+ getEndpoints(): { chatUrl: string };
103
+ getUserAgent(): string;
104
+ getSessionPrefix(): string;
105
+ createSessionId(fresh: boolean): string;
106
+ applyRecipe(patch: Record<string, unknown>, tag?: string): void;
107
+ refresh(options?: { force?: boolean }): Promise<unknown>;
108
+ onGateRejection: (status: number, type: string, message: string, attempted: boolean) => Promise<{ retry: boolean; reason: string }>;
109
+ __setLastCheckTime(ms: number): void;
110
+ __setToolProfile(profile: Record<string, unknown> | null, tag: string): void;
111
+ __setSessionPrefix(prefix: string): void;
112
+ DEFAULT_TOOLS: Record<string, unknown>;
113
+ }
114
+
115
+ /** What main() hands each drill. */
116
+ interface DrillContext {
117
+ identity: IdentityModule;
118
+ __syncUserAgent: () => void;
119
+ sessionCache: Map<string, { sessionId: string }>;
120
+ }
121
+
122
+ function ask(port: number, body: Record<string, unknown>): Promise<DrillResponse> {
123
+ return new Promise((resolve, reject) => {
124
+ // The live drills must exercise the shape upstream actually accepts. A
125
+ // request without `stream` is refused with 403 FreeTierError before its
126
+ // content is read (measured 6/6 vs 0/6 against the same IP), which would
127
+ // make every drill report the gate as closed for a reason the drill itself
128
+ // created. `stream` is forced here rather than at each call site so a new
129
+ // drill cannot reintroduce the mistake.
130
+ const payload = JSON.stringify({ ...body, stream: true });
131
+ const req = http.request(
132
+ {
133
+ host: "127.0.0.1",
134
+ port,
135
+ path: "/v1/chat/completions",
136
+ method: "POST",
137
+ headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) },
138
+ },
139
+ (res) => {
140
+ const chunks = [];
141
+ res.on("data", (c) => chunks.push(c));
142
+ res.on("end", () => {
143
+ const text = Buffer.concat(chunks).toString("utf8");
144
+ let json = null;
145
+ try {
146
+ json = JSON.parse(text);
147
+ } catch {}
148
+ // A streaming answer arrives as SSE. Fold it into the completion
149
+ // shape `content()` expects so call sites stay protocol-agnostic.
150
+ if (!json && /^\s*data:/.test(text)) json = assembleSse(text);
151
+ resolve({ status: res.statusCode, json, text });
152
+ });
153
+ }
154
+ );
155
+ req.on("error", reject);
156
+ req.setTimeout(180000, () => req.destroy(new Error("client timeout")));
157
+ req.write(payload);
158
+ req.end();
159
+ });
160
+ }
161
+
162
+ /** Fold an SSE answer from the bridge into one completion object. */
163
+ function assembleSse(raw: string): CompletionBody {
164
+ let content = "";
165
+ let reasoning = "";
166
+ let finish: string | null = null;
167
+ let usage: Usage | null = null;
168
+ for (const line of raw.split("\n")) {
169
+ if (!line.startsWith("data:")) continue;
170
+ const chunk = line.slice(5).trim();
171
+ if (!chunk || chunk === "[DONE]") continue;
172
+ let ev: CompletionBody | null = null;
173
+ try { ev = JSON.parse(chunk); } catch { continue; }
174
+ if (ev?.error) return { error: ev.error };
175
+ const choice = ev?.choices?.[0];
176
+ if (choice?.delta?.content) content += choice.delta.content;
177
+ if (choice?.delta?.reasoning_content) reasoning += choice.delta.reasoning_content;
178
+ if (choice?.finish_reason) finish = choice.finish_reason;
179
+ if (ev?.usage) usage = ev.usage;
180
+ }
181
+ return {
182
+ choices: [{ message: { role: "assistant", content, reasoning_content: reasoning }, finish_reason: finish }],
183
+ usage,
184
+ };
185
+ }
186
+
187
+ function content(res: DrillResponse): string {
188
+ const msg = res.json?.choices?.[0]?.message;
189
+ return (msg?.content || "").trim();
190
+ }
191
+
192
+ function line(ok: boolean, label: string, detail: string = ""): void {
193
+ const mark = ok ? "OK " : "FAIL";
194
+ console.log(` ${mark} ${label}${detail ? " " + detail : ""}`);
195
+ }
196
+
197
+ /**
198
+ * Tri-state line: `true` prints OK, `false` prints FAIL, `null` prints SKIP.
199
+ *
200
+ * A live drill can only judge the layer it staged if upstream actually read the
201
+ * request. `429` is capacity, not a verdict on the request shape (the control
202
+ * probe treats it the same way), so an assertion that depends on upstream
203
+ * answering is `null` rather than a false failure.
204
+ */
205
+ function lineMaybe(ok: boolean | null, label: string, detail: string = ""): void {
206
+ const mark = ok === null ? "SKIP" : ok ? "OK " : "FAIL";
207
+ console.log(` ${mark} ${label}${detail ? " " + detail : ""}`);
208
+ }
209
+
210
+ /** Upstream answered with capacity pressure instead of a gate verdict. */
211
+ function isBusy(res: { status: number }): boolean {
212
+ return res.status === 429;
213
+ }
214
+
215
+ /** `ok`, or `null` when upstream gave no verdict to judge. */
216
+ function judge(ok: boolean, undecided: boolean): boolean | null {
217
+ return ok ? true : undecided ? null : false;
218
+ }
219
+
220
+ async function waitHealthy(port: number, timeoutMs: number = 30000): Promise<boolean> {
221
+ const deadline = Date.now() + timeoutMs;
222
+ while (Date.now() < deadline) {
223
+ try {
224
+ const res = await ask(port, { model: "big-pickle", messages: [{ role: "user", content: "ping" }] });
225
+ if (res.status === 200) return true;
226
+ } catch {}
227
+ await new Promise((r) => setTimeout(r, 1000));
228
+ }
229
+ return false;
230
+ }
231
+
232
+ async function drillVersionFloor({ identity, __syncUserAgent }: DrillContext): Promise<boolean | null> {
233
+ console.log("\nversion-floor — UA below the advertised floor (426 UpgradeRequired)");
234
+ const floorBefore = identity.getState().versionFloor;
235
+
236
+ // Pretend this bridge predates the floor. The request path stays reactive, so
237
+ // no proactive refresh is allowed to hide the rejection.
238
+ identity.applyRecipe({ version: "1.0.0" });
239
+ __syncUserAgent();
240
+ identity.__setLastCheckTime(Date.now());
241
+
242
+ const uaBefore = identity.getUserAgent();
243
+ console.log(` staged UA: ${uaBefore}`);
244
+ console.log(" sending one request (upstream should reject it)…");
245
+
246
+ const res = await ask(port(), {
247
+ model: "big-pickle",
248
+ messages: [{ role: "user", content: "Reply with exactly: OK" }],
249
+ });
250
+
251
+ const state = identity.getState();
252
+ const uaAfter = identity.getUserAgent();
253
+ const healed = state.versionFloor && state.versionFloor !== floorBefore;
254
+
255
+ console.log(` upstream floor: ${state.versionFloor || "(none)"}`);
256
+ console.log(` UA after : ${uaAfter}`);
257
+ console.log(` client saw : HTTP ${res.status} ${JSON.stringify(content(res))}`);
258
+
259
+ const busy = isBusy(res);
260
+ const answered = res.status === 200 && content(res).length > 0;
261
+ const moved =
262
+ uaAfter !== uaBefore &&
263
+ uaAfter.startsWith("opencode/latest/") &&
264
+ !uaAfter.includes("/1.0.0/");
265
+
266
+ lineMaybe(judge(res.status === 200, busy), "client received 200, not the gate error");
267
+ lineMaybe(judge(content(res).length > 0, busy), "client received real content");
268
+ // The heal half can only be judged when upstream issued a gate verdict: a 429
269
+ // never triggers the reactive refresh, so a stale UA/floor is the expected
270
+ // outcome, not a bridge fault (2026-11-07 CI: a 429 burst FAILed this drill).
271
+ lineMaybe(judge(healed, busy), "version floor was learned from the rejection");
272
+ lineMaybe(judge(uaAfter !== uaBefore, busy), "User-Agent moved off the rejected version");
273
+ lineMaybe(judge(moved, busy), "identity now follows the current release");
274
+
275
+ // A 429 means upstream never judged the healed shape, so the client-facing
276
+ // half of this drill is undecided even when every heal assertion passed.
277
+ if (busy) return null;
278
+ if (!healed || !moved) return false;
279
+ return judge(answered, busy);
280
+ }
281
+
282
+ async function drillLegacyShape({ identity, __syncUserAgent }: DrillContext): Promise<boolean | null> {
283
+ console.log("\nlegacy-shape — the v1.5.0 access pattern, through the current bridge");
284
+ console.log(" (control: this shape is accepted upstream, so it must keep working)");
285
+
286
+ // v1.5.0 sent this User-Agent and these tool names. Replaying them proves the
287
+ // current bridge is not relying on the *new* shape to pass — and that an old
288
+ // shape does not need "healing" it never needed.
289
+ const LEGACY_UA = "opencode/1.18.31 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14";
290
+ process.env.OPENCODE_USER_AGENT = LEGACY_UA;
291
+ __syncUserAgent();
292
+
293
+ const res = await ask(port(), {
294
+ model: "big-pickle",
295
+ messages: [{ role: "user", content: "Reply with exactly: OK" }],
296
+ tools: [
297
+ {
298
+ type: "function",
299
+ function: {
300
+ name: "read",
301
+ description: "Read a file",
302
+ parameters: { type: "object", properties: { path: { type: "string" } }, required: ["path"] },
303
+ },
304
+ },
305
+ ],
306
+ });
307
+
308
+ delete process.env.OPENCODE_USER_AGENT;
309
+ __syncUserAgent();
310
+
311
+ console.log(` legacy UA : ${LEGACY_UA}`);
312
+ console.log(` client saw : HTTP ${res.status} ${JSON.stringify(content(res))}`);
313
+
314
+ const busy = isBusy(res);
315
+ const answered = res.status === 200 && content(res).length > 0;
316
+ lineMaybe(judge(res.status === 200, busy), "legacy access pattern still accepted");
317
+ lineMaybe(judge(content(res).length > 0, busy), "legacy pattern returns real content");
318
+
319
+ return judge(answered, busy);
320
+ }
321
+
322
+ async function drillEmptyTools({ identity }: DrillContext): Promise<boolean | null> {
323
+ console.log("\nempty-tools — profile resolves to nothing (upstream 403 FreeTierError)");
324
+ const before = identity.getToolList(false).map((t) => t.function.name);
325
+
326
+ // An empty profile used to win over the shipped fallback (objects are
327
+ // truthy), so the bridge sent `tools: []` and upstream answered 403.
328
+ identity.__setToolProfile({}, "test");
329
+ identity.__setLastCheckTime(Date.now());
330
+
331
+ const res = await ask(port(), {
332
+ model: "big-pickle",
333
+ messages: [{ role: "user", content: "Reply with exactly: OK" }],
334
+ });
335
+ const after = identity.getToolList(false).map((t) => t.function.name);
336
+
337
+ console.log(` tools before: ${JSON.stringify(before)}`);
338
+ console.log(` tools after : ${JSON.stringify(after)}`);
339
+ console.log(` client saw : HTTP ${res.status} ${JSON.stringify(content(res))}`);
340
+
341
+ const busy = isBusy(res);
342
+ const answered = res.status === 200 && content(res).length > 0;
343
+ line(after.length > 0, "an empty profile falls back to the shipped tools");
344
+ lineMaybe(judge(res.status === 200, busy), "client received 200, not 403");
345
+ lineMaybe(judge(content(res).length > 0, busy), "client received real content");
346
+
347
+ if (after.length === 0) return false;
348
+ return judge(answered, busy);
349
+ }
350
+
351
+ async function drillSessionShape({ identity, __syncUserAgent, sessionCache }: DrillContext): Promise<boolean | null> {
352
+ console.log("\nsession-shape — id upstream reads as \"not OpenCode\" (403 FreeTierError)");
353
+ console.log(" measured rule: `ses_` + 12 lowercase hex + 14 base62 (30 chars)");
354
+
355
+ // Drop the underscore from the prefix. Upstream rejects that deterministically
356
+ // with the FreeTierError, while a correct id passes — the two differ only in
357
+ // the prefix, so the drill isolates exactly the layer it claims to.
358
+ const goodPrefix = identity.getSessionPrefix();
359
+ identity.__setSessionPrefix("ses");
360
+ __syncUserAgent();
361
+ identity.__setLastCheckTime(Date.now());
362
+
363
+ const staged = identity.createSessionId(true);
364
+ console.log(` staged id : ${staged} (len ${staged.length}, prefix "ses")`);
365
+ console.log(" sending one request (upstream should reject it as not-OpenCode)…");
366
+
367
+ const res = await ask(port(), {
368
+ model: "big-pickle",
369
+ messages: [{ role: "user", content: "Reply with exactly: OK" }],
370
+ });
371
+
372
+ const after = identity.createSessionId(true);
373
+ const cached = [...sessionCache.values()].map((e) => e.sessionId);
374
+
375
+ console.log(` id after : ${after} (len ${after.length}, prefix "${identity.getSessionPrefix()}")`);
376
+ console.log(` client saw : HTTP ${res.status} ${JSON.stringify(content(res))}`);
377
+
378
+ const busy = isBusy(res);
379
+ const answered = res.status === 200 && content(res).length > 0;
380
+ const prefixRestored = identity.getSessionPrefix() === goodPrefix;
381
+ const shapeOk = /^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/.test(after);
382
+ const cacheClean = cached.every((id) => /^ses_/.test(id));
383
+
384
+ lineMaybe(judge(res.status === 200, busy), "client received 200, not the FreeTierError");
385
+ lineMaybe(judge(content(res).length > 0, busy), "client received real content");
386
+ // This drill stages a 403 shape rejection, and the refresh it asserts only
387
+ // runs on one. Upstream now answers a malformed id with the same
388
+ // `429 FreeUsageLimitError` it uses for a spent allowance, so a 429 means the
389
+ // premise never ran — capacity, not a bridge fault. Reporting FAIL there
390
+ // blamed the bridge for upstream's verdict, which the two lines above
391
+ // already model as undecided.
392
+ lineMaybe(judge(prefixRestored, busy), "prefix restored by the refresh");
393
+ lineMaybe(judge(shapeOk, busy), "re-minted id matches the accepted shape");
394
+ lineMaybe(judge(cacheClean, busy), "no rejected id left in the session cache");
395
+
396
+ if (busy) return null;
397
+ if (!prefixRestored || !shapeOk || !cacheClean) return false;
398
+ return judge(answered, busy);
399
+ }
400
+
401
+ /**
402
+ * routing — the wire endpoint is read per request from the derived value.
403
+ *
404
+ * The whole point of deriving endpoints from the upstream catalog is that a
405
+ * path migration upstream (the /zen/v1 → /inference/v1 move) must not need a
406
+ * bridge release. This drill proves the read happens on the request path, not
407
+ * at boot: it repoints the chat endpoint at a local fake *after* the bridge is
408
+ * up, sends a request, and checks the fake received it.
409
+ */
410
+ async function drillRouting({ identity }: DrillContext): Promise<boolean> {
411
+ console.log("\nrouting — endpoint derived at request time, not frozen at boot");
412
+
413
+ const received = [];
414
+ const fake = http.createServer((req, res) => {
415
+ received.push(req.url);
416
+ res.writeHead(200, { "Content-Type": "text/event-stream" });
417
+ res.write(
418
+ `data: ${JSON.stringify({
419
+ id: "chatcmpl-fake",
420
+ object: "chat.completion.chunk",
421
+ choices: [{ index: 0, delta: { content: "OK" }, finish_reason: null }],
422
+ })}\n\n`
423
+ );
424
+ res.write(
425
+ `data: ${JSON.stringify({
426
+ id: "chatcmpl-fake",
427
+ object: "chat.completion.chunk",
428
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
429
+ })}\n\n`
430
+ );
431
+ res.write("data: [DONE]\n\n");
432
+ res.end();
433
+ });
434
+ await new Promise((resolve) => fake.listen(0, "127.0.0.1", resolve));
435
+ const fakePort = fake.address().port;
436
+
437
+ const before = identity.getEndpoints().chatUrl;
438
+ identity.applyRecipe({ chatUrl: `http://127.0.0.1:${fakePort}/inference/openai/v1/chat/completions` });
439
+
440
+ const res = await ask(port(), {
441
+ model: "big-pickle",
442
+ messages: [{ role: "user", content: "Reply with exactly: OK" }],
443
+ });
444
+
445
+ identity.applyRecipe({ chatUrl: before });
446
+ await new Promise((resolve) => fake.close(resolve));
447
+
448
+ console.log(` endpoint before : ${before}`);
449
+ console.log(` endpoint staged : http://127.0.0.1:${fakePort}/inference/openai/v1/chat/completions`);
450
+ console.log(` fake received : ${JSON.stringify(received)}`);
451
+ console.log(` client saw : HTTP ${res.status} ${JSON.stringify(content(res))}`);
452
+
453
+ line(received.length === 1, "the request went to the newly derived endpoint");
454
+ line(
455
+ received[0] === "/inference/openai/v1/chat/completions",
456
+ "the full derived path was used, not the boot-time one"
457
+ );
458
+ line(res.status === 200, "client received 200");
459
+ line(identity.getEndpoints().chatUrl === before, "endpoint restored after the drill");
460
+
461
+ return received.length === 1 && res.status === 200;
462
+ }
463
+
464
+ /**
465
+ * allowlist — tool names are derived from the release's tool sources.
466
+ *
467
+ * The gate validates which tools are present; the schemas are not compared.
468
+ * This checks that a name learned from source reaches the wire in `full` scope
469
+ * (the scope the gate-rejection retry uses) even when everything else is
470
+ * unchanged, which is what makes an upstream rename self-healing.
471
+ */
472
+ async function drillAllowlist({ identity }: DrillContext): Promise<boolean> {
473
+ console.log("\nallowlist — source-derived tool names reach the wire");
474
+
475
+ const before = identity.getState().toolNames;
476
+ // Simulate upstream renaming `shell` → `run` in its tool sources.
477
+ identity.applyRecipe({
478
+ tools: {
479
+ read: { description: "r".repeat(30), parameters: { type: "object", properties: {} } },
480
+ run: { description: "x".repeat(30), parameters: { type: "object", properties: {} } },
481
+ },
482
+ toolNames: ["read", "run"],
483
+ });
484
+
485
+ const core = identity.getToolList(false).map((t) => t.function.name);
486
+ const full = identity.getToolList(false, "full").map((t) => t.function.name);
487
+
488
+ console.log(` allowlist : ${JSON.stringify(identity.getState().toolNames)}`);
489
+ console.log(` core scope wire : ${JSON.stringify(core)}`);
490
+ console.log(` full scope wire : ${JSON.stringify(full)}`);
491
+
492
+ line(core.length > 0, "core scope still sends a gate anchor");
493
+ line(full.includes("run"), "the renamed tool reaches the wire in full scope");
494
+ line(!full.includes("shell"), "the retired name is not kept alive");
495
+
496
+ identity.__setToolProfile(null, "default");
497
+ identity.applyRecipe({ toolNames: before });
498
+
499
+ return full.includes("run") && core.length > 0;
500
+ }
501
+
502
+ /**
503
+ * retry-endpoint — the gate-rejection retry re-resolves the endpoint.
504
+ *
505
+ * A refresh can learn a new endpoint from the catalog. If the retry reused the
506
+ * URL captured before the refresh, the healed request would still go to the
507
+ * stale path. This drill stages a rejecting upstream at the boot-time URL and a
508
+ * healthy fake at the catalog-derived URL, then checks the retry lands on the
509
+ * latter.
510
+ */
511
+ async function drillRetryEndpoint({ identity }: DrillContext): Promise<boolean> {
512
+ console.log("\nretry-endpoint — the self-heal retry uses the refreshed endpoint");
513
+
514
+ const hits = [];
515
+ const rejecting = http.createServer((req, res) => {
516
+ hits.push("old");
517
+ res.writeHead(403, { "Content-Type": "application/json" });
518
+ res.end(
519
+ JSON.stringify({
520
+ type: "error",
521
+ error: { type: "FreeTierError", message: "OpenCode's free tier can only be used from within OpenCode." },
522
+ })
523
+ );
524
+ });
525
+ const healthy = http.createServer((req, res) => {
526
+ hits.push("new");
527
+ res.writeHead(200, { "Content-Type": "text/event-stream" });
528
+ res.write(
529
+ `data: ${JSON.stringify({
530
+ id: "chatcmpl-fake",
531
+ object: "chat.completion.chunk",
532
+ choices: [{ index: 0, delta: { content: "OK" }, finish_reason: null }],
533
+ })}\n\n`
534
+ );
535
+ res.write(
536
+ `data: ${JSON.stringify({
537
+ id: "chatcmpl-fake",
538
+ object: "chat.completion.chunk",
539
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
540
+ })}\n\n`
541
+ );
542
+ res.write("data: [DONE]\n\n");
543
+ res.end();
544
+ });
545
+ await new Promise((r) => rejecting.listen(0, "127.0.0.1", r));
546
+ await new Promise((r) => healthy.listen(0, "127.0.0.1", r));
547
+ const oldPort = rejecting.address().port;
548
+ const newPort = healthy.address().port;
549
+
550
+ const before = identity.getEndpoints().chatUrl;
551
+ identity.applyRecipe({ chatUrl: `http://127.0.0.1:${oldPort}/chat/completions` });
552
+
553
+ // A refresh that "learns" the new endpoint: the drill calls applyRecipe the
554
+ // way refresh() does when the catalog moved.
555
+ const realOnGate = identity.onGateRejection;
556
+ identity.onGateRejection = async () => {
557
+ identity.applyRecipe({ chatUrl: `http://127.0.0.1:${newPort}/chat/completions` });
558
+ return { retry: true, reason: "drill-catalog-move" };
559
+ };
560
+
561
+ let res;
562
+ try {
563
+ res = await ask(port(), {
564
+ model: "big-pickle",
565
+ messages: [{ role: "user", content: "Reply with exactly: OK" }],
566
+ });
567
+ } finally {
568
+ identity.onGateRejection = realOnGate;
569
+ identity.applyRecipe({ chatUrl: before });
570
+ await new Promise((r) => rejecting.close(r));
571
+ await new Promise((r) => healthy.close(r));
572
+ }
573
+
574
+ console.log(` attempts : ${JSON.stringify(hits)}`);
575
+ console.log(` client saw : HTTP ${res.status} ${JSON.stringify(content(res))}`);
576
+
577
+ line(hits[0] === "old", "first attempt used the pre-refresh endpoint");
578
+ line(hits[1] === "new", "retry used the endpoint learned by the refresh");
579
+ line(res.status === 200, "client received 200");
580
+
581
+ return hits[0] === "old" && hits[1] === "new" && res.status === 200;
582
+ }
583
+
584
+ /**
585
+ * endpoint-move — a 404 at a stale path re-derives the endpoint and retries.
586
+ *
587
+ * This is the failure mode of an upstream path migration: the old URL stops
588
+ * routing and answers 404 (HTML, not a gate error). Without this heal the
589
+ * client would see the 404 even though the bridge knows a catalog URL. Two
590
+ * local servers stand in for the old and new paths, so the drill is
591
+ * deterministic and does not depend on what upstream currently serves.
592
+ */
593
+ async function drillEndpointMove({ identity }: DrillContext): Promise<boolean> {
594
+ console.log("\nendpoint-move — a 404 at the stale path re-derives and retries");
595
+
596
+ const hits = [];
597
+ const gone = http.createServer((req, res) => {
598
+ hits.push("old");
599
+ res.writeHead(404, { "Content-Type": "text/html" });
600
+ res.end("<!DOCTYPE html><html><body>not found</body></html>");
601
+ });
602
+ const healthy = http.createServer((req, res) => {
603
+ hits.push("new");
604
+ res.writeHead(200, { "Content-Type": "text/event-stream" });
605
+ res.write(
606
+ `data: ${JSON.stringify({
607
+ id: "chatcmpl-fake",
608
+ object: "chat.completion.chunk",
609
+ choices: [{ index: 0, delta: { content: "OK" }, finish_reason: null }],
610
+ })}\n\n`
611
+ );
612
+ res.write(
613
+ `data: ${JSON.stringify({
614
+ id: "chatcmpl-fake",
615
+ object: "chat.completion.chunk",
616
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
617
+ })}\n\n`
618
+ );
619
+ res.write("data: [DONE]\n\n");
620
+ res.end();
621
+ });
622
+ await new Promise((r) => gone.listen(0, "127.0.0.1", r));
623
+ await new Promise((r) => healthy.listen(0, "127.0.0.1", r));
624
+ const gonePort = gone.address().port;
625
+ const healthyPort = healthy.address().port;
626
+
627
+ const before = identity.getEndpoints().chatUrl;
628
+ identity.applyRecipe({ chatUrl: `http://127.0.0.1:${gonePort}/old/chat/completions` });
629
+ identity.__setLastCheckTime(Date.now());
630
+
631
+ // Stand in for the catalog refresh: the drill stages the migrated URL the way
632
+ // refresh() adopts `chatUrl` from the provider catalog.
633
+ const realRefresh = identity.refresh;
634
+ identity.refresh = async () => {
635
+ identity.applyRecipe({ chatUrl: `http://127.0.0.1:${healthyPort}/v1/chat/completions` });
636
+ return { updated: true, changed: ["chatUrl"] };
637
+ };
638
+
639
+ let res;
640
+ try {
641
+ res = await ask(port(), {
642
+ model: "big-pickle",
643
+ messages: [{ role: "user", content: "Reply with exactly: OK" }],
644
+ });
645
+ } finally {
646
+ identity.refresh = realRefresh;
647
+ identity.applyRecipe({ chatUrl: before });
648
+ await new Promise((r) => gone.close(r));
649
+ await new Promise((r) => healthy.close(r));
650
+ }
651
+
652
+ console.log(` attempts : ${JSON.stringify(hits)}`);
653
+ console.log(` client saw : HTTP ${res.status} ${JSON.stringify(content(res))}`);
654
+
655
+ line(hits[0] === "old", "first attempt hit the stale path");
656
+ line(hits[1] === "new", "the 404 triggered a re-derived retry");
657
+ line(res.status === 200, "client received 200, not the 404");
658
+ line(content(res).length > 0, "client received real content");
659
+
660
+ return hits[0] === "old" && hits[1] === "new" && res.status === 200;
661
+ }
662
+
663
+ /**
664
+ * Control probe: is upstream accepting this IP *at all* right now?
665
+ *
666
+ * The live drills stage a rejected shape and expect the bridge to heal it. But
667
+ * the gateway also refuses a healthy request with the same `403 FreeTierError`
668
+ * when the caller's allowance is exhausted — measured: byte-identical CLI
669
+ * requests alternate 200/403 within seconds. Without a control, a throttled IP
670
+ * makes every live drill report FAIL even though nothing is wrong with the
671
+ * bridge, and each of those failures pushes the cooldown further out.
672
+ *
673
+ * The probe is a direct request, not one through the bridge, shaped the way the
674
+ * real CLI shapes it (`max_completion_tokens`, `store: false`, full tool set).
675
+ * 200 or 429 means the gate is open (429 is capacity, not refusal). It honours
676
+ * the configured egress proxy, so its verdict describes the IP upstream would
677
+ * actually see.
678
+ */
679
+ async function probeUpstream(identity: IdentityModule): Promise<{ open: boolean; status: number; detail: string }> {
680
+ const { buildUpstreamPayload, buildUpstreamHeaders, resolveEndpoints } = require("./server");
681
+ const model = "big-pickle";
682
+ const sessionId = identity.createSessionId(true);
683
+ const headers = buildUpstreamHeaders({ headers: {} }, sessionId);
684
+ const body = buildUpstreamPayload(
685
+ { model, messages: [{ role: "user", content: "Reply with exactly: OK" }], max_tokens: 24 },
686
+ model,
687
+ false,
688
+ "full"
689
+ ).upstreamBody;
690
+ // Match the CLI's own token field: this is the shape measured to pass.
691
+ body.max_completion_tokens = body.max_tokens;
692
+ delete body.max_tokens;
693
+ body.store = false;
694
+ // `stream` must stay `true`. buildUpstreamPayload sets it, and this probe
695
+ // deliberately keeps the whole shape: measured from one IP and one header
696
+ // set, the same request without `stream` is refused with 403 FreeTierError
697
+ // while the streaming one succeeds (6/6 vs 0/6, interleaved). A probe that
698
+ // dropped it would report a healthy IP as gate-closed.
699
+ if (body.stream !== true) {
700
+ throw new Error("probeUpstream must send stream: true or the verdict is meaningless");
701
+ }
702
+
703
+ try {
704
+ const res = await require("./proxy").netFetch(resolveEndpoints(model).chatUrl, {
705
+ method: "POST",
706
+ headers,
707
+ body: JSON.stringify(body),
708
+ signal: AbortSignal.timeout(60000),
709
+ });
710
+ const text = await res.text().catch(() => "");
711
+ const open = res.status === 200 || res.status === 429;
712
+ return { open, status: res.status, detail: text.slice(0, 120).replace(/\n/g, " ") };
713
+ } catch (err) {
714
+ return { open: false, status: 0, detail: err.message };
715
+ }
716
+ }
717
+
718
+ /**
719
+ * gate-heal — the whole reactive path, against a deterministic fake gate.
720
+ *
721
+ * The live drills prove the heal against the real service, but they need the
722
+ * caller's IP to be inside its allowance. This drill stages the same sequence
723
+ * offline: a fake upstream that refuses the staged shape with `403
724
+ * FreeTierError` and accepts the refreshed one. It asserts the *order* of the
725
+ * heal (stale request → refresh → re-minted id → full tool set → retry → 200),
726
+ * which is what the bridge controls; whether upstream is in the mood is not.
727
+ */
728
+ async function drillGateHeal({ identity }: DrillContext): Promise<boolean> {
729
+ console.log("\ngate-heal — reactive heal, deterministic fake gate (no live upstream)");
730
+
731
+ const seen: Array<{ ok: boolean; sid: string; toolCount: number }> = [];
732
+ let rejectedOnce = false;
733
+ const fake = http.createServer((req, res) => {
734
+ let raw = "";
735
+ req.on("data", (c) => (raw += c));
736
+ req.on("end", () => {
737
+ let body: CompletionBody = {};
738
+ try {
739
+ body = JSON.parse(raw);
740
+ } catch {}
741
+ const sid = String(req.headers["x-opencode-session-id"] || "");
742
+ const toolCount = Array.isArray(body.tools) ? body.tools.length : 0;
743
+ const shapeOk = sid.startsWith("ses_") && toolCount > 2;
744
+
745
+ if (!shapeOk && !rejectedOnce) {
746
+ rejectedOnce = true;
747
+ seen.push({ ok: false, sid, toolCount });
748
+ res.writeHead(403, { "Content-Type": "application/json" });
749
+ return res.end(
750
+ JSON.stringify({
751
+ type: "error",
752
+ error: {
753
+ type: "FreeTierError",
754
+ message: "OpenCode's free tier can only be used from within OpenCode.",
755
+ },
756
+ })
757
+ );
758
+ }
759
+ seen.push({ ok: true, sid, toolCount });
760
+ res.writeHead(200, { "Content-Type": "text/event-stream" });
761
+ res.write(
762
+ `data: ${JSON.stringify({
763
+ id: "chatcmpl-fake",
764
+ object: "chat.completion.chunk",
765
+ choices: [{ index: 0, delta: { content: "OK" }, finish_reason: null }],
766
+ })}\n\n`
767
+ );
768
+ res.write(
769
+ `data: ${JSON.stringify({
770
+ id: "chatcmpl-fake",
771
+ object: "chat.completion.chunk",
772
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
773
+ })}\n\n`
774
+ );
775
+ res.write("data: [DONE]\n\n");
776
+ res.end();
777
+ });
778
+ });
779
+ await new Promise((r) => fake.listen(0, "127.0.0.1", r));
780
+ const fakePort = fake.address().port;
781
+
782
+ const beforeUrl = identity.getEndpoints().chatUrl;
783
+ identity.applyRecipe({ chatUrl: `http://127.0.0.1:${fakePort}/v1/chat/completions` });
784
+ identity.__setSessionPrefix("ses"); // the shape upstream reads as "not OpenCode"
785
+ identity.__setLastCheckTime(Date.now());
786
+
787
+ // Stand in for the refresh: restore the derived shape the real refresh learns.
788
+ const realOnGate = identity.onGateRejection;
789
+ identity.onGateRejection = async () => {
790
+ identity.__setSessionPrefix("ses_");
791
+ // A real refresh also reads the release's tool sources. Seed the profile it
792
+ // would produce, so this drill asserts the escalation path rather than the
793
+ // "source unreachable" fallback (which can only offer the shipped set).
794
+ identity.applyRecipe({
795
+ tools: {
796
+ read: identity.DEFAULT_TOOLS.read,
797
+ shell: identity.DEFAULT_TOOLS.shell,
798
+ glob: { description: "g".repeat(40), parameters: { type: "object", properties: {} } },
799
+ edit: { description: "e".repeat(40), parameters: { type: "object", properties: {} } },
800
+ },
801
+ toolNames: ["read", "shell", "glob", "edit"],
802
+ });
803
+ return { retry: true, reason: "drill-refresh" };
804
+ };
805
+
806
+ let res;
807
+ try {
808
+ res = await ask(port(), {
809
+ model: "big-pickle",
810
+ messages: [{ role: "user", content: "Reply with exactly: OK" }],
811
+ });
812
+ } finally {
813
+ identity.onGateRejection = realOnGate;
814
+ identity.applyRecipe({ chatUrl: beforeUrl });
815
+ identity.__setSessionPrefix("ses_");
816
+ await new Promise((r) => fake.close(r));
817
+ }
818
+
819
+ const first = seen[0];
820
+ const retry = seen[1];
821
+ console.log(` attempts : ${JSON.stringify(seen.map((s) => ({ ok: s.ok, sid: s.sid.slice(0, 8), tools: s.toolCount })))}`);
822
+ console.log(` client saw : HTTP ${res.status} ${JSON.stringify(content(res))}`);
823
+
824
+ line(Boolean(first) && !first.ok, "first attempt carried the rejected shape");
825
+ line(Boolean(retry) && retry.ok, "the retry carried a refreshed shape");
826
+ line(Boolean(retry) && retry.sid.startsWith("ses_"), "the retry re-minted the session id");
827
+ line(Boolean(retry) && retry.toolCount > 2, "the retry escalated to the full tool set");
828
+ line(res.status === 200, "client received 200, not the gate error");
829
+ line(content(res).length > 0, "client received real content");
830
+
831
+ return Boolean(retry) && retry.ok && res.status === 200 && content(res).length > 0;
832
+ }
833
+
834
+
835
+ /**
836
+ * full-corrupt — break every adaptive layer at once, then prove one request
837
+ * heals them all.
838
+ *
839
+ * The other drills each break one layer. This one breaks all of them together,
840
+ * which is what a real upstream change looks like when it lands: the version
841
+ * floor moves, the session shape changes, and the tool set is replaced in the
842
+ * same release. The gate here is local and deterministic, so the drill reports
843
+ * a verdict even when the live IP is throttled.
844
+ *
845
+ * The layers corrupted:
846
+ * version -> 0.9.9 (below any floor)
847
+ * session prefix -> old_
848
+ * session length -> 20 (valid range, wrong value)
849
+ * session charset-> hex only (wrong alphabet)
850
+ * tool set -> the shipped default instead of the derived profile
851
+ *
852
+ * Everything is asserted against the values derived from source, not against
853
+ * hardcoded expectations, so this keeps working when upstream changes them.
854
+ */
855
+ async function drillFullCorrupt({ identity }: DrillContext): Promise<boolean> {
856
+ console.log("\nfull-corrupt — every layer broken at once, one request heals them");
857
+
858
+ await identity.refresh({ force: true });
859
+ const good = {
860
+ version: identity.getRecipe().version,
861
+ prefix: identity.getRecipe().sessionPrefix,
862
+ length: identity.getRecipe().sessionLength,
863
+ charset: identity.getRecipe().sessionCharset,
864
+ tools: Object.keys(identity.getTools()).sort().join(","),
865
+ ua: identity.getUserAgent(),
866
+ };
867
+
868
+ const SESSION = /^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/;
869
+ const seen: Array<{ sid: string; ua: string; toolCount: number; bad: string[] }> = [];
870
+ const fake = http.createServer((req, res) => {
871
+ let raw = "";
872
+ req.on("data", (c) => (raw += c));
873
+ req.on("end", () => {
874
+ let body: CompletionBody = {};
875
+ try {
876
+ body = JSON.parse(raw);
877
+ } catch {}
878
+ const sid = String(req.headers["x-opencode-session-id"] || req.headers["x-opencode-session"] || "");
879
+ const ua = String(req.headers["user-agent"] || "");
880
+ const toolCount = Array.isArray(body.tools) ? body.tools.length : 0;
881
+ const bad = [];
882
+ if (!SESSION.test(sid)) bad.push("session");
883
+ if (!/^opencode\/latest\/\d+\.\d+\.\d+\/cli$/.test(ua)) bad.push("ua");
884
+ if (toolCount < 3) bad.push("tools");
885
+ seen.push({ sid, ua, toolCount, bad });
886
+
887
+ if (bad.length) {
888
+ res.writeHead(403, { "Content-Type": "application/json" });
889
+ return res.end(
890
+ JSON.stringify({
891
+ type: "error",
892
+ error: { type: "FreeTierError", message: "rejected: " + bad.join(",") },
893
+ })
894
+ );
895
+ }
896
+ res.writeHead(200, { "Content-Type": "text/event-stream" });
897
+ res.write(
898
+ `data: ${JSON.stringify({
899
+ id: "chatcmpl-fake",
900
+ object: "chat.completion.chunk",
901
+ choices: [{ index: 0, delta: { content: "HEALED" }, finish_reason: null }],
902
+ })}\n\n`
903
+ );
904
+ res.write(
905
+ `data: ${JSON.stringify({
906
+ id: "chatcmpl-fake",
907
+ object: "chat.completion.chunk",
908
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
909
+ })}\n\n`
910
+ );
911
+ res.write("data: [DONE]\n\n");
912
+ res.end();
913
+ });
914
+ });
915
+ await new Promise((r) => fake.listen(0, "127.0.0.1", r));
916
+ const fakePort = fake.address().port;
917
+
918
+ const beforeUrl = identity.getEndpoints().chatUrl;
919
+ const realOnGate = identity.onGateRejection;
920
+ identity.applyRecipe(
921
+ {
922
+ version: "0.9.9",
923
+ sessionPrefix: "old_",
924
+ sessionLength: 20,
925
+ sessionCharset: "abcdef0123456789",
926
+ chatUrl: `http://127.0.0.1:${fakePort}/v1/chat/completions`,
927
+ },
928
+ "full-corrupt"
929
+ );
930
+ identity.__setLastCheckTime(Date.now());
931
+
932
+ // Let the real onGateRejection run (that is the code under test); only pin the
933
+ // endpoint afterwards so the retry reaches this local gate instead of the
934
+ // internet. Endpoint healing itself is covered by endpoint-move.
935
+ identity.onGateRejection = async (status, type, msg, attempted) => {
936
+ const verdict = await realOnGate(status, type, msg, attempted);
937
+ identity.applyRecipe({ chatUrl: `http://127.0.0.1:${fakePort}/v1/chat/completions` });
938
+ return verdict;
939
+ };
940
+
941
+ let res;
942
+ try {
943
+ res = await ask(port(), {
944
+ model: "big-pickle",
945
+ messages: [{ role: "user", content: "Reply with exactly: OK" }],
946
+ });
947
+ } finally {
948
+ identity.onGateRejection = realOnGate;
949
+ identity.applyRecipe({ chatUrl: beforeUrl });
950
+ await new Promise((r) => fake.close(r));
951
+ }
952
+
953
+ const after = {
954
+ version: identity.getRecipe().version,
955
+ prefix: identity.getRecipe().sessionPrefix,
956
+ length: identity.getRecipe().sessionLength,
957
+ charset: identity.getRecipe().sessionCharset,
958
+ tools: Object.keys(identity.getTools()).sort().join(","),
959
+ ua: identity.getUserAgent(),
960
+ };
961
+
962
+ console.log(` corrupted : v0.9.9, old_/20, hex charset, shipped tools`);
963
+ console.log(` attempts : ${JSON.stringify(seen.map((s) => ({ sid: s.sid.slice(0, 12), ua: s.ua.split("/")[2] || "?", tools: s.toolCount, bad: s.bad })))}`);
964
+ console.log(` client saw : HTTP ${res.status} ${JSON.stringify(content(res))}`);
965
+
966
+ line(Boolean(seen[0]) && seen[0].bad.length > 0, "first attempt carried every broken layer");
967
+ line(Boolean(seen[1]) && seen[1].bad.length === 0, "the retry carried a fully healed shape");
968
+ line(res.status === 200, "client received 200, not the gate error");
969
+ line(after.version === good.version, `version healed to ${good.version}`, `(was 0.9.9)`);
970
+ line(after.prefix === good.prefix, `session prefix healed to ${good.prefix}`, `(was old_)`);
971
+ line(after.length === good.length, `session length healed to ${good.length}`, `(was 20)`);
972
+ line(after.charset === good.charset, `session charset healed`, `(${after.charset?.length} chars)`);
973
+ line(after.tools === good.tools, `tool set healed`, `(${after.tools.split(",").length} tools)`);
974
+ line(after.ua === good.ua, `User-Agent healed`, `(${after.ua})`);
975
+
976
+ return (
977
+ Boolean(seen[0]) &&
978
+ seen[0].bad.length > 0 &&
979
+ Boolean(seen[1]) &&
980
+ seen[1].bad.length === 0 &&
981
+ res.status === 200 &&
982
+ after.version === good.version &&
983
+ after.prefix === good.prefix &&
984
+ after.length === good.length &&
985
+ after.charset === good.charset &&
986
+ after.tools === good.tools &&
987
+ after.ua === good.ua
988
+ );
989
+ }
990
+
991
+ async function main(): Promise<void> {
992
+ const wanted = process.argv.slice(2).filter((a) => !a.startsWith("-"));
993
+ const drills = wanted.length > 0 ? wanted : DRILLS;
994
+ const unknown = drills.filter((d) => !DRILLS.includes(d));
995
+ if (unknown.length > 0) {
996
+ console.error(`unknown drill(s): ${unknown.join(", ")}\nknown: ${DRILLS.join(", ")}`);
997
+ process.exit(2);
998
+ }
999
+
1000
+ const srv = require("./server");
1001
+ const { server, identity, discoverModels, __syncUserAgent, sessionCache } = srv;
1002
+
1003
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
1004
+ const boundPort = server.address().port;
1005
+ port = () => boundPort;
1006
+
1007
+ console.log(`gate drill — bridge v${srv.VERSION} on http://127.0.0.1:${boundPort}`);
1008
+ console.log(" live upstream, no mocks, sequential (upstream rate-limits failures)");
1009
+
1010
+ await discoverModels();
1011
+ const models = srv.__getDiscoveryState().activeModels;
1012
+ console.log(` discovered ${models.length} free models`);
1013
+
1014
+ // Only the drills that talk to upstream need the gate to be open.
1015
+ const LIVE = new Set(["version-floor", "legacy-shape", "empty-tools", "session-shape"]);
1016
+ const liveWanted = drills.filter((d) => LIVE.has(d));
1017
+ let gateOpen = true;
1018
+ if (liveWanted.length > 0) {
1019
+ const probe = await probeUpstream(identity);
1020
+ gateOpen = probe.open;
1021
+ console.log(
1022
+ ` upstream control: HTTP ${probe.status} → gate ${gateOpen ? "open" : "CLOSED"}${gateOpen ? "" : ` (${probe.detail})`}`
1023
+ );
1024
+ if (!gateOpen) {
1025
+ console.log(
1026
+ " live drills skipped: a direct CLI-shaped request was refused, so upstream is not accepting this IP right now."
1027
+ );
1028
+ console.log(
1029
+ " This is the per-IP allowance, not a bridge fault — rerun later for a live verdict. Offline drills still run."
1030
+ );
1031
+ }
1032
+ await new Promise((r) => setTimeout(r, 3000));
1033
+ }
1034
+
1035
+ const results: Array<[string, boolean | null]> = [];
1036
+ for (const name of drills) {
1037
+ if (LIVE.has(name) && !gateOpen) {
1038
+ results.push([name, null]); // skipped, not failed
1039
+ continue;
1040
+ }
1041
+ const DRILL_FNS: Record<string, (ctx: DrillContext) => Promise<boolean | null>> = {
1042
+ "version-floor": drillVersionFloor,
1043
+ "legacy-shape": drillLegacyShape,
1044
+ "empty-tools": drillEmptyTools,
1045
+ "session-shape": drillSessionShape,
1046
+ routing: drillRouting,
1047
+ allowlist: drillAllowlist,
1048
+ "retry-endpoint": drillRetryEndpoint,
1049
+ "endpoint-move": drillEndpointMove,
1050
+ "gate-heal": drillGateHeal,
1051
+ "full-corrupt": drillFullCorrupt,
1052
+ };
1053
+ const fn = DRILL_FNS[name];
1054
+ // A cached session id from a previous drill would be reused for an
1055
+ // identical message and hide the condition being staged.
1056
+ sessionCache.clear();
1057
+ const ctx: DrillContext = { identity, __syncUserAgent, sessionCache };
1058
+ try {
1059
+ results.push([name, await fn(ctx)]);
1060
+ } catch (err) {
1061
+ console.log(` FAIL ${name} threw: ${err.message}`);
1062
+ results.push([name, false]);
1063
+ }
1064
+ // Upstream cools down after bursts of failures; keep the drill gentle.
1065
+ await new Promise((r) => setTimeout(r, 3000));
1066
+ }
1067
+
1068
+ server.close();
1069
+
1070
+ console.log("\nSummary");
1071
+ for (const [name, ok] of results) {
1072
+ console.log(` ${ok === null ? "SKIP" : ok ? "PASS" : "FAIL"} ${name}`);
1073
+ }
1074
+ const failed = results.filter(([, ok]) => ok === false);
1075
+ const skipped = results.filter(([, ok]) => ok === null);
1076
+ if (skipped.length > 0) {
1077
+ console.log(
1078
+ `\n ${skipped.length} live drill(s) undecided: upstream gave no verdict (gate closed or 429 capacity).` +
1079
+ `\n Every assertion that could be checked locally still passed; rerun when the IP has allowance.`
1080
+ );
1081
+ }
1082
+ process.exit(failed.length === 0 ? 0 : 1);
1083
+ }
1084
+
1085
+ let port: () => number = () => 0;
1086
+
1087
+ // Exported for test/drill-semantics.test.js: the tri-state verdict contract
1088
+ // (true / null / false) is what keeps an undecided live drill from failing CI.
1089
+ module.exports = { DRILLS, judge };
1090
+
1091
+ if (require.main === module) {
1092
+ main().catch((err) => {
1093
+ console.error(err);
1094
+ process.exit(1);
1095
+ });
1096
+ }