@chibitek/chibi 0.1.207 → 0.1.208

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 (93) hide show
  1. package/dist/assets/{TerminalPanel-Cqjxle8G.js → TerminalPanel-B5bwdaJ5.js} +1 -1
  2. package/dist/assets/{abnfDiagram-O67JEVCF-XB80WX43.js → abnfDiagram-O67JEVCF-BLKuHvdS.js} +1 -1
  3. package/dist/assets/{arc-BERcgYDi.js → arc-BeOf3Y3d.js} +1 -1
  4. package/dist/assets/{architectureDiagram-NJMV4G6O-Dnc9s6SQ.js → architectureDiagram-NJMV4G6O-DnXr729a.js} +1 -1
  5. package/dist/assets/{blockDiagram-BEXU5L5S-Cxc21eYL.js → blockDiagram-BEXU5L5S-CEiwrTaI.js} +1 -1
  6. package/dist/assets/{c4Diagram-YGBWAQC7-CW-3gUcf.js → c4Diagram-YGBWAQC7-C0-29khR.js} +1 -1
  7. package/dist/assets/channel-_JFliC5C.js +1 -0
  8. package/dist/assets/{chunk-2Q5K7J3B-Bs484eiW.js → chunk-2Q5K7J3B-D8dKbbui.js} +1 -1
  9. package/dist/assets/{chunk-3FUC2YCW-qhnBgRDy.js → chunk-3FUC2YCW-fAEY1oOe.js} +2 -2
  10. package/dist/assets/{chunk-5VM5RSS4-CsCqAEkH.js → chunk-5VM5RSS4-Djza4B4b.js} +1 -1
  11. package/dist/assets/{chunk-GTNCS2PH-ChBgFjPw.js → chunk-GTNCS2PH-BWFGSXNt.js} +1 -1
  12. package/dist/assets/{chunk-GWA4HPMP-Df5-WClq.js → chunk-GWA4HPMP-BGo5oevY.js} +1 -1
  13. package/dist/assets/{chunk-JWPE2WC7-BdMXRJhO.js → chunk-JWPE2WC7-DIdxOMOn.js} +1 -1
  14. package/dist/assets/{chunk-NETBCI7D-rmAqJ9nY.js → chunk-NETBCI7D-Dc4tJ9uD.js} +1 -1
  15. package/dist/assets/{chunk-WEXAMYUT-DYmTw4lw.js → chunk-WEXAMYUT-DvZ9F5yw.js} +1 -1
  16. package/dist/assets/{chunk-XXDRQBXY-C4o5SHm0.js → chunk-XXDRQBXY-BYUVYcxq.js} +1 -1
  17. package/dist/assets/{classDiagram-v2-NBCMYWYE-Bm-ZzDk5.js → classDiagram-v2-NBCMYWYE-BtnsJQvT.js} +1 -1
  18. package/dist/assets/{cose-bilkent-JH36ORCC-CFMRSfMu.js → cose-bilkent-JH36ORCC-DLDe1VHc.js} +1 -1
  19. package/dist/assets/{cynefin-OW5HDTMX-BDedZ5yW.js → cynefin-OW5HDTMX-a1GJE5iI.js} +1 -1
  20. package/dist/assets/{cynefinDiagram-VND7K2PF-i7KARSqF.js → cynefinDiagram-VND7K2PF-DXxGLDlQ.js} +1 -1
  21. package/dist/assets/{dagre-6A5THRUB-CwWpV0i_.js → dagre-6A5THRUB-DAW_YZe9.js} +1 -1
  22. package/dist/assets/{diagram-22UHCM2B-CWIMT3-K.js → diagram-22UHCM2B-oq3saywD.js} +1 -1
  23. package/dist/assets/{diagram-3UASUU5V-C7HGc_ap.js → diagram-3UASUU5V-BhCP3hS9.js} +1 -1
  24. package/dist/assets/{diagram-ATOU4E4O-BeLM7ihN.js → diagram-ATOU4E4O-ByFRn1dW.js} +1 -1
  25. package/dist/assets/{diagram-CDSNMT55-CN1rVM-W.js → diagram-CDSNMT55-DWoCvkNH.js} +1 -1
  26. package/dist/assets/{diagram-MLGK6HIB-CuLcsx4e.js → diagram-MLGK6HIB-CSH5kSlk.js} +1 -1
  27. package/dist/assets/{diagram-MPIPVDR6-Bie61r-h.js → diagram-MPIPVDR6-Cnpx1s-T.js} +1 -1
  28. package/dist/assets/{ebnfDiagram-ZINNZB2B-ChMg86y3.js → ebnfDiagram-ZINNZB2B-DPmX63Vg.js} +1 -1
  29. package/dist/assets/{elk-276RUBZZ-DG9xXwoW.js → elk-276RUBZZ-DUtmO9kb.js} +1 -1
  30. package/dist/assets/{erDiagram-OPXOYQCR-C9bl-nWK.js → erDiagram-OPXOYQCR-SxwJeJu-.js} +1 -1
  31. package/dist/assets/{flowDiagram-KWPJA3E3-DvdWxFI8.js → flowDiagram-KWPJA3E3--QZAAUjB.js} +1 -1
  32. package/dist/assets/{ganttDiagram-FUAMR5RP-DDCNSEYc.js → ganttDiagram-FUAMR5RP-CRz6i2Pe.js} +1 -1
  33. package/dist/assets/{gitGraphDiagram-X574FWY7-PFvmOSMd.js → gitGraphDiagram-X574FWY7-Dx9Cisl2.js} +1 -1
  34. package/dist/assets/{index-DnniNB7N.js → index-BGkOob08.js} +1 -1
  35. package/dist/assets/{index-Ci2mINhA.js → index-vIsgWbJW.js} +83 -83
  36. package/dist/assets/{infoDiagram-VRGFBTTK-HEZh-PnK.js → infoDiagram-VRGFBTTK-CDLogk8N.js} +1 -1
  37. package/dist/assets/{ishikawaDiagram-OU5B5YK6-P3mmCGAU.js → ishikawaDiagram-OU5B5YK6-DsrF1wno.js} +1 -1
  38. package/dist/assets/{journeyDiagram-ZHPQQLJL-dKG4AQu2.js → journeyDiagram-ZHPQQLJL-DUi8LEA6.js} +1 -1
  39. package/dist/assets/{kanban-definition-PNTS6WVX-BeIHeQTt.js → kanban-definition-PNTS6WVX-BAdWXobw.js} +1 -1
  40. package/dist/assets/{linear-DnEqDr6r.js → linear-Dha948ns.js} +1 -1
  41. package/dist/assets/{mermaid.core-D7hz6n4u.js → mermaid.core-BqT1aUP9.js} +5 -5
  42. package/dist/assets/{mindmap-definition-NLK3R4M7-BxJ8p-DN.js → mindmap-definition-NLK3R4M7-XS1wDQ80.js} +1 -1
  43. package/dist/assets/{pegDiagram-GJSIUBJH-CkQT2dHJ.js → pegDiagram-GJSIUBJH-BphuafcF.js} +1 -1
  44. package/dist/assets/{pieDiagram-5QR66LMP-DmVVhYaY.js → pieDiagram-5QR66LMP-JN9mbdiU.js} +1 -1
  45. package/dist/assets/{quadrantDiagram-O4NWA36T-DsOz-qCY.js → quadrantDiagram-O4NWA36T-CkBF7Woa.js} +1 -1
  46. package/dist/assets/{railroadDiagram-XR7U4H2S-CeYfvaki.js → railroadDiagram-XR7U4H2S-Ie1GVpj5.js} +1 -1
  47. package/dist/assets/{requirementDiagram-PLB6GJNP-BCtM-2uN.js → requirementDiagram-PLB6GJNP-B8xGM6w4.js} +1 -1
  48. package/dist/assets/{sankeyDiagram-IPEJSGJF-Cu8ki35x.js → sankeyDiagram-IPEJSGJF-BgTSlqMg.js} +1 -1
  49. package/dist/assets/{sequenceDiagram-PO4LG4MO-DKbS5Gcs.js → sequenceDiagram-PO4LG4MO-B1J4EIne.js} +1 -1
  50. package/dist/assets/{sizeCapture-INFHLROL-Ceut6PrE.js → sizeCapture-INFHLROL-Cpcjc5oE.js} +1 -1
  51. package/dist/assets/{stateDiagram-v2-GCMORJYK-Bl5uMY2f.js → stateDiagram-v2-GCMORJYK-CtQKYLT4.js} +1 -1
  52. package/dist/assets/{swimlanes-2SLR337P-CoMPbJ2k.js → swimlanes-2SLR337P-DpIk02zs.js} +1 -1
  53. package/dist/assets/swimlanesDiagram-TC7HE7FX-DPTl4zVS.js +8 -0
  54. package/dist/assets/{timeline-definition-EJHVYXUP-D0xkKp46.js → timeline-definition-EJHVYXUP-DsA7dQhy.js} +1 -1
  55. package/dist/assets/{usecaseDiagram-POWQR4AR-BCCL6QIf.js → usecaseDiagram-POWQR4AR-BM42_rDz.js} +1 -1
  56. package/dist/assets/{vennDiagram-UO4OBE2U-B7g3jK72.js → vennDiagram-UO4OBE2U-DgLtqgJF.js} +1 -1
  57. package/dist/assets/{wardleyDiagram-VNRHLVJA-DFhnqQKP.js → wardleyDiagram-VNRHLVJA-BKUUTKBJ.js} +1 -1
  58. package/dist/assets/{xychartDiagram-PMCCYNJV-mIXMscRS.js → xychartDiagram-PMCCYNJV-B9RWvizV.js} +1 -1
  59. package/dist/index.html +1 -1
  60. package/dist-server/index.js +3150 -2724
  61. package/dist-server/openmausbot.js +816 -635
  62. package/dist-server/pair-cli.js +816 -635
  63. package/dist-server/server/connection-cap-failover.js +8 -6
  64. package/dist-server/server/drivers/acp/core.js +20 -47
  65. package/dist-server/server/drivers/acp/custom.js +5 -0
  66. package/dist-server/server/drivers/acp/hermes.js +1 -0
  67. package/dist-server/server/drivers/acp/kimi-turn-failure.js +68 -0
  68. package/dist-server/server/drivers/acp/kimi.js +7 -0
  69. package/dist-server/server/drivers/acp/mcp-limit.js +47 -0
  70. package/dist-server/server/drivers/acp/rpc-error.js +35 -0
  71. package/dist-server/server/drivers/acp/setup-failure.js +9 -0
  72. package/dist-server/server/drivers/acp/vibe.js +11 -5
  73. package/dist-server/server/drivers/chat-text-only.js +47 -0
  74. package/dist-server/server/drivers/openai-chat-protocol.js +15 -0
  75. package/dist-server/server/drivers/openai-chat.js +8 -18
  76. package/dist-server/server/drivers/turn-mcp.js +3 -0
  77. package/dist-server/server/drivers/vibe-login.js +17 -8
  78. package/dist-server/server/engine-failover.js +16 -29
  79. package/dist-server/server/engine-rest.js +4 -3
  80. package/dist-server/server/engine-tiers.js +12 -9
  81. package/dist-server/server/index.js +16 -15
  82. package/dist-server/server/injected-model-rest.js +17 -0
  83. package/dist-server/server/model-levels/aliases.js +243 -38
  84. package/dist-server/server/model-levels/chibitek-rankings.js +8 -8
  85. package/dist-server/server/model-levels/classes.js +106 -38
  86. package/dist-server/server/model-levels/index.js +26 -14
  87. package/dist-server/server/model-levels/model-ids.js +91 -0
  88. package/dist-server/server/model-levels/overrides.js +7 -4
  89. package/dist-server/server/model-levels/sources.js +4 -1
  90. package/dist-server/server/pay-per-use.js +13 -1
  91. package/package.json +1 -1
  92. package/dist/assets/channel-DaeKCO76.js +0 -1
  93. package/dist/assets/swimlanesDiagram-TC7HE7FX-DLJq0mAR.js +0 -8
@@ -3,8 +3,10 @@
3
3
  // A turn whose engine runs out of its usage allowance, turns out to be
4
4
  // signed out, goes fully silent, or fails in any other way, is not failed:
5
5
  // the engine rests and the same turn runs on the next engine of the bot's
6
- // ladder at the same level, at most two tries per turn. No chat message is
7
- // added; the client shows a small banner that fades (src/lib/engine-switch.ts).
6
+ // ladder, and on the one after that, until an engine answers or none is left
7
+ // (Erick, 2026-11-22: "if it fails for any reason, just go to the next one").
8
+ // No chat message is added; the client shows a small banner that fades
9
+ // (src/lib/engine-switch.ts).
8
10
  //
9
11
  // Modelled on OpenRouter's routing (docs/chibitek/engine-tiers.md): any
10
12
  // error is a reason to try the next candidate, not only the ones we have
@@ -34,28 +36,14 @@
34
36
  import { newEventId } from "./contracts.js";
35
37
  import { classifyEngineFailure, isCredentialDead, mayBeReplyFailure, replyEngineFailure, statedReset } from "./engine-failure.js";
36
38
  import { hermesReplyFailure } from "./hermes-reply-failure.js";
37
- /** The two-try cap: at most this many engines do work in one turn, the
38
- * first and one switch. A failed attempt counts toward it when the engine
39
- * ran (a usage limit, a stall, an error no pattern recognises). When the
40
- * second such engine fails too, the turn stops with its one plain line
41
- * rather than walking the rest of the ladder. */
42
- export const MAX_ENGINES_PER_TURN = 2;
43
- /** However many engines were passed over, a turn never tries more than this. */
44
- export const MAX_ENGINES_WALKED = 8;
45
- /** Whether a turn has used up its tries. An engine that failed only because
46
- * its account needs the person (a sign-in, an expired key) did no work, so
47
- * it does not count: the turn walks past it to the next engine rather than
48
- * stopping on an error while a ready engine is one rung away (Erick,
49
- * 2026-11-14). `needsPerson` reads the resting store. */
50
- export function triesSpent(tried, needsPerson) {
51
- const all = [...tried];
52
- return all.length >= MAX_ENGINES_WALKED || all.filter((instanceId) => !needsPerson(instanceId)).length >= MAX_ENGINES_PER_TURN;
53
- }
54
- /** The `needsPerson` of triesSpent widened: an engine that failed before
55
- * accepting the prompt (session, gateway: `setup` on its rest, or on this
56
- * turn's own failure) did not run the turn either, so it is not a try. */
57
- export const uncountedTry = (turn, resting, needsPerson) => (instanceId) => needsPerson(instanceId) ||
58
- (instanceId === turn.instanceId && turn.failure?.setup === true) || resting.some((entry) => entry.instanceId === instanceId && entry.setup === true);
39
+ /** The loop guard, not a budget: a turn moves on until an engine answers or
40
+ * every engine it may use has failed or is resting. Each engine is tried at
41
+ * most once per turn (`tried`), so the walk always ends; this bounds it at
42
+ * the longest ladder (MAX_LADDER_LENGTH). The two-try cap that stood here
43
+ * (2026-10-26) stopped turns with a dozen ready engines left. */
44
+ export const MAX_ENGINES_WALKED = 24;
45
+ /** Whether a turn has walked as many engines as the guard allows. */
46
+ export const triesSpent = (tried) => [...tried].length >= MAX_ENGINES_WALKED;
59
47
  const accountOf = (engine) => engine.snapshot.account?.email ?? engine.snapshot.account?.organization;
60
48
  /** Another instance of the same engine on the same account (or on none): it
61
49
  * sends a model down the route a failure just broke (two OpenCode instances
@@ -284,18 +272,17 @@ export function restingLine(engines, formatTime, computer, options = {}) {
284
272
  const unavailable = fresh(computer?.unavailable).map((label) => `${label} is unavailable`);
285
273
  const hint = listed.some((engine) => engine.keyExpired || engine.needsSignIn) || signedOut.length ? ` ${ACCOUNTS_HINT}` : "";
286
274
  const cannot = fresh(computer?.engines).map((label) => `${label} can't control ${computer.place}`);
287
- // After the two-try cap the cap line says more, unless an engine cannot
275
+ // At the walk's guard the capped line says more, unless an engine cannot
288
276
  // control the place at all; the passed-over engines are named either way.
289
277
  if (cannot.length || ((signedOut.length || unavailable.length) && !options.capped)) {
290
278
  return `No engine that can work on ${computer.place} is free, so this turn stopped: ${[...parts, ...signedOut, ...unavailable, ...cannot].join("; ")}.${hint}`;
291
279
  }
292
280
  parts.push(...signedOut, ...unavailable);
293
- // The two-try cap, not an empty ladder: say so, with what each engine hit.
281
+ // The guard, not an empty ladder: say so, with what each engine hit.
294
282
  if (options.capped) {
295
- const count = MAX_ENGINES_PER_TURN === 2 ? "two" : String(MAX_ENGINES_PER_TURN);
296
283
  return parts.length
297
- ? `This turn stopped after ${count} engines failed: ${parts.join(", ")}.${hint}`
298
- : `This turn stopped after ${count} engines failed.`;
284
+ ? `This turn stopped after ${MAX_ENGINES_WALKED} engines failed: ${parts.join(", ")}.${hint}`
285
+ : `This turn stopped after ${MAX_ENGINES_WALKED} engines failed.`;
299
286
  }
300
287
  if (parts.length === 0)
301
288
  return "No engine is available for this turn, so it stopped.";
@@ -32,7 +32,7 @@
32
32
  // provider_error any other provider failure (OpenRouter-style: an
33
33
  // unrecognised error moves the turn): a circuit breaker of
34
34
  // 1 minute, doubling on each repeat within an hour, capped
35
- // at 15 minutes, so a failing engine is not hammered
35
+ // at 2 hours, so a failing engine is not hammered
36
36
  // stalled the engine went fully silent mid-turn (the driver's idle
37
37
  // guard stopped it): 10 minutes, doubling on each repeat
38
38
  // within an hour, capped at 1 hour; Settings shows "Not
@@ -62,7 +62,7 @@ export const KEY_EXPIRED_REST_MS = 7 * 24 * HOUR_MS;
62
62
  /** The first silent probe of a dead key, before doubling. */
63
63
  export const KEY_PROBE_BASE_MS = 30 * MINUTE_MS;
64
64
  export const PROVIDER_ERROR_REST_BASE_MS = MINUTE_MS;
65
- export const PROVIDER_ERROR_REST_CAP_MS = 15 * MINUTE_MS;
65
+ export const PROVIDER_ERROR_REST_CAP_MS = 2 * HOUR_MS;
66
66
  /** A stated retry time for a short rate limit is trusted this far out. */
67
67
  const RATE_REST_MAX_STATED_MS = HOUR_MS;
68
68
  /** The first silent probe of a rolling-window rest, before doubling. */
@@ -100,7 +100,8 @@ export function probeDelayMs(count, failedProbes, baseMs = PROBE_BASE_MS) {
100
100
  return baseMs * 2 ** doublings;
101
101
  }
102
102
  /** Circuit breaker for the `count`th unrecognised provider failure in a
103
- * row: 1 minute, doubling, capped at 15 minutes. */
103
+ * row: 1 minute, doubling, capped at 2 hours: an engine that fails the
104
+ * same way all day is benched for hours, not tried again every 15 minutes. */
104
105
  export function providerErrorRestMs(count) {
105
106
  const doublings = Math.max(0, Math.min(Math.floor(count) - 1, 16));
106
107
  return Math.min(PROVIDER_ERROR_REST_BASE_MS * 2 ** doublings, PROVIDER_ERROR_REST_CAP_MS);
@@ -124,8 +124,7 @@ export function checkedLadder(value) {
124
124
  }
125
125
  const configObject = (engineTiers) => engineTiers && typeof engineTiers === "object" && !Array.isArray(engineTiers) ? engineTiers : {};
126
126
  /** The workspace's ladders: the defaults (the generated ones), with any
127
- * tier the person edited replaced by their list. `engineTiers` is
128
- * config.json's raw value. */
127
+ * tier the person edited replaced by their list. `engineTiers` is config.json's raw value. */
129
128
  export function engineTierLadders(engineTiers, defaults = DEFAULT_LADDERS) {
130
129
  const stored = configObject(engineTiers).ladders;
131
130
  const ladders = stored && typeof stored === "object" && !Array.isArray(stored) ? stored : {};
@@ -150,10 +149,12 @@ function storedClasses(engineTiers) {
150
149
  const current = engineTierClasses(engineTiers);
151
150
  return Object.fromEntries(BOT_TIERS.filter((tier) => current[tier] !== DEFAULT_TIER_CLASSES[tier]).map((tier) => [tier, current[tier]]));
152
151
  }
153
- const withClasses = (config, classes) => Object.keys(classes).length ? { ...config, classes } : config;
152
+ function withClasses(engineTiers, ladders, classes) {
153
+ const { ladders: _ladders, classes: _classes, ...kept } = configObject(engineTiers); // kept: includeFree, connectionRunOut
154
+ return Object.keys(classes).length ? { ...kept, ladders, classes } : { ...kept, ladders };
155
+ }
154
156
  /** The config value to store after one tier's ladder changes. A ladder equal
155
- * to its default is not stored, so later default changes (a refresh) still
156
- * reach it; null resets the tier. */
157
+ * to its default is not stored, so later default changes (a refresh) still reach it; null resets the tier. */
157
158
  export function withLadder(engineTiers, tier, ladder, defaults = DEFAULT_LADDERS) {
158
159
  const stored = configObject(engineTiers).ladders;
159
160
  const raw = stored && typeof stored === "object" && !Array.isArray(stored) ? stored : {};
@@ -163,7 +164,7 @@ export function withLadder(engineTiers, tier, ladder, defaults = DEFAULT_LADDERS
163
164
  if (value && JSON.stringify(value) !== JSON.stringify(defaults[name]))
164
165
  next[name] = value.map((entry) => ({ ...entry }));
165
166
  }
166
- return withClasses({ ladders: next }, storedClasses(engineTiers));
167
+ return withClasses(engineTiers, next, storedClasses(engineTiers));
167
168
  }
168
169
  /** The config value to store after a tier's class changes; null resets it. */
169
170
  export function withTierClass(engineTiers, tier, modelClass) {
@@ -178,7 +179,7 @@ export function withTierClass(engineTiers, tier, modelClass) {
178
179
  classes[tier] = modelClass;
179
180
  else
180
181
  delete classes[tier];
181
- return withClasses({ ladders }, classes);
182
+ return withClasses(engineTiers, ladders, classes);
182
183
  }
183
184
  /** The tier a bot's job suggests. Chibi (and any Chief of Staff) orchestrates. */
184
185
  export function deriveTier(bot) {
@@ -265,6 +266,8 @@ export function resolveLadder(ladder, stored, context) {
265
266
  const step = ladder.findIndex((entry) => matchesEngine(entry, candidate));
266
267
  return step < 0 ? ladder.length : step;
267
268
  };
269
+ const ownRung = (entry, candidate) => // a same-driver rung naming a model this account lacks: its own default
270
+ (entry && entryModel(entry, candidate) ? entry : { engine: candidate.instanceId });
268
271
  for (const [index, candidate] of context.candidates.entries()) {
269
272
  // Ollama Cloud joins every ladder by itself, as it always has: now as the
270
273
  // flat plan it is, in the subscription band.
@@ -276,13 +279,13 @@ export function resolveLadder(ladder, stored, context) {
276
279
  // ever names one, same as how a key-based engine joins automatically.
277
280
  if (freeCandidate(candidate)) {
278
281
  const step = rungOf(candidate);
279
- free.push({ step, entry: ladder[step] ?? { engine: candidate.instanceId }, candidate, band: "free", index });
282
+ free.push({ step, entry: ownRung(ladder[step], candidate), candidate, band: "free", index });
280
283
  continue;
281
284
  }
282
285
  if (!keyBased(candidate) || candidate.driverKind === "boxAgent")
283
286
  continue;
284
287
  const step = rungOf(candidate);
285
- key.push({ step, entry: ladder[step] ?? { engine: candidate.instanceId }, candidate, band: "key", index });
288
+ key.push({ step, entry: ownRung(ladder[step], candidate), candidate, band: "key", index });
286
289
  }
287
290
  subscription.sort((a, b) => atomicFirst(a.candidate) - atomicFirst(b.candidate) || a.step - b.step);
288
291
  key.sort((a, b) => a.step - b.step || storedFirst(a.candidate, b.candidate) || a.index - b.index);
@@ -278,7 +278,7 @@ import { localHost, probeLocalInjects } from "./drivers/local-inject.js";
278
278
  import { totalmem } from "node:os";
279
279
  import { loadInstanceKeys } from "./instance-keys.js";
280
280
  import { createProviderAccountRoutes } from "./routes/provider-accounts.js";
281
- import { accountStops, injectedModel, modelScope, refusedModelScope, restScope } from "./injected-model-rest.js";
281
+ import { accountStops, failureRestScope, injectedModel, modelScope, restScope } from "./injected-model-rest.js";
282
282
  import { accountProvider } from "../shared/provider-accounts.js";
283
283
  import { createAccountRoutes } from "./routes/accounts.js";
284
284
  import { installNativeVault } from "./vault/runtime.js";
@@ -327,7 +327,7 @@ import { createNexusMemoryRoutes, NexusImportOffer } from "./routes/nexus-memory
327
327
  import { createBoardRoutes } from "./routes/board.js";
328
328
  import { readBoardFromNexus } from "./board/nexus-board.js";
329
329
  import { LocalModelInventory, localModePlacement, machineMemory } from "./local-models-mode.js";
330
- import { eventBase, restTime, FailoverGate, MAX_ENGINES_PER_TURN, triesSpent, uncountedTry, continuationNote, restingLine, restingOnRoute, sameRoute } from "./engine-failover.js";
330
+ import { eventBase, restTime, FailoverGate, triesSpent, continuationNote, restingLine, restingOnRoute, sameRoute } from "./engine-failover.js";
331
331
  import { connectionRunOutPolicy, finalizeConnectionCapPick, finalizeNewTurnPlacement, pauseKeyBandForRunOut } from "./connection-cap-failover.js";
332
332
  import { TURN_ERROR_CATEGORIES } from "../shared/runtime-events.js";
333
333
  import { EngineProbes, PROBE_PROMPT, isProbeThread, probeThreadId } from "./engine-probe.js";
@@ -3326,10 +3326,9 @@ function placedTurn(resolution, persist) {
3326
3326
  });
3327
3327
  }
3328
3328
  // ── pay-per-use (docs/chibitek/engine-tiers.md, "Pay-per-use notice") ────
3329
- // The one thing about engines and billing the person hears of: a paid key
3330
- // is used only after stored approval when every subscription is resting,
3331
- // signed out or unavailable. That opens an episode, announced once; a turn
3332
- // placed on a subscription ends it. Ollama Cloud is a subscription.
3329
+ // The one thing about engines and billing the person hears of: a paid key is used only after stored approval
3330
+ // when every subscription is resting, signed out or unavailable. That opens an episode, announced once;
3331
+ // a turn a subscription answers ends it (noteEngineBack). Ollama Cloud is a subscription.
3333
3332
  const payPerUse = new PayPerUseEpisodes(DATA_DIR, (episode) => broadcast({ kind: "engines.pay_per_use", episode }, { adminOnly: true }));
3334
3333
  const SUBSCRIPTION_OUT = new Set(["resting", "signed-out", "unavailable", "tried"]);
3335
3334
  function notePayPerUse(resolution) {
@@ -3397,7 +3396,7 @@ const probeEnvMs = (name) => {
3397
3396
  const value = Number(process.env[name]);
3398
3397
  return Number.isFinite(value) && value > 0 ? value : undefined;
3399
3398
  };
3400
- const engineRests = new EngineRestStore(DATA_DIR, undefined, { probeBaseMs: probeEnvMs("OMB_ENGINE_PROBE_BASE_MS") }), needsPerson = (instanceId) => engineRests.active().some((entry) => entry.instanceId === instanceId && entry.needsSignIn === true); // needsPerson: a failed sign-in or expired key, which does not use up a turn's try (triesSpent)
3399
+ const engineRests = new EngineRestStore(DATA_DIR, undefined, { probeBaseMs: probeEnvMs("OMB_ENGINE_PROBE_BASE_MS") });
3401
3400
  // Atomic Engine runs on the person's Atomic accounts (server/atomic-engine-accounts.ts).
3402
3401
  // An account resting here (its limit was hit through another engine) shares its
3403
3402
  // quota with the engine, so the engine is told when it is back. A stall is that
@@ -3630,6 +3629,8 @@ function noteEngineBack(event) {
3630
3629
  const model = selection?.instanceId === instanceId ? selection.model : undefined;
3631
3630
  for (const scope of new Set([candidate ? restScope(candidate, model) : undefined, modelScope(model)]))
3632
3631
  engineRests.noteBack(instanceId, candidate ? engineAccount(candidate) : undefined, scope);
3632
+ if (candidate && !keyBased(candidate) && !freeCandidate(candidate) && !(model && perTokenModel(candidate, model)))
3633
+ (instanceOwner(instanceId) === "personal" ? personalPayPerUse : payPerUse).subscriptionAnswered();
3633
3634
  }
3634
3635
  /** Rest a refused engine and continue on an eligible engine, or show an actionable line. */
3635
3636
  function engineFailover(turn, completion) {
@@ -3650,7 +3651,7 @@ function engineFailover(turn, completion) {
3650
3651
  // that provider rests, the engine's others stay free. A stall is the engine's.
3651
3652
  // A dead key is the whole account's, whichever provider the model ran on:
3652
3653
  // the rest names no provider, so Atomic Engine skips the account too.
3653
- const scope = failure.kind === "stalled" || failure.permanent || !failedCandidate ? undefined : restScope(failedCandidate, ran?.model) ?? refusedModelScope(failure.message, ran?.model);
3654
+ const scope = failedCandidate ? failureRestScope(failedCandidate, ran?.model, failure) : undefined;
3654
3655
  const restFailed = () => engineRests.rest(turn.instanceId, failedCandidate ? engineAccount(failedCandidate) : undefined, failure.kind, { resetAt: failure.resetAt, resetText: failure.resetText, windowMs: failure.windowMs, message: redactSecretsInText(failure.message),
3655
3656
  ...(failure.permanent ? { permanent: true } : {}), ...(scope ? { scope } : {}), ...(ran?.model ? { model: ran.model } : {}), ...(failure.setup ? { setup: true } : {}),
3656
3657
  ...(failure.kind === "auth_failed" && failedCandidate ? { reportedSignedIn: failedCandidate.snapshot.state === "available" && failedCandidate.snapshot.authenticated === true } : {}) });
@@ -3841,7 +3842,7 @@ function roomEngineFailover(turn, completion, room, profile, candidates, failedC
3841
3842
  * before a key), or the one line it stops with. Books pay-per-use for the
3842
3843
  * move. Shared by a bot's own turns and room member turns. */
3843
3844
  function failoverPick(turn, profile, projected, candidates, failedCandidate, restingNamed, attempt) {
3844
- const tried = new Set(attempt.tried), uncounted = uncountedTry(turn, engineRests.active(), needsPerson); // a setup failure is not a try
3845
+ const tried = new Set(attempt.tried);
3845
3846
  const tier = turnTier(profile, turn.threadId);
3846
3847
  const plan = enginePlan(profile, turn.threadId, tier);
3847
3848
  const required = plan.modelClass;
@@ -3851,7 +3852,7 @@ function failoverPick(turn, profile, projected, candidates, failedCandidate, res
3851
3852
  // provider on its side of the personal line; with none left it stops with
3852
3853
  // its one line.
3853
3854
  const subscriptionMove = isSubscriptionBot(profile)
3854
- ? triesSpent(tried, uncounted) || !projected
3855
+ ? triesSpent(tried) || !projected
3855
3856
  ? { line: subscriptionLine(profile, candidates) }
3856
3857
  : subscriptionPlacement({ profile, projected, candidates, tried: new Set([...tried, turn.instanceId]), auto: attempt.persist, modelClass: neededClass })
3857
3858
  : undefined;
@@ -3863,7 +3864,7 @@ function failoverPick(turn, profile, projected, candidates, failedCandidate, res
3863
3864
  const personalMove = subscriptionMove?.choice
3864
3865
  ? { choice: { selection: subscriptionMove.choice.selection, candidate: subscriptionMove.choice.candidate, step: 0, band: "subscription" }, line: "" }
3865
3866
  : personalTurn
3866
- ? triesSpent(tried, uncounted) || !projected
3867
+ ? triesSpent(tried) || !projected
3867
3868
  ? { line: personalLine(candidates, false) }
3868
3869
  : personalPlacement({ profile, projected, candidates, tried, needs: { tools: true, vision: attempt.vision }, modelClass: neededClass, computer })
3869
3870
  : undefined;
@@ -3872,7 +3873,7 @@ function failoverPick(turn, profile, projected, candidates, failedCandidate, res
3872
3873
  // Every bot, pinned or not and of any tier, falls to the next subscription
3873
3874
  // the person has, in any class, before a pay-per-use key (resolveFailover).
3874
3875
  const resting = (candidate, model) => engineResting(candidate, model) || (model === attempt.selection.model && !!failedCandidate && sameRoute(candidate, failedCandidate));
3875
- const resolution = personalMove || triesSpent(tried, uncounted) || !projected ? { skipped: [] } : resolveFailover({
3876
+ const resolution = personalMove || triesSpent(tried) || !projected ? { skipped: [] } : resolveFailover({
3876
3877
  ladder: plan.ladder,
3877
3878
  classLadder: (modelClass) => classLadder(classedModels(), modelClass),
3878
3879
  failed: attempt.selection,
@@ -3896,7 +3897,7 @@ function failoverPick(turn, profile, projected, candidates, failedCandidate, res
3896
3897
  return finalizeConnectionCapPick({
3897
3898
  choice, subscriptionLine: subscriptionMove?.line, failureKind: turn.failure?.kind,
3898
3899
  pausedUntil: payPerUse.pausedUntil(), skipped: resolution.skipped, payPerUsePausedLine, restingNamed,
3899
- failedInstanceId: turn.instanceId, alreadyTried: attempt.tried, triedCount: [...tried].filter((instanceId) => !uncounted(instanceId)).length,
3900
+ failedInstanceId: turn.instanceId, alreadyTried: attempt.tried, triedCount: tried.size,
3900
3901
  cannotDrive: cannotDriveNamed(candidates, resolution.skipped, computer),
3901
3902
  policy: connectionRunOutPolicy(cfg.engineTiers), paidApproved: Boolean(payPerUse.current()?.keptGoingAt),
3902
3903
  local: Boolean(placed.local), currentLabel: engineLabel(candidates, attempt.selection),
@@ -3939,8 +3940,8 @@ function jevRerunOnNextRung(c, replyIds) {
3939
3940
  const profile = store.bot(c.botId);
3940
3941
  const projected = profile ? store.projectBotForTask(c.botId, c.threadId) : undefined;
3941
3942
  const tried = new Set(record.tried);
3942
- if (!profile || !projected || tried.size > MAX_ENGINES_PER_TURN)
3943
- return null; // tried includes the engine that answered: the failure cap is a strict bound here
3943
+ if (!profile || !projected || triesSpent(tried))
3944
+ return null;
3944
3945
  const candidates = engineSnapshots.current() ?? [];
3945
3946
  const tier = turnTier(profile, c.threadId);
3946
3947
  const plan = enginePlan(profile, c.threadId, tier);
@@ -32,3 +32,20 @@ export const modelScope = (model) => (model ? `model:${model}` : undefined);
32
32
  export const refusedModelScope = (message, model) => (message && isModelAccessRefused(message) ? modelScope(model) : undefined);
33
33
  /** Whether the engine's account state (signed out, resting) stops this model. */
34
34
  export const accountStops = (model) => !injectedModel(model);
35
+ /** A limit on one model family, in the provider's own words ("You've hit
36
+ * your Fable limit ... Switch to another model"): the word before "limit" is
37
+ * part of the model's id, so the account's other models still have room and
38
+ * that model rests alone. "5-hour limit" and "usage limit" name no model. */
39
+ export const limitedModelScope = (message, model) => {
40
+ const word = /\bhit your ([a-z][\w.]{2,}) limit\b/i.exec(message ?? "")?.[1]?.toLowerCase();
41
+ return word && model?.toLowerCase().includes(word) ? modelScope(model) : undefined;
42
+ };
43
+ /** The scope a failed turn's rest names. A stall, a dead key and a failure
44
+ * before the prompt was accepted (`setup`: session, gateway) are the whole
45
+ * engine's; otherwise the provider, the refused model or the limited model. */
46
+ export function failureRestScope(candidate, model, failure) {
47
+ if (failure.kind === "stalled" || failure.permanent || failure.setup)
48
+ return undefined;
49
+ return restScope(candidate, model) ?? refusedModelScope(failure.message, model)
50
+ ?? (failure.kind === "usage_limited" ? limitedModelScope(failure.message, model) : undefined);
51
+ }