@chibitek/chibi 0.1.206 → 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 (102) hide show
  1. package/dist/assets/{TerminalPanel-BBJ8EeT7.js → TerminalPanel-B5bwdaJ5.js} +1 -1
  2. package/dist/assets/{abnfDiagram-O67JEVCF-a06YszXx.js → abnfDiagram-O67JEVCF-BLKuHvdS.js} +1 -1
  3. package/dist/assets/{arc-Fe3WbFfc.js → arc-BeOf3Y3d.js} +1 -1
  4. package/dist/assets/{architectureDiagram-NJMV4G6O-DYcb0ZrL.js → architectureDiagram-NJMV4G6O-DnXr729a.js} +1 -1
  5. package/dist/assets/{blockDiagram-BEXU5L5S-xC5y8We2.js → blockDiagram-BEXU5L5S-CEiwrTaI.js} +1 -1
  6. package/dist/assets/{c4Diagram-YGBWAQC7-Dm81dUJa.js → c4Diagram-YGBWAQC7-C0-29khR.js} +1 -1
  7. package/dist/assets/channel-_JFliC5C.js +1 -0
  8. package/dist/assets/{chunk-2Q5K7J3B-CDVJUGUd.js → chunk-2Q5K7J3B-D8dKbbui.js} +1 -1
  9. package/dist/assets/{chunk-3FUC2YCW-BvPx7oJb.js → chunk-3FUC2YCW-fAEY1oOe.js} +2 -2
  10. package/dist/assets/{chunk-5VM5RSS4-kUQxxDSH.js → chunk-5VM5RSS4-Djza4B4b.js} +1 -1
  11. package/dist/assets/{chunk-GTNCS2PH-hmSLPBzT.js → chunk-GTNCS2PH-BWFGSXNt.js} +1 -1
  12. package/dist/assets/{chunk-GWA4HPMP-ivlnCC25.js → chunk-GWA4HPMP-BGo5oevY.js} +1 -1
  13. package/dist/assets/{chunk-JWPE2WC7-hjxL5olg.js → chunk-JWPE2WC7-DIdxOMOn.js} +1 -1
  14. package/dist/assets/{chunk-NETBCI7D-ClgHcSe7.js → chunk-NETBCI7D-Dc4tJ9uD.js} +1 -1
  15. package/dist/assets/{chunk-WEXAMYUT-1i-fNDpg.js → chunk-WEXAMYUT-DvZ9F5yw.js} +1 -1
  16. package/dist/assets/{chunk-XXDRQBXY-BhPdm5u4.js → chunk-XXDRQBXY-BYUVYcxq.js} +1 -1
  17. package/dist/assets/{classDiagram-v2-NBCMYWYE-BsL-gKkF.js → classDiagram-v2-NBCMYWYE-BtnsJQvT.js} +1 -1
  18. package/dist/assets/{cose-bilkent-JH36ORCC-piSPlA0p.js → cose-bilkent-JH36ORCC-DLDe1VHc.js} +1 -1
  19. package/dist/assets/{cynefin-OW5HDTMX-D2T5q7wD.js → cynefin-OW5HDTMX-a1GJE5iI.js} +1 -1
  20. package/dist/assets/{cynefinDiagram-VND7K2PF-CWHt2804.js → cynefinDiagram-VND7K2PF-DXxGLDlQ.js} +1 -1
  21. package/dist/assets/{dagre-6A5THRUB-BNioVBDz.js → dagre-6A5THRUB-DAW_YZe9.js} +1 -1
  22. package/dist/assets/{diagram-22UHCM2B-DULW9a3n.js → diagram-22UHCM2B-oq3saywD.js} +1 -1
  23. package/dist/assets/{diagram-3UASUU5V-EYvilvye.js → diagram-3UASUU5V-BhCP3hS9.js} +1 -1
  24. package/dist/assets/{diagram-ATOU4E4O-BRkFLoxi.js → diagram-ATOU4E4O-ByFRn1dW.js} +1 -1
  25. package/dist/assets/{diagram-CDSNMT55-B0IbbTpB.js → diagram-CDSNMT55-DWoCvkNH.js} +1 -1
  26. package/dist/assets/{diagram-MLGK6HIB-u7n_3e2v.js → diagram-MLGK6HIB-CSH5kSlk.js} +1 -1
  27. package/dist/assets/{diagram-MPIPVDR6-NegomnHr.js → diagram-MPIPVDR6-Cnpx1s-T.js} +1 -1
  28. package/dist/assets/{ebnfDiagram-ZINNZB2B-BPZmiseK.js → ebnfDiagram-ZINNZB2B-DPmX63Vg.js} +1 -1
  29. package/dist/assets/{elk-276RUBZZ-BcBEThvp.js → elk-276RUBZZ-DUtmO9kb.js} +1 -1
  30. package/dist/assets/{erDiagram-OPXOYQCR-BVAGByE5.js → erDiagram-OPXOYQCR-SxwJeJu-.js} +1 -1
  31. package/dist/assets/{flowDiagram-KWPJA3E3-ByZ1IyAE.js → flowDiagram-KWPJA3E3--QZAAUjB.js} +1 -1
  32. package/dist/assets/{ganttDiagram-FUAMR5RP-CEa3O2pJ.js → ganttDiagram-FUAMR5RP-CRz6i2Pe.js} +1 -1
  33. package/dist/assets/{gitGraphDiagram-X574FWY7-dul-ZoaX.js → gitGraphDiagram-X574FWY7-Dx9Cisl2.js} +1 -1
  34. package/dist/assets/{index-CFUbzTrj.js → index-BGkOob08.js} +1 -1
  35. package/dist/assets/{index-Tw4-5a-J.js → index-vIsgWbJW.js} +153 -153
  36. package/dist/assets/{infoDiagram-VRGFBTTK-Bt9KS597.js → infoDiagram-VRGFBTTK-CDLogk8N.js} +1 -1
  37. package/dist/assets/{ishikawaDiagram-OU5B5YK6-BjJTuEjh.js → ishikawaDiagram-OU5B5YK6-DsrF1wno.js} +1 -1
  38. package/dist/assets/{journeyDiagram-ZHPQQLJL-j07hDjg4.js → journeyDiagram-ZHPQQLJL-DUi8LEA6.js} +1 -1
  39. package/dist/assets/{kanban-definition-PNTS6WVX-DU8baSEs.js → kanban-definition-PNTS6WVX-BAdWXobw.js} +1 -1
  40. package/dist/assets/{linear-Dj1tr9Bh.js → linear-Dha948ns.js} +1 -1
  41. package/dist/assets/{mermaid.core-BeSGZMCl.js → mermaid.core-BqT1aUP9.js} +5 -5
  42. package/dist/assets/{mindmap-definition-NLK3R4M7-LiRl-Bq2.js → mindmap-definition-NLK3R4M7-XS1wDQ80.js} +1 -1
  43. package/dist/assets/{pegDiagram-GJSIUBJH-COL7EWof.js → pegDiagram-GJSIUBJH-BphuafcF.js} +1 -1
  44. package/dist/assets/{pieDiagram-5QR66LMP-BnMXaara.js → pieDiagram-5QR66LMP-JN9mbdiU.js} +1 -1
  45. package/dist/assets/{quadrantDiagram-O4NWA36T-BjLcZ6bG.js → quadrantDiagram-O4NWA36T-CkBF7Woa.js} +1 -1
  46. package/dist/assets/{railroadDiagram-XR7U4H2S-wKCzKLAA.js → railroadDiagram-XR7U4H2S-Ie1GVpj5.js} +1 -1
  47. package/dist/assets/{requirementDiagram-PLB6GJNP-BjoTwmZ-.js → requirementDiagram-PLB6GJNP-B8xGM6w4.js} +1 -1
  48. package/dist/assets/{sankeyDiagram-IPEJSGJF-CuGyR0Tn.js → sankeyDiagram-IPEJSGJF-BgTSlqMg.js} +1 -1
  49. package/dist/assets/{sequenceDiagram-PO4LG4MO-DxOzUuSx.js → sequenceDiagram-PO4LG4MO-B1J4EIne.js} +1 -1
  50. package/dist/assets/{sizeCapture-INFHLROL-B-bTrmx9.js → sizeCapture-INFHLROL-Cpcjc5oE.js} +1 -1
  51. package/dist/assets/{stateDiagram-v2-GCMORJYK-D6ZflrZQ.js → stateDiagram-v2-GCMORJYK-CtQKYLT4.js} +1 -1
  52. package/dist/assets/{swimlanes-2SLR337P-DKgdDJlH.js → swimlanes-2SLR337P-DpIk02zs.js} +1 -1
  53. package/dist/assets/swimlanesDiagram-TC7HE7FX-DPTl4zVS.js +8 -0
  54. package/dist/assets/{timeline-definition-EJHVYXUP-Dli4hqxc.js → timeline-definition-EJHVYXUP-DsA7dQhy.js} +1 -1
  55. package/dist/assets/{usecaseDiagram-POWQR4AR-CQ8Cc1rN.js → usecaseDiagram-POWQR4AR-BM42_rDz.js} +1 -1
  56. package/dist/assets/{vennDiagram-UO4OBE2U-JEu7ZkzA.js → vennDiagram-UO4OBE2U-DgLtqgJF.js} +1 -1
  57. package/dist/assets/{wardleyDiagram-VNRHLVJA-DkFigbd0.js → wardleyDiagram-VNRHLVJA-BKUUTKBJ.js} +1 -1
  58. package/dist/assets/{xychartDiagram-PMCCYNJV-DwOctln8.js → xychartDiagram-PMCCYNJV-B9RWvizV.js} +1 -1
  59. package/dist/index.html +1 -1
  60. package/dist-server/accounts-proxy.js +12 -2
  61. package/dist-server/browser-proxy.js +15 -2
  62. package/dist-server/drivers/phone-proxy.js +13 -4
  63. package/dist-server/index.js +3168 -2730
  64. package/dist-server/openmausbot.js +821 -638
  65. package/dist-server/pair-cli.js +821 -638
  66. package/dist-server/server/accounts-proxy.js +17 -2
  67. package/dist-server/server/agents-token-file.js +10 -7
  68. package/dist-server/server/browser-proxy.js +18 -2
  69. package/dist-server/server/connection-cap-failover.js +8 -4
  70. package/dist-server/server/drivers/acp/core.js +20 -47
  71. package/dist-server/server/drivers/acp/custom.js +5 -0
  72. package/dist-server/server/drivers/acp/hermes.js +1 -0
  73. package/dist-server/server/drivers/acp/kimi-turn-failure.js +68 -0
  74. package/dist-server/server/drivers/acp/kimi.js +7 -0
  75. package/dist-server/server/drivers/acp/mcp-limit.js +47 -0
  76. package/dist-server/server/drivers/acp/rpc-error.js +35 -0
  77. package/dist-server/server/drivers/acp/setup-failure.js +9 -0
  78. package/dist-server/server/drivers/acp/vibe.js +11 -5
  79. package/dist-server/server/drivers/chat-text-only.js +47 -0
  80. package/dist-server/server/drivers/openai-chat-protocol.js +15 -0
  81. package/dist-server/server/drivers/openai-chat.js +8 -18
  82. package/dist-server/server/drivers/phone-proxy.js +18 -4
  83. package/dist-server/server/drivers/turn-mcp.js +3 -0
  84. package/dist-server/server/drivers/vibe-login.js +17 -8
  85. package/dist-server/server/engine-failover.js +16 -24
  86. package/dist-server/server/engine-failure.js +3 -3
  87. package/dist-server/server/engine-rest.js +5 -3
  88. package/dist-server/server/engine-tiers.js +12 -9
  89. package/dist-server/server/harness/bus.js +7 -2
  90. package/dist-server/server/index.js +19 -18
  91. package/dist-server/server/injected-model-rest.js +17 -0
  92. package/dist-server/server/model-levels/aliases.js +243 -38
  93. package/dist-server/server/model-levels/chibitek-rankings.js +8 -8
  94. package/dist-server/server/model-levels/classes.js +106 -38
  95. package/dist-server/server/model-levels/index.js +26 -14
  96. package/dist-server/server/model-levels/model-ids.js +91 -0
  97. package/dist-server/server/model-levels/overrides.js +7 -4
  98. package/dist-server/server/model-levels/sources.js +4 -1
  99. package/dist-server/server/pay-per-use.js +13 -1
  100. package/package.json +1 -1
  101. package/dist/assets/channel-D3ihDYTR.js +0 -1
  102. package/dist/assets/swimlanesDiagram-TC7HE7FX-DSlLxTUH.js +0 -8
@@ -5,24 +5,10 @@ import { toolDetailPreview } from "../tool-summary.js";
5
5
  import { ChatToolSessionError, mountChatTools } from "./chat-mcp-tools.js";
6
6
  import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent } from "./chat-images.js";
7
7
  import { createChatToolApproval } from "./chat-tool-approval.js";
8
- import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, MAX_CHAT_TOOL_CALLS, object } from "./openai-chat-protocol.js";
8
+ import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, MAX_CHAT_TOOL_CALLS, object, providerError } from "./openai-chat-protocol.js";
9
+ import { hasImageParts, learnTextOnly, sendableMessages } from "./chat-text-only.js";
9
10
  import { appendNative } from "./native.js";
10
11
  import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS } from "./retry.js";
11
- /** The message of a JSON error body a provider returned with HTTP 200.
12
- * MiniMax reports auth, balance, and parameter failures as `base_resp`. */
13
- function providerError(json) {
14
- if (typeof json.error === "string")
15
- return json.error;
16
- const error = object(json.error);
17
- if (error)
18
- return typeof error.message === "string" ? error.message : "unknown error";
19
- const code = json.base_resp?.status_code;
20
- if (typeof code === "number" && code !== 0) {
21
- const msg = typeof json.base_resp?.status_msg === "string" ? json.base_resp.status_msg : "";
22
- return `upstream error ${code}${msg ? `: ${msg}` : ""}`;
23
- }
24
- return null;
25
- }
26
12
  const usageFrom = (usage) => usage
27
13
  ? { input: usage.prompt_tokens ?? 0, output: usage.completion_tokens ?? 0 }
28
14
  : null;
@@ -59,18 +45,22 @@ export function createOpenAIChatRuntime(options) {
59
45
  const activeSignal = signal
60
46
  ? AbortSignal.any([signal, timeoutController.signal])
61
47
  : timeoutController.signal;
48
+ const sendable = sendableMessages(options.apiUrl, model, messages);
62
49
  const response = await fetch(`${options.apiUrl}/chat/completions`, {
63
50
  method: "POST",
64
- ...(messages.some(message => Array.isArray(message.content) && message.content.some(part => part.type === "image_url")) ? { redirect: "error" } : {}),
51
+ ...(hasImageParts(sendable) ? { redirect: "error" } : {}),
65
52
  headers: { ...options.extraHeaders, authorization: `Bearer ${options.apiKey}`, "content-type": "application/json" },
66
53
  body: JSON.stringify({
67
- ...options.requestBody(model, messages, stream),
54
+ ...options.requestBody(model, sendable, stream),
68
55
  ...(tools.length ? { tools } : {}),
69
56
  }),
70
57
  signal: activeSignal,
71
58
  });
72
59
  if (!response.ok) {
73
60
  const body = await response.text().catch(() => "");
61
+ // A text-only model refused the image parts: once more, with a note in their place.
62
+ if (learnTextOnly(options.apiUrl, model, response.status, body, sendable))
63
+ return await complete(messages, model, stream, signal, onDelta, tools, onIdentity);
74
64
  throw new Error(`${options.httpErrorLabel} HTTP ${response.status}${body ? `: ${body.slice(0, 200)}` : ""}`);
75
65
  }
76
66
  if (!stream || response.headers.get("content-type")?.includes("application/json")) {
@@ -1,7 +1,7 @@
1
1
  // First-party Android phone MCP server. It deliberately accepts physical USB
2
2
  // devices only: no emulators, wireless debugging, network ADB, or Tailscale.
3
3
  import { spawn } from "node:child_process";
4
- import { accessSync, constants, existsSync } from "node:fs";
4
+ import { accessSync, constants, existsSync, readFileSync } from "node:fs";
5
5
  import { createInterface } from "node:readline";
6
6
  import { delimiter, join } from "node:path";
7
7
  import { homedir } from "node:os";
@@ -252,18 +252,32 @@ const textResult = (text, isError = false) => ({ content: [{ type: "text", text
252
252
  // is idempotent; a blocked caller can retry once the holding turn settles.
253
253
  export function createPhoneClaim(env = process.env, fetchImpl = fetch) {
254
254
  const url = env.OMB_HARNESS_URL?.trim();
255
- const token = env.OMB_PHONE_TOKEN?.trim();
256
- if (!url || !token) {
255
+ const spawnToken = env.OMB_PHONE_TOKEN?.trim() ?? "";
256
+ const tokenFile = env.OMB_PHONE_TOKEN_FILE?.trim() ?? "";
257
+ if (!url || (!spawnToken && !tokenFile)) {
257
258
  // Spawned outside the harness (development, direct debugging): no
258
259
  // exclusivity to enforce, exactly the behavior this proxy always had.
259
260
  return async () => ({ ok: true });
260
261
  }
262
+ // Read per call: the harness rewrites the file each turn, and a pooled
263
+ // engine keeps this process across turns, so the spawn-time token is
264
+ // revoked by turn two.
265
+ const token = () => {
266
+ if (!tokenFile)
267
+ return spawnToken;
268
+ try {
269
+ return readFileSync(tokenFile, "utf8").trim() || spawnToken;
270
+ }
271
+ catch {
272
+ return spawnToken;
273
+ }
274
+ };
261
275
  return async () => {
262
276
  try {
263
277
  const response = await fetchImpl(new URL("/api/internal/phone/claim", url), {
264
278
  method: "POST",
265
279
  redirect: "error",
266
- headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
280
+ headers: { authorization: `Bearer ${token()}`, "content-type": "application/json" },
267
281
  body: "{}",
268
282
  signal: AbortSignal.timeout(10_000),
269
283
  });
@@ -1,4 +1,7 @@
1
1
  import { gateServer, resultBudget } from "../mcp-gate-config.js";
2
+ /** The names Atomic's own servers mount under (below); a person's server
3
+ * never takes one of them. */
4
+ export const ATOMIC_MCP_SERVERS = new Set(["agents", "atomic_accounts", "browser", "computer"]);
2
5
  export function turnMcpServers(turn) {
3
6
  const servers = [];
4
7
  const agents = turn.integrations?.agents;
@@ -29,14 +29,19 @@ export class VibeAcpClient {
29
29
  nextId = 1;
30
30
  buffer = "";
31
31
  closed = false;
32
+ /** The command was not found: nothing is installed to sign in to. */
33
+ missing = false;
32
34
  constructor(cli, env) {
33
35
  this.child = spawnCli(cli, [], { env, stdio: ["pipe", "pipe", "pipe"] });
34
36
  this.child.stderr?.resume();
35
37
  this.child.stdout?.on("data", (chunk) => this.receive(chunk.toString("utf8")));
36
38
  const fail = (message) => this.close(new Error(message));
37
- this.child.once("error", (error) => fail(error.code === "ENOENT"
38
- ? "Mistral Vibe is not installed on this computer. Install it, then try again."
39
- : "Mistral Vibe could not start on this computer. Check its install, then try again."));
39
+ this.child.once("error", (error) => {
40
+ this.missing = error.code === "ENOENT";
41
+ fail(this.missing
42
+ ? "Mistral Vibe is not installed on this computer. Install it, then try again."
43
+ : "Mistral Vibe could not start on this computer. Check its install, then try again.");
44
+ });
40
45
  this.child.once("close", () => fail("Mistral Vibe stopped before it answered. Update Vibe and try again."));
41
46
  }
42
47
  /** initialize, opting in to the delegated browser sign-in. */
@@ -126,27 +131,31 @@ export function vibeSignInFailure(error) {
126
131
  return error.message;
127
132
  return "Mistral Vibe sign-in did not finish. Check this computer's connection and that Vibe is up to date, then try again.";
128
133
  }
129
- /** Vibe's own answer to whether it can run a turn now. */
130
- export async function vibeSignedIn(cli, env, timeoutMs = 20_000) {
134
+ /** Vibe's own answer to whether it can run a turn now; `missing` when the
135
+ * command is not there to ask, which is not a sign-in problem. */
136
+ export async function vibeSignInState(cli, env, timeoutMs = 20_000) {
131
137
  let client;
132
138
  try {
133
139
  client = new VibeAcpClient(cli, env);
134
140
  }
135
141
  catch {
136
- return false;
142
+ return "signed-out";
137
143
  }
138
144
  try {
139
145
  await client.initialize(timeoutMs);
140
146
  const status = await client.request("_auth/status", {}, timeoutMs);
141
- return status?.authenticated === true;
147
+ return status?.authenticated === true ? "signed-in" : "signed-out";
142
148
  }
143
149
  catch {
144
- return false;
150
+ return client.missing ? "missing" : "signed-out";
145
151
  }
146
152
  finally {
147
153
  client.close();
148
154
  }
149
155
  }
156
+ export async function vibeSignedIn(cli, env, timeoutMs = 20_000) {
157
+ return (await vibeSignInState(cli, env, timeoutMs)) === "signed-in";
158
+ }
150
159
  export class VibeLoginController {
151
160
  flow = null;
152
161
  disposed = false;
@@ -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,23 +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
- }
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;
54
47
  const accountOf = (engine) => engine.snapshot.account?.email ?? engine.snapshot.account?.organization;
55
48
  /** Another instance of the same engine on the same account (or on none): it
56
49
  * sends a model down the route a failure just broke (two OpenCode instances
@@ -279,18 +272,17 @@ export function restingLine(engines, formatTime, computer, options = {}) {
279
272
  const unavailable = fresh(computer?.unavailable).map((label) => `${label} is unavailable`);
280
273
  const hint = listed.some((engine) => engine.keyExpired || engine.needsSignIn) || signedOut.length ? ` ${ACCOUNTS_HINT}` : "";
281
274
  const cannot = fresh(computer?.engines).map((label) => `${label} can't control ${computer.place}`);
282
- // 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
283
276
  // control the place at all; the passed-over engines are named either way.
284
277
  if (cannot.length || ((signedOut.length || unavailable.length) && !options.capped)) {
285
278
  return `No engine that can work on ${computer.place} is free, so this turn stopped: ${[...parts, ...signedOut, ...unavailable, ...cannot].join("; ")}.${hint}`;
286
279
  }
287
280
  parts.push(...signedOut, ...unavailable);
288
- // 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.
289
282
  if (options.capped) {
290
- const count = MAX_ENGINES_PER_TURN === 2 ? "two" : String(MAX_ENGINES_PER_TURN);
291
283
  return parts.length
292
- ? `This turn stopped after ${count} engines failed: ${parts.join(", ")}.${hint}`
293
- : `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.`;
294
286
  }
295
287
  if (parts.length === 0)
296
288
  return "No engine is available for this turn, so it stopped.";
@@ -49,7 +49,7 @@ const USAGE_LIMITED = [
49
49
  // Codex: "You've hit your usage limit. Upgrade to Pro ... or try again in 2 days 4 hours";
50
50
  // Cursor: "You've hit your usage limit for this month".
51
51
  /\busage limit\b/i,
52
- /\bhit your (?:\w+ )?limit\b/i,
52
+ /\bhit your (?:[\w-]+ )?limit\b/i, // \"hit your 5-hour limit · resets 3:50am\" (Claude Code, 2026-11-22)
53
53
  /\b(?:5-hour|five-hour|hourly|weekly|daily|monthly|session|opus|sonnet) (?:usage )?limit (?:reached|exceeded|hit)\b/i,
54
54
  /\blimit reached\b[^.]*\breset/i,
55
55
  // OpenAI API: "You exceeded your current quota, please check your plan and billing details." (insufficient_quota);
@@ -60,7 +60,7 @@ const USAGE_LIMITED = [
60
60
  /\bplan limit\b|\blimit (?:of|for) your (?:plan|subscription)\b/i,
61
61
  // Anthropic API: "Your credit balance is too low to access the Anthropic API."
62
62
  // xAI: "Your team ... has either used all available credits or reached its monthly spending limit."
63
- /\bcredit balance (?:is )?too low\b|\binsufficient (?:\w+ )?(?:credits?|balance|funds)\b|\b(?:out|run out) of credits\b/i,
63
+ /\bcredit balance (?:is )?too low\b|\binsufficient (?:\w+ )?(?:credits?|balance|funds)\b|\b(?:out|run out) of (?:usage )?credits\b/i,
64
64
  /\bused all (?:available |of your )?credits\b|\bno credits? (?:left|remaining)\b|\bspending limit\b/i,
65
65
  /\bexhausted your (?:\w+ )?quota\b/i,
66
66
  /\bquota\b[^.]{0,60}\b(?:exceeded|exhausted|reached|used up)\b|\b(?:exceeded|exhausted|reached)\b[^.]{0,40}\bquota\b/i,
@@ -121,7 +121,7 @@ const AUTH_FAILED = [
121
121
  // the message and the turn was stopped." Drivers tag it structurally
122
122
  // (runtime.error failure "stalled"); this reads the text form too.
123
123
  const STALLED = [
124
- /\bwent fully silent\b[^.]{0,80}\bturn was stopped\b/i,
124
+ /\bwent fully silent\b[^.]{0,80}\bturn was stopped\b|\bGateway inaccessible\b/i, // the second: Hermes `acp` could not reach or start its gateway service, so it is not responding (2026-11-22)
125
125
  ];
126
126
  // OpenCode's ACP answer when its provider's API returned a bare 400: the
127
127
  // JSON-RPC internal error with the provider's status text and nothing else,
@@ -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);
@@ -181,6 +182,7 @@ export class EngineRestStore {
181
182
  instanceId, ...(scope ? { scope } : {}), ...(account ? { account } : {}), reason, since: active?.since ?? now,
182
183
  until: restUntil, count,
183
184
  ...(reason === "auth_failed" ? { needsSignIn: true } : {}),
185
+ ...(detail.setup ? { setup: true } : {}),
184
186
  ...(keyExpired ? { keyExpired: true } : {}),
185
187
  ...(reason === "auth_failed" && detail.reportedSignedIn !== undefined ? { reportedSignedIn: detail.reportedSignedIn } : {}),
186
188
  ...(reason === "auth_failed" && active?.sawSignedOut ? { sawSignedOut: true } : {}),
@@ -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);
@@ -16,6 +16,9 @@ export class EventBus {
16
16
  gate = null;
17
17
  unsubscribes = new Map();
18
18
  pendingLogWarnings = new Map();
19
+ /** Events already in the canonical log: a held event released later by the
20
+ * gate is the same object, logged once. */
21
+ recorded = new WeakSet();
19
22
  appendLog;
20
23
  constructor(appendLog = appendFileSync) {
21
24
  this.appendLog = appendLog;
@@ -44,12 +47,14 @@ export class EventBus {
44
47
  this.record(event);
45
48
  const deliveries = this.gate ? this.gate(event) : [event];
46
49
  for (const delivery of deliveries) {
47
- if (delivery !== event)
48
- this.record(delivery);
50
+ this.record(delivery);
49
51
  this.deliver(delivery);
50
52
  }
51
53
  }
52
54
  record(event) {
55
+ if (this.recorded.has(event))
56
+ return;
57
+ this.recorded.add(event);
53
58
  const pendingWarning = this.pendingLogWarnings.get(event.threadId);
54
59
  const persistedEvents = pendingWarning ? [pendingWarning, redactSecrets(event)] : [redactSecrets(event)];
55
60
  try {
@@ -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, 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";
@@ -2094,7 +2094,7 @@ async function browserIntegration(botId, profile, turn) {
2094
2094
  kind: "browser", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 });
2095
2095
  return { profile: partitionId, session, spec, integration: {
2096
2096
  command: process.execPath, args: [SPAWNED_PROXIES.browser], env: {
2097
- ...AGENTS_NODE_FLAG, OMB_BROWSER_TOKEN: token, OMB_HARNESS_URL: `http://127.0.0.1:${PORT}`,
2097
+ ...AGENTS_NODE_FLAG, OMB_BROWSER_TOKEN: token, OMB_BROWSER_TOKEN_FILE: writeAgentsTokenFile(botId, turn.threadId, token, undefined, "browser"), OMB_HARNESS_URL: `http://127.0.0.1:${PORT}`,
2098
2098
  },
2099
2099
  } };
2100
2100
  }
@@ -2125,7 +2125,7 @@ function phoneIntegration(botId, threadId, generation) {
2125
2125
  });
2126
2126
  const env = {
2127
2127
  ...AGENTS_NODE_FLAG,
2128
- OMB_PHONE_TOKEN: token,
2128
+ OMB_PHONE_TOKEN: token, OMB_PHONE_TOKEN_FILE: writeAgentsTokenFile(botId, threadId, token, undefined, "phone"),
2129
2129
  OMB_HARNESS_URL: `http://127.0.0.1:${PORT}`,
2130
2130
  };
2131
2131
  if (process.env.OMB_ADB_PATH)
@@ -2153,7 +2153,7 @@ function accountsIntegration(botId, threadId, generation) {
2153
2153
  return {
2154
2154
  command: process.execPath,
2155
2155
  args: [SPAWNED_PROXIES.accounts],
2156
- env: { ...AGENTS_NODE_FLAG, OMB_ACCOUNTS_TOKEN: token, OMB_HARNESS_URL: `http://127.0.0.1:${PORT}` },
2156
+ env: { ...AGENTS_NODE_FLAG, OMB_ACCOUNTS_TOKEN: token, OMB_ACCOUNTS_TOKEN_FILE: writeAgentsTokenFile(botId, threadId, token, undefined, "accounts"), OMB_HARNESS_URL: `http://127.0.0.1:${PORT}` },
2157
2157
  readOnlyTools: ACCOUNT_TOOLS.filter((tool) => isReadOnlyAccountTool(tool.name)).map((tool) => tool.name),
2158
2158
  askTools: ACCOUNT_TOOLS.filter((tool) => !isReadOnlyAccountTool(tool.name)).map((tool) => tool.name),
2159
2159
  };
@@ -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,9 +3651,9 @@ 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
- ...(failure.permanent ? { permanent: true } : {}), ...(scope ? { scope } : {}), ...(ran?.model ? { model: ran.model } : {}),
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 } : {}) });
3657
3658
  // Unknown failures rest only when the turn moves; otherwise preserve their report.
3658
3659
  const rest = failure.kind === "provider_error" || failure.kind === "rate_limited" ? undefined : restFailed();
@@ -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, needsPerson) || !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, needsPerson) || !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, needsPerson) || !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) => !needsPerson(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
+ }