@chibitek/chibi 0.1.179 → 0.1.182

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 (104) hide show
  1. package/dist/assets/{abnfDiagram-O67JEVCF-BFpvXOmW.js → abnfDiagram-O67JEVCF-B8rB4VYk.js} +1 -1
  2. package/dist/assets/{arc-0cz8QAA9.js → arc-COTt5eKp.js} +1 -1
  3. package/dist/assets/{architectureDiagram-NJMV4G6O-DxG1U8Tf.js → architectureDiagram-NJMV4G6O-CPejbWZ8.js} +1 -1
  4. package/dist/assets/{blockDiagram-BEXU5L5S-DdpIUUid.js → blockDiagram-BEXU5L5S-DoioDp90.js} +1 -1
  5. package/dist/assets/{c4Diagram-YGBWAQC7-CNB5U3O1.js → c4Diagram-YGBWAQC7-8PWWVdYW.js} +1 -1
  6. package/dist/assets/channel-CDw9Li4I.js +1 -0
  7. package/dist/assets/{chunk-2Q5K7J3B-DixTESOo.js → chunk-2Q5K7J3B-DxtJtts-.js} +1 -1
  8. package/dist/assets/{chunk-3FUC2YCW-9KbkQg_1.js → chunk-3FUC2YCW-D3YkXW5d.js} +2 -2
  9. package/dist/assets/{chunk-5VM5RSS4-DMNRleww.js → chunk-5VM5RSS4-CsKzmOcP.js} +1 -1
  10. package/dist/assets/{chunk-GTNCS2PH-kxGMXg9R.js → chunk-GTNCS2PH-gZEIPwuj.js} +1 -1
  11. package/dist/assets/{chunk-GWA4HPMP-B7sa9Us9.js → chunk-GWA4HPMP-Bjt2-00s.js} +1 -1
  12. package/dist/assets/{chunk-JWPE2WC7-BF65Wqy-.js → chunk-JWPE2WC7-BvUQuiRB.js} +1 -1
  13. package/dist/assets/{chunk-NETBCI7D-Du36YO_k.js → chunk-NETBCI7D-Dq0TzVqk.js} +1 -1
  14. package/dist/assets/{chunk-WEXAMYUT-BMTNPIkJ.js → chunk-WEXAMYUT-DYCSZnMz.js} +1 -1
  15. package/dist/assets/{chunk-XXDRQBXY-BqdQPY5v.js → chunk-XXDRQBXY-B_OfX3TH.js} +1 -1
  16. package/dist/assets/{classDiagram-v2-NBCMYWYE-DYSOprmY.js → classDiagram-v2-NBCMYWYE-CyGFfePO.js} +1 -1
  17. package/dist/assets/{cose-bilkent-JH36ORCC-DXKY6FnT.js → cose-bilkent-JH36ORCC-v7FbM5j-.js} +1 -1
  18. package/dist/assets/{cynefin-OW5HDTMX-DamnOWMn.js → cynefin-OW5HDTMX-CqvJgX3t.js} +1 -1
  19. package/dist/assets/{cynefinDiagram-VND7K2PF-Bb-wuGye.js → cynefinDiagram-VND7K2PF-CA2yN6Xd.js} +1 -1
  20. package/dist/assets/{dagre-6A5THRUB-DVMvGhu7.js → dagre-6A5THRUB-Zr9etAoq.js} +1 -1
  21. package/dist/assets/{diagram-22UHCM2B-BX4_NJ2M.js → diagram-22UHCM2B-DtUG2c4U.js} +1 -1
  22. package/dist/assets/{diagram-3UASUU5V-4J3gjVZn.js → diagram-3UASUU5V-D9Y-Wrhr.js} +1 -1
  23. package/dist/assets/{diagram-ATOU4E4O-Bbune_ll.js → diagram-ATOU4E4O-DkeBHA-m.js} +1 -1
  24. package/dist/assets/{diagram-CDSNMT55-EEDiwifm.js → diagram-CDSNMT55-CdGlcHWC.js} +1 -1
  25. package/dist/assets/{diagram-MLGK6HIB-D5lseSZO.js → diagram-MLGK6HIB-BeHhIQjn.js} +1 -1
  26. package/dist/assets/{diagram-MPIPVDR6-isxlwvOO.js → diagram-MPIPVDR6-AgCxokZc.js} +1 -1
  27. package/dist/assets/{ebnfDiagram-ZINNZB2B-DXhf0QK8.js → ebnfDiagram-ZINNZB2B-CqYoX9yZ.js} +1 -1
  28. package/dist/assets/{elk-276RUBZZ-rR6aJBHM.js → elk-276RUBZZ-Br_wamlb.js} +1 -1
  29. package/dist/assets/{erDiagram-OPXOYQCR-DRIV4t6Y.js → erDiagram-OPXOYQCR-YuGMoUl0.js} +1 -1
  30. package/dist/assets/{flowDiagram-KWPJA3E3-BT3z2JmZ.js → flowDiagram-KWPJA3E3-VflMWlTN.js} +1 -1
  31. package/dist/assets/{ganttDiagram-FUAMR5RP-CR0drs2s.js → ganttDiagram-FUAMR5RP-q1LvQaev.js} +1 -1
  32. package/dist/assets/{gitGraphDiagram-X574FWY7-BrjfMmlB.js → gitGraphDiagram-X574FWY7-CHRdJIvn.js} +1 -1
  33. package/dist/assets/{index-DAGHO7rw.js → index-B_gcNCKf.js} +131 -131
  34. package/dist/assets/{index-BISPpSBx.js → index-C2q5K4Lk.js} +1 -1
  35. package/dist/assets/{infoDiagram-VRGFBTTK-fIajbwUK.js → infoDiagram-VRGFBTTK-DRwVvitP.js} +1 -1
  36. package/dist/assets/{ishikawaDiagram-OU5B5YK6-DlOC_sEC.js → ishikawaDiagram-OU5B5YK6-BXZw4L0c.js} +1 -1
  37. package/dist/assets/{journeyDiagram-ZHPQQLJL-BY4NF3Iq.js → journeyDiagram-ZHPQQLJL-B7AeEVRV.js} +1 -1
  38. package/dist/assets/{kanban-definition-PNTS6WVX-CjcD7Qp-.js → kanban-definition-PNTS6WVX-CQLN4aVl.js} +1 -1
  39. package/dist/assets/{linear-D2XvBjOb.js → linear-CbYhE1pa.js} +1 -1
  40. package/dist/assets/{mermaid.core-DbXyvZNy.js → mermaid.core-D1syQdvp.js} +5 -5
  41. package/dist/assets/{mindmap-definition-NLK3R4M7-rjla1J-s.js → mindmap-definition-NLK3R4M7-B2IFEIiB.js} +1 -1
  42. package/dist/assets/{pegDiagram-GJSIUBJH-hvEPNypQ.js → pegDiagram-GJSIUBJH-DHZYilhs.js} +1 -1
  43. package/dist/assets/{pieDiagram-5QR66LMP-D-jjzmff.js → pieDiagram-5QR66LMP-DO_aJLMk.js} +1 -1
  44. package/dist/assets/{quadrantDiagram-O4NWA36T-DJsTKR54.js → quadrantDiagram-O4NWA36T-gUPrtKHH.js} +1 -1
  45. package/dist/assets/{railroadDiagram-XR7U4H2S-CgA8NcMY.js → railroadDiagram-XR7U4H2S-BBF0wp-6.js} +1 -1
  46. package/dist/assets/{requirementDiagram-PLB6GJNP-D5BkeVLA.js → requirementDiagram-PLB6GJNP-xcAp1hln.js} +1 -1
  47. package/dist/assets/{sankeyDiagram-IPEJSGJF-lEfgZleC.js → sankeyDiagram-IPEJSGJF-Dm5c9FwQ.js} +1 -1
  48. package/dist/assets/{sequenceDiagram-PO4LG4MO-iDpAQv2z.js → sequenceDiagram-PO4LG4MO-vRzb3zIA.js} +1 -1
  49. package/dist/assets/{sizeCapture-INFHLROL-hEJsAOhI.js → sizeCapture-INFHLROL-Czu8kIt2.js} +1 -1
  50. package/dist/assets/{stateDiagram-v2-GCMORJYK-CKDZvZXj.js → stateDiagram-v2-GCMORJYK-BOfJjcD1.js} +1 -1
  51. package/dist/assets/{swimlanes-2SLR337P-_dOmzve2.js → swimlanes-2SLR337P-D0ipJonR.js} +1 -1
  52. package/dist/assets/swimlanesDiagram-TC7HE7FX-BJpOJd6C.js +8 -0
  53. package/dist/assets/{timeline-definition-EJHVYXUP-9GwS2a9Y.js → timeline-definition-EJHVYXUP-TpaYbjnd.js} +1 -1
  54. package/dist/assets/{usecaseDiagram-POWQR4AR-CqJl0zf1.js → usecaseDiagram-POWQR4AR-B-jKTFl6.js} +1 -1
  55. package/dist/assets/{vennDiagram-UO4OBE2U-CGQiSSZm.js → vennDiagram-UO4OBE2U-Dy6k1yAu.js} +1 -1
  56. package/dist/assets/{wardleyDiagram-VNRHLVJA-D4KBo3Q_.js → wardleyDiagram-VNRHLVJA-DYRJUBY6.js} +1 -1
  57. package/dist/assets/{xychartDiagram-PMCCYNJV-BgvRJLNL.js → xychartDiagram-PMCCYNJV-CETDzaRA.js} +1 -1
  58. package/dist/index.html +1 -1
  59. package/dist-server/companion/src/routes.js +1 -0
  60. package/dist-server/index.js +1958 -1194
  61. package/dist-server/server/connection-cap-failover.js +243 -0
  62. package/dist-server/server/engine-tiers-view.js +2 -0
  63. package/dist-server/server/index.js +58 -57
  64. package/dist-server/server/model-levels/chibitek-rankings.js +15 -5
  65. package/dist-server/server/paw/fill.js +342 -0
  66. package/dist-server/server/paw/http.js +66 -0
  67. package/dist-server/server/paw/loader.js +19 -2
  68. package/dist-server/server/paw/service.js +61 -4
  69. package/dist-server/server/paw/templates.js +15 -2
  70. package/dist-server/server/routes/engine-tiers.js +12 -1
  71. package/dist-server/server/skill-library.js +8 -0
  72. package/dist-server/server/workspace-backup-copy.js +67 -0
  73. package/dist-server/server/workspace-backup-http.js +1 -0
  74. package/dist-server/server/workspace-backup-maintenance.js +12 -2
  75. package/dist-server/server/workspace-backup.js +32 -50
  76. package/dist-server/shared/engine-tiers.js +9 -0
  77. package/dist-server/shared/paw.js +2 -2
  78. package/package.json +1 -1
  79. package/skills/build-paw/SKILL.md +212 -0
  80. package/skills/build-paw/VENDORED.md +5 -0
  81. package/skills/build-paw/manifest.json +19 -0
  82. package/skills/build-paw/paw-skeleton/AGENTS.md +9 -0
  83. package/skills/build-paw/paw-skeleton/CLAUDE.md +9 -0
  84. package/skills/build-paw/paw-skeleton/CONTEXT.md +10 -0
  85. package/skills/build-paw/paw-skeleton/README.md +5 -0
  86. package/skills/build-paw/paw-skeleton/departments/example-team/CONTEXT.md +5 -0
  87. package/skills/build-paw/paw-skeleton/departments/example-team/skills/README.md +1 -0
  88. package/skills/build-paw/paw-skeleton/departments/example-team/templates/README.md +1 -0
  89. package/skills/build-paw/paw-skeleton/departments/example-team/voice.md +3 -0
  90. package/skills/build-paw/paw-skeleton/me/CHANGELOG.md +7 -0
  91. package/skills/build-paw/paw-skeleton/me/about-me.md +7 -0
  92. package/skills/build-paw/paw-skeleton/me/personal/README.md +1 -0
  93. package/skills/build-paw/paw-skeleton/me/projects/.gitkeep +1 -0
  94. package/skills/build-paw/paw-skeleton/org/brand/voice.md +5 -0
  95. package/skills/build-paw/paw-skeleton/org/company.md +6 -0
  96. package/skills/build-paw/paw-skeleton/org/glossary.md +6 -0
  97. package/skills/build-paw/paw-skeleton/org/marketing/positioning.md +3 -0
  98. package/skills/build-paw/paw-skeleton/org/policies/ai-use.md +5 -0
  99. package/skills/build-paw/paw-skeleton/org/policies/engineering.md +5 -0
  100. package/skills/build-paw/paw-skeleton/org/policies/secrets.md +5 -0
  101. package/skills/build-paw/paw-skeleton/org/tools.md +3 -0
  102. package/skills/build-paw/paw-skeleton/paw.yaml +45 -0
  103. package/dist/assets/channel-DktfdxuU.js +0 -1
  104. package/dist/assets/swimlanesDiagram-TC7HE7FX-BROCOsEt.js +0 -8
@@ -0,0 +1,243 @@
1
+ import { DEFAULT_CONNECTION_RUN_OUT, isConnectionRunOutPolicy, } from "../shared/engine-tiers.js";
2
+ import { redactSecretsInText } from "../shared/redact.js";
3
+ import { MAX_ENGINES_PER_TURN, restingLine } from "./engine-failover.js";
4
+ import { computeBackoff, interruptibleDelay, RETRY_MAX_RETRIES } from "./drivers/retry.js";
5
+ export { DEFAULT_CONNECTION_RUN_OUT, interruptibleDelay };
6
+ /** Matches the driver retry budget so harness policy and CLI retries agree. */
7
+ export const TRANSIENT_RETRY_LIMIT = RETRY_MAX_RETRIES;
8
+ export function parseConnectionRunOut(value) {
9
+ return isConnectionRunOutPolicy(value) ? value : DEFAULT_CONNECTION_RUN_OUT;
10
+ }
11
+ /** config.json engineTiers.connectionRunOut: ask-before-paid when absent. */
12
+ export function connectionRunOutPolicy(engineTiers) {
13
+ const record = engineTiers && typeof engineTiers === "object" && !Array.isArray(engineTiers)
14
+ ? engineTiers : {};
15
+ return parseConnectionRunOut(record.connectionRunOut);
16
+ }
17
+ export function sameConnectionScope(a, b) {
18
+ return a.ownerId === b.ownerId && a.tenantId === b.tenantId;
19
+ }
20
+ /** Same provider on the same named account (or on none): not a way out. */
21
+ export function sameAccountTwin(a, b) {
22
+ return a.id !== b.id && a.driverKind === b.driverKind && a.accountKey === b.accountKey;
23
+ }
24
+ export function eligibleConnections(connections, scope) {
25
+ return connections.filter((connection) => connection.enabled && connection.approved && connection.supported
26
+ && connection.modelCompatible && sameConnectionScope(connection, scope));
27
+ }
28
+ /** Stay on the thread's connection while it is still eligible; otherwise the first in order. */
29
+ export function pickStickyConnection(connections, scope, threadConnectionId) {
30
+ const usable = eligibleConnections(connections, scope);
31
+ if (threadConnectionId) {
32
+ const sticky = usable.find((connection) => connection.id === threadConnectionId);
33
+ if (sticky)
34
+ return sticky;
35
+ }
36
+ return usable[0];
37
+ }
38
+ export function nextCompatibleConnection(current, connections) {
39
+ return eligibleConnections(connections, current).find((connection) => connection.id !== current.id && !sameAccountTwin(connection, current));
40
+ }
41
+ export function isGenuineAllowanceExhaustion(kind) {
42
+ return kind === "usage_limited";
43
+ }
44
+ export function isTransientThrottle(kind) {
45
+ return kind === "rate_limited";
46
+ }
47
+ /** Delay before harness retry `attempt` (0-based), or undefined once the bound is reached. */
48
+ export function nextTransientBackoff(attempt, random = Math.random) {
49
+ if (!Number.isInteger(attempt) || attempt < 0 || attempt >= TRANSIENT_RETRY_LIMIT)
50
+ return undefined;
51
+ return computeBackoff(attempt, random);
52
+ }
53
+ /** Report the provider's own counts, or UNKNOWN. Never invent a missing figure. */
54
+ export function usageReport(usage) {
55
+ if (!usage || !Number.isFinite(usage.input) || !Number.isFinite(usage.output))
56
+ return { status: "unknown" };
57
+ if (usage.cachedInput !== undefined && usage.cachedInput !== null && !Number.isFinite(usage.cachedInput))
58
+ return { status: "unknown" };
59
+ return {
60
+ status: "accurate",
61
+ input: usage.input,
62
+ output: usage.output,
63
+ ...(typeof usage.cachedInput === "number" ? { cachedInput: usage.cachedInput } : {}),
64
+ };
65
+ }
66
+ export function connectionSwitchNotice(input) {
67
+ const when = input.resetAt !== undefined ? ` until ${input.formatTime(input.resetAt)}` : "";
68
+ return `${input.fromLabel} is used up${when}. Running on ${input.toLabel}.`;
69
+ }
70
+ export function paidFallbackAskLine(input) {
71
+ const when = input.resetAt !== undefined ? ` until ${input.formatTime(input.resetAt)}` : "";
72
+ return `${input.fromLabel} is used up${when}. This turn stopped before using a pay-per-use API key, so nothing was charged. Allow pay-per-use (Keep going) or wait until a subscription is back.`;
73
+ }
74
+ export function askBeforeSwitchLine(input) {
75
+ const when = input.resetAt !== undefined ? ` until ${input.formatTime(input.resetAt)}` : "";
76
+ return `${input.fromLabel} is used up${when}. This turn stopped before switching to ${input.toLabel}.`;
77
+ }
78
+ export function transientThrottleStopLine(label) {
79
+ return `${label} is briefly rate-limited, so this turn stayed on it and stopped instead of switching connections.`;
80
+ }
81
+ export function unsupportedConnectionLine(label) {
82
+ return `${label} cannot be used: Atomic has no supported transport or stored credentials for that connection. This turn stopped.`;
83
+ }
84
+ export function exhaustedConnectionsLine(label, resetAt, formatTime) {
85
+ const when = resetAt !== undefined ? ` until ${formatTime(resetAt)}` : "";
86
+ return `${label} is used up${when}, and no other approved connection can serve this thread, so this turn stopped.`;
87
+ }
88
+ export function connectionCapAudit(entry) {
89
+ return {
90
+ threadId: entry.threadId,
91
+ action: entry.action,
92
+ ...(entry.fromId ? { fromId: entry.fromId } : {}),
93
+ ...(entry.toId ? { toId: entry.toId } : {}),
94
+ ...(entry.detail ? { detail: redactSecretsInText(entry.detail) } : {}),
95
+ };
96
+ }
97
+ export function decideConnectionCapFailover(input) {
98
+ if (input.cancelled)
99
+ return { action: "stay-stop", line: transientThrottleStopLine(input.current.label) };
100
+ if (isTransientThrottle(input.failureKind)) {
101
+ const attempt = input.transientAttempt ?? 0;
102
+ const delayMs = nextTransientBackoff(attempt, () => 0.5);
103
+ if (delayMs !== undefined)
104
+ return { action: "backoff", delayMs, attempt };
105
+ return { action: "stay-stop", line: transientThrottleStopLine(input.current.label) };
106
+ }
107
+ if (!isGenuineAllowanceExhaustion(input.failureKind))
108
+ return { action: "passthrough" };
109
+ const remaining = input.connections.filter((connection) => connection.id !== input.current.id && !sameAccountTwin(connection, input.current)
110
+ && sameConnectionScope(connection, input.current) && connection.modelCompatible);
111
+ const next = nextCompatibleConnection(input.current, input.connections);
112
+ if (!next) {
113
+ const blocked = remaining.find((connection) => !connection.supported);
114
+ if (blocked)
115
+ return { action: "unsupported", line: unsupportedConnectionLine(blocked.label) };
116
+ return { action: "stop", line: exhaustedConnectionsLine(input.current.label, input.resetAt, input.formatTime) };
117
+ }
118
+ if (input.policy === "ask") {
119
+ return { action: "ask", line: askBeforeSwitchLine({ fromLabel: input.current.label, toLabel: next.label, resetAt: input.resetAt, formatTime: input.formatTime }) };
120
+ }
121
+ if (next.billing === "payPerUse" && input.policy === "ask-before-paid" && !input.paidApproved) {
122
+ return { action: "ask", line: paidFallbackAskLine({ fromLabel: input.current.label, resetAt: input.resetAt, formatTime: input.formatTime }) };
123
+ }
124
+ return {
125
+ action: "switch",
126
+ notice: connectionSwitchNotice({ fromLabel: input.current.label, toLabel: next.label, resetAt: input.resetAt, formatTime: input.formatTime }),
127
+ persistThreadDefault: false,
128
+ next,
129
+ };
130
+ }
131
+ /** Production hook used by failoverPick: keep existing stop lines, and gate cap switches. */
132
+ export function finalizeConnectionCapPick(input) {
133
+ if (input.failureKind === "rate_limited") {
134
+ return { line: transientThrottleStopLine(input.currentLabel), category: "failover_exhausted" };
135
+ }
136
+ const { choice } = input;
137
+ if (!choice && input.fallback)
138
+ return { line: input.subscriptionLine ?? "No engine is available for this turn, so it stopped." };
139
+ if (!choice && input.failureKind === "provider_error")
140
+ return { passthrough: true };
141
+ if (!choice) {
142
+ if (input.pausedUntil !== undefined && input.skipped.some((skip) => skip.reason === "paused")) {
143
+ return { line: input.payPerUsePausedLine(input.pausedUntil) };
144
+ }
145
+ const waiting = decideNewTurnPlacement({
146
+ policy: input.policy, paidApproved: input.paidApproved,
147
+ skippedPausedKey: input.skipped.some((skip) => skip.reason === "paused"),
148
+ currentLabel: input.currentLabel, resetAt: input.resetAt, formatTime: input.formatTime,
149
+ });
150
+ if (waiting.action === "ask") {
151
+ input.announceWaiting?.();
152
+ return { line: waiting.line, category: "failover_exhausted" };
153
+ }
154
+ const resting = input.skipped.filter((skip) => skip.reason === "resting" || skip.reason === "tried").map((skip) => skip.instanceId);
155
+ const named = input.restingNamed([input.failedInstanceId, ...input.alreadyTried, ...resting]);
156
+ return {
157
+ line: restingLine(named, input.formatTime, input.cannotDrive, { capped: input.triedCount >= MAX_ENGINES_PER_TURN }),
158
+ category: named.some((engine) => engine.needsSignIn || engine.keyExpired) ? "account" : "failover_exhausted",
159
+ };
160
+ }
161
+ if (input.failureKind === "usage_limited") {
162
+ const gated = gateUsageLimitedChoice({
163
+ policy: input.policy,
164
+ paidApproved: input.paidApproved,
165
+ local: input.local,
166
+ nextBand: input.nextBand ?? choice.band,
167
+ currentLabel: input.currentLabel,
168
+ nextLabel: input.nextLabel ?? choice.selection.instanceId,
169
+ resetAt: input.resetAt,
170
+ formatTime: input.formatTime,
171
+ });
172
+ if (gated) {
173
+ input.announceWaiting?.();
174
+ return gated;
175
+ }
176
+ }
177
+ input.bookChoice();
178
+ return { choice };
179
+ }
180
+ export function gateUsageLimitedChoice(input) {
181
+ const paid = input.nextBand === "key" && !input.local;
182
+ if (input.policy === "ask") {
183
+ return { line: askBeforeSwitchLine({ fromLabel: input.currentLabel, toLabel: input.nextLabel, resetAt: input.resetAt, formatTime: input.formatTime }), category: "failover_exhausted" };
184
+ }
185
+ if (paid && input.policy === "ask-before-paid" && !input.paidApproved) {
186
+ return { line: paidFallbackAskLine({ fromLabel: input.currentLabel, resetAt: input.resetAt, formatTime: input.formatTime }), category: "failover_exhausted" };
187
+ }
188
+ return undefined;
189
+ }
190
+ /** Stored Keep going (`keptGoingAt`) or an explicit keep-going policy. A pause always wins. */
191
+ export function paidKeysApproved(input) {
192
+ if (input.pausedUntil !== undefined)
193
+ return false;
194
+ return input.policy === "keep-going" || input.paidApproved;
195
+ }
196
+ /** Close the key band so resolveLadder never selects a pay-per-use engine. */
197
+ export function pauseKeyBandForRunOut(input) {
198
+ if (input.subscriptionsOnly || input.pausedUntil !== undefined)
199
+ return true;
200
+ if (input.localUntil !== undefined)
201
+ return false;
202
+ if (input.sweep)
203
+ return !input.paidApproved;
204
+ return !paidKeysApproved(input);
205
+ }
206
+ /** New-turn, retry, and resume: stop before constructing a paid driver unless stored approval allows it. */
207
+ export function decideNewTurnPlacement(input) {
208
+ if (input.cancelled) {
209
+ return { action: "ask", line: paidFallbackAskLine({ fromLabel: input.currentLabel, resetAt: input.resetAt, formatTime: input.formatTime }), announceWaiting: false };
210
+ }
211
+ if (input.band === "subscription" || input.band === "free" || (input.band === "key" && input.local)) {
212
+ return { action: "place" };
213
+ }
214
+ if (!input.band && input.pausedUntil !== undefined && input.skippedPausedKey) {
215
+ return { action: "paused", until: input.pausedUntil };
216
+ }
217
+ const wouldUsePaid = input.band === "key" || Boolean(!input.band && input.skippedPausedKey);
218
+ if (wouldUsePaid && !paidKeysApproved(input)) {
219
+ return { action: "ask", line: paidFallbackAskLine({ fromLabel: input.currentLabel, resetAt: input.resetAt, formatTime: input.formatTime }), announceWaiting: true };
220
+ }
221
+ return input.band ? { action: "place" } : { action: "none" };
222
+ }
223
+ /** Production hook used by placedTurn: throw before booking an unapproved paid driver. */
224
+ export function finalizeNewTurnPlacement(input) {
225
+ const decision = decideNewTurnPlacement({
226
+ policy: input.policy, paidApproved: input.paidApproved, local: input.local, band: input.choice?.band,
227
+ skippedPausedKey: input.skipped.some((skip) => skip.reason === "paused"),
228
+ pausedUntil: input.pausedUntil, currentLabel: input.currentLabel, resetAt: input.resetAt,
229
+ formatTime: input.formatTime, cancelled: input.cancelled,
230
+ });
231
+ if (decision.action === "ask") {
232
+ if (decision.announceWaiting)
233
+ input.announceWaiting();
234
+ throw Object.assign(new Error(decision.line), { status: 409, code: "pay_per_use_ask", category: "failover_exhausted" });
235
+ }
236
+ if (decision.action === "paused") {
237
+ throw Object.assign(new Error(input.pausedLine(decision.until)), { status: 409, code: "pay_per_use_paused", category: "failover_exhausted" });
238
+ }
239
+ if (decision.action !== "place" || !input.choice)
240
+ return undefined;
241
+ input.book();
242
+ return { selection: input.choice.selection, persist: input.persist };
243
+ }
@@ -2,6 +2,7 @@
2
2
  // tier's ladder with health and rest, the installed engines, rest history,
3
3
  // pay-per-use episodes and the "Include free models in Auto" setting.
4
4
  import { BOT_TIERS, DEFAULT_LADDERS, DEFAULT_TIER_CLASSES } from "../shared/engine-tiers.js";
5
+ import { connectionRunOutPolicy } from "./connection-cap-failover.js";
5
6
  import { engineHealth, engineTierClasses, engineTierLadders, engineTiersIncludeFree, keyBased, matchesEngine } from "./engine-tiers.js";
6
7
  import { perTokenModel } from "./harness-import/engine-policy.js";
7
8
  const DRIVER_NAMES = {
@@ -42,6 +43,7 @@ export function engineTiersView(engineTiers, candidates, rests, defaults = DEFAU
42
43
  ladder: ladders[tier].map(rung), custom: JSON.stringify(ladders[tier]) !== JSON.stringify(defaults[tier]) })),
43
44
  engines,
44
45
  ...(engineTiersIncludeFree(engineTiers) ? { includeFree: true } : {}),
46
+ connectionRunOut: connectionRunOutPolicy(engineTiers),
45
47
  ...(rests?.payPerUse ? { payPerUse: rests.payPerUse() } : {}),
46
48
  ...(rests ? { restHistory: rests.history().map((record) => ({ ...record,
47
49
  label: record.scope ? `${label(record.instanceId)} (${record.scope})` : label(record.instanceId) })) } : {}),
@@ -1,3 +1,4 @@
1
+ import "../electron/socket-qos.mjs";
1
2
  import { createMessageFileRoutes } from "./routes/message-file.js";
2
3
  import { SharedDeliverables, createSharedDeliverablesRoutes, sharedDeliverableAccess } from "./shared-deliverables.js";
3
4
  import { connectionCredentialServer } from "./connection-credential.js";
@@ -214,10 +215,11 @@ import { installReticle, reticleInstallState } from "./reticle.js";
214
215
  import { RTK_LAUNCHER_PATH, rtkLocalStatus } from "./rtk.js";
215
216
  import { withoutRtkLauncher } from "./rtk-rewrite.js";
216
217
  import { loadAddonSkillLibraries } from "./skill-addons.js";
217
- import { browserSkillCapabilities, loadBundledSkills, loadUserSkills, mergeSkills, renderSkillInstructions, selectBundledSkills } from "./skill-library.js";
218
+ import { browserSkillCapabilities, loadBundledSkills, loadUserSkills, mergeSkills, renderSkillInstructions, selectBundledSkills, withBuildPawSkill } from "./skill-library.js";
218
219
  import { AboutMeSync, nexusAboutMe } from "./about-me-sync.js";
219
220
  import { icmAboutMeSummary, icmEnabled, icmStatus, icmSystemPrompt, resolveIcmPath } from "./icm-context.js";
220
221
  import { PawService } from "./paw/service.js";
222
+ import { interviewCommitResponse, interviewPlanResponse, shortInterviewAnswers, shouldMountBuildPaw } from "./paw/http.js";
221
223
  import { chibiFilingPrompt, parseFiledTaskId } from "./paw/change-requests.js";
222
224
  import { installedPlaybookInstructions } from "./installed-playbooks.js";
223
225
  import { createBotPackageExport } from "./package-export.js";
@@ -319,6 +321,7 @@ import { createBoardRoutes } from "./routes/board.js";
319
321
  import { readBoardFromNexus } from "./board/nexus-board.js";
320
322
  import { LocalModelInventory, localModePlacement, machineMemory } from "./local-models-mode.js";
321
323
  import { eventBase, restTime, FailoverGate, MAX_ENGINES_PER_TURN, continuationNote, restingLine, restingOnRoute, sameRoute } from "./engine-failover.js";
324
+ import { connectionRunOutPolicy, finalizeConnectionCapPick, finalizeNewTurnPlacement, pauseKeyBandForRunOut } from "./connection-cap-failover.js";
322
325
  import { enterSessionFallback, onSessionFallback, ownOrFallback, sessionFallbackSpentLine, withoutSubscription } from "./session-fallback.js";
323
326
  import { TURN_ERROR_CATEGORIES } from "../shared/runtime-events.js";
324
327
  import { EngineProbes, PROBE_PROMPT, isProbeThread, probeThreadId } from "./engine-probe.js";
@@ -2969,7 +2972,7 @@ function personalPlacement(input) {
2969
2972
  // Own accounts and opted-in local compute come first. Company compute is
2970
2973
  // separate from personal connections; the final dispatch gate confirms Mezcal.
2971
2974
  const companyContext = {
2972
- ...context, keyBandPaused: payPerUse.pausedUntil() !== undefined,
2975
+ ...context, keyBandPaused: keyBandPausedFor(projected.threadId),
2973
2976
  accept: (candidate, model) => tried.has(candidate.instanceId) ? "tried"
2974
2977
  : ownerAllows(profile, ownerCheck(candidate, model), personalLocalAllowed()) ? undefined : "owner",
2975
2978
  refuse: (candidate) => instanceOwner(candidate.instanceId) !== "company" ? "owner" : engineTierRefusal(projected)?.(candidate),
@@ -3094,7 +3097,7 @@ function ladderTurnEngineChoice(profile, projected, threadId, needs, runOn, subs
3094
3097
  const { ladder } = plan;
3095
3098
  const computer = turnComputer(projected, threadId, runOn);
3096
3099
  const context = { candidates, needsDelegation: needsDelegation(tier, profile), computer, refuse: engineTierRefusal(projected), resting: engineResting,
3097
- keyBandPaused: subscriptionsOnly || payPerUse.pausedUntil() !== undefined, includeFree: engineTiersIncludeFree(cfg.engineTiers), clientData: handlesClientData(profile) };
3100
+ keyBandPaused: subscriptionsOnly || keyBandPausedFor(threadId), includeFree: engineTiersIncludeFree(cfg.engineTiers), clientData: handlesClientData(profile) };
3098
3101
  const local = (resolution) => localModeTurn(resolution, { tier, context, needs, prefer: [projected.modelSelection.instanceId] });
3099
3102
  const wider = (tried, modelClass) => resolveFailover({
3100
3103
  ladder, classLadder: (cls) => classLadder(classedModels(), cls), failed: projected.modelSelection, context, tried,
@@ -3253,9 +3256,8 @@ function dictationSubscription() {
3253
3256
  /** The key band is closed to a sweep unless the person chose "Keep going"
3254
3257
  * (or local mode, which turns a key choice into a local model). */
3255
3258
  function keyBandPausedFor(threadId) {
3256
- if (payPerUse.pausedUntil() !== undefined)
3257
- return true;
3258
- return isSweepTurn(threadId) && payPerUse.current()?.keptGoingAt === undefined && payPerUse.localUntil() === undefined;
3259
+ return pauseKeyBandForRunOut({ policy: connectionRunOutPolicy(cfg.engineTiers), paidApproved: Boolean(payPerUse.current()?.keptGoingAt),
3260
+ pausedUntil: payPerUse.pausedUntil(), localUntil: payPerUse.localUntil(), sweep: isSweepTurn(threadId) });
3259
3261
  }
3260
3262
  /** The sweep turn's engine, or null when nothing it may use is free. `note`
3261
3263
  * books the choice for pay-per-use; the sweeper's own probe does not. */
@@ -3300,23 +3302,20 @@ function sweepEngineChoice(botId, threadId, note, runOn) {
3300
3302
  return { selection: placed.choice.selection, persist: true };
3301
3303
  }
3302
3304
  /** A turn start's ladder walk, as startTurn uses it: noted for pay-per-use,
3303
- * and refused with one plain line when pay-per-use is paused and nothing
3304
- * else is free. */
3305
+ * refused before an unapproved paid key, or when pay-per-use is paused. */
3305
3306
  function placedTurn(resolution, persist) {
3306
- notePayPerUse(resolution);
3307
- const { choice } = resolution;
3308
- if (choice)
3309
- return { selection: choice.selection, persist };
3310
- const paused = payPerUse.pausedUntil();
3311
- if (paused !== undefined && resolution.skipped.some((skip) => skip.reason === "paused")) {
3312
- throw Object.assign(new Error(payPerUsePausedLine(paused)), { status: 409, code: "pay_per_use_paused", category: "failover_exhausted" });
3313
- }
3314
- return undefined;
3307
+ return finalizeNewTurnPlacement({
3308
+ policy: connectionRunOutPolicy(cfg.engineTiers), paidApproved: Boolean(payPerUse.current()?.keptGoingAt),
3309
+ local: resolution.local, choice: resolution.choice, skipped: resolution.skipped, pausedUntil: payPerUse.pausedUntil(),
3310
+ currentLabel: "A subscription", formatTime: restTime, persist, pausedLine: payPerUsePausedLine,
3311
+ announceWaiting: () => notePayPerUse({ skipped: resolution.skipped, local: true, choice: { band: "key", selection: { instanceId: "", model: "" }, candidate: { instanceId: "" }, step: 0 } }),
3312
+ book: () => notePayPerUse(resolution),
3313
+ });
3315
3314
  }
3316
3315
  // ── pay-per-use (docs/chibitek/engine-tiers.md, "Pay-per-use notice") ────
3317
- // The one thing about engines and billing the person hears of: a turn placed
3318
- // on an API key because every subscription in its class is resting, signed
3319
- // out or unavailable opens an episode, announced once to the app; a turn
3316
+ // The one thing about engines and billing the person hears of: a paid key
3317
+ // is used only after stored approval when every subscription is resting,
3318
+ // signed out or unavailable. That opens an episode, announced once; a turn
3320
3319
  // placed on a subscription ends it. Ollama Cloud is a subscription.
3321
3320
  const payPerUse = new PayPerUseEpisodes(DATA_DIR, (episode) => broadcast({ kind: "engines.pay_per_use", episode }, { adminOnly: true }));
3322
3321
  const SUBSCRIPTION_OUT = new Set(["resting", "signed-out", "unavailable", "tried"]);
@@ -3342,7 +3341,7 @@ function notePayPerUse(resolution) {
3342
3341
  // a turn Atomic would place on an API key runs on a model this machine
3343
3342
  // serves, chosen for the job (server/local-models-mode.ts). It applies to
3344
3343
  // every tier: it is the person's choice, not a silent stand-in. With no
3345
- // suitable local model the turn keeps its key, as it would have anyway.
3344
+ // suitable local model the turn stops unless stored approval allows the key.
3346
3345
  const localModels = new LocalModelInventory();
3347
3346
  /** The turn carries images, so a local model must see them. */
3348
3347
  const turnHasImages = (message) => Boolean(message?.attachments?.some((attachment) => attachment.kind === "image"));
@@ -3642,7 +3641,7 @@ function engineFailover(turn, completion) {
3642
3641
  ...(failure.permanent ? { permanent: true } : {}), ...(scope ? { scope } : {}), ...(ran?.model ? { model: ran.model } : {}),
3643
3642
  ...(failure.kind === "auth_failed" && failedCandidate ? { reportedSignedIn: failedCandidate.snapshot.state === "available" && failedCandidate.snapshot.authenticated === true } : {}) });
3644
3643
  // Unknown failures rest only when the turn moves; otherwise preserve their report.
3645
- const rest = failure.kind === "provider_error" ? undefined : restFailed();
3644
+ const rest = failure.kind === "provider_error" || failure.kind === "rate_limited" ? undefined : restFailed();
3646
3645
  const label = (instanceId) => candidates.find((candidate) => candidate.instanceId === instanceId)?.displayName ?? instanceId;
3647
3646
  // The one plain line, never the provider's own words: which account needs
3648
3647
  // the person and where to fix it, or that every engine is resting.
@@ -3698,7 +3697,7 @@ function engineFailover(turn, completion) {
3698
3697
  threadId: turn.threadId,
3699
3698
  userMessage: record.userMessage,
3700
3699
  excludeMessageIds: [...(record.opts.excludeMessageIds ?? []), ...said.map((message) => message.id)],
3701
- failover: { selection: choice.selection, persist: record.persist, tried: [...tried], attempt, originalText: record.text },
3700
+ failover: { selection: choice.selection, persist: record.persist && failure.kind !== "usage_limited", tried: [...tried], attempt, originalText: record.text },
3702
3701
  });
3703
3702
  if (directTurnGenerationByThread.get(turn.threadId) === turn.generation) {
3704
3703
  // Refused before it claimed the thread (a spend cap, settings being
@@ -3885,27 +3884,23 @@ function failoverPick(turn, profile, projected, candidates, failedCandidate, res
3885
3884
  context: { candidates, needsDelegation: needsDelegation(tier, profile), computer, refuse: engineTierRefusal(projected), resting } })
3886
3885
  : { ...resolution, local: false };
3887
3886
  const choice = placed.choice && placed.local ? { ...placed.choice, modelClass: "Añejo" } : placed.choice;
3888
- if (!choice && fallback)
3889
- return { line: subscriptionMove.line };
3890
- if (!choice && turn.failure?.kind === "provider_error")
3891
- return { passthrough: true };
3892
- if (!choice) {
3893
- const paused = payPerUse.pausedUntil();
3894
- if (paused !== undefined && resolution.skipped.some((skip) => skip.reason === "paused"))
3895
- return { line: payPerUsePausedLine(paused) };
3896
- const resting = resolution.skipped.filter((skip) => skip.reason === "resting" || skip.reason === "tried").map((skip) => skip.instanceId);
3897
- const named = restingNamed([turn.instanceId, ...attempt.tried, ...resting]);
3898
- return {
3899
- line: restingLine(named, restTime, cannotDriveNamed(candidates, resolution.skipped.map((skip) => skip.instanceId), computer), { capped: tried.size >= MAX_ENGINES_PER_TURN }),
3900
- category: named.some((engine) => engine.needsSignIn || engine.keyExpired) ? "account" : "failover_exhausted",
3901
- };
3902
- }
3903
- if (subscriptionMove || fallback) { /* subscriptions only: no pay-per-use episode */ }
3904
- else if (personalMove)
3905
- notePersonalPayPerUse(personalMove);
3906
- else
3907
- notePayPerUse({ choice, skipped: resolution.skipped, local: placed.local });
3908
- return { choice };
3887
+ return finalizeConnectionCapPick({
3888
+ choice, fallback, subscriptionLine: subscriptionMove?.line, failureKind: turn.failure?.kind,
3889
+ pausedUntil: payPerUse.pausedUntil(), skipped: resolution.skipped, payPerUsePausedLine, restingNamed,
3890
+ failedInstanceId: turn.instanceId, alreadyTried: attempt.tried, triedCount: tried.size,
3891
+ cannotDrive: cannotDriveNamed(candidates, resolution.skipped.map((skip) => skip.instanceId), computer),
3892
+ policy: connectionRunOutPolicy(cfg.engineTiers), paidApproved: Boolean(payPerUse.current()?.keptGoingAt),
3893
+ local: Boolean(placed.local), currentLabel: engineLabel(candidates, attempt.selection),
3894
+ nextLabel: choice ? engineLabel(candidates, choice.selection) : undefined,
3895
+ nextBand: choice && "band" in choice ? choice.band : undefined, resetAt: turn.failure?.resetAt, formatTime: restTime,
3896
+ announceWaiting: () => notePayPerUse({ skipped: resolution.skipped, local: true, choice: { band: "key", selection: { instanceId: "", model: "" }, candidate: { instanceId: "" }, step: 0 } }),
3897
+ bookChoice: () => { if (!(subscriptionMove || fallback)) {
3898
+ if (personalMove)
3899
+ notePersonalPayPerUse(personalMove);
3900
+ else
3901
+ notePayPerUse({ choice: choice, skipped: resolution.skipped, local: placed.local });
3902
+ } },
3903
+ });
3909
3904
  }
3910
3905
  /** Requests (their user message ids) already re-run once after a check. */
3911
3906
  const jevRecheckedRequests = new Set();
@@ -10685,6 +10680,8 @@ async function startTurn(botId, text, opts) {
10685
10680
  ...browserSkillCapabilities({ browserMounted: true, tier: botTier(liveBot ?? bot) }),
10686
10681
  ], turnSkills);
10687
10682
  }
10683
+ if (shouldMountBuildPaw({ runOn: opts?.runOn, personalBot: isPersonalBot(liveBot ?? bot), freeBilling: accountProvider(providerConfigs()[instance.instanceId]?.account)?.billing === "free", needsInterview: paw.needsInterview() }))
10684
+ selectedSkills = withBuildPawSkill(selectedSkills, turnSkills, true);
10688
10685
  const skillInstructions = renderSkillInstructions(selectedSkills, {
10689
10686
  includeRoot: worksInWorkspace && opts?.runOn !== "cloud",
10690
10687
  });
@@ -12635,7 +12632,7 @@ failover) {
12635
12632
  { id: "memory", label: "Memory", text: roomMemory ? `\n${roomMemory.trim()}` : "" },
12636
12633
  { id: "nexus", label: "Nexus memory", text: roomNexusContext },
12637
12634
  { id: "skills", label: "Skills index", text: workspace ? skillsSystemPrompt(bot.id) : "" },
12638
- { id: "skill-instructions", label: "Skill instructions", text: renderSkillInstructions(selectedSkills, { includeRoot: Boolean(workspace) }) },
12635
+ { id: "skill-instructions", label: "Skill instructions", text: renderSkillInstructions(shouldMountBuildPaw({ personalBot: isPersonalBot(bot), freeBilling: accountProvider(providerConfigs()[instance.instanceId]?.account)?.billing === "free", needsInterview: paw.needsInterview() }) ? withBuildPawSkill(selectedSkills, skills, true) : selectedSkills, { includeRoot: Boolean(workspace) }) },
12639
12636
  { id: "playbooks", label: "Playbooks", text: installedPlaybookInstructions(text, bot.playbooks) },
12640
12637
  { id: "addons", label: "Add-ons", text: roomAddons.instructions },
12641
12638
  ]);
@@ -15141,9 +15138,9 @@ const workspaceBackupRoutes = createWorkspaceBackupRoutes({
15141
15138
  resume: () => { routines?.start(); primaryBot.start(); calendarCalls?.start(); watchdog.start(); },
15142
15139
  flush: async () => {
15143
15140
  await Promise.all([flushAllProfileHistory(), flushAllMemoryJournals(), flushUsageLedger(DATA_DIR), flushDecisionLog(DATA_DIR), flushAdminActivity(DATA_DIR)]);
15144
- // With writers gated and work idle, release our WAL connection for the
15145
- // consistent snapshot. Store reopens it lazily after maintenance.
15146
- closeMessageDb();
15141
+ // Export uses SQLite online backup while writers keep their connection.
15142
+ if (keepLocked)
15143
+ closeMessageDb();
15147
15144
  },
15148
15145
  }, keepLocked),
15149
15146
  });
@@ -24246,20 +24243,25 @@ const handleRequest = async (req, res) => {
24246
24243
  if (path === "/api/paw" || path.startsWith("/api/paw/")) {
24247
24244
  if (auth.kind === "session" && !auth.scopes.includes("admin"))
24248
24245
  return json(res, 403, { error: "Only the owner of this computer can change PAW" });
24249
- if (method === "GET" && path === "/api/paw") {
24246
+ if (method === "GET" && path === "/api/paw")
24250
24247
  return json(res, 200, { ...paw.status(), aboutMe: paw.aboutMe(), changes: paw.store.list().slice(0, 20).map(({ before: _b, after: _a, ...rest }) => rest) });
24251
- }
24252
24248
  if (method === "PUT" && path === "/api/paw/interview") {
24253
24249
  const body = await readBody(req);
24254
- const field = (key, max) => (typeof body?.[key] === "string" ? body[key].slice(0, max) : undefined);
24255
- const status = await paw.interview({
24256
- name: field("name", 80), role: field("role", 120), department: field("department", 80), company: field("company", 120),
24257
- goals: field("goals", 2_000), workingStyle: field("workingStyle", 2_000),
24258
- }, { chibitek: body?.chibitek === true });
24250
+ const status = await paw.interview(shortInterviewAnswers(body), { chibitek: body?.chibitek === true });
24259
24251
  aboutMe.sync(0);
24260
24252
  broadcast({ kind: "config", ...configStatus() });
24261
24253
  return json(res, 200, { ...status, aboutMe: paw.aboutMe() });
24262
24254
  }
24255
+ if (method === "POST" && path === "/api/paw/interview/plan")
24256
+ return json(res, 200, interviewPlanResponse(paw, await readBody(req, 64_000)));
24257
+ if (method === "POST" && path === "/api/paw/interview/commit") {
24258
+ const committed = await interviewCommitResponse(paw, await readBody(req, 64_000));
24259
+ if (committed.written.length) {
24260
+ aboutMe.sync(0);
24261
+ broadcast({ kind: "config", ...configStatus() });
24262
+ }
24263
+ return json(res, 200, { ...committed.status, aboutMe: paw.aboutMe(), plan: committed.plan, written: committed.written, rejected: committed.rejected, changelog: committed.changelog });
24264
+ }
24263
24265
  if (method === "PUT" && path === "/api/paw/about-me") {
24264
24266
  const body = await readBody(req);
24265
24267
  if (typeof body?.text !== "string")
@@ -24275,9 +24277,8 @@ const handleRequest = async (req, res) => {
24275
24277
  return await aboutMe.resolve(String(side)) ? json(res, 200, { ok: true }) : json(res, 409, { error: "Nothing to choose: About me already agrees." });
24276
24278
  }
24277
24279
  // Bot settings > Memory > Workspace knowledge
24278
- if (method === "GET" && path === "/api/paw/suggestable") {
24280
+ if (method === "GET" && path === "/api/paw/suggestable")
24279
24281
  return json(res, 200, { files: paw.suggestable() });
24280
- }
24281
24282
  if (method === "POST" && path === "/api/paw/suggestions") {
24282
24283
  const body = await readBody(req, 64_000);
24283
24284
  const made = paw.suggestChange({
@@ -18,8 +18,11 @@ import { writeFileAtomic } from "../atomic.js";
18
18
  import { normalizeName } from "./aliases.js";
19
19
  export const CHIBITEK_RANKINGS_CACHE = "model-rankings-chibitek.json";
20
20
  const CACHE_VERSION = 1;
21
- /** Where the published document lives. Overridable for staging and tests. */
22
- export const CHIBITEK_RANKINGS_URL = process.env.CHIBITEK_RANKINGS_URL ?? "https://atomic.chibitek.com/model-rankings.json";
21
+ /** Where the published document lives: beside the update feed in the public
22
+ * atomic-updates bucket (electron-builder.yml), so it rides the same hosting
23
+ * the releases already depend on. Overridable for staging and tests. */
24
+ export const CHIBITEK_RANKINGS_URL = process.env.CHIBITEK_RANKINGS_URL ??
25
+ "https://ugmbfkqvogfuvufzjxtb.supabase.co/storage/v1/object/public/atomic-updates/atomic/K_5FMcrZFZ5AE2K-Lydn-Tis/model-rankings.json";
23
26
  const CLASS_SET = new Set(MODEL_CLASSES);
24
27
  /** The document, validated and resolved against the catalog. Unknown ids
25
28
  * are dropped and named in `unknown` so a typo never silently grades the
@@ -87,7 +90,14 @@ export async function fetchRankings(options) {
87
90
  signal: AbortSignal.timeout(30_000),
88
91
  headers: { accept: "application/json" },
89
92
  });
90
- if (!response.ok)
91
- throw new Error(`chibitek-rankings: HTTP ${response.status}`);
92
- return response.json();
93
+ if (response.ok)
94
+ return response.json();
95
+ // Supabase Storage answers a missing object with 400 and a NoSuchKey body,
96
+ // not 404; report it as the 404 the caller reads as "not published yet".
97
+ if (response.status === 400) {
98
+ const body = (await response.json().catch(() => null));
99
+ if (body?.code === "NoSuchKey")
100
+ throw new Error("chibitek-rankings: HTTP 404");
101
+ }
102
+ throw new Error(`chibitek-rankings: HTTP ${response.status}`);
93
103
  }