@chibitek/chibi 0.1.208 → 0.1.210

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 (145) hide show
  1. package/dist/assets/{TerminalPanel-B5bwdaJ5.js → TerminalPanel-DxQoOfkY.js} +1 -1
  2. package/dist/assets/{abnfDiagram-O67JEVCF-BLKuHvdS.js → abnfDiagram-O67JEVCF-Ds2qYdjS.js} +1 -1
  3. package/dist/assets/{arc-BeOf3Y3d.js → arc-1O9tchZk.js} +1 -1
  4. package/dist/assets/{architectureDiagram-NJMV4G6O-DnXr729a.js → architectureDiagram-NJMV4G6O-CWuQ1x2F.js} +1 -1
  5. package/dist/assets/{blockDiagram-BEXU5L5S-CEiwrTaI.js → blockDiagram-BEXU5L5S-CNcEkXEx.js} +1 -1
  6. package/dist/assets/{c4Diagram-YGBWAQC7-C0-29khR.js → c4Diagram-YGBWAQC7-BKI_wi9I.js} +1 -1
  7. package/dist/assets/channel-CT5xRPK0.js +1 -0
  8. package/dist/assets/{chunk-2Q5K7J3B-D8dKbbui.js → chunk-2Q5K7J3B-gO88emfN.js} +1 -1
  9. package/dist/assets/{chunk-3FUC2YCW-fAEY1oOe.js → chunk-3FUC2YCW-DbKNT_-r.js} +2 -2
  10. package/dist/assets/{chunk-5VM5RSS4-Djza4B4b.js → chunk-5VM5RSS4-BbJCoZVg.js} +1 -1
  11. package/dist/assets/{chunk-GTNCS2PH-BWFGSXNt.js → chunk-GTNCS2PH-DXurSCcp.js} +1 -1
  12. package/dist/assets/{chunk-GWA4HPMP-BGo5oevY.js → chunk-GWA4HPMP-BWyt0I_m.js} +1 -1
  13. package/dist/assets/{chunk-JWPE2WC7-DIdxOMOn.js → chunk-JWPE2WC7-6iWSsogl.js} +1 -1
  14. package/dist/assets/{chunk-NETBCI7D-Dc4tJ9uD.js → chunk-NETBCI7D-CFoqO9Hw.js} +1 -1
  15. package/dist/assets/{chunk-WEXAMYUT-DvZ9F5yw.js → chunk-WEXAMYUT-BZEzAlNi.js} +1 -1
  16. package/dist/assets/{chunk-XXDRQBXY-BYUVYcxq.js → chunk-XXDRQBXY-W4hfC50f.js} +1 -1
  17. package/dist/assets/{classDiagram-v2-NBCMYWYE-BtnsJQvT.js → classDiagram-v2-NBCMYWYE-BsGmL9e7.js} +1 -1
  18. package/dist/assets/{cose-bilkent-JH36ORCC-DLDe1VHc.js → cose-bilkent-JH36ORCC-CYtTgIzk.js} +1 -1
  19. package/dist/assets/{cynefin-OW5HDTMX-a1GJE5iI.js → cynefin-OW5HDTMX-DLOi2Q2V.js} +1 -1
  20. package/dist/assets/{cynefinDiagram-VND7K2PF-DXxGLDlQ.js → cynefinDiagram-VND7K2PF-BXcXJ3hv.js} +1 -1
  21. package/dist/assets/{dagre-6A5THRUB-DAW_YZe9.js → dagre-6A5THRUB-BdBOiuzt.js} +1 -1
  22. package/dist/assets/{diagram-22UHCM2B-oq3saywD.js → diagram-22UHCM2B-DCf3M4WE.js} +1 -1
  23. package/dist/assets/{diagram-3UASUU5V-BhCP3hS9.js → diagram-3UASUU5V-CzdF-UXi.js} +1 -1
  24. package/dist/assets/{diagram-ATOU4E4O-ByFRn1dW.js → diagram-ATOU4E4O-_UmmlMOD.js} +1 -1
  25. package/dist/assets/{diagram-CDSNMT55-DWoCvkNH.js → diagram-CDSNMT55-DrQODVuX.js} +1 -1
  26. package/dist/assets/{diagram-MLGK6HIB-CSH5kSlk.js → diagram-MLGK6HIB-CE16iJlJ.js} +1 -1
  27. package/dist/assets/{diagram-MPIPVDR6-Cnpx1s-T.js → diagram-MPIPVDR6-DJuTbhbP.js} +1 -1
  28. package/dist/assets/{ebnfDiagram-ZINNZB2B-DPmX63Vg.js → ebnfDiagram-ZINNZB2B-f1VEI2Po.js} +1 -1
  29. package/dist/assets/{elk-276RUBZZ-DUtmO9kb.js → elk-276RUBZZ-BRbs9WzY.js} +1 -1
  30. package/dist/assets/{erDiagram-OPXOYQCR-SxwJeJu-.js → erDiagram-OPXOYQCR-DvMp_cQr.js} +1 -1
  31. package/dist/assets/{flowDiagram-KWPJA3E3--QZAAUjB.js → flowDiagram-KWPJA3E3-CYS1A0fu.js} +1 -1
  32. package/dist/assets/{ganttDiagram-FUAMR5RP-CRz6i2Pe.js → ganttDiagram-FUAMR5RP-qya_JE9x.js} +1 -1
  33. package/dist/assets/{gitGraphDiagram-X574FWY7-Dx9Cisl2.js → gitGraphDiagram-X574FWY7-ChMUJ3hH.js} +1 -1
  34. package/dist/assets/{index-vIsgWbJW.js → index-COH7BlyH.js} +196 -196
  35. package/dist/assets/index-H8vkXbLq.css +1 -0
  36. package/dist/assets/{index-BGkOob08.js → index-xE4Li_H2.js} +1 -1
  37. package/dist/assets/{infoDiagram-VRGFBTTK-CDLogk8N.js → infoDiagram-VRGFBTTK-B2VudqsE.js} +1 -1
  38. package/dist/assets/{ishikawaDiagram-OU5B5YK6-DsrF1wno.js → ishikawaDiagram-OU5B5YK6-Bdk47y0t.js} +1 -1
  39. package/dist/assets/{journeyDiagram-ZHPQQLJL-DUi8LEA6.js → journeyDiagram-ZHPQQLJL-A4StgNQ9.js} +1 -1
  40. package/dist/assets/{kanban-definition-PNTS6WVX-BAdWXobw.js → kanban-definition-PNTS6WVX-DZo45dQw.js} +1 -1
  41. package/dist/assets/{linear-Dha948ns.js → linear-D_rK-Ord.js} +1 -1
  42. package/dist/assets/{mermaid.core-BqT1aUP9.js → mermaid.core-C7CvDDvz.js} +5 -5
  43. package/dist/assets/{mindmap-definition-NLK3R4M7-XS1wDQ80.js → mindmap-definition-NLK3R4M7-6fmVPMyc.js} +1 -1
  44. package/dist/assets/{pegDiagram-GJSIUBJH-BphuafcF.js → pegDiagram-GJSIUBJH-CD4Qg24h.js} +1 -1
  45. package/dist/assets/{pieDiagram-5QR66LMP-JN9mbdiU.js → pieDiagram-5QR66LMP-DmzQ883B.js} +1 -1
  46. package/dist/assets/{quadrantDiagram-O4NWA36T-CkBF7Woa.js → quadrantDiagram-O4NWA36T-BW37utPZ.js} +1 -1
  47. package/dist/assets/{railroadDiagram-XR7U4H2S-Ie1GVpj5.js → railroadDiagram-XR7U4H2S-CWXiMlAb.js} +1 -1
  48. package/dist/assets/{requirementDiagram-PLB6GJNP-B8xGM6w4.js → requirementDiagram-PLB6GJNP-DHSfr9U3.js} +1 -1
  49. package/dist/assets/{sankeyDiagram-IPEJSGJF-BgTSlqMg.js → sankeyDiagram-IPEJSGJF-PebTt4eq.js} +1 -1
  50. package/dist/assets/{sequenceDiagram-PO4LG4MO-B1J4EIne.js → sequenceDiagram-PO4LG4MO-DPwp8fia.js} +1 -1
  51. package/dist/assets/{sizeCapture-INFHLROL-Cpcjc5oE.js → sizeCapture-INFHLROL-BX_46o3S.js} +1 -1
  52. package/dist/assets/{stateDiagram-v2-GCMORJYK-CtQKYLT4.js → stateDiagram-v2-GCMORJYK-W2e0RRrZ.js} +1 -1
  53. package/dist/assets/{swimlanes-2SLR337P-DpIk02zs.js → swimlanes-2SLR337P-CkyXpQX9.js} +1 -1
  54. package/dist/assets/swimlanesDiagram-TC7HE7FX-BH9Yry0J.js +8 -0
  55. package/dist/assets/{timeline-definition-EJHVYXUP-DsA7dQhy.js → timeline-definition-EJHVYXUP-BS-sCjlN.js} +1 -1
  56. package/dist/assets/{usecaseDiagram-POWQR4AR-BM42_rDz.js → usecaseDiagram-POWQR4AR-BQre-k6x.js} +1 -1
  57. package/dist/assets/{vennDiagram-UO4OBE2U-DgLtqgJF.js → vennDiagram-UO4OBE2U-CEWCsi_s.js} +1 -1
  58. package/dist/assets/{wardleyDiagram-VNRHLVJA-BKUUTKBJ.js → wardleyDiagram-VNRHLVJA-CXUxqghG.js} +1 -1
  59. package/dist/assets/{xychartDiagram-PMCCYNJV-B9RWvizV.js → xychartDiagram-PMCCYNJV-DBgVMpwp.js} +1 -1
  60. package/dist/index.html +4 -2
  61. package/dist-server/accounts-proxy.js +19 -12
  62. package/dist-server/browser-proxy.js +19 -14
  63. package/dist-server/container-mcp.js +84 -12
  64. package/dist-server/drivers/agents-proxy.js +28 -13
  65. package/dist-server/drivers/phone-proxy.js +21 -13
  66. package/dist-server/index.js +4000 -2834
  67. package/dist-server/local-computer-proxy.js +77 -11
  68. package/dist-server/local-computer.js +2 -1
  69. package/dist-server/mcp-gate.js +53 -4
  70. package/dist-server/mcp-server.js +1 -1
  71. package/dist-server/openmausbot.js +458 -93
  72. package/dist-server/pair-cli.js +458 -93
  73. package/dist-server/server/accounts-proxy.js +3 -17
  74. package/dist-server/server/atomic-engine-release.js +7 -0
  75. package/dist-server/server/browser-proxy.js +3 -17
  76. package/dist-server/server/child-env.js +79 -0
  77. package/dist-server/server/config.js +11 -5
  78. package/dist-server/server/container-computer.js +1 -1
  79. package/dist-server/server/container-mcp.js +3 -2
  80. package/dist-server/server/control-client.js +7 -6
  81. package/dist-server/server/delegated-full-access.js +98 -0
  82. package/dist-server/server/desktop-loopback-gate.js +57 -0
  83. package/dist-server/server/drivers/acp/core.js +4 -4
  84. package/dist-server/server/drivers/acp/hermes-hosts.js +9 -0
  85. package/dist-server/server/drivers/acp/hermes.js +6 -9
  86. package/dist-server/server/drivers/acp/session-key.js +8 -0
  87. package/dist-server/server/drivers/agents-client.js +2 -14
  88. package/dist-server/server/drivers/gcloud-token.js +28 -0
  89. package/dist-server/server/drivers/github-copilot.js +152 -0
  90. package/dist-server/server/drivers/openai-chat-protocol.js +8 -0
  91. package/dist-server/server/drivers/openai-chat.js +10 -8
  92. package/dist-server/server/drivers/openai-compat.js +44 -9
  93. package/dist-server/server/drivers/phone-proxy.js +5 -18
  94. package/dist-server/server/engine-tiers.js +9 -9
  95. package/dist-server/server/harness/http.js +47 -1
  96. package/dist-server/server/index.js +54 -54
  97. package/dist-server/server/ladder-pick.js +18 -0
  98. package/dist-server/server/local-computer-proxy.js +3 -2
  99. package/dist-server/server/local-computer.js +1 -0
  100. package/dist-server/server/mcp-bridge.js +3 -2
  101. package/dist-server/server/mcp-gate.js +2 -1
  102. package/dist-server/server/mcp-registry.js +5 -1
  103. package/dist-server/server/model-gateway/failover.js +4 -1
  104. package/dist-server/server/model-gateway/route.js +64 -14
  105. package/dist-server/server/model-gateway/usage.js +66 -0
  106. package/dist-server/server/model-levels/aa-scale.js +42 -0
  107. package/dist-server/server/model-levels/aliases.js +16 -3
  108. package/dist-server/server/model-levels/index.js +8 -3
  109. package/dist-server/server/model-levels/rankings-build.js +76 -0
  110. package/dist-server/server/model-prices.js +6 -0
  111. package/dist-server/server/nexus-memory/index.js +5 -13
  112. package/dist-server/server/nexus-memory/policy.js +5 -17
  113. package/dist-server/server/oauth-account-vault.js +7 -2
  114. package/dist-server/server/provider-accounts.js +20 -1
  115. package/dist-server/server/provider-key-check.js +31 -1
  116. package/dist-server/server/registry-load.js +88 -0
  117. package/dist-server/server/request-auth.js +6 -28
  118. package/dist-server/server/routes/provider-accounts.js +124 -6
  119. package/dist-server/server/routine-daily-schedule.js +20 -0
  120. package/dist-server/server/routine-prompt-escape.js +18 -0
  121. package/dist-server/server/routine-tick-guard.js +16 -0
  122. package/dist-server/server/routine-tool-problems.js +36 -0
  123. package/dist-server/server/routines.js +36 -38
  124. package/dist-server/server/shutdown-triggers.js +18 -0
  125. package/dist-server/server/spend.js +23 -13
  126. package/dist-server/server/store.js +4 -13
  127. package/dist-server/server/terminal.js +2 -1
  128. package/dist-server/server/turn-token-file.js +79 -0
  129. package/dist-server/server/turn-token.js +23 -0
  130. package/dist-server/server/vps-container-mcp.js +3 -2
  131. package/dist-server/server/webhook-ingress.js +11 -1
  132. package/dist-server/server/webhook-prompt.js +82 -0
  133. package/dist-server/server/webhooks.js +8 -65
  134. package/dist-server/server/workspace-backup-policy.js +3 -3
  135. package/dist-server/server/workspace-backup.js +1 -1
  136. package/dist-server/server/workspace-time-zone.js +47 -0
  137. package/dist-server/shared/engine-choices.js +12 -1
  138. package/dist-server/shared/engine-tiers.js +0 -12
  139. package/dist-server/shared/provider-accounts.js +114 -2
  140. package/dist-server/shared/zoned-time.js +55 -0
  141. package/dist-server/vps-container-mcp.js +84 -12
  142. package/package.json +1 -1
  143. package/dist/assets/channel-_JFliC5C.js +0 -1
  144. package/dist/assets/index-Bi3hprmz.css +0 -1
  145. package/dist/assets/swimlanesDiagram-TC7HE7FX-DPTl4zVS.js +0 -8
@@ -0,0 +1,66 @@
1
+ // Token counts out of an answer as it passes through the gateway, for the
2
+ // usage ledger. Reads only `usage` objects (OpenAI Responses and Chat
3
+ // Completions, Anthropic Messages; whole JSON or event stream); message text
4
+ // is never kept past the line or body it arrived in.
5
+ const MAX_JSON = 4 * 1024 * 1024;
6
+ const MAX_LINE = 256 * 1024;
7
+ const count = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0);
8
+ const record = (value) => (typeof value === "object" && value !== null ? value : null);
9
+ function usageIn(value) {
10
+ const body = record(value);
11
+ const usage = record(body?.usage) ?? record(record(body?.response)?.usage) ?? record(record(body?.message)?.usage);
12
+ if (!usage)
13
+ return null;
14
+ return { input: count(usage.input_tokens ?? usage.prompt_tokens), output: count(usage.output_tokens ?? usage.completion_tokens) };
15
+ }
16
+ function parsed(text) {
17
+ try {
18
+ return JSON.parse(text);
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ }
24
+ /** Feed it the answer's bytes; `total()` is the usage the upstream reported, or null. */
25
+ export function usageMeter(contentType) {
26
+ const stream = contentType.includes("event-stream");
27
+ const decoder = new TextDecoder();
28
+ let pending = "";
29
+ let overflow = false;
30
+ let seen = null;
31
+ const take = (usage) => {
32
+ if (usage)
33
+ seen = { input: Math.max(seen?.input ?? 0, usage.input), output: Math.max(seen?.output ?? 0, usage.output) };
34
+ };
35
+ const line = (text) => {
36
+ if (text.startsWith("data:") && text.includes("\"usage\""))
37
+ take(usageIn(parsed(text.slice(5))));
38
+ };
39
+ return {
40
+ push(chunk) {
41
+ if (overflow)
42
+ return;
43
+ pending += decoder.decode(chunk, { stream: true });
44
+ if (stream) {
45
+ const lines = pending.split("\n");
46
+ pending = lines.pop() ?? "";
47
+ for (const text of lines)
48
+ line(text.trimEnd());
49
+ if (pending.length > MAX_LINE)
50
+ pending = "";
51
+ }
52
+ else if (pending.length > MAX_JSON) {
53
+ overflow = true;
54
+ pending = "";
55
+ }
56
+ },
57
+ total() {
58
+ if (stream)
59
+ line(pending.trimEnd());
60
+ else if (!overflow)
61
+ take(usageIn(parsed(pending)));
62
+ pending = "";
63
+ return seen;
64
+ },
65
+ };
66
+ }
@@ -0,0 +1,42 @@
1
+ /** Fewer shared rows than this and the fetch is used as it is. */
2
+ export const MIN_SCALE_PAIRS = 8;
3
+ /** Mean gap (points) under which the two are taken to be the same scale. */
4
+ export const SAME_SCALE_POINTS = 1;
5
+ const round3 = (value) => Math.round(value * 1000) / 1000;
6
+ /** The fit from `fetched` onto `baseline`'s scale; null when the two agree
7
+ * or too few rows are shared to say. */
8
+ export function aaScale(fetched, baseline) {
9
+ const byId = new Map(baseline.map((row) => [row.id, row]));
10
+ const bySlug = new Map(baseline.map((row) => [row.slug, row]));
11
+ const pairs = [];
12
+ for (const row of fetched) {
13
+ const base = byId.get(row.id) ?? bySlug.get(row.slug);
14
+ if (base && Number.isFinite(row.intelligence) && Number.isFinite(base.intelligence))
15
+ pairs.push([row.intelligence, base.intelligence]);
16
+ }
17
+ if (pairs.length < MIN_SCALE_PAIRS)
18
+ return null;
19
+ const n = pairs.length;
20
+ const meanX = pairs.reduce((sum, [x]) => sum + x, 0) / n;
21
+ const meanY = pairs.reduce((sum, [, y]) => sum + y, 0) / n;
22
+ const meanGap = pairs.reduce((sum, [x, y]) => sum + Math.abs(y - x), 0) / n;
23
+ if (meanGap < SAME_SCALE_POINTS)
24
+ return null;
25
+ const sxx = pairs.reduce((sum, [x]) => sum + (x - meanX) ** 2, 0);
26
+ const sxy = pairs.reduce((sum, [x, y]) => sum + (x - meanX) * (y - meanY), 0);
27
+ // A flat or upside-down fit means the rows disagree, not a rescale: shift
28
+ // by the mean gap instead of stretching.
29
+ const fitted = sxx > 0 ? sxy / sxx : 0;
30
+ const slope = fitted >= 0.5 && fitted <= 2 ? fitted : 1;
31
+ return { pairs: n, slope: round3(slope), intercept: round3(meanY - slope * meanX) };
32
+ }
33
+ /** The fetch with every score on the baseline's scale (one decimal, as the
34
+ * index is published); unchanged when `scale` is null. */
35
+ export function onBaselineScale(snapshot, scale) {
36
+ if (!scale)
37
+ return snapshot;
38
+ return {
39
+ ...snapshot,
40
+ rows: snapshot.rows.map((row) => ({ ...row, intelligence: Math.round((scale.slope * row.intelligence + scale.intercept) * 10) / 10 })),
41
+ };
42
+ }
@@ -196,7 +196,7 @@ export const MODEL_CATALOG = [
196
196
  id: "gemini-3.8-flash", label: "Gemini 3.8 Flash",
197
197
  aa: ["Gemini 3.8 Flash"], leaderboard: ["Gemini 3.8 Flash (High)", "gemini-3.8-flash-high"],
198
198
  runs: [run("antigravityAgent", "gemini-3.8-flash-high", "high"), run("antigravityAgent", "gemini-3.8-flash-medium", "medium"),
199
- run("antigravityAgent", "gemini-3.8-flash-low", "low"), opencode("gemini-3.8-flash"), hermes("google/gemini-3.8-flash")],
199
+ run("antigravityAgent", "gemini-3.8-flash-low", "low"), opencode("gemini-3.8-flash"), hermes("google/gemini-3.8-flash"), run("openai-compat", "google/gemini-3.8-flash")],
200
200
  },
201
201
  {
202
202
  id: "gemini-3.7-flash", label: "Gemini 3.7 Flash",
@@ -247,19 +247,32 @@ export const MODEL_CATALOG = [
247
247
  {
248
248
  id: "deepseek-v4-pro", label: "DeepSeek V4 Pro",
249
249
  aa: ["DeepSeek V4 Pro 0813"], leaderboard: ["DeepSeek V4 Pro", "DeepSeek V4 Pro (High) (0813)", "deepseek-v4-pro", "deepseek-v4-pro-high-20260813"],
250
- runs: [opencode("deepseek-v4-pro"), hermes("deepseek/deepseek-v4-pro")],
250
+ runs: [opencode("deepseek-v4-pro"), hermes("deepseek/deepseek-v4-pro"), run("openai-compat", "deepseek-v4-pro")],
251
251
  ollama: ["deepseek-v4-pro:cloud"],
252
252
  },
253
253
  {
254
254
  id: "deepseek-v4.1-flash", label: "DeepSeek V4.1 Flash",
255
255
  aa: ["DeepSeek V4.1 Flash"], leaderboard: ["Deepseek V4.1 Flash (Max)", "deepseek-v4.1-flash-max"],
256
- runs: [opencode("deepseek-v4.1-flash"), hermes("deepseek/deepseek-v4.1-flash")],
256
+ // DeepSeek's own API serves V4.1 Flash as "deepseek-flash" (api-docs, 2026-11-22).
257
+ runs: [opencode("deepseek-v4.1-flash"), hermes("deepseek/deepseek-v4.1-flash"), run("openai-compat", "deepseek-flash")],
257
258
  },
258
259
  {
259
260
  id: "deepseek-v4-flash", label: "DeepSeek V4 Flash",
260
261
  leaderboard: ["deepseek-v4-flash", "deepseek-v4-flash-high"],
261
262
  runs: [codex("deepseek-v4-flash:cloud"), opencode("deepseek-v4-flash")],
262
263
  },
264
+ // OpenAI's open-weight models on OpenAI-compatible hosts: Pollinations'
265
+ // keyless "openai-fast" is gpt-oss-20b (its answers name the model);
266
+ // Hugging Face and Cerebras serve gpt-oss-120b.
267
+ {
268
+ id: "gpt-oss-20b", label: "gpt-oss-20b", leaderboard: ["gpt-oss-20b"],
269
+ runs: [run("openai-compat", "openai-fast"), run("openai-compat", "openai/gpt-oss-20b"), run("openai-compat", "gpt-oss-20b")],
270
+ },
271
+ {
272
+ id: "gpt-oss-120b", label: "gpt-oss-120b", leaderboard: ["gpt-oss-120b"],
273
+ // Hugging Face, Together, Groq and Cerebras name it plainly; Fireworks and Bedrock add a prefix.
274
+ runs: [run("openai-compat", "openai/gpt-oss-120b"), run("openai-compat", "gpt-oss-120b"), run("openai-compat", "accounts/fireworks/models/gpt-oss-120b"), run("openai-compat", "openai.gpt-oss-120b-1:0")],
275
+ },
263
276
  // Meta, through Muse Code (ids from dev.meta.ai/docs/models, 2026-10-23).
264
277
  // Muse Wonder 1.0 is not listed: the boards now carry "Muse Wonder" and
265
278
  // "Muse Wonder Full", and which of the two it is has not been settled, so
@@ -19,6 +19,7 @@ import { BASELINE } from "./baseline.js";
19
19
  import { AA_CACHE_FILE, CACHE_FILE, readAaCache, readCache, validSnapshots, writeAaCache, writeCache } from "./cache.js";
20
20
  import { setPublishedHarnessWeights } from "../ladder-order.js";
21
21
  import { CHIBITEK_RANKINGS_CACHE, fetchRankings, parseRankings, readRankingsCache, writeRankingsCache } from "./chibitek-rankings.js";
22
+ import { aaScale, onBaselineScale } from "./aa-scale.js";
22
23
  import { AA_STALE_AFTER_DAYS, byClass, classifyModels, gradedFamilies, inheritedClass, matchAaRows } from "./classes.js";
23
24
  import { fetchSource } from "./fetch.js";
24
25
  import { PERCENTILE_CUTOFFS, gradeCapabilities } from "./grade.js";
@@ -89,7 +90,10 @@ export function createModelLevels(options) {
89
90
  const { overrides, problems } = readOverrides(overridesPath);
90
91
  const fetchedLmarena = current().filter((snapshot) => origins.get(snapshot.source) !== "baseline");
91
92
  const lmarena = lmarenaInput(current(), overrides.aliases);
92
- const aa = aaFetched ? matchAaRows(aaFetched.rows, catalog, overrides.aliases) : undefined;
93
+ // A fetch on a newer Intelligence Index is read on the baseline's scale,
94
+ // the one the bands were set on (aa-scale.ts).
95
+ const scale = aaFetched && aaBaseline ? aaScale(aaFetched.rows, aaBaseline.rows) : null;
96
+ const aa = aaFetched ? matchAaRows(onBaselineScale(aaFetched, scale).rows, catalog, overrides.aliases) : undefined;
93
97
  const aaBase = aaBaseline ? matchAaRows(aaBaseline.rows, catalog, overrides.aliases) : undefined;
94
98
  const models = classifyModels({
95
99
  catalog,
@@ -105,7 +109,7 @@ export function createModelLevels(options) {
105
109
  const unmatched = new Map();
106
110
  for (const entry of [...(aa ?? aaBase)?.unmatched ?? [], ...lmarena.unmatched])
107
111
  unmatched.set(`${entry.sources[0]}:${entry.name}`, entry);
108
- return { models, unmatched: [...unmatched.values()], problems, bands: overrides.bands };
112
+ return { models, unmatched: [...unmatched.values()], problems, bands: overrides.bands, scale };
109
113
  };
110
114
  // Classes are read on every turn start and failover; they are cached until
111
115
  // a refresh, an override, or a change to the overrides file on disk.
@@ -126,7 +130,7 @@ export function createModelLevels(options) {
126
130
  return memo.value;
127
131
  };
128
132
  const report = () => {
129
- const { models, unmatched, problems, bands } = classified();
133
+ const { models, unmatched, problems, bands, scale } = classified();
130
134
  return {
131
135
  generatedAt: now().toISOString(),
132
136
  attribution: { artificialAnalysis: AA_ATTRIBUTION, lmarena: ATTRIBUTION },
@@ -136,6 +140,7 @@ export function createModelLevels(options) {
136
140
  fetchedAt: (aaFetched ?? aaBaseline)?.fetchedAt ?? null,
137
141
  origin: aaOrigin,
138
142
  rows: (aaFetched ?? aaBaseline)?.rows.length ?? 0,
143
+ scale,
139
144
  },
140
145
  chibitekRankings: rankings
141
146
  ? { week: rankings.week, fetchedAt: rankings.fetchedAt, rows: rankings.rows.length }
@@ -0,0 +1,76 @@
1
+ // Builds the weekly Chibitek rankings document (chibitek-rankings.ts) from
2
+ // the same live public sources Atomic grades classes from, so the document
3
+ // is real data with its sources named inside it, never hand-typed numbers:
4
+ // - Artificial Analysis Intelligence Index (live with a key, else the
5
+ // bundled rows, dated), the class and the order inside the class;
6
+ // - LMArena boards (Hugging Face datasets, fetched live, no key), for
7
+ // models Artificial Analysis does not list.
8
+ // The weekly document itself is never read back while building (its URL is
9
+ // answered "not published" here), so a week never ranks from last week.
10
+ import { mkdtempSync, rmSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { DEFAULT_CLASS_BANDS, MODEL_CLASSES, classForScore } from "../../shared/engine-tiers.js";
14
+ import { AA_ATTRIBUTION, AA_MODELS_URL } from "./artificial-analysis.js";
15
+ import { CHIBITEK_RANKINGS_URL } from "./chibitek-rankings.js";
16
+ import { scoreVariants } from "./classes.js";
17
+ import { createModelLevels } from "./index.js";
18
+ const GRADED = new Set(["artificial-analysis", "lmarena", "baseline"]);
19
+ /** A model's class: banded from its Artificial Analysis score (medium/high
20
+ * rule, on the bands' scale) when it has one, the documented primary scorer;
21
+ * else Atomic's own grade (LMArena). The order inside a class: that score,
22
+ * highest first; then models only LMArena grades, by percentile. */
23
+ export function rankingsFromReport(report, week, generatedAt) {
24
+ const rows = [];
25
+ for (const model of report.models) {
26
+ const grade = model.modelClass;
27
+ if (model.overrideOnly || !GRADED.has(grade.source))
28
+ continue;
29
+ const aa = grade.score ?? scoreVariants(grade.variants)?.score;
30
+ const basis = { source: grade.baselineOf ? `baseline:${grade.baselineOf}` : grade.source };
31
+ if (grade.sourceDate)
32
+ basis.sourceDate = grade.sourceDate;
33
+ if (aa !== undefined)
34
+ basis.aaIntelligence = aa;
35
+ if (grade.percentile !== undefined)
36
+ basis.lmarenaPercentile = grade.percentile;
37
+ const modelClass = aa !== undefined ? classForScore(aa, report.bands ?? DEFAULT_CLASS_BANDS) : grade.modelClass;
38
+ basis.classFrom = aa !== undefined ? "artificial-analysis" : basis.source;
39
+ rows.push({ id: model.id, label: model.label, modelClass, ...(aa !== undefined ? { aa } : {}), ...(grade.percentile !== undefined ? { percentile: grade.percentile } : {}), basis });
40
+ }
41
+ const models = [];
42
+ for (const modelClass of MODEL_CLASSES) {
43
+ const inClass = rows.filter((row) => row.modelClass === modelClass).sort((a, b) => (a.aa === undefined ? 1 : 0) - (b.aa === undefined ? 1 : 0) || (b.aa ?? 0) - (a.aa ?? 0) ||
44
+ (b.percentile ?? -1) - (a.percentile ?? -1) || a.id.localeCompare(b.id));
45
+ inClass.forEach((row, index) => models.push({ id: row.id, label: row.label, class: modelClass, rank: index + 1, basis: row.basis }));
46
+ }
47
+ const aa = report.artificialAnalysis;
48
+ return {
49
+ week, generatedAt,
50
+ method: "Class: the Artificial Analysis Intelligence Index (mean of medium and high effort) on the class bands (Mezcal 50, Plata 44, Reposado 38); a model Artificial Analysis does not list keeps Atomic's LMArena grade. Rank inside a class: that index, highest first, then LMArena overall percentile. docs/chibitek/engine-tiers.md, Model classes.",
51
+ sources: [
52
+ { name: `Artificial Analysis (${AA_ATTRIBUTION})`, url: AA_MODELS_URL, date: aa.fetchedAt?.slice(0, 10) ?? null, origin: aa.origin, rows: aa.rows },
53
+ ...report.sources.map((source) => ({ name: `LMArena ${source.id}`, url: source.url, date: source.publishDate, origin: source.origin, rows: source.rows })),
54
+ ],
55
+ models,
56
+ };
57
+ }
58
+ /** Refreshes every source live into a scratch directory and builds the
59
+ * document. `apiKey` absent: Artificial Analysis comes from the bundled rows. */
60
+ export async function buildRankings(options = {}) {
61
+ const base = options.fetch ?? globalThis.fetch;
62
+ const fetch = async (url, init) => (String(url) === CHIBITEK_RANKINGS_URL
63
+ ? { ok: false, status: 404, headers: { get: () => null }, json: async () => ({}) }
64
+ : base(url, init));
65
+ const now = options.now ?? (() => new Date());
66
+ const dataDir = mkdtempSync(join(tmpdir(), "chibitek-rankings-"));
67
+ try {
68
+ const levels = createModelLevels({ dataDir, fetch, now, apiKey: options.apiKey ?? (() => undefined), log: () => { } });
69
+ const refresh = await levels.refresh();
70
+ const at = now();
71
+ return { document: rankingsFromReport(levels.report(), at.toISOString().slice(0, 10), at.toISOString()), errors: refresh.errors };
72
+ }
73
+ finally {
74
+ rmSync(dataDir, { recursive: true, force: true });
75
+ }
76
+ }
@@ -10,6 +10,9 @@ const MINIMAX = "https://platform.minimax.io/docs/guides/pricing-paygo";
10
10
  // models, so these are read from that list rather than copied from the
11
11
  // vendors. Its 5.5% fee on buying credits is not a per-token price.
12
12
  const OPENROUTER = "https://openrouter.ai/api/v1/models";
13
+ // DeepSeek bills half price off-peak; these are the PEAK rates (01:00-04:00
14
+ // and 06:00-10:00 UTC on weekdays), so an estimate never runs under the bill.
15
+ const DEEPSEEK = "https://api-docs.deepseek.com/quick_start/pricing";
13
16
  const price = (source, input, cached, output, extra = {}) => ({
14
17
  inputPerMillion: input,
15
18
  cachedInputPerMillion: cached,
@@ -78,6 +81,9 @@ export const LIST_PRICES = {
78
81
  "google/gemini-3.8-flash": price(OPENROUTER, 0.75, 0.075, 3.75),
79
82
  "minimax/minimax-m3": price(OPENROUTER, 0.3, 0.06, 1.2),
80
83
  "minimax/minimax-m2.7": price(OPENROUTER, 0.3, 0.06, 1.2),
84
+ // DeepSeek's own API, peak rates, read 2026-11-22.
85
+ "deepseek-flash": price(DEEPSEEK, 0.3, 0.006, 1.2, { asOf: "2026-11-22" }),
86
+ "deepseek-v4-pro": price(DEEPSEEK, 1.32, 0.044, 3.96, { asOf: "2026-11-22" }),
81
87
  };
82
88
  /** Catalog ids that name a listed model with a setting attached: the
83
89
  * Antigravity picker offers Gemini 3.8 Flash at three thinking levels. */
@@ -33,7 +33,7 @@ import { guardNexusClient, UnavailableBackoff } from "./backoff.js";
33
33
  import { nexusClientFor, NexusRejectedError, NexusUnavailableError } from "./client.js";
34
34
  import { buildSessionOutcome, promptText } from "./outcome.js";
35
35
  import { NexusOutbox } from "./outbox.js";
36
- import { classifyBotFile, containsSecret, desktopSurface, hipaaModeOn, isMediaMime, isTextMime, markedPatientData, mimeForPath, scopeForBot, scrubSecrets, } from "./policy.js";
36
+ import { classifyBotFile, containsSecret, desktopSurface, hipaaModeOn, isMediaMime, isTextMime, mimeForPath, scopeForBot, scrubSecrets, } from "./policy.js";
37
37
  import { DEFAULT_BUDGET_CHARS, fetchReadBack, formatReadBack } from "./readback.js";
38
38
  import { hostname } from "node:os";
39
39
  import { isPersonalBot } from "../../shared/personal-bot.js";
@@ -323,8 +323,7 @@ export class NexusMemory {
323
323
  }
324
324
  }
325
325
  queueOutcome(turn, hipaa) {
326
- if (hipaa && (markedPatientData({ text: `${turn.prompt}\n${turn.reply}`, bot: turn.bot }) ||
327
- turn.toolResults?.some((tool) => markedPatientData({ text: tool.output ?? "", bot: turn.bot }))))
326
+ if (hipaa)
328
327
  return "hipaa";
329
328
  const outcome = buildSessionOutcome({
330
329
  botName: turn.bot.name,
@@ -373,7 +372,7 @@ export class NexusMemory {
373
372
  const route = nexusRouteFor(input.bot, settings.personalConnection);
374
373
  if (route.to === "local")
375
374
  return route.reason;
376
- if (hipaaModeOn(this.hipaaContext(), input.bot) && markedPatientData({ text: input.content, bot: input.bot }))
375
+ if (hipaaModeOn(this.hipaaContext(), input.bot))
377
376
  return "hipaa";
378
377
  const source = this.writeSource(input.bot, input.threadId);
379
378
  const queued = this.outbox.enqueue({
@@ -427,10 +426,7 @@ export class NexusMemory {
427
426
  const media = isMediaMime(mime);
428
427
  if (media && !settings.saveMedia)
429
428
  return "media_off";
430
- const hipaa = hipaaModeOn(this.hipaaContext(), input.bot);
431
- // The whole local path is checked (a patients/ folder anywhere above the
432
- // file counts); it is only read here, never sent.
433
- if (hipaa && markedPatientData({ path: `${input.path}\n${display}`, bot: input.bot }))
429
+ if (hipaaModeOn(this.hipaaContext(), input.bot))
434
430
  return "hipaa";
435
431
  let size;
436
432
  try {
@@ -463,8 +459,6 @@ export class NexusMemory {
463
459
  this.log(`refused to upload ${basename(display)}: it looks like it contains a secret`);
464
460
  return "secret";
465
461
  }
466
- if (hipaa && isTextMime(mime) && markedPatientData({ text: asText }))
467
- return "hipaa";
468
462
  const sha256 = createHash("sha256").update(bytes).digest("hex");
469
463
  const queued = this.outbox.enqueue({
470
464
  private: isPersonalBot(input.bot),
@@ -656,7 +650,7 @@ export class NexusMemory {
656
650
  state = "not_connected";
657
651
  else if (!settings.alwaysSave)
658
652
  state = "off";
659
- else if (bot.hipaa === true)
653
+ else if (bot.hipaa === true || settings.hipaa)
660
654
  state = "hipaa_bot";
661
655
  else
662
656
  state = "connected";
@@ -745,8 +739,6 @@ export class NexusMemory {
745
739
  const view = this.botView(bot);
746
740
  if (view.state !== "connected")
747
741
  return view.state;
748
- if (view.hipaaMode && markedPatientData({ text: body }))
749
- return "hipaa";
750
742
  const hash = createHash("sha256").update(body).digest("hex");
751
743
  const current = this.notes[bot.id];
752
744
  if (current?.hash === hash && current.scope === view.scope)
@@ -1,7 +1,9 @@
1
1
  // What Atomic may write back to Nexus, and under which scope and surface.
2
2
  // Pure rules, shared by the writer, the read-back and their tests:
3
3
  // - The Private Bot writes to the person's personal scope only, never work.
4
- // - HIPAA mode skips anything marked as patient data.
4
+ // - HIPAA mode keeps memory on this computer: nothing is written, marked
5
+ // as patient data or not. A rule that trusts markers protects only the
6
+ // text someone remembered to mark.
5
7
  // - Nothing that looks like a secret is ever uploaded.
6
8
  // - Only handoffs, documents and media are uploaded, never source code.
7
9
  import { extname, basename } from "node:path";
@@ -31,25 +33,11 @@ export function surfaceForRequest(origin, platform = process.platform) {
31
33
  return "cli";
32
34
  return desktopSurface(platform);
33
35
  }
34
- // ── HIPAA ────────────────────────────────────────────────────────────────
35
- /** Explicit markers a person or bot puts on patient data. */
36
- const PATIENT_MARKERS = /#patient-?data\b|\[(?:PHI|patient data)\]|\bpatient[-_ ]data:|\bPHI:/i;
37
- /** Folders and file names that hold patient data. */
38
- const PATIENT_PATH = /(?:^|[\\/_.\- ])(?:phi|patients?|patient[-_ ]?data|hipaa)(?:[\\/_.\- ]|$)/i;
36
+ /** True when nothing of this bot's may be written to Nexus: the workspace or
37
+ * the organization is in HIPAA mode, or the bot is flagged for HIPAA work. */
39
38
  export function hipaaModeOn(ctx, bot) {
40
39
  return ctx.workspace || ctx.managed || bot?.hipaa === true;
41
40
  }
42
- /** True when this text or path is marked as patient data. A bot flagged for
43
- * HIPAA work is treated as handling patient data in everything it does. */
44
- export function markedPatientData(item) {
45
- if (item.bot?.hipaa === true)
46
- return true;
47
- if (item.text && PATIENT_MARKERS.test(item.text))
48
- return true;
49
- if (item.path && (PATIENT_PATH.test(item.path) || PATIENT_MARKERS.test(item.path)))
50
- return true;
51
- return false;
52
- }
53
41
  // ── secrets ──────────────────────────────────────────────────────────────
54
42
  /** True when text carries anything the release scanner or the transcript
55
43
  * redactor would treat as a credential. */
@@ -120,6 +120,11 @@ export class DesktopAccountVault {
120
120
  }
121
121
  }
122
122
  const FILE_VERSION = 1;
123
+ const AUTH_TAG_BYTES = 16;
124
+ /** Node accepts GCM tags as short as 4 bytes unless told otherwise, and a
125
+ * short tag is far easier to forge, so only the full tag this file is written
126
+ * with is read back. */
127
+ const fullAuthTag = z.string().refine((tag) => Buffer.from(tag, "base64").length === AUTH_TAG_BYTES);
123
128
  /** One encrypted file for servers without Electron. The directory sits under
124
129
  * providers/, which workspace backups never export. */
125
130
  export class FileAccountVault {
@@ -152,8 +157,8 @@ export class FileAccountVault {
152
157
  return {};
153
158
  }
154
159
  try {
155
- const envelope = z.object({ v: z.literal(FILE_VERSION), iv: z.string(), tag: z.string(), data: z.string() }).parse(JSON.parse(raw));
156
- const decipher = createDecipheriv("aes-256-gcm", this.key(), Buffer.from(envelope.iv, "base64"));
160
+ const envelope = z.object({ v: z.literal(FILE_VERSION), iv: z.string(), tag: fullAuthTag, data: z.string() }).parse(JSON.parse(raw));
161
+ const decipher = createDecipheriv("aes-256-gcm", this.key(), Buffer.from(envelope.iv, "base64"), { authTagLength: AUTH_TAG_BYTES });
157
162
  decipher.setAuthTag(Buffer.from(envelope.tag, "base64"));
158
163
  const plain = Buffer.concat([decipher.update(Buffer.from(envelope.data, "base64")), decipher.final()]).toString("utf8");
159
164
  return parseStoredAccounts(JSON.parse(plain));
@@ -24,6 +24,9 @@ export const addAccountSchema = z.object({
24
24
  home: z.string().trim().min(1).max(4096).refine(noControl, "Folder cannot contain control characters").optional(),
25
25
  /** Whose account this is (shared/personal-bot.ts): absent is the company's. */
26
26
  owner: z.enum(["company", "personal"]).optional(),
27
+ /** The account's own endpoint and model, for providers that ask (setup). */
28
+ url: z.string().trim().max(512).optional(),
29
+ model: z.string().trim().min(1).max(200).refine(noControl, "Model cannot contain control characters").optional(),
27
30
  }).strict();
28
31
  export const renameAccountSchema = z.object({ displayName }).strict();
29
32
  /** PATCH body that sets (a number) or clears (null) an account's included
@@ -102,12 +105,28 @@ function installedCli(instances, driver) {
102
105
  .find((value) => typeof value === "string" && value.trim() !== "");
103
106
  return cli ? { cli } : {};
104
107
  }
105
- export function newApiKeyAccount(cfg, provider, name, dataDir) {
108
+ /** The endpoint and model a provider's add form asks for, checked against
109
+ * the provider's own pattern; anything it does not ask for is refused. */
110
+ export function accountSetup(provider, body) {
111
+ const ask = provider.setup;
112
+ if (body.url !== undefined && !ask?.url)
113
+ throw failure(400, "This provider has a fixed address.");
114
+ if (body.model !== undefined && !ask?.model)
115
+ throw failure(400, "This provider picks its model in the engine settings.");
116
+ const url = body.url?.replace(/\/+$/, "");
117
+ if (ask?.url && !(url && new RegExp(ask.url.pattern).test(url)))
118
+ throw failure(400, `Enter the address in this form: ${ask.url.example}`);
119
+ if (ask?.model?.required && !body.model)
120
+ throw failure(400, "Enter the model or deployment name.");
121
+ return { ...(url ? { url } : {}), ...(body.model ? { model: body.model } : {}) };
122
+ }
123
+ export function newApiKeyAccount(cfg, provider, name, dataDir, setup = {}) {
106
124
  const instances = persistableInstanceConfigs(cfg);
107
125
  const instanceId = `${provider.driver}-${randomUUID()}`;
108
126
  const config = {
109
127
  ...installedCli(instances, provider.driver),
110
128
  ...provider.config,
129
+ ...setup,
111
130
  // A Claude API account still needs a directory of its own, or it would
112
131
  // share (and collide with) the default Claude login's folder.
113
132
  ...(provider.driver === "claudeAgent" ? { configDir: join(dataDir, "providers", instanceId) } : {}),
@@ -1,10 +1,11 @@
1
- export const PROVIDER_KEY_KINDS = ["anthropic", "openaiCompat", "xai", "mistral", "ollamaCloud"];
1
+ export const PROVIDER_KEY_KINDS = ["anthropic", "openaiCompat", "xai", "mistral", "ollamaCloud", "huggingface"];
2
2
  const DEFAULT_URLS = {
3
3
  anthropic: "https://api.anthropic.com",
4
4
  openaiCompat: "https://openrouter.ai/api/v1",
5
5
  xai: "https://api.x.ai/v1",
6
6
  mistral: "https://api.mistral.ai/v1",
7
7
  ollamaCloud: "https://ollama.com/v1",
8
+ huggingface: "https://huggingface.co/api",
8
9
  };
9
10
  /** OpenAI's team headers (https://developers.openai.com/api/reference/overview):
10
11
  * which organization and project a key's requests count against. Only sent
@@ -15,6 +16,27 @@ export function openAiTeamHeaders(ids) {
15
16
  ...(ids.project?.trim() ? { "OpenAI-Project": ids.project.trim() } : {}),
16
17
  };
17
18
  }
19
+ const sameAddress = (left, right) => left.trim().replace(/\/+$/, "") === right.trim().replace(/\/+$/, "");
20
+ /** Every provider address this workspace already has configured on an engine. */
21
+ export function configuredProviderUrls(cfg) {
22
+ return Object.values(cfg.instances ?? {}).flatMap((instance) => {
23
+ const url = instance?.config?.url;
24
+ return typeof url === "string" && url.trim() ? [url.trim()] : [];
25
+ });
26
+ }
27
+ /** The address a key test may go to instead of the saved one. A caller may
28
+ * name any address for a key it pastes in the same request. A saved key is
29
+ * only ever sent to an address this workspace already configured, so no
30
+ * caller can have the server post a stored key to a host of its choosing. */
31
+ export function pastedKeyTestUrl(body, configured = []) {
32
+ const draft = body && typeof body === "object" ? body : null;
33
+ const url = typeof draft?.url === "string" ? draft.url.trim() : "";
34
+ if (!url)
35
+ return undefined;
36
+ if (typeof draft?.key === "string")
37
+ return url;
38
+ return configured.some((known) => sameAddress(known, url)) ? url : undefined;
39
+ }
18
40
  const MAX_MODELS = 5;
19
41
  function isLoopback(hostname) {
20
42
  const host = hostname.replace(/^\[|\]$/g, "");
@@ -25,6 +47,8 @@ export function providerModelsUrl(provider, base) {
25
47
  const root = (base?.trim() || DEFAULT_URLS[provider]).replace(/\/+$/, "");
26
48
  if (provider === "anthropic")
27
49
  return root.endsWith("/v1") ? `${root}/models` : `${root}/v1/models`;
50
+ if (provider === "huggingface")
51
+ return `${root}/whoami-v2`;
28
52
  return `${root}/models`;
29
53
  }
30
54
  function modelIds(body) {
@@ -74,6 +98,12 @@ export async function checkProviderKey(input, fetchImpl = fetch, timeoutMs = 10_
74
98
  const body = await response.json().catch(() => null);
75
99
  if (!body || typeof body !== "object")
76
100
  return { ok: false, reason: "unexpected", status: response.status };
101
+ if (input.provider === "huggingface") {
102
+ // whoami-v2 also returns the account's name, email and orgs; none belong in this verdict.
103
+ return typeof body.name === "string"
104
+ ? { ok: true, check: "authentication", models: [] }
105
+ : { ok: false, reason: "unexpected", status: response.status };
106
+ }
77
107
  if (authenticate) {
78
108
  const data = body.data;
79
109
  if (!data || typeof data !== "object" || Array.isArray(data)
@@ -0,0 +1,88 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { writeFileAtomic } from "./atomic.js";
3
+ // The roster files (bots.json, groups.json) are rewritten whole on every
4
+ // change, so what the server loads at boot is what the next save writes
5
+ // back. Reading a damaged file as "no bots" would therefore erase the
6
+ // roster for good. A missing file is a new workspace; anything else that
7
+ // cannot be read as a list of records is a failure, answered from the copy
8
+ // kept at the last good boot or, with no such copy, by refusing to start.
9
+ export class RegistryUnreadableError extends Error {
10
+ file;
11
+ reason;
12
+ kept;
13
+ constructor(file, reason, kept) {
14
+ super(`${file} could not be read (${reason}) and there is no earlier good copy to fall back on. `
15
+ + "Atomic will not start with an empty roster, because the next save would replace this file. "
16
+ + (kept ? `The unreadable file was copied to ${kept}. ` : "")
17
+ + "Restore the file from a backup, or move it aside to start a new roster.");
18
+ this.name = "RegistryUnreadableError";
19
+ this.file = file;
20
+ this.reason = reason;
21
+ this.kept = kept;
22
+ }
23
+ }
24
+ export function lastGoodPath(file) {
25
+ return `${file}.last-good`;
26
+ }
27
+ function readRecords(file) {
28
+ let text;
29
+ try {
30
+ text = readFileSync(file, "utf8");
31
+ }
32
+ catch (error) {
33
+ const code = error.code;
34
+ if (code === "ENOENT")
35
+ return { state: "missing" };
36
+ return { state: "bad", text: null, reason: code ?? "read failed" };
37
+ }
38
+ let parsed;
39
+ try {
40
+ parsed = JSON.parse(text);
41
+ }
42
+ catch {
43
+ return { state: "bad", text, reason: "not valid JSON" };
44
+ }
45
+ if (!Array.isArray(parsed))
46
+ return { state: "bad", text, reason: "not a list" };
47
+ if (!parsed.every((entry) => entry !== null && typeof entry === "object" && !Array.isArray(entry))) {
48
+ return { state: "bad", text, reason: "an entry is not a record" };
49
+ }
50
+ return { state: "ok", text, records: parsed };
51
+ }
52
+ function keepUnreadable(file, text, now) {
53
+ if (text === null)
54
+ return null;
55
+ const kept = `${file}.unreadable-${now()}`;
56
+ try {
57
+ writeFileAtomic(kept, text, { mode: 0o600 });
58
+ return kept;
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ }
64
+ export function loadRegistry(file, options = {}) {
65
+ const warn = options.warn ?? ((message) => console.error(message));
66
+ const primary = readRecords(file);
67
+ if (primary.state === "missing")
68
+ return [];
69
+ if (primary.state === "ok") {
70
+ const good = readRecords(lastGoodPath(file));
71
+ if (good.state !== "ok" || good.text !== primary.text) {
72
+ try {
73
+ writeFileAtomic(lastGoodPath(file), primary.text, { mode: 0o600 });
74
+ }
75
+ catch (error) {
76
+ warn(`[registry] could not keep a good copy of ${file}: ${error.message}`);
77
+ }
78
+ }
79
+ return primary.records;
80
+ }
81
+ const kept = keepUnreadable(file, primary.text, options.now ?? Date.now);
82
+ const good = readRecords(lastGoodPath(file));
83
+ if (good.state !== "ok")
84
+ throw new RegistryUnreadableError(file, primary.reason, kept);
85
+ warn(`[registry] ${file} could not be read (${primary.reason}); loaded the copy kept at the last good start instead.`
86
+ + (kept ? ` The unreadable file was copied to ${kept}.` : ""));
87
+ return good.records;
88
+ }