ceulen 0.1.0 → 0.5.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.
Files changed (56) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +103 -14
  3. package/extensions/index.ts +113 -0
  4. package/extensions/lib/env.ts +75 -0
  5. package/extensions/lib/panel.ts +1720 -0
  6. package/extensions/lib/registry.ts +182 -0
  7. package/extensions/modules/composer/index.ts +128 -0
  8. package/extensions/modules/composer/lib/settings.ts +55 -0
  9. package/extensions/modules/composer/lib/shapes.ts +436 -0
  10. package/extensions/modules/composer/test/editor.test.ts +138 -0
  11. package/extensions/modules/composer/test/module.test.ts +218 -0
  12. package/extensions/modules/composer/test/screen.test.ts +195 -0
  13. package/extensions/modules/composer/test/shapes.test.ts +175 -0
  14. package/extensions/modules/config/index.ts +298 -0
  15. package/extensions/modules/config/piSettings.ts +467 -0
  16. package/extensions/modules/config/plugins.ts +290 -0
  17. package/extensions/modules/config/test/kernel.test.ts +523 -0
  18. package/extensions/modules/config/test/kernelV4.test.ts +196 -0
  19. package/extensions/modules/config/test/menu.test.ts +226 -0
  20. package/extensions/modules/config/test/panel.test.ts +395 -0
  21. package/extensions/modules/config/test/piSettings.test.ts +185 -0
  22. package/extensions/modules/config/test/plugins.test.ts +181 -0
  23. package/extensions/modules/config/test/preview-block.test.ts +88 -0
  24. package/extensions/modules/ponytail/UPSTREAM +26 -0
  25. package/extensions/modules/ponytail/index.ts +336 -0
  26. package/extensions/modules/ponytail/lib/config.ts +149 -0
  27. package/extensions/modules/ponytail/lib/instructions.ts +98 -0
  28. package/extensions/modules/ponytail/lib/subagent.ts +31 -0
  29. package/extensions/modules/ponytail/test/extension.test.ts +422 -0
  30. package/extensions/modules/ponytail/test/helpers.test.ts +163 -0
  31. package/extensions/modules/ponytail/test/subagent.test.ts +33 -0
  32. package/extensions/modules/router/commands/commands.ts +99 -0
  33. package/extensions/modules/router/configPanel.ts +89 -0
  34. package/extensions/modules/router/index.ts +75 -0
  35. package/extensions/modules/router/lib/client.ts +390 -0
  36. package/extensions/modules/router/lib/config.ts +142 -0
  37. package/extensions/modules/router/lib/migrate.ts +92 -0
  38. package/extensions/modules/router/lib/provider.ts +138 -0
  39. package/extensions/modules/router/lib/refresh.ts +19 -0
  40. package/extensions/modules/router/test/guard.test.ts +77 -0
  41. package/extensions/modules/router/test/unit.test.ts +1126 -0
  42. package/extensions/modules/usage/index.ts +1975 -0
  43. package/extensions/modules/usage/test/context.test.ts +387 -0
  44. package/extensions/modules/usage/test/env-gating.test.ts +113 -0
  45. package/extensions/modules/usage/test/opencode-go-usage.test.ts +139 -0
  46. package/extensions/modules/usage/test/parsers.test.ts +244 -0
  47. package/extensions/modules/usage/test/stale-ctx-regression.test.ts +294 -0
  48. package/extensions/modules/usage/test/zai-anthropic-adapter.test.ts +40 -0
  49. package/package.json +15 -3
  50. package/skills/ponytail/SKILL.md +124 -0
  51. package/skills/ponytail-audit/SKILL.md +41 -0
  52. package/skills/ponytail-debt/SKILL.md +44 -0
  53. package/skills/ponytail-gain/SKILL.md +51 -0
  54. package/skills/ponytail-help/SKILL.md +73 -0
  55. package/skills/ponytail-review/SKILL.md +57 -0
  56. package/extensions/index.js +0 -42
@@ -0,0 +1,1126 @@
1
+ import { describe, it, before, after, mock } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdirSync, writeFileSync, unlinkSync, existsSync, readFileSync, rmSync, statSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { tmpdir } from "node:os";
7
+
8
+ // ── Isolation ────────────────────────────────────────────────────────────────
9
+ // Point PI_CODING_AGENT_DIR at a temp dir so tests never touch the user's live
10
+ // ~/.pi/agent (settings.json / auth.json / 9router-config.json).
11
+ const TMP_HOME = join(tmpdir(), "pi-router-test-" + process.pid);
12
+ before(() => {
13
+ mkdirSync(TMP_HOME, { recursive: true });
14
+ process.env.PI_CODING_AGENT_DIR = TMP_HOME;
15
+ });
16
+ after(() => {
17
+ delete process.env.PI_CODING_AGENT_DIR;
18
+ try { rmSync(TMP_HOME, { recursive: true, force: true }); } catch { /* ignore */ }
19
+ });
20
+
21
+ // ── config ───────────────────────────────────────────────────────────────────
22
+
23
+ describe("config", () => {
24
+ const settingsPath = () => join(TMP_HOME, "settings.json");
25
+
26
+ function writeSettings(router: unknown): void {
27
+ writeFileSync(settingsPath(), JSON.stringify({ other: true, router }), null as never);
28
+ }
29
+
30
+ it("getSettings reads router.baseUrl from global settings.json", async () => {
31
+ try { unlinkSync(settingsPath()); } catch { /* ignore */ }
32
+ writeSettings({ baseUrl: "http://localhost:20128/v1/" });
33
+ const { getSettings } = await import("../lib/config.js");
34
+ const s = getSettings();
35
+ assert.equal(s.baseUrl, "http://localhost:20128/v1"); // normalized
36
+ assert.equal(s.enableReasoning, true); // default
37
+ });
38
+
39
+ it("enableReasoning: false is respected from settings", async () => {
40
+ writeSettings({ baseUrl: "http://x", enableReasoning: false });
41
+ const { getSettings } = await import("../lib/config.js");
42
+ assert.equal(getSettings().enableReasoning, false);
43
+ });
44
+
45
+ it("env ROUTER_BASE_URL overrides settings.json", async () => {
46
+ writeSettings({ baseUrl: "http://from-settings" });
47
+ process.env.ROUTER_BASE_URL = "http://from-env/";
48
+ try {
49
+ const { getSettings } = await import("../lib/config.js");
50
+ assert.equal(getSettings().baseUrl, "http://from-env");
51
+ } finally {
52
+ delete process.env.ROUTER_BASE_URL;
53
+ }
54
+ });
55
+
56
+ // Repo-scope settings are trust-gated: default getSettings() ignores them
57
+ // (an untrusted checkout must not redirect baseUrl while the auth.json key
58
+ // is sent there as Bearer). Path is process.cwd()/.pi/settings.json — tests
59
+ // run from the package root; any pre-existing file is saved and restored.
60
+ describe("repo .pi/settings.json trust gate", () => {
61
+ const repoPath = () => join(process.cwd(), ".pi", "settings.json");
62
+
63
+ async function withRepoSettings(router: unknown, fn: () => Promise<void>): Promise<void> {
64
+ const prev = existsSync(repoPath()) ? readFileSync(repoPath(), "utf8") : null;
65
+ mkdirSync(join(process.cwd(), ".pi"), { recursive: true });
66
+ writeFileSync(repoPath(), JSON.stringify({ router }));
67
+ try {
68
+ await fn();
69
+ } finally {
70
+ if (prev === null) unlinkSync(repoPath());
71
+ else writeFileSync(repoPath(), prev);
72
+ }
73
+ }
74
+
75
+ it("untrusted (default): repo router.baseUrl is ignored — falls back to global/env", async () => {
76
+ try { unlinkSync(settingsPath()); } catch { /* ignore */ }
77
+ const { getSettings } = await import("../lib/config.js");
78
+ await withRepoSettings({ baseUrl: "http://attacker", enableReasoning: false }, async () => {
79
+ assert.equal(getSettings().baseUrl, ""); // repo ignored, nothing else configured
80
+ assert.equal(getSettings().enableReasoning, true); // repo flag ignored too
81
+ });
82
+ });
83
+
84
+ it("trusted: repo router.baseUrl overrides global settings.json", async () => {
85
+ writeSettings({ baseUrl: "http://global" });
86
+ const { getSettings } = await import("../lib/config.js");
87
+ await withRepoSettings({ baseUrl: "http://trusted-repo/v1", enableReasoning: false }, async () => {
88
+ const s = getSettings({ trustProject: true });
89
+ assert.equal(s.baseUrl, "http://trusted-repo/v1");
90
+ assert.equal(s.enableReasoning, false);
91
+ });
92
+ });
93
+
94
+ it("trusted: env still beats repo", async () => {
95
+ try { unlinkSync(settingsPath()); } catch { /* ignore */ }
96
+ process.env.ROUTER_BASE_URL = "http://from-env";
97
+ try {
98
+ const { getSettings } = await import("../lib/config.js");
99
+ await withRepoSettings({ baseUrl: "http://trusted-repo" }, async () => {
100
+ assert.equal(getSettings({ trustProject: true }).baseUrl, "http://from-env");
101
+ });
102
+ } finally {
103
+ delete process.env.ROUTER_BASE_URL;
104
+ }
105
+ });
106
+ });
107
+
108
+ it("legacy NINE_ROUTER_BASE_URL still works", async () => {
109
+ try { unlinkSync(settingsPath()); } catch { /* ignore */ }
110
+ process.env.NINE_ROUTER_BASE_URL = "http://legacy-env";
111
+ try {
112
+ const { getSettings } = await import("../lib/config.js");
113
+ assert.equal(getSettings().baseUrl, "http://legacy-env");
114
+ } finally {
115
+ delete process.env.NINE_ROUTER_BASE_URL;
116
+ }
117
+ });
118
+
119
+ it("readStoredApiKey reads router credential from auth.json", async () => {
120
+ writeFileSync(join(TMP_HOME, "auth.json"), JSON.stringify({ openai: { type: "api_key", key: "sk-other" }, router: { type: "api_key", key: "sk-mine" } }));
121
+ const { readStoredApiKey } = await import("../lib/config.js");
122
+ assert.equal(readStoredApiKey(), "sk-mine");
123
+ });
124
+
125
+ it("maskApiKey masks middle characters", async () => {
126
+ const { maskApiKey } = await import("../lib/config.js");
127
+ const key = "sk-12345678";
128
+ assert.equal(maskApiKey(key), key.slice(0, 4) + "●".repeat(key.length - 8) + key.slice(-4));
129
+ assert.equal(maskApiKey(undefined), "(not set)");
130
+ assert.equal(maskApiKey(""), "(not set)");
131
+ assert.equal(maskApiKey("short"), "(5 chars)");
132
+ assert.equal(maskApiKey("12345678"), "(8 chars)");
133
+ assert.equal(maskApiKey("x".repeat(9)), "xxxx●xxxx");
134
+ });
135
+ });
136
+
137
+ // ── commands (atomic settings write) ─────────────────────────────────────────
138
+
139
+ describe("commands", () => {
140
+ it("writeRouterSection replaces settings.json via tmp+rename (not an in-place rewrite)", async () => {
141
+ const settingsPath = join(TMP_HOME, "settings.json");
142
+ writeFileSync(settingsPath, JSON.stringify({ other: true, router: { baseUrl: "http://x" } }));
143
+ const inoBefore = statSync(settingsPath).ino;
144
+ const { writeRouterSection } = await import("../lib/config.js");
145
+ writeRouterSection({ enableReasoning: true });
146
+ const settings = JSON.parse(readFileSync(settingsPath, "utf8")) as {
147
+ other: boolean;
148
+ router: Record<string, unknown>;
149
+ };
150
+ assert.equal(settings.other, true); // unrelated keys survive
151
+ assert.equal(settings.router.baseUrl, "http://x");
152
+ assert.equal(settings.router.enableReasoning, true);
153
+ // Rename swaps the directory entry → new inode; a direct writeFileSync
154
+ // rewrites in place and keeps the inode. Catches regression to the
155
+ // non-atomic write without fs interception.
156
+ assert.notEqual(inoBefore, statSync(settingsPath).ino);
157
+ assert.ok(!existsSync(settingsPath + ".tmp")); // no tmp residue
158
+ });
159
+
160
+ it("writeRouterSection refuses to clobber a corrupt settings.json (data-loss guard)", async () => {
161
+ const settingsPath = join(TMP_HOME, "settings.json");
162
+ const corrupt = '{ "router": { "baseUrl": "http://x" }, "other": true\nOOPS';
163
+ writeFileSync(settingsPath, corrupt);
164
+ const before = readFileSync(settingsPath, "utf8");
165
+ const { writeRouterSection } = await import("../lib/config.js");
166
+ assert.throws(() => writeRouterSection({ enableReasoning: true }), /not valid JSON/);
167
+ assert.equal(readFileSync(settingsPath, "utf8"), before,
168
+ "corrupt file must be left byte-identical — no rename-overwrite");
169
+ assert.ok(!existsSync(settingsPath + ".tmp")); // no tmp residue either
170
+ // Recovery path: once the user fixes the file, saving works again.
171
+ writeFileSync(settingsPath, JSON.stringify({ other: true }));
172
+ writeRouterSection({ enableReasoning: true });
173
+ assert.equal(JSON.parse(readFileSync(settingsPath, "utf8")).other, true);
174
+ });
175
+ });
176
+
177
+ // ── migration ────────────────────────────────────────────────────────────────
178
+
179
+ describe("migration", () => {
180
+ it("migrates 9router-config.json → settings.json + auth.json, renames legacy file", async () => {
181
+ const legacy = join(TMP_HOME, "9router-config.json");
182
+ const settingsPath = join(TMP_HOME, "settings.json");
183
+ const authPath = join(TMP_HOME, "auth.json");
184
+ for (const p of [legacy, settingsPath, authPath, legacy + ".migrated"]) {
185
+ try { unlinkSync(p); } catch { /* ignore */ }
186
+ }
187
+ writeFileSync(settingsPath, JSON.stringify({ theme: "dark" })); // existing unrelated settings
188
+ writeFileSync(authPath, JSON.stringify({ openai: { type: "api_key", key: "sk-x" } }));
189
+ writeFileSync(legacy, JSON.stringify({
190
+ baseUrl: "http://localhost:20128/v1",
191
+ apiKey: "sk-legacy",
192
+ enableReasoning: false,
193
+ configVersion: 1,
194
+ }));
195
+
196
+ const { migrateLegacyConfig } = await import("../lib/migrate.js");
197
+ assert.equal(migrateLegacyConfig(), true);
198
+
199
+ // settings.json: router section merged, unrelated keys preserved
200
+ const settings = JSON.parse(readFileSync(settingsPath, "utf8"));
201
+ assert.equal(settings.theme, "dark");
202
+ assert.equal(settings.router.baseUrl, "http://localhost:20128/v1");
203
+ assert.equal(settings.router.enableReasoning, false);
204
+
205
+ // auth.json: router credential added, openai preserved
206
+ const auth = JSON.parse(readFileSync(authPath, "utf8"));
207
+ assert.equal(auth.openai.key, "sk-x");
208
+ assert.equal(auth.router.type, "api_key");
209
+ assert.equal(auth.router.key, "sk-legacy");
210
+
211
+ // legacy file renamed, not deleted
212
+ assert.ok(!existsSync(legacy));
213
+ assert.ok(existsSync(legacy + ".migrated"));
214
+
215
+ // Idempotent: second run does nothing
216
+ assert.equal(migrateLegacyConfig(), false);
217
+ });
218
+
219
+ it("never overwrites existing router settings/auth entries", async () => {
220
+ const legacy = join(TMP_HOME, "9router-config.json");
221
+ const settingsPath = join(TMP_HOME, "settings.json");
222
+ const authPath = join(TMP_HOME, "auth.json");
223
+ for (const p of [legacy, legacy + ".migrated"]) {
224
+ try { unlinkSync(p); } catch { /* ignore */ }
225
+ }
226
+ writeFileSync(settingsPath, JSON.stringify({ router: { baseUrl: "http://existing" } }));
227
+ writeFileSync(authPath, JSON.stringify({ router: { type: "api_key", key: "sk-existing" } }));
228
+ writeFileSync(legacy, JSON.stringify({ baseUrl: "http://old", apiKey: "sk-old" }));
229
+
230
+ const { migrateLegacyConfig } = await import("../lib/migrate.js");
231
+ migrateLegacyConfig();
232
+
233
+ const settings = JSON.parse(readFileSync(settingsPath, "utf8"));
234
+ assert.equal(settings.router.baseUrl, "http://existing");
235
+ const auth = JSON.parse(readFileSync(authPath, "utf8"));
236
+ assert.equal(auth.router.key, "sk-existing");
237
+ });
238
+
239
+ it("consumes unreadable legacy config without writing anything", async () => {
240
+ const legacy = join(TMP_HOME, "9router-config.json");
241
+ const settingsPath = join(TMP_HOME, "settings.json");
242
+ for (const p of [legacy, legacy + ".migrated", settingsPath]) {
243
+ try { unlinkSync(p); } catch { /* ignore */ }
244
+ }
245
+ writeFileSync(legacy, "{not json");
246
+
247
+ const { migrateLegacyConfig } = await import("../lib/migrate.js");
248
+ assert.equal(migrateLegacyConfig(), false);
249
+ assert.ok(!existsSync(settingsPath)); // nothing written
250
+ assert.ok(existsSync(legacy + ".migrated"));
251
+ });
252
+
253
+ it("never wipes an unparseable settings.json during migration", async () => {
254
+ const legacy = join(TMP_HOME, "9router-config.json");
255
+ const settingsPath = join(TMP_HOME, "settings.json");
256
+ for (const p of [legacy, legacy + ".migrated"]) {
257
+ try { unlinkSync(p); } catch { /* ignore */ }
258
+ }
259
+ writeFileSync(settingsPath, "{corrupt settings");
260
+ writeFileSync(legacy, JSON.stringify({ baseUrl: "http://x", apiKey: "sk-k" }));
261
+
262
+ const { migrateLegacyConfig } = await import("../lib/migrate.js");
263
+ assert.equal(migrateLegacyConfig(), false); // bails — leaves legacy for retry
264
+ assert.equal(readFileSync(settingsPath, "utf8"), "{corrupt settings"); // untouched
265
+ assert.ok(existsSync(legacy)); // legacy file NOT consumed — retried next load
266
+ });
267
+
268
+ it("never wipes an unparseable auth.json during migration", async () => {
269
+ const legacy = join(TMP_HOME, "9router-config.json");
270
+ const authPath = join(TMP_HOME, "auth.json");
271
+ const settingsPath = join(TMP_HOME, "settings.json");
272
+ for (const p of [legacy, legacy + ".migrated", settingsPath, authPath]) {
273
+ try { unlinkSync(p); } catch { /* ignore */ }
274
+ }
275
+ writeFileSync(authPath, "{corrupt auth");
276
+ writeFileSync(legacy, JSON.stringify({ baseUrl: "http://x", apiKey: "sk-k" }));
277
+
278
+ const { migrateLegacyConfig } = await import("../lib/migrate.js");
279
+ migrateLegacyConfig();
280
+ assert.equal(readFileSync(authPath, "utf8"), "{corrupt auth"); // untouched
281
+ // settings migration still completed and legacy was consumed
282
+ assert.ok(existsSync(legacy + ".migrated"));
283
+ });
284
+ });
285
+
286
+ // ── client (mapModel + applyReasoning) ───────────────────────────────────────
287
+
288
+ describe("client", () => {
289
+ it("mapModel maps capabilities and honors context overrides", async () => {
290
+ const { mapModel } = await import("../lib/client.js");
291
+ const m = mapModel({ id: "zai-coding/glm-5.2", capabilities: { contextWindow: 128000, maxOutput: 8192, vision: true } }, true);
292
+ assert.equal(m.id, "zai-coding/glm-5.2");
293
+ assert.equal(m.contextWindow, 1_000_000); // GLM-5.2 override
294
+ assert.equal(m.maxTokens, 131_072);
295
+ assert.deepEqual(m.input, ["text", "image"]);
296
+ assert.equal(m.reasoning, true);
297
+ assert.ok(m.thinkingLevelMap); // zai map
298
+ });
299
+
300
+ it("mapModel without reasoning flag has no thinkingLevelMap", async () => {
301
+ const { mapModel } = await import("../lib/client.js");
302
+ const m = mapModel({ id: "gpt-5.2" }, false);
303
+ assert.equal(m.reasoning, false);
304
+ assert.equal(m.thinkingLevelMap, undefined);
305
+ assert.equal(m.compat?.supportsReasoningEffort, false);
306
+ });
307
+
308
+ it("requiresReasoningContentOnAssistantMessages: ocg-scoped passback flag", async () => {
309
+ const { mapModel } = await import("../lib/client.js");
310
+ // ocg/ wire: DeepSeek family + glm-5.1 + kimi-k2.7-code (pi native opencode-go compat)
311
+ for (const id of ["ocg/deepseek-v4.1-flash", "ocg/deepseek-v4-pro", "ocg/glm-5.1", "ocg/kimi-k2.7-code"]) {
312
+ const m = mapModel({ id }, true);
313
+ assert.equal(m.compat?.requiresReasoningContentOnAssistantMessages, true, id);
314
+ }
315
+ // other ocg models are false natively
316
+ assert.equal(mapModel({ id: "ocg/glm-5.3-flash" }, true).compat?.requiresReasoningContentOnAssistantMessages, false);
317
+ // scoping: same family ids on other wires stay flagless (no verified contract)
318
+ for (const id of ["zai/glm-5.3", "cmd/deepseek/deepseek-v4-flash-vision-exp", "ds/deepseek-v4.1-flash", "glm-cn/glm-5.1", "deepseek-v4.1-flash"]) {
319
+ const m = mapModel({ id }, true);
320
+ assert.equal(m.compat?.requiresReasoningContentOnAssistantMessages, false, id);
321
+ }
322
+ });
323
+
324
+ it("mapModel vision: probe-verified routes gain image input, verified strips lose it", async () => {
325
+ const { mapModel } = await import("../lib/client.js");
326
+ // VISION_OVERRIDES: probe-verified PASS route, no router vision flag
327
+ const gemini = mapModel({ id: "cmd/google/gemini-3.7-flash" }, true);
328
+ assert.deepEqual(gemini.input, ["text", "image"]);
329
+ // effort-tier variants of a probed base are covered by the suffix group
330
+ const geminiHigh = mapModel({ id: "cmd/google/gemini-3.7-flash-high" }, true);
331
+ assert.deepEqual(geminiHigh.input, ["text", "image"]);
332
+ // unprobed sibling variants stay text-only (anchored patterns)
333
+ const geminiPreview = mapModel({ id: "cmd/google/gemini-3.7-flash-preview" }, true);
334
+ assert.deepEqual(geminiPreview.input, ["text"]);
335
+ // VISION_DOWNGRADES: router claims vision:true but probe verified STRIP
336
+ const or = mapModel({ id: "openrouter/z-ai/glm-5.3-flash", capabilities: { vision: true } }, true);
337
+ assert.deepEqual(or.input, ["text"]);
338
+ // unverified route without flag stays text-only (no blanket enable)
339
+ const glm = mapModel({ id: "glm-cn/glm-5.3-flash" }, true);
340
+ assert.deepEqual(glm.input, ["text"]);
341
+ });
342
+
343
+ it("applyReasoning toggles the flag on an already-mapped model", async () => {
344
+ const { mapModel, applyReasoning } = await import("../lib/client.js");
345
+ const on = mapModel({ id: "deepseek-v4" }, true);
346
+ assert.equal(on.thinkingLevelMap?.high, "high");
347
+ const off = applyReasoning(on, false);
348
+ assert.equal(off.reasoning, false);
349
+ assert.equal(off.compat?.supportsReasoningEffort, false);
350
+ const back = applyReasoning(off, true);
351
+ assert.equal(back.reasoning, true);
352
+ assert.ok(back.thinkingLevelMap);
353
+ });
354
+
355
+ it("combo models get the 🔀 name prefix", async () => {
356
+ const { mapModel } = await import("../lib/client.js");
357
+ const m = mapModel({ id: "x", owned_by: "combo" }, false);
358
+ assert.equal(m.name, "🔀 x");
359
+ });
360
+
361
+ it("fetchModels never doubles the /v1 segment", async () => {
362
+ const { fetchModels } = await import("../lib/client.js");
363
+ const urls: string[] = [];
364
+ const realFetch = globalThis.fetch;
365
+ globalThis.fetch = (async (input: RequestInfo | URL) => {
366
+ urls.push(String(input));
367
+ return new Response(JSON.stringify({ object: "list", data: [] }), { status: 200 });
368
+ }) as typeof fetch;
369
+ try {
370
+ await fetchModels({ baseUrl: "http://h:20128/v1", enableReasoning: true });
371
+ await fetchModels({ baseUrl: "http://h:20128/v1/", enableReasoning: true });
372
+ await fetchModels({ baseUrl: "http://h:20128", enableReasoning: true });
373
+ } finally {
374
+ globalThis.fetch = realFetch;
375
+ }
376
+ assert.deepEqual(urls, [
377
+ "http://h:20128/v1/models",
378
+ "http://h:20128/v1/models",
379
+ "http://h:20128/v1/models",
380
+ ]);
381
+ });
382
+
383
+ it("fetchModels sends NINE_ROUTER_API_KEY as Bearer fallback", async () => {
384
+ const { fetchModels } = await import("../lib/client.js");
385
+ let auth: string | undefined;
386
+ const realFetch = globalThis.fetch;
387
+ globalThis.fetch = (async (_input: unknown, init?: RequestInit) => {
388
+ auth = (init?.headers as Record<string, string>)?.Authorization;
389
+ return new Response(JSON.stringify({ object: "list", data: [] }), { status: 200 });
390
+ }) as typeof fetch;
391
+ process.env.NINE_ROUTER_API_KEY = "sk-legacy-env";
392
+ try {
393
+ await fetchModels({ baseUrl: "http://h/v1", enableReasoning: true });
394
+ assert.equal(auth, "Bearer sk-legacy-env");
395
+ } finally {
396
+ globalThis.fetch = realFetch;
397
+ delete process.env.NINE_ROUTER_API_KEY;
398
+ }
399
+ });
400
+
401
+ it("claude 3-5/3-7 use budget thinking; 4-6/4.6/5/sonnet-5 use adaptive", async () => {
402
+ const { mapModel } = await import("../lib/client.js");
403
+ const xhigh = (id: string) => (mapModel({ id }, true).thinkingLevelMap ?? {}).xhigh;
404
+ assert.equal(xhigh("claude-3-5-sonnet"), "xhigh"); // budget: xhigh native
405
+ assert.equal(xhigh("claude-3-7-opus"), "xhigh"); // budget
406
+ assert.equal(xhigh("claude-sonnet-5"), "max"); // adaptive: xhigh → max
407
+ assert.equal(xhigh("claude-4-6-opus"), "max"); // adaptive (dash form → 4.6)
408
+ assert.equal(xhigh("claude-opus-4.6"), "max"); // adaptive (dot form)
409
+ assert.equal(xhigh("claude-haiku-4.5"), "xhigh"); // 4.5 < 4.6 — budget boundary
410
+ assert.equal(xhigh("claude-3-5-haiku-20241022"), "xhigh"); // dated id, still 3.5 budget
411
+ });
412
+
413
+ it("mapModel reads top-level context_length / max_output_tokens (omniroute shape)", async () => {
414
+ const { mapModel } = await import("../lib/client.js");
415
+ const m = mapModel(
416
+ { id: "cmd/meta/muse-spark-1.2-contributor", context_length: 1048576, max_output_tokens: 131072, capabilities: { vision: true } } as never,
417
+ false,
418
+ );
419
+ assert.equal(m.contextWindow, 1048576);
420
+ assert.equal(m.maxTokens, 131072);
421
+ });
422
+
423
+ it("top-level context_length is authoritative over the override table (no inflation)", async () => {
424
+ const { mapModel } = await import("../lib/client.js");
425
+ // zai-coding/glm-5.2 has a 1M override — a stale 1M must not inflate a
426
+ // router that truthfully reports a smaller window at the top level.
427
+ const m = mapModel({ id: "zai-coding/glm-5.2", context_length: 256000, capabilities: {} } as never, false);
428
+ assert.equal(m.contextWindow, 256000);
429
+ });
430
+
431
+ it("one top-level field gates the override for the OTHER field (no mixed provenance)", async () => {
432
+ const { mapModel } = await import("../lib/client.js");
433
+ // Direction A: context_length present, max_output_tokens absent — the stale
434
+ // 131072 override must NOT apply over the router's truthful capabilities.maxOutput.
435
+ const a = mapModel({ id: "zai-coding/glm-5.2", context_length: 256000, capabilities: { maxOutput: 32768 } } as never, false);
436
+ assert.equal(a.contextWindow, 256000);
437
+ assert.equal(a.maxTokens, 32768, "override maxTokens bypassed when any top-level field is present");
438
+ // Direction B: max_output_tokens present, context_length absent — stale 1M
439
+ // override must NOT override a truthful capabilities.contextWindow.
440
+ const b = mapModel({ id: "zai-coding/glm-5.2", max_output_tokens: 65536, capabilities: { contextWindow: 262144 } } as never, false);
441
+ assert.equal(b.contextWindow, 262144, "override contextWindow bypassed when any top-level field is present");
442
+ assert.equal(b.maxTokens, 65536);
443
+ });
444
+
445
+ it("numeric-string top-level fields are parsed (heterogeneous gateways)", async () => {
446
+ const { mapModel } = await import("../lib/client.js");
447
+ const m = mapModel({ id: "cmd/meta/muse-spark-1.2-contributor", context_length: "1048576", max_output_tokens: "131072" } as never, false);
448
+ assert.equal(m.contextWindow, 1048576);
449
+ assert.equal(m.maxTokens, 131072);
450
+ });
451
+
452
+ it("present-but-invalid top-level values still suppress the override (no resurrection)", async () => {
453
+ const { mapModel } = await import("../lib/client.js");
454
+ // context_length present with 0 → override must NOT apply; value falls to caps.
455
+ const zero = mapModel({ id: "zai-coding/glm-5.2", context_length: 0, capabilities: { contextWindow: 262144, maxOutput: 32768 } } as never, false);
456
+ assert.equal(zero.contextWindow, 262144, "0 context_length suppresses the 1M override");
457
+ assert.equal(zero.maxTokens, 32768);
458
+ // "unknown" string present → override suppressed, falls through to caps.
459
+ const unk = mapModel({ id: "zai-coding/glm-5.2", context_length: "unknown", capabilities: { contextWindow: 262144 } } as never, false);
460
+ assert.equal(unk.contextWindow, 262144);
461
+ });
462
+
463
+ it("explicit null top-level fields count as absent (override still applies for 9router)", async () => {
464
+ const { mapModel } = await import("../lib/client.js");
465
+ const m = mapModel({ id: "zai-coding/glm-5.2", context_length: null, max_output_tokens: null, capabilities: { contextWindow: 128000, maxOutput: 8192 } } as never, false);
466
+ assert.equal(m.contextWindow, 1_000_000, "null top-level = absent → GLM-5.2 override applies");
467
+ assert.equal(m.maxTokens, 131_072);
468
+ });
469
+
470
+ it("9router capabilities.contextWindow still honored when no top-level field", async () => {
471
+ const { mapModel } = await import("../lib/client.js");
472
+ const m = mapModel({ id: "generic/model-a", capabilities: { contextWindow: 200000, maxOutput: 16384 } } as never, false);
473
+ assert.equal(m.contextWindow, 200000);
474
+ assert.equal(m.maxTokens, 16384);
475
+ });
476
+
477
+ // ── floor-aware override (DEFAULT_CAPABILITIES de-poisoning) ───────────────
478
+ // Omniroute (9router fork) intermittently emits top-level `context_length: 200000,
479
+ // max_output_tokens: 128000` — its DEFAULT_CAPABILITIES floor — for unprofiled
480
+ // models like GLM-5.3. pi-router 1.1.1's single-tier provenance trusted that pair
481
+ // as router truth, bypassing the verified override. The fix de-poisons the
482
+ // floor pair only when an override exceeds the floor; above-floor values are
483
+ // still router-trusted (no inflation of e.g. openrouter/z-ai/glm-5.2:free = 256K).
484
+
485
+ it("floor pair on a matched-override model lets the override win (the user's exact case)", async () => {
486
+ const { mapModel } = await import("../lib/client.js");
487
+ // Live omniroute response shape for glm-cn/glm-5.3 when its capabilities cache is warm.
488
+ const m = mapModel({ id: "glm-cn/glm-5.3", context_length: 200000, max_output_tokens: 128000 } as never, false);
489
+ assert.equal(m.contextWindow, 1_000_000);
490
+ assert.equal(m.maxTokens, 131_072);
491
+ });
492
+
493
+ it("floor value without an override entry stays verbatim (genuine 200K models unaffected)", async () => {
494
+ const { mapModel } = await import("../lib/client.js");
495
+ const m = mapModel({ id: "some/200k-model", context_length: 200000, max_output_tokens: 128000 } as never, false);
496
+ assert.equal(m.contextWindow, 200000, "no override match → router value kept");
497
+ assert.equal(m.maxTokens, 128000);
498
+ });
499
+
500
+ it("above-floor truthful values stay verbatim (no inflation of e.g. glm-5.2:free)", async () => {
501
+ const { mapModel } = await import("../lib/client.js");
502
+ // openrouter/z-ai/glm-5.2:free truthfully reports 256000 — above floor, override suppressed.
503
+ const m = mapModel({ id: "openrouter/z-ai/glm-5.2:free", context_length: 256000, max_output_tokens: 230400 } as never, false);
504
+ assert.equal(m.contextWindow, 256000);
505
+ assert.equal(m.maxTokens, 230400);
506
+ });
507
+
508
+ it("deepseek-v4 floor pair: override has no maxTokens so pair rule doesn't fire → router values kept", async () => {
509
+ const { mapModel } = await import("../lib/client.js");
510
+ // deepseek-v[34] override has only contextWindow (no maxTokens). When omniroute
511
+ // stamps the floor pair (200000/128000), maxFloorPoisoned is false (override.max
512
+ // undefined), so the strict pair rule doesn't fire and the override is bypassed
513
+ // (1.1.1 single-tier back-compat). Both fields stay router. The override's value
514
+ // for ctx is correct (1M) but cannot apply until either (a) the override entry
515
+ // gains maxTokens so the pair rule matches, or (b) omniroute drops the top-level
516
+ // fields entirely (next test) — then override fires.
517
+ const m = mapModel({ id: "opencode-go/deepseek-v4-flash", context_length: 200000, max_output_tokens: 128000 } as never, false);
518
+ assert.equal(m.contextWindow, 200_000, "override bypassed (pair rule needs both fields poisoned)");
519
+ assert.equal(m.maxTokens, 128_000);
520
+ });
521
+
522
+ it("deepseek-v4 metadata-less path (no top-level) → override 1M/384K", async () => {
523
+ const { mapModel } = await import("../lib/client.js");
524
+ // When omniroute omits top-level fields entirely for opencode-go/deepseek-v4-flash,
525
+ // both fields are absent → useOverride=true → override fires for ctx only
526
+ // (no maxTokens in entry → falls to caps.maxOutput=undefined → FALLBACK 4096).
527
+ // The 1M context correction is the critical fix; the 4096 max is the pre-existing
528
+ // behavior (override entry has always omitted maxTokens — a separate gap if the
529
+ // user wants 384K output, add maxTokens to the override entry).
530
+ const m = mapModel({ id: "opencode-go/deepseek-v4-flash" } as never, false);
531
+ assert.equal(m.contextWindow, 1_000_000);
532
+ assert.equal(m.maxTokens, 4_096, "FALLBACK (override has no maxTokens entry — pre-existing)");
533
+ });
534
+
535
+ it("above-floor glm-5.1 value is not overridden (200000 is the override's own value too)", async () => {
536
+ const { mapModel } = await import("../lib/client.js");
537
+ // 204800 from router (matches Z.ai official) — above the floor, override suppressed.
538
+ const m = mapModel({ id: "glm-cn/glm-5.1", context_length: 204800, max_output_tokens: 131072 } as never, false);
539
+ assert.equal(m.contextWindow, 204800);
540
+ assert.equal(m.maxTokens, 131072);
541
+ });
542
+
543
+ it("floor poison on glm-5.1 (router stale 200000) → override 200000/131072 still applied", async () => {
544
+ const { mapModel } = await import("../lib/client.js");
545
+ // When router reports the 9router floor (200000/128000) for glm-5.1, override fires.
546
+ // Both fields equal the floor so both are corrected; values match the override entry.
547
+ const m = mapModel({ id: "glm-cn/glm-5.1", context_length: 200000, max_output_tokens: 128000 } as never, false);
548
+ assert.equal(m.contextWindow, 200_000);
549
+ assert.equal(m.maxTokens, 131_072);
550
+ });
551
+
552
+ it("kimi-k3 floor poison → override 1M/131072 (no blanket-override inflation of kimi-k2.7)", async () => {
553
+ const { mapModel } = await import("../lib/client.js");
554
+ const m = mapModel({ id: "opencode-go/kimi-k3", context_length: 200000, max_output_tokens: 128000 } as never, false);
555
+ assert.equal(m.contextWindow, 1_048_576);
556
+ assert.equal(m.maxTokens, 131_072);
557
+ });
558
+
559
+ it("kimi-k2.7-code above floor stays verbatim (specific kimi-k3 pattern does not match)", async () => {
560
+ const { mapModel } = await import("../lib/client.js");
561
+ // Real kimi-k2.7-code context = 262144 (above floor) — the kimi-k3 pattern must not match.
562
+ const m = mapModel({ id: "opencode-go/kimi-k2.7-code", context_length: 262144, max_output_tokens: 262144 } as never, false);
563
+ assert.equal(m.contextWindow, 262144);
564
+ assert.equal(m.maxTokens, 262144);
565
+ });
566
+
567
+ it("glm-4.6 floor poison → override 200K/131072", async () => {
568
+ const { mapModel } = await import("../lib/client.js");
569
+ const m = mapModel({ id: "glm-cn/glm-4.6", context_length: 200000, max_output_tokens: 128000 } as never, false);
570
+ assert.equal(m.contextWindow, 200_000);
571
+ assert.equal(m.maxTokens, 131_072);
572
+ });
573
+
574
+ it("no top-level + no caps → override applies (kimi-k3 metadata-less path)", async () => {
575
+ const { mapModel } = await import("../lib/client.js");
576
+ // Live omniroute shape when glm-cn/kimi-k3 has no top-level fields at all.
577
+ const m = mapModel({ id: "opencode-go/kimi-k3" } as never, false);
578
+ assert.equal(m.contextWindow, 1_048_576);
579
+ assert.equal(m.maxTokens, 131_072);
580
+ });
581
+
582
+ it("present-but-invalid ctx (0) still suppresses the override (no resurrection)", async () => {
583
+ const { mapModel } = await import("../lib/client.js");
584
+ // 0 fails parsePositiveInt (n>0) → undefined → ctxFloorPoisoned false → override suppressed.
585
+ // Falls through to caps (262144) — preserves the 1.1.1 guarantee.
586
+ const m = mapModel({ id: "zai-coding/glm-5.2", context_length: 0, capabilities: { contextWindow: 262144, maxOutput: 32768 } } as never, false);
587
+ assert.equal(m.contextWindow, 262144);
588
+ assert.equal(m.maxTokens, 32768);
589
+ });
590
+ });
591
+
592
+ // ── no-disable prefix (command-code upstream bug class) ──────────────────────
593
+
594
+ describe("client thinkingLevelMap no-disable prefix override", () => {
595
+ it("command-code/ minimax model: off and minimal are nulled, low/medium/high/xhigh retained", async () => {
596
+ const { mapModel } = await import("../lib/client.js");
597
+ const m = mapModel({ id: "command-code/MiniMaxAI/MiniMax-M3" }, true);
598
+ assert.equal(m.thinkingLevelMap?.off, null);
599
+ assert.equal(m.thinkingLevelMap?.minimal, null);
600
+ // Format-detection (contains "minimax") keeps the rest of the minimax map intact
601
+ // so interactive "low"/"medium"/"high"/"xhigh" still send valid values.
602
+ assert.equal(m.thinkingLevelMap?.low, "low");
603
+ assert.equal(m.thinkingLevelMap?.medium, "medium");
604
+ assert.equal(m.thinkingLevelMap?.high, "high");
605
+ assert.equal(m.thinkingLevelMap?.xhigh, "xhigh");
606
+ });
607
+
608
+ it("glm-cn/ zai model: off stays \"none\" (not a command-code route — untouched)", async () => {
609
+ const { mapModel } = await import("../lib/client.js");
610
+ const m = mapModel({ id: "glm-cn/glm-5.3" }, true);
611
+ // zai format: off="none" by design (GLM upstream accepts none via its executor).
612
+ assert.equal(m.thinkingLevelMap?.off, "none");
613
+ });
614
+
615
+ it("cmd/ alias prefix also nulls off/minimal", async () => {
616
+ const { mapModel } = await import("../lib/client.js");
617
+ const m = mapModel({ id: "cmd/MiniMaxAI/MiniMax-M3" }, true);
618
+ assert.equal(m.thinkingLevelMap?.off, null);
619
+ assert.equal(m.thinkingLevelMap?.minimal, null);
620
+ });
621
+
622
+ it("applyReasoning re-derives nulls on a stored command-code model (restart path)", async () => {
623
+ const { mapModel, applyReasoning } = await import("../lib/client.js");
624
+ // Simulate a stored model from models-store.json that was mapped before the fix
625
+ // (off:"none"). applyReasoning re-runs getThinkingLevelMap from the id, so after
626
+ // the fix a Pi restart re-applies the override without a network refresh.
627
+ const stale = mapModel({ id: "command-code/MiniMaxAI/MiniMax-M3" }, false);
628
+ // sanity: before-fix maps would have off:"none" — but with the fix in place we
629
+ // already null it; the meaningful assertion is that re-derivation produces the
630
+ // same nulls as the network path.
631
+ const remapped = applyReasoning(stale, true);
632
+ assert.equal(remapped.thinkingLevelMap?.off, null);
633
+ assert.equal(remapped.thinkingLevelMap?.minimal, null);
634
+ assert.equal(remapped.thinkingLevelMap?.low, "low");
635
+ });
636
+ });
637
+
638
+ // ── provider registration shape ──────────────────────────────────────────────
639
+
640
+ describe("provider", () => {
641
+ it("registers with dynamic refreshModels and $ROUTER_API_KEY", async () => {
642
+ const { registerProvider, PROVIDER_ID } = await import("../lib/provider.js");
643
+ let registered: { name: string; config: Record<string, unknown> } | null = null;
644
+ const fakePi = {
645
+ registerProvider: (name: string, config: Record<string, unknown>) => { registered = { name, config }; },
646
+ };
647
+ registerProvider(fakePi as never, { baseUrl: "http://localhost:20128/v1", enableReasoning: true });
648
+ assert.ok(registered);
649
+ assert.equal((registered as never as { name: string }).name, PROVIDER_ID);
650
+ const cfg = (registered as { config: Record<string, unknown> }).config;
651
+ assert.equal(cfg.apiKey, "$ROUTER_API_KEY");
652
+ assert.equal(cfg.api, "openai-completions");
653
+ assert.equal(cfg.baseUrl, "http://localhost:20128/v1");
654
+ assert.ok(Array.isArray(cfg.models));
655
+ assert.equal(cfg.models!.length, 0);
656
+ assert.equal(typeof cfg.refreshModels, "function");
657
+ });
658
+
659
+ it("refreshModels offline restores stored models remapped with reasoning flag", async () => {
660
+ const { mapModel } = await import("../lib/client.js");
661
+ const { registerProvider } = await import("../lib/provider.js");
662
+ let refreshModels: (ctx: unknown) => Promise<unknown>;
663
+ registerProvider({
664
+ registerProvider: (_n: string, config: { refreshModels: (ctx: unknown) => Promise<unknown> }) => { refreshModels = config.refreshModels; },
665
+ } as never, { baseUrl: "http://x", enableReasoning: false });
666
+
667
+ const stored = { id: "m1", name: "m1" } as never; // shape of a mapped model
668
+ const ctx = { stored: { models: [mapModel({ id: "m1" }, true)] }, allowNetwork: false, signal: new AbortController().signal };
669
+ void stored;
670
+ const result = (await refreshModels!(ctx)) as { reasoning: boolean; id: string }[];
671
+ assert.equal(result.length, 1);
672
+ assert.equal(result[0].id, "m1");
673
+ assert.equal(result[0].reasoning, false); // remapped with settings flag
674
+ });
675
+
676
+ it("refreshModels offline restore re-resolves vision (stale flags self-heal)", async () => {
677
+ const { registerProvider } = await import("../lib/provider.js");
678
+ let refreshModels: (ctx: unknown) => Promise<unknown>;
679
+ registerProvider({
680
+ registerProvider: (_n: string, config: { refreshModels: (ctx: unknown) => Promise<unknown> }) => { refreshModels = config.refreshModels; },
681
+ } as never, { baseUrl: "http://x", enableReasoning: false });
682
+ const ctx = {
683
+ stored: {
684
+ models: [
685
+ { id: "cmd/google/gemini-3.7-flash", name: "g", reasoning: false, input: ["text"], cost: {}, contextWindow: 1, maxTokens: 1 },
686
+ { id: "openrouter/z-ai/glm-5.3-flash", name: "o", reasoning: false, input: ["text", "image"], cost: {}, contextWindow: 1, maxTokens: 1 },
687
+ // pattern-unmatched: persisted router metadata must survive the restore
688
+ { id: "other/vision-model", name: "v", reasoning: false, input: ["text", "image"], cost: {}, contextWindow: 1, maxTokens: 1 },
689
+ // legacy/malformed entry without input: must not throw, degrades to text-only
690
+ { id: "legacy/entry", name: "l", reasoning: false, cost: {}, contextWindow: 1, maxTokens: 1 },
691
+ ],
692
+ },
693
+ allowNetwork: false,
694
+ signal: new AbortController().signal,
695
+ };
696
+ const result = (await refreshModels!(ctx)) as { id: string; input: string[] }[];
697
+ assert.deepEqual(result[0].input, ["text", "image"]); // override upgrades stale entry
698
+ assert.deepEqual(result[1].input, ["text"]); // downgrade strips lying flag
699
+ assert.deepEqual(result[2].input, ["text", "image"]); // unmatched: metadata preserved
700
+ assert.deepEqual(result[3].input, ["text"]); // malformed: text-only, no crash
701
+ });
702
+
703
+ it("refreshModels network path fetches, persists, and returns models", async () => {
704
+ const { registerProvider } = await import("../lib/provider.js");
705
+ let refreshModels: (ctx: unknown) => Promise<unknown>;
706
+ let emitted: { channel: string; count: number } | undefined;
707
+ registerProvider({
708
+ registerProvider: (_n: string, config: { refreshModels: (ctx: unknown) => Promise<unknown> }) => { refreshModels = config.refreshModels; },
709
+ events: { emit: (c: string, d: { count: number }) => { emitted = { channel: c, count: d.count }; } },
710
+ } as never, { baseUrl: "http://x", enableReasoning: true });
711
+
712
+ let persisted: unknown;
713
+ const ctx = {
714
+ stored: undefined,
715
+ allowNetwork: true,
716
+ signal: new AbortController().signal,
717
+ credential: { type: "api_key", key: "sk-from-login" },
718
+ publish: async (pub: { persist?: unknown }) => { persisted = pub.persist; },
719
+ };
720
+ let authHeader: string | undefined;
721
+ const realFetch = globalThis.fetch;
722
+ globalThis.fetch = (async (_input: unknown, init?: RequestInit) => {
723
+ authHeader = (init?.headers as Record<string, string>)?.Authorization;
724
+ return new Response(JSON.stringify({ object: "list", data: [{ id: "net-model" }] }), { status: 200 });
725
+ }) as typeof fetch;
726
+ try {
727
+ const result = (await refreshModels!(ctx)) as { id: string; reasoning: boolean }[];
728
+ assert.equal(result.length, 1);
729
+ assert.equal(result[0].id, "net-model");
730
+ assert.equal(result[0].reasoning, true);
731
+ assert.ok(persisted); // persisted to models-store
732
+ assert.equal(authHeader, "Bearer sk-from-login"); // /login credential drives discovery
733
+ assert.ok(emitted && emitted.channel === "router:models-loaded" && emitted.count === 1);
734
+ } finally {
735
+ globalThis.fetch = realFetch;
736
+ }
737
+ });
738
+
739
+ it("refreshModels keeps restored models when network fetch returns empty", async () => {
740
+ const { registerProvider } = await import("../lib/provider.js");
741
+ let refreshModels: (ctx: unknown) => Promise<unknown>;
742
+ registerProvider({
743
+ registerProvider: (_n: string, config: { refreshModels: (ctx: unknown) => Promise<unknown> }) => { refreshModels = config.refreshModels; },
744
+ } as never, { baseUrl: "http://x", enableReasoning: true });
745
+
746
+ const ctx = {
747
+ stored: { models: [{ id: "old", name: "old", reasoning: false, input: ["text"], cost: {}, contextWindow: 1, maxTokens: 1 }] },
748
+ allowNetwork: true,
749
+ signal: new AbortController().signal,
750
+ publish: async () => {},
751
+ };
752
+ const realFetch = globalThis.fetch;
753
+ globalThis.fetch = (async () =>
754
+ new Response(JSON.stringify({ object: "list", data: [] }), { status: 200 })) as typeof fetch;
755
+ try {
756
+ const result = await refreshModels!(ctx);
757
+ assert.equal(result, undefined); // keeps current list — no wipe
758
+ } finally {
759
+ globalThis.fetch = realFetch;
760
+ }
761
+ });
762
+ });
763
+
764
+ // ── automatic catalog refresh (TTL + in-flight guard + checkedAt persist) ────
765
+
766
+ describe("maybeRefreshCatalog", () => {
767
+ // fake ModelRegistry.refresh — counts calls, records options
768
+ function fakeRegistry() {
769
+ const calls: { providers?: string[]; force?: boolean }[] = [];
770
+ return {
771
+ calls,
772
+ modelRegistry: {
773
+ refresh: async (opts?: { providers?: string[]; force?: boolean }) => {
774
+ calls.push(opts ?? {});
775
+ return { aborted: false, errors: new Map() };
776
+ },
777
+ },
778
+ };
779
+ }
780
+
781
+ // capture the refreshModels callback + feed it a network success, so a
782
+ // registry refresh updates lastFetchedAt exactly like production does.
783
+ async function primeFresh(): Promise<void> {
784
+ const { registerProvider } = await import("../lib/provider.js");
785
+ let refreshModels: (ctx: unknown) => Promise<unknown>;
786
+ registerProvider({
787
+ registerProvider: (_n: string, config: { refreshModels: (ctx: unknown) => Promise<unknown> }) => { refreshModels = config.refreshModels; },
788
+ events: { emit: () => {} },
789
+ } as never, { baseUrl: "http://x", enableReasoning: true });
790
+ const realFetch = globalThis.fetch;
791
+ globalThis.fetch = (async () =>
792
+ new Response(JSON.stringify({ object: "list", data: [{ id: "m" }] }), { status: 200 })) as typeof fetch;
793
+ try {
794
+ await refreshModels!({ stored: undefined, allowNetwork: true, signal: new AbortController().signal, publish: async () => {} });
795
+ } finally {
796
+ globalThis.fetch = realFetch;
797
+ }
798
+ }
799
+
800
+ before(async () => { (await import("../lib/provider.js")).resetCatalogState(); });
801
+ after(async () => { delete process.env.PI_OFFLINE; (await import("../lib/provider.js")).resetCatalogState(); });
802
+
803
+ it("network phase persists checkedAt into the store entry", async () => {
804
+ const { registerProvider, catalogAgeMs, resetCatalogState } = await import("../lib/provider.js");
805
+ let refreshModels: (ctx: unknown) => Promise<unknown>;
806
+ registerProvider({
807
+ registerProvider: (_n: string, config: { refreshModels: (ctx: unknown) => Promise<unknown> }) => { refreshModels = config.refreshModels; },
808
+ events: { emit: () => {} },
809
+ } as never, { baseUrl: "http://x", enableReasoning: true });
810
+ let persisted: { checkedAt?: number } | undefined;
811
+ const realFetch = globalThis.fetch;
812
+ globalThis.fetch = (async () =>
813
+ new Response(JSON.stringify({ object: "list", data: [{ id: "m" }] }), { status: 200 })) as typeof fetch;
814
+ try {
815
+ await refreshModels!({
816
+ stored: undefined, allowNetwork: true, signal: new AbortController().signal,
817
+ publish: async (pub: { persist?: unknown }) => { persisted = pub.persist as { checkedAt?: number }; },
818
+ });
819
+ assert.ok(persisted?.checkedAt && Math.abs(Date.now() - persisted.checkedAt) < 5_000);
820
+ // offline phase backfills freshness from the persisted entry
821
+ await refreshModels!({
822
+ stored: { models: [], checkedAt: persisted.checkedAt } as never, allowNetwork: false,
823
+ signal: new AbortController().signal,
824
+ });
825
+ assert.ok(catalogAgeMs() !== undefined);
826
+ } finally {
827
+ globalThis.fetch = realFetch;
828
+ resetCatalogState();
829
+ }
830
+ });
831
+
832
+ it("fresh catalog → no refresh call; stale → exactly one", async () => {
833
+ const { maybeRefreshCatalog, resetCatalogState, catalogAgeMs, ROUTER_MODELS_TTL_MS } = await import("../lib/provider.js");
834
+ resetCatalogState();
835
+ const reg = fakeRegistry();
836
+ await maybeRefreshCatalog(reg as never);
837
+ assert.equal(reg.calls.length, 1); // unknown freshness → backfill fetch
838
+ assert.deepEqual(reg.calls[0].providers, ["router"]);
839
+
840
+ await primeFresh(); // lastFetchedAt = now
841
+ assert.ok(catalogAgeMs()! < ROUTER_MODELS_TTL_MS);
842
+ const fresh = fakeRegistry();
843
+ await maybeRefreshCatalog(fresh as never);
844
+ assert.equal(fresh.calls.length, 0); // TTL gate: no call
845
+
846
+ // force bypasses the TTL gate
847
+ const forced = fakeRegistry();
848
+ await maybeRefreshCatalog(forced as never, { force: true });
849
+ assert.equal(forced.calls.length, 1);
850
+ assert.equal(forced.calls[0].force, true);
851
+ resetCatalogState();
852
+ });
853
+
854
+ it("concurrent callers share one refresh (in-flight guard)", async () => {
855
+ const { maybeRefreshCatalog, resetCatalogState } = await import("../lib/provider.js");
856
+ resetCatalogState();
857
+ let release!: () => void;
858
+ const gate = new Promise<void>((r) => { release = r; });
859
+ const calls: unknown[] = [];
860
+ const reg = {
861
+ modelRegistry: {
862
+ refresh: async (opts: unknown) => { calls.push(opts); await gate; return {}; },
863
+ },
864
+ };
865
+ const a = maybeRefreshCatalog(reg as never);
866
+ const b = maybeRefreshCatalog(reg as never);
867
+ assert.equal(a, b); // same shared promise
868
+ release();
869
+ await Promise.all([a, b]);
870
+ assert.equal(calls.length, 1);
871
+ // guard cleared after settle → next call refreshes again
872
+ await maybeRefreshCatalog(reg as never);
873
+ assert.equal(calls.length, 2);
874
+ resetCatalogState();
875
+ });
876
+
877
+ it("force with a refresh in flight supersedes it instead of joining (endpoint flip)", async () => {
878
+ const { maybeRefreshCatalog, resetCatalogState } = await import("../lib/provider.js");
879
+ resetCatalogState();
880
+ let releaseA!: () => void;
881
+ const gateA = new Promise<void>((r) => { releaseA = r; });
882
+ const calls: { force?: boolean }[] = [];
883
+ let callsSeen = 0;
884
+ const reg = {
885
+ modelRegistry: {
886
+ refresh: async (opts: { force?: boolean }) => {
887
+ calls.push(opts);
888
+ if (callsSeen++ === 0) await gateA; // first (stale-endpoint) fetch hangs
889
+ return {};
890
+ },
891
+ },
892
+ };
893
+ // Auto refresh for the OLD endpoint starts and hangs (slow endpoint).
894
+ const stale = maybeRefreshCatalog(reg as never);
895
+ // baseUrl flips; forced refresh must NOT join the stale fetch.
896
+ const forced = maybeRefreshCatalog(reg as never, { force: true });
897
+ assert.notEqual(forced, stale); // new job, not the joined old one
898
+ await forced;
899
+ assert.equal(calls.length, 2);
900
+ assert.equal(calls[1].force, true); // new endpoint fetched
901
+ // The superseded stale job must not clear the NEW job's guard when it
902
+ // finally settles, and must not be affected by it either.
903
+ releaseA();
904
+ await Promise.allSettled([stale]);
905
+ await maybeRefreshCatalog(reg as never); // works — guard not corrupted
906
+ assert.equal(calls.length, 3);
907
+ resetCatalogState();
908
+ });
909
+
910
+ it("PI_OFFLINE skips the refresh entirely", async () => {
911
+ const { maybeRefreshCatalog, resetCatalogState } = await import("../lib/provider.js");
912
+ resetCatalogState();
913
+ process.env.PI_OFFLINE = "1";
914
+ try {
915
+ const reg = fakeRegistry();
916
+ await maybeRefreshCatalog(reg as never);
917
+ assert.equal(reg.calls.length, 0);
918
+ } finally {
919
+ delete process.env.PI_OFFLINE;
920
+ resetCatalogState();
921
+ }
922
+ });
923
+ });
924
+
925
+
926
+ // ── extension wiring (session_start / shutdown / interval / commands) ────────
927
+
928
+ // ── extension wiring (session_start / shutdown / interval / commands) ────────
929
+
930
+ describe("wiring (index.ts + commands)", () => {
931
+ const indexPromise = import("../index.js");
932
+
933
+ interface Harness {
934
+ pi: {
935
+ handlers: Map<string, (event: unknown, ctx: unknown) => Promise<void> | void>;
936
+ commands: Map<string, { handler: (args: unknown, ctx: unknown) => Promise<void> }>;
937
+ };
938
+ refreshes: { providers?: string[]; force?: boolean }[];
939
+ setModelCalls: { n: number };
940
+ thinking: { level: string; default: string };
941
+ ctx: Record<string, unknown>;
942
+ fireSessionStart: (ctxExtra?: Record<string, unknown>) => Promise<void>;
943
+ fireShutdown: () => Promise<void>;
944
+ tick: (ms: number) => Promise<void>;
945
+ }
946
+
947
+ /** Build the extension under test with a fake pi + counting registry. */
948
+ async function makeHarness(): Promise<Harness> {
949
+ const [{ default: factory }, { resetCatalogState }] = await Promise.all([
950
+ indexPromise,
951
+ import("../lib/provider.js"),
952
+ ]);
953
+ resetCatalogState();
954
+ const refreshes: { providers?: string[]; force?: boolean }[] = [];
955
+ // Capture the real refreshModels callback; registry refresh runs it (with
956
+ // stubbed fetch) so lastFetchedAt advances exactly like production.
957
+ let refreshModelsCb: ((ctx: unknown) => Promise<unknown>) | undefined;
958
+ const runRefreshModels = async () => {
959
+ if (!refreshModelsCb) return;
960
+ const realFetch = globalThis.fetch;
961
+ globalThis.fetch = (async () =>
962
+ new Response(JSON.stringify({ object: "list", data: [{ id: "m" }] }), { status: 200 })) as typeof fetch;
963
+ try {
964
+ await refreshModelsCb({ stored: undefined, allowNetwork: true, signal: new AbortController().signal, publish: async () => {} });
965
+ } finally {
966
+ globalThis.fetch = realFetch;
967
+ }
968
+ };
969
+ const modelRegistry: Record<string, unknown> = {
970
+ refresh: async (opts?: { providers?: string[]; force?: boolean }) => {
971
+ refreshes.push(opts ?? {});
972
+ await runRefreshModels();
973
+ return { aborted: false, errors: new Map() };
974
+ },
975
+ getAll: () => [] as unknown[],
976
+ find: () => undefined,
977
+ };
978
+ const ctx: Record<string, unknown> = {
979
+ isProjectTrusted: () => false,
980
+ model: undefined,
981
+ modelRegistry,
982
+ ui: { notify: () => {} },
983
+ mode: "rpc",
984
+ hasUI: false,
985
+ };
986
+ const setModelCalls = { n: 0 };
987
+ // Mirror Pi core: setModel re-applies the global thinking default even for
988
+ // an unchanged model (its modelsAreEqual guard covers the event only).
989
+ const thinking = { level: "high" as string, default: "high" as string };
990
+ const pi = {
991
+ handlers: new Map<string, (event: unknown, ctx: unknown) => Promise<void> | void>(),
992
+ commands: new Map<string, { handler: (args: unknown, ctx: unknown) => Promise<void> }>(),
993
+ events: { emit: () => {} },
994
+ getThinkingLevel: () => thinking.level,
995
+ setThinkingLevel: (level: string) => { thinking.level = level; },
996
+ registerProvider: (_n: string, config: { refreshModels: (ctx: unknown) => Promise<unknown> }) => {
997
+ refreshModelsCb = config.refreshModels;
998
+ },
999
+ registerCommand: (name: string, def: { handler: (args: unknown, ctx: unknown) => Promise<void> }) => {
1000
+ pi.commands.set(name, def);
1001
+ },
1002
+ on: (event: string, handler: (event: unknown, ctx: unknown) => Promise<void> | void) => {
1003
+ pi.handlers.set(event, handler);
1004
+ },
1005
+ setModel: async () => { setModelCalls.n++; thinking.level = thinking.default; },
1006
+ };
1007
+ factory(pi as never);
1008
+ return {
1009
+ pi,
1010
+ refreshes,
1011
+ setModelCalls,
1012
+ thinking,
1013
+ ctx,
1014
+ fireSessionStart: async (extra?: Record<string, unknown>) => {
1015
+ await pi.handlers.get("session_start")!({}, { ...ctx, ...extra });
1016
+ },
1017
+ fireShutdown: async () => {
1018
+ await pi.handlers.get("session_shutdown")!({}, ctx);
1019
+ },
1020
+ tick: async (ms: number) => {
1021
+ mock.timers.tick(ms);
1022
+ await new Promise((r) => setImmediate(r)); // let fire-and-forget chains settle
1023
+ },
1024
+ };
1025
+ }
1026
+
1027
+ before(() => { mock.timers.enable({ apis: ["setInterval"] }); });
1028
+ after(async () => {
1029
+ mock.timers.reset();
1030
+ delete process.env.PI_OFFLINE;
1031
+ (await import("../lib/provider.js")).resetCatalogState();
1032
+ });
1033
+
1034
+ it("session_start refreshes once, fire-and-forget, in every mode", async () => {
1035
+ const h = await makeHarness();
1036
+ await h.fireSessionStart();
1037
+ await h.tick(0);
1038
+ assert.equal(h.refreshes.length, 1);
1039
+ assert.deepEqual(h.refreshes[0].providers, ["router"]);
1040
+ });
1041
+
1042
+ it("endpoint flip forces the refresh (bypasses TTL + in-flight)", async () => {
1043
+ const h = await makeHarness();
1044
+ // Prime TTL-fresh state via the session-start auto refresh.
1045
+ await h.fireSessionStart();
1046
+ await h.tick(0);
1047
+ assert.equal(h.refreshes.length, 1);
1048
+ // Second session with a flipped endpoint (env override wins over saved
1049
+ // baseUrl): force must refresh even though the catalog is fresh.
1050
+ process.env.ROUTER_BASE_URL = "http://flipped-endpoint";
1051
+ try {
1052
+ await h.fireSessionStart();
1053
+ await h.tick(0);
1054
+ } finally {
1055
+ delete process.env.ROUTER_BASE_URL;
1056
+ }
1057
+ assert.equal(h.refreshes.length, 2);
1058
+ assert.equal(h.refreshes[1].force, true);
1059
+ });
1060
+
1061
+ it("session_shutdown clears the interval's ctx — no refresh on later ticks", async () => {
1062
+ const h = await makeHarness();
1063
+ await h.fireSessionStart();
1064
+ await h.tick(0);
1065
+ await h.fireShutdown();
1066
+ const before = h.refreshes.length;
1067
+ await h.tick(5 * 60_000); // tick after shutdown: lastCtx cleared → no-op
1068
+ assert.equal(h.refreshes.length, before);
1069
+ });
1070
+
1071
+ it("interval fires while session is live and respects the TTL gate", async () => {
1072
+ const h = await makeHarness();
1073
+ await h.fireSessionStart();
1074
+ await h.tick(0); // refresh #1 → lastFetchedAt = now
1075
+ assert.equal(h.refreshes.length, 1);
1076
+ await h.tick(5 * 60_000); // within TTL → no fetch
1077
+ assert.equal(h.refreshes.length, 1);
1078
+ });
1079
+
1080
+ it("/router-model awaits maybeRefreshCatalog before listing", async () => {
1081
+ const h = await makeHarness();
1082
+ const order: string[] = [];
1083
+ h.refreshes.length = 0;
1084
+ h.ctx.modelRegistry = {
1085
+ ...h.ctx.modelRegistry as Record<string, unknown>,
1086
+ getAll: () => {
1087
+ order.push("list");
1088
+ return [{ provider: "router", id: "m1" }];
1089
+ },
1090
+ refresh: async (opts?: { providers?: string[] }) => {
1091
+ order.push("refresh");
1092
+ h.refreshes.push(opts ?? {});
1093
+ return { aborted: false, errors: new Map() };
1094
+ },
1095
+ find: () => ({ provider: "router", id: "m1" }),
1096
+ };
1097
+ const cmd = h.pi.commands.get("router-model")!;
1098
+ await cmd.handler("", {
1099
+ ...h.ctx,
1100
+ mode: "tui",
1101
+ hasUI: true,
1102
+ } as never);
1103
+ assert.deepEqual(order, ["refresh", "list"]); // pre-pull before listing
1104
+ assert.equal(h.setModelCalls.n, 1); // single match auto-selected
1105
+ });
1106
+
1107
+ it("refreshActiveModel preserves a session thinking level across the re-select", async () => {
1108
+ const h = await makeHarness();
1109
+ h.ctx.model = { provider: "router", id: "m" };
1110
+ (h.ctx.modelRegistry as Record<string, unknown>).find = () => ({ provider: "router", id: "m" });
1111
+ // session_start itself runs refreshActiveModel (immediately + after the
1112
+ // fire-and-forget catalog pull); core's setModel would re-apply the
1113
+ // global default — restoration must keep the level equal.
1114
+ await h.fireSessionStart();
1115
+ await h.tick(0);
1116
+ assert.ok(h.setModelCalls.n >= 1);
1117
+ assert.equal(h.thinking.level, "high");
1118
+ // User picks a session-only level, then a catalog refresh re-selects the
1119
+ // same model (the revert scenario): level must survive.
1120
+ h.thinking.level = "max";
1121
+ await h.fireSessionStart();
1122
+ await h.tick(0);
1123
+ assert.ok(h.setModelCalls.n > 2);
1124
+ assert.equal(h.thinking.level, "max");
1125
+ });
1126
+ });