@lokeraar/pi-enclave-bridge 0.1.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.
@@ -0,0 +1,233 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * test-sync.mjs — offline checks for the whole donor pipeline.
4
+ *
5
+ * The rules being pinned, in the order they apply:
6
+ * 1. a bare name match, and the near miss that must NOT match
7
+ * 2. hand-written is the top authority, displaced only by rounding
8
+ * 3. strict order: openrouter second, the rest are corroboration only
9
+ * 4. nothing is ever averaged
10
+ * 5. "free" models are excluded from every bundled catalog
11
+ * 6. only providers with a credential are read
12
+ * 7. router aliases are never resolved from a donor
13
+ * 8. a dated vendor slug resolves to the short name
14
+ * 9. an output ceiling can never exceed the window minus a prompt reserve
15
+ * 10. the catalog is found without a stored path, so a Pi update is harmless
16
+ */
17
+
18
+ import { join } from "node:path";
19
+
20
+ const ROOT = join(new URL(".", import.meta.url).pathname, "..");
21
+ const { bareName, resolveModel, readBundledCatalog, readPiCatalogs, findBundledCatalogDir, findBundledCatalogs, ROUNDING_TOLERANCE } =
22
+ await import(join(ROOT, "donors.ts"));
23
+ const { buildBlock } = await import(join(ROOT, "enclave-live.ts"));
24
+
25
+ let passed = 0;
26
+ const failed = [];
27
+ const check = (name, cond, detail) => {
28
+ if (cond) {
29
+ passed++;
30
+ console.log(` ok ${name}`);
31
+ } else {
32
+ failed.push(name);
33
+ console.log(` FAIL ${name}${detail ? ` — ${detail}` : ""}`);
34
+ }
35
+ };
36
+
37
+ const cat = (provider, models) => ({ provider, models: new Map(Object.entries(models)) });
38
+ const agentDir = join(process.env.HOME ?? "", ".pi", "agent");
39
+
40
+ console.log("\nbare name");
41
+ check("strips a vendor prefix", bareName("cyberouter/glm-5.3") === "glm-5.3");
42
+ check("leaves an unprefixed id alone", bareName("glm-5.3") === "glm-5.3");
43
+ check("strips only the last segment", bareName("a/b/c") === "c");
44
+
45
+ console.log("\nthe vendor's model card outranks every catalog");
46
+ {
47
+ const { VENDOR_SPEC } = await import(join(ROOT, "donors.ts"));
48
+ check("glm-5.3 has a card", !!VENDOR_SPEC["glm-5.3"]);
49
+ check("glm-5.2 has a card", !!VENDOR_SPEC["glm-5.2"]);
50
+ check("each card records why it exists", Object.values(VENDOR_SPEC).every((v) => v.why.length > 40));
51
+
52
+ // A catalog that claims 943718 and all six levels must not win.
53
+ const loud = cat("openrouter", {
54
+ "glm-5.3": { maxTokens: 943718, input: ["text", "image"], thinkingLevelMap: { off: null, minimal: "minimal", low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" } },
55
+ });
56
+ const r = resolveModel("glm-5.3", undefined, [loud], false);
57
+ check("the card sets the output ceiling", r.entry.maxTokens === 131072, String(r.entry.maxTokens));
58
+ check("the card sets the modalities", JSON.stringify(r.entry.input) === '["text"]', JSON.stringify(r.entry.input));
59
+ check("the card keeps only the implemented levels",
60
+ Object.entries(r.entry.thinkingLevelMap).filter(([, v]) => v !== null).map(([k]) => k).join(",") === "low,high,max",
61
+ JSON.stringify(r.entry.thinkingLevelMap));
62
+ check("it is attributed to the model card", r.source === "model card", String(r.source));
63
+ check("the catalog is still recorded as corroboration", r.corroborating.includes("openrouter"), r.corroborating.join(","));
64
+
65
+ // The card applies to the exact name only; a neighbour is untouched.
66
+ const neighbour = resolveModel("glm-5.3-flash", undefined, [loud], false);
67
+ check("the card does not bleed to a neighbour", neighbour.entry.maxTokens === undefined, String(neighbour.entry.maxTokens));
68
+ }
69
+
70
+ console.log("\nopenrouter decides; what is written is only a fallback");
71
+ {
72
+ // A catalog that contradicts what is written: the catalog wins, because it is
73
+ // the source of truth the user chose.
74
+ const r = resolveModel("deepseek-v4-pro", { maxTokens: 232000 }, [cat("openrouter", { "deepseek-v4-pro": { maxTokens: 384000 } })], false);
75
+ check("the catalog overrides what was written", r.entry.maxTokens === 384000, String(r.entry.maxTokens));
76
+ check("and it is attributed to openrouter", r.source === "openrouter", String(r.source));
77
+
78
+ // Two catalogs disagree: the primary wins outright, never a midpoint.
79
+ const two = resolveModel("minimax-m3", undefined, [cat("openrouter", { "minimax-m3": { maxTokens: 512000 } }), cat("opencode", { "minimax-m3": { maxTokens: 128000 } })], false);
80
+ check("the highest-priority catalog supplies the value", two.entry.maxTokens === 512000, String(two.entry.maxTokens));
81
+ check("NOT the midpoint of the two", two.entry.maxTokens !== 320000, String(two.entry.maxTokens));
82
+ check("the lower one is recorded as corroboration", two.corroborating.join(",") === "opencode", two.corroborating.join(","));
83
+
84
+ // Nothing in any catalog knows the model: what is written stands.
85
+ const orphan = resolveModel("orphan", { maxTokens: 999, thinkingLevelMap: { low: "low" } }, [cat("openrouter", {})], false);
86
+ check("what is written is the fallback", orphan.entry.maxTokens === 999, String(orphan.entry.maxTokens));
87
+ check("and it is attributed to models.json", orphan.source === "models.json", String(orphan.source));
88
+
89
+ // compat is never taken from a catalog, whatever else is.
90
+ const withCompat = resolveModel("deepseek-v4-pro", undefined, [cat("openrouter", { "deepseek-v4-pro": { maxTokens: 1000, compat: { thinkingFormat: "openrouter" } } })], false);
91
+ check("compat is never inherited from a catalog", withCompat.entry.compat === undefined, JSON.stringify(withCompat.entry.compat));
92
+
93
+ // A dated slug is still resolved and recorded with its full id.
94
+ const dated = resolveModel("qwen3.8-max", undefined, [cat("openrouter", { "qwen3.8-max-0902": { id: "qwen/qwen3.8-max-0902", maxTokens: 131072 } })], false);
95
+ check("a dated slug resolves", dated.entry.maxTokens === 131072, String(dated.entry.maxTokens));
96
+ check("and the matched id keeps its prefix", dated.matchedId === "qwen/qwen3.8-max-0902", String(dated.matchedId));
97
+ }
98
+
99
+ console.log("\nfree models are excluded, no credential needed");
100
+ {
101
+ const dir = findBundledCatalogDir(agentDir);
102
+ if (!dir) {
103
+ console.log(" -- catálogo bundled no encontrado, se omiten estas pruebas");
104
+ } else {
105
+ const or = readBundledCatalog(dir, "openrouter");
106
+ const oc = readBundledCatalog(dir, "opencode");
107
+ check("openrouter catalog loads", !!or && or.models.size > 300, String(or && or.models.size));
108
+ const anyFree = (c) => [...c.models.keys()].some((k) => /free/i.test(k));
109
+ check("no free id survives in openrouter", !anyFree(or));
110
+ check("no free id survives in opencode", !anyFree(oc));
111
+ const inkling = or.models.get("inkling");
112
+ check("the paid entry wins over its :free sibling", !!inkling && inkling.maxTokens !== undefined, JSON.stringify(inkling && inkling.id));
113
+
114
+ const cats = readPiCatalogs(agentDir, { exclude: ["EnClave"] });
115
+ const providers = cats.map((c) => c.provider);
116
+ check("every catalog Pi ships is read, credential or not", providers.length > 30, String(providers.length));
117
+ check("openrouter leads as the primary donor", providers[0] === "openrouter", providers.slice(0, 3).join(","));
118
+ check("opencode is available even without an account", providers.includes("opencode"), "falta opencode");
119
+ }
120
+ }
121
+
122
+ console.log("\naliases are never resolved from a donor");
123
+ {
124
+ const r = resolveModel("auto", { maxTokens: 999 }, [cat("openrouter", { auto: { maxTokens: 30000, contextWindow: 2000000 } })], true);
125
+ check("an alias yields no donor values", Object.keys(r.entry).length === 0, JSON.stringify(r.entry));
126
+ check("an alias is reported as untouched", r.rule === "none" && r.source === undefined && r.corroborating.length === 0, r.rule);
127
+ }
128
+
129
+ console.log("\na dated vendor slug resolves to the short name");
130
+ {
131
+ const c = cat("openrouter", { "qwen3.8-max-0902": { maxTokens: 131072, input: ["text", "image"] } });
132
+ const r = resolveModel("qwen3.8-max", undefined, [c], false);
133
+ check("the dated slug is found", r.entry.maxTokens === 131072, String(r.entry.maxTokens));
134
+ check("and its modalities come with it", JSON.stringify(r.entry.input) === '["text","image"]', JSON.stringify(r.entry.input));
135
+
136
+ const both = cat("openrouter", { "qwen3.8-max": { maxTokens: 555 }, "qwen3.8-max-0902": { maxTokens: 131072 } });
137
+ check("the exact name beats the alias", resolveModel("qwen3.8-max", undefined, [both], false).entry.maxTokens === 555);
138
+
139
+ const n = cat("openrouter", { "nemotron-3-ultra-550b-a55b": { maxTokens: 32768 } });
140
+ check("nemotron-ultra resolves too", resolveModel("nemotron-ultra", undefined, [n], false).entry.maxTokens === 32768);
141
+ }
142
+
143
+ console.log("\nthe catalog is found without a stored path");
144
+ {
145
+ const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import("node:fs");
146
+ const { tmpdir } = await import("node:os");
147
+ const { join: J } = await import("node:path");
148
+ const fake = mkdtempSync(J(tmpdir(), "enclave-upd-"));
149
+ const mk = (ver, hash, max) => {
150
+ const p = J(fake, "npm/node_modules/.pnpm/@earendil-works+pi-ai@" + ver + "_" + hash, "node_modules/@earendil-works/pi-ai");
151
+ mkdirSync(J(p, "dist/providers/data"), { recursive: true });
152
+ writeFileSync(J(p, "package.json"), JSON.stringify({ version: ver }));
153
+ writeFileSync(J(p, "dist/providers/data/openrouter.json"), JSON.stringify({ "openai-completions": { "z-ai/glm-5.3": { id: "z-ai/glm-5.3", maxTokens: max } } }));
154
+ };
155
+ mk("0.85.1", "old", 100);
156
+ mk("0.99.0", "new", 999);
157
+ mk("0.90.0+dev", "plusbuild", 500);
158
+
159
+ // The Pi install is found by an absolute prefix and would shadow the store, so
160
+ // the preference order is exercised on the store scanner directly.
161
+ const { storeCatalogs } = await import(join(ROOT, "donors.ts"));
162
+ const dirs = storeCatalogs(fake);
163
+ check("store catalogs are found without a stored path", dirs.length >= 1, String(dirs.length));
164
+ check("the newest version wins whatever the folder is called", dirs[0].includes("0.99.0"), dirs[0]);
165
+ const cat2 = readBundledCatalog(dirs[0], "openrouter");
166
+ check("the newest catalog is the one read", cat2.models.get("glm-5.3").maxTokens === 999, String(cat2.models.get("glm-5.3").maxTokens));
167
+ check("a + prerelease is never preferred", !dirs.some((d) => d.includes("0.90.0+dev")), dirs.join(","));
168
+
169
+ const locs = findBundledCatalogs(fake);
170
+ check("the Pi install is preferred over the store", locs[0].origin === "la que usa Pi", locs[0].origin);
171
+ rmSync(fake, { recursive: true, force: true });
172
+
173
+ // A bogus agentDir must not throw. The Pi install is found by an absolute
174
+ // prefix, so it can still be returned here; what matters is that nothing
175
+ // breaks and the store scan contributes nothing.
176
+ const bogus = findBundledCatalogs("/no/existe/path");
177
+ check("a bogus agent dir does not throw", Array.isArray(bogus), typeof bogus);
178
+ check("and contributes no store catalog", !bogus.some((b) => b.origin === "pi install"));
179
+ }
180
+
181
+ console.log("\nthe block: matching, near misses, endpoint-owned fields");
182
+ {
183
+ const catalog = {
184
+ models: [
185
+ { id: "cyberouter/glm-5.3-flash", name: "GLM 5.3 Flash", contextLength: 1048576, pricingPrompt: 0.15, pricingCompletion: 0.5, routeable: true },
186
+ { id: "cyberouter/glm-5.3", name: "GLM 5.3", contextLength: 1048576, pricingPrompt: 1.4, pricingCompletion: 4.4, routeable: true },
187
+ { id: "cyberouter/inkling", name: "Inkling", contextLength: 262144, pricingPrompt: 1, pricingCompletion: 4, routeable: true },
188
+ { id: "cyberouter/dead", name: "Dead", contextLength: 262144, routeable: false },
189
+ { id: "cyberouter/orphan", name: "Orphan", contextLength: 262144, pricingPrompt: 1, pricingCompletion: 2, routeable: true },
190
+ ],
191
+ aliases: [{ id: "cyberouter/auto", task: null }],
192
+ };
193
+ const hand = new Map([
194
+ ["glm-5.3-flash", { maxTokens: 128000, thinkingLevelMap: { off: null, low: "low" } }],
195
+ ["glm-5.3", { maxTokens: 999999 }],
196
+ ]);
197
+ const bundled = [cat("openrouter", { "glm-5.3-flash": { maxTokens: 131072 }, inkling: { maxTokens: 471859 } })];
198
+
199
+ const out = buildBlock(catalog, hand, bundled, "https://x", () => true);
200
+ const by = Object.fromEntries(out.models.map((m) => [m.id, m]));
201
+
202
+ check("the near miss does not take the bundled figure", by["cyberouter/glm-5.3"].donor?.source !== "openrouter", JSON.stringify(by["cyberouter/glm-5.3"]?.donor));
203
+ check("the near miss keeps its own hand value", by["cyberouter/glm-5.3"].maxTokens === 999999, String(by["cyberouter/glm-5.3"].maxTokens));
204
+ check("the exact match takes the exact bundled figure", by["cyberouter/glm-5.3-flash"].maxTokens === 131072, String(by["cyberouter/glm-5.3-flash"].maxTokens));
205
+ check("the endpoint owns the context window", by["cyberouter/glm-5.3-flash"].contextWindow === 1048576, String(by["cyberouter/glm-5.3-flash"].contextWindow));
206
+ check("the endpoint owns the price", by["cyberouter/glm-5.3-flash"].cost.input === 0.15, String(by["cyberouter/glm-5.3-flash"].cost.input));
207
+ check("compat defaults on", by["cyberouter/glm-5.3-flash"].compat?.supportsDeveloperRole === false, JSON.stringify(by["cyberouter/glm-5.3-flash"].compat));
208
+ check("a model with no route is excluded", !by["cyberouter/dead"]);
209
+ check("the exclusion says why", out.skipped.find((s) => s.id === "cyberouter/dead")?.why.includes("ruta"), JSON.stringify(out.skipped));
210
+ check("a model with no donor is reported as pending", out.pending.includes("cyberouter/orphan"), out.pending.join(","));
211
+
212
+ check("aliases are published", !!by["cyberouter/auto"]);
213
+ check("alias context is the catalog floor", by["cyberouter/auto"].contextWindow === 262144, String(by["cyberouter/auto"].contextWindow));
214
+ check("alias price is the catalog ceiling", by["cyberouter/auto"].cost.input === 1.4, String(by["cyberouter/auto"].cost.input));
215
+ check("aliases carry no donor record", by["cyberouter/auto"].donor === undefined);
216
+
217
+ check("an impossible ceiling is clamped below the window", by["cyberouter/inkling"].maxTokens === 262144 - 2048, String(by["cyberouter/inkling"].maxTokens));
218
+ check("maxTokens is never null (Pi crashes formatting it)", out.models.every((m) => typeof m.maxTokens === "number"), "hay un null");
219
+ }
220
+
221
+ console.log("\nexisting values are kept when there is no donor at all");
222
+ {
223
+ const catalog = { models: [{ id: "cyberouter/orphan", name: "Orphan", contextLength: 262144, pricingPrompt: 1, pricingCompletion: 2, routeable: true }], aliases: [] };
224
+ const hand = new Map([["orphan", { maxTokens: 999, thinkingLevelMap: { low: "low" } }]]);
225
+ const out = buildBlock(catalog, hand, [], "https://x", () => true);
226
+ check("the hand value survives", out.models[0].maxTokens === 999, String(out.models[0].maxTokens));
227
+ }
228
+
229
+ console.log(`\n${passed} passed, ${failed.length} failed`);
230
+ if (failed.length) {
231
+ for (const f of failed) console.log(` - ${f}`);
232
+ process.exit(1);
233
+ }