@chibitek/chibi 0.1.209 → 0.1.211

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 (155) hide show
  1. package/dist/assets/{TerminalPanel-CHGq3udb.js → TerminalPanel-Dro3aeVy.js} +1 -1
  2. package/dist/assets/{abnfDiagram-O67JEVCF-BMaKhJ-b.js → abnfDiagram-O67JEVCF-kzAr7vQ8.js} +1 -1
  3. package/dist/assets/{arc-CYAiNWN8.js → arc-DKMhcYud.js} +1 -1
  4. package/dist/assets/{architectureDiagram-NJMV4G6O-CxJFFlbO.js → architectureDiagram-NJMV4G6O-_XDnZ7Jz.js} +1 -1
  5. package/dist/assets/{blockDiagram-BEXU5L5S-C7AbPjRB.js → blockDiagram-BEXU5L5S-D5MoWro9.js} +1 -1
  6. package/dist/assets/{c4Diagram-YGBWAQC7-DfVnCJmT.js → c4Diagram-YGBWAQC7-CGvTMpGE.js} +1 -1
  7. package/dist/assets/channel-YcZdlysP.js +1 -0
  8. package/dist/assets/{chunk-2Q5K7J3B-CzAUFkgv.js → chunk-2Q5K7J3B-pjTwr5y0.js} +1 -1
  9. package/dist/assets/{chunk-3FUC2YCW-BgeBXphm.js → chunk-3FUC2YCW-BR6zkd-l.js} +2 -2
  10. package/dist/assets/{chunk-5VM5RSS4-DPRdTAXc.js → chunk-5VM5RSS4-CfVFFBeH.js} +1 -1
  11. package/dist/assets/{chunk-GTNCS2PH-BS-_dIVl.js → chunk-GTNCS2PH-TIoAkccw.js} +1 -1
  12. package/dist/assets/{chunk-GWA4HPMP-D6I7xMmd.js → chunk-GWA4HPMP-BNFBgzbt.js} +1 -1
  13. package/dist/assets/{chunk-JWPE2WC7-BKSKe7C9.js → chunk-JWPE2WC7-B_3QFchU.js} +1 -1
  14. package/dist/assets/{chunk-NETBCI7D-R48UYTRN.js → chunk-NETBCI7D-Cj9q80P-.js} +1 -1
  15. package/dist/assets/{chunk-WEXAMYUT-C8z4mL-2.js → chunk-WEXAMYUT-DFZPGo9K.js} +1 -1
  16. package/dist/assets/{chunk-XXDRQBXY-Bml3ZRJ5.js → chunk-XXDRQBXY-CekDrT9T.js} +1 -1
  17. package/dist/assets/{classDiagram-v2-NBCMYWYE-w5wo22FO.js → classDiagram-v2-NBCMYWYE-C3R6Z4Qe.js} +1 -1
  18. package/dist/assets/{cose-bilkent-JH36ORCC-Cum9v--4.js → cose-bilkent-JH36ORCC-C1CKyj0L.js} +1 -1
  19. package/dist/assets/{cynefin-OW5HDTMX-BzN0-KsP.js → cynefin-OW5HDTMX-Deh9QGb0.js} +1 -1
  20. package/dist/assets/{cynefinDiagram-VND7K2PF-CkOpm32D.js → cynefinDiagram-VND7K2PF-BIlWyG_M.js} +1 -1
  21. package/dist/assets/{dagre-6A5THRUB-BItQkKZD.js → dagre-6A5THRUB-Dx4bWOog.js} +1 -1
  22. package/dist/assets/{diagram-22UHCM2B-BI0zDn7c.js → diagram-22UHCM2B-DPxb-FUO.js} +1 -1
  23. package/dist/assets/{diagram-3UASUU5V-jwcDxsu6.js → diagram-3UASUU5V-BLPCNc4m.js} +1 -1
  24. package/dist/assets/{diagram-ATOU4E4O-2RnY9egJ.js → diagram-ATOU4E4O-DOCbp2Dw.js} +1 -1
  25. package/dist/assets/{diagram-CDSNMT55-eVdEZmEF.js → diagram-CDSNMT55-62uSG-tn.js} +1 -1
  26. package/dist/assets/{diagram-MLGK6HIB-BCDGCJJ0.js → diagram-MLGK6HIB-De1ZAWVZ.js} +1 -1
  27. package/dist/assets/{diagram-MPIPVDR6-DtN5uO5w.js → diagram-MPIPVDR6-CIGX9tku.js} +1 -1
  28. package/dist/assets/{ebnfDiagram-ZINNZB2B-B9GpXSEs.js → ebnfDiagram-ZINNZB2B-CegjStdk.js} +1 -1
  29. package/dist/assets/{elk-276RUBZZ-Bk_eaK4T.js → elk-276RUBZZ-ClI52Pqm.js} +1 -1
  30. package/dist/assets/{erDiagram-OPXOYQCR-BiGoW6C6.js → erDiagram-OPXOYQCR-BQuzjt2-.js} +1 -1
  31. package/dist/assets/{flowDiagram-KWPJA3E3-ZW5w0BaJ.js → flowDiagram-KWPJA3E3-D1xbKgbB.js} +1 -1
  32. package/dist/assets/{ganttDiagram-FUAMR5RP-yyrKgsx1.js → ganttDiagram-FUAMR5RP-CH1jGSZz.js} +1 -1
  33. package/dist/assets/{gitGraphDiagram-X574FWY7-CeiDikzD.js → gitGraphDiagram-X574FWY7-BvAUPEmQ.js} +1 -1
  34. package/dist/assets/{index-CZGnshrJ.js → index-BcXDfnlQ.js} +197 -197
  35. package/dist/assets/{index-DUFlRZuA.js → index-DbkR_erP.js} +1 -1
  36. package/dist/assets/index-H8vkXbLq.css +1 -0
  37. package/dist/assets/{infoDiagram-VRGFBTTK-q2B-KJFm.js → infoDiagram-VRGFBTTK-CyMmMbMv.js} +1 -1
  38. package/dist/assets/{ishikawaDiagram-OU5B5YK6-D8gXFuc0.js → ishikawaDiagram-OU5B5YK6-Uw-hE1tO.js} +1 -1
  39. package/dist/assets/{journeyDiagram-ZHPQQLJL-BmHL2mbq.js → journeyDiagram-ZHPQQLJL-ClEDnNRB.js} +1 -1
  40. package/dist/assets/{kanban-definition-PNTS6WVX-B9Ll2WkA.js → kanban-definition-PNTS6WVX-erx0BEal.js} +1 -1
  41. package/dist/assets/{linear-CMVGYrKx.js → linear-CSSxpyL0.js} +1 -1
  42. package/dist/assets/{mermaid.core-qO11n1kV.js → mermaid.core-n13K6vlC.js} +5 -5
  43. package/dist/assets/{mindmap-definition-NLK3R4M7-CxLGFX45.js → mindmap-definition-NLK3R4M7-BcTEIqpD.js} +1 -1
  44. package/dist/assets/{pegDiagram-GJSIUBJH-CxK1MJG4.js → pegDiagram-GJSIUBJH-CJdsm3en.js} +1 -1
  45. package/dist/assets/{pieDiagram-5QR66LMP-H5jiF5Eu.js → pieDiagram-5QR66LMP-C7rk-ash.js} +1 -1
  46. package/dist/assets/{quadrantDiagram-O4NWA36T-CKaqCruv.js → quadrantDiagram-O4NWA36T-BSXOYov0.js} +1 -1
  47. package/dist/assets/{railroadDiagram-XR7U4H2S-BCzKiQOd.js → railroadDiagram-XR7U4H2S-Cmg_FtZY.js} +1 -1
  48. package/dist/assets/{requirementDiagram-PLB6GJNP-Cqtr43DT.js → requirementDiagram-PLB6GJNP-B_9aE6Mg.js} +1 -1
  49. package/dist/assets/{sankeyDiagram-IPEJSGJF-B2tQewX8.js → sankeyDiagram-IPEJSGJF-DyxaQPy3.js} +1 -1
  50. package/dist/assets/{sequenceDiagram-PO4LG4MO-nggwQyrw.js → sequenceDiagram-PO4LG4MO-D5CJeESq.js} +1 -1
  51. package/dist/assets/{sizeCapture-INFHLROL-qSPXJBv2.js → sizeCapture-INFHLROL-9-Q4eosQ.js} +1 -1
  52. package/dist/assets/{stateDiagram-v2-GCMORJYK-DraPbL2T.js → stateDiagram-v2-GCMORJYK-jgsHnEQl.js} +1 -1
  53. package/dist/assets/{swimlanes-2SLR337P-C6HVkIDA.js → swimlanes-2SLR337P-MIVacUbv.js} +1 -1
  54. package/dist/assets/swimlanesDiagram-TC7HE7FX-Dekwo1KL.js +8 -0
  55. package/dist/assets/{timeline-definition-EJHVYXUP-DZmPRTsx.js → timeline-definition-EJHVYXUP-Ch8ins-D.js} +1 -1
  56. package/dist/assets/{usecaseDiagram-POWQR4AR-CsVuROW_.js → usecaseDiagram-POWQR4AR-BDwBIuhZ.js} +1 -1
  57. package/dist/assets/{vennDiagram-UO4OBE2U-B9IRbuhp.js → vennDiagram-UO4OBE2U-BiiDxcHO.js} +1 -1
  58. package/dist/assets/{wardleyDiagram-VNRHLVJA-CGmVK53n.js → wardleyDiagram-VNRHLVJA-D79CK2__.js} +1 -1
  59. package/dist/assets/{xychartDiagram-PMCCYNJV-BAw-x9Y1.js → xychartDiagram-PMCCYNJV-CI7S0o-6.js} +1 -1
  60. package/dist/index.html +4 -2
  61. package/dist-server/accounts-proxy.js +19 -12
  62. package/dist-server/browser-proxy.js +19 -14
  63. package/dist-server/container-mcp.js +165 -93
  64. package/dist-server/drivers/agents-proxy.js +109 -94
  65. package/dist-server/drivers/phone-proxy.js +21 -13
  66. package/dist-server/index.js +6487 -4926
  67. package/dist-server/local-computer-proxy.js +77 -11
  68. package/dist-server/local-computer.js +2 -1
  69. package/dist-server/mcp-gate.js +53 -4
  70. package/dist-server/mcp-server.js +1 -1
  71. package/dist-server/openmausbot.js +1068 -642
  72. package/dist-server/pair-cli.js +1068 -642
  73. package/dist-server/server/accounts-proxy.js +3 -17
  74. package/dist-server/server/atomic-engine-release.js +7 -0
  75. package/dist-server/server/auto-approve.js +12 -0
  76. package/dist-server/server/browser-proxy.js +3 -17
  77. package/dist-server/server/child-env.js +79 -0
  78. package/dist-server/server/config.js +11 -5
  79. package/dist-server/server/container-computer.js +1 -1
  80. package/dist-server/server/container-mcp.js +3 -2
  81. package/dist-server/server/control-client.js +7 -6
  82. package/dist-server/server/delegated-full-access.js +98 -0
  83. package/dist-server/server/desktop-loopback-gate.js +57 -0
  84. package/dist-server/server/drivers/acp/core.js +4 -4
  85. package/dist-server/server/drivers/acp/custom.js +3 -1
  86. package/dist-server/server/drivers/acp/hermes.js +2 -1
  87. package/dist-server/server/drivers/acp/session-key.js +8 -0
  88. package/dist-server/server/drivers/agents-client.js +2 -14
  89. package/dist-server/server/drivers/gcloud-token.js +28 -0
  90. package/dist-server/server/drivers/github-copilot.js +152 -0
  91. package/dist-server/server/drivers/hermes-context-floor.js +68 -0
  92. package/dist-server/server/drivers/openai-chat-protocol.js +8 -0
  93. package/dist-server/server/drivers/openai-chat.js +10 -8
  94. package/dist-server/server/drivers/openai-compat.js +44 -9
  95. package/dist-server/server/drivers/phone-proxy.js +5 -18
  96. package/dist-server/server/engine-tiers.js +9 -9
  97. package/dist-server/server/god-mode-goal.js +78 -0
  98. package/dist-server/server/god-mode-run-host.js +69 -0
  99. package/dist-server/server/harness/http.js +47 -1
  100. package/dist-server/server/index.js +86 -86
  101. package/dist-server/server/ladder-pick.js +18 -0
  102. package/dist-server/server/local-computer-proxy.js +3 -2
  103. package/dist-server/server/local-computer.js +1 -0
  104. package/dist-server/server/mcp-bridge.js +3 -2
  105. package/dist-server/server/mcp-gate.js +2 -1
  106. package/dist-server/server/mcp-registry.js +5 -1
  107. package/dist-server/server/model-fallback-repair.js +20 -0
  108. package/dist-server/server/model-gateway/failover.js +4 -1
  109. package/dist-server/server/model-gateway/route.js +64 -14
  110. package/dist-server/server/model-gateway/usage.js +66 -0
  111. package/dist-server/server/model-levels/aa-scale.js +42 -0
  112. package/dist-server/server/model-levels/aliases.js +16 -3
  113. package/dist-server/server/model-levels/index.js +8 -3
  114. package/dist-server/server/model-levels/rankings-build.js +76 -0
  115. package/dist-server/server/model-prices.js +6 -0
  116. package/dist-server/server/nexus-memory/index.js +5 -13
  117. package/dist-server/server/nexus-memory/policy.js +5 -17
  118. package/dist-server/server/oauth-account-vault.js +7 -2
  119. package/dist-server/server/personal-goal-runtime.js +29 -3
  120. package/dist-server/server/personal-goal-turn.js +2 -1
  121. package/dist-server/server/personal-goals.js +20 -2
  122. package/dist-server/server/provider-accounts.js +20 -1
  123. package/dist-server/server/provider-key-check.js +31 -1
  124. package/dist-server/server/registry-load.js +88 -0
  125. package/dist-server/server/request-auth.js +6 -28
  126. package/dist-server/server/routes/provider-accounts.js +124 -6
  127. package/dist-server/server/routine-daily-schedule.js +20 -0
  128. package/dist-server/server/routine-prompt-escape.js +18 -0
  129. package/dist-server/server/routine-tick-guard.js +16 -0
  130. package/dist-server/server/routine-tool-problems.js +36 -0
  131. package/dist-server/server/routines.js +36 -38
  132. package/dist-server/server/shutdown-triggers.js +18 -0
  133. package/dist-server/server/spend.js +23 -13
  134. package/dist-server/server/store.js +4 -13
  135. package/dist-server/server/terminal.js +2 -1
  136. package/dist-server/server/turn-token-file.js +79 -0
  137. package/dist-server/server/turn-token.js +23 -0
  138. package/dist-server/server/vps-container-mcp.js +3 -2
  139. package/dist-server/server/webhook-ingress.js +11 -1
  140. package/dist-server/server/webhook-prompt.js +82 -0
  141. package/dist-server/server/webhooks.js +8 -65
  142. package/dist-server/server/workspace-backup-policy.js +3 -3
  143. package/dist-server/server/workspace-backup.js +1 -1
  144. package/dist-server/server/workspace-time-zone.js +47 -0
  145. package/dist-server/shared/engine-choices.js +12 -1
  146. package/dist-server/shared/god-mode-run.js +173 -0
  147. package/dist-server/shared/personal-goal.js +42 -0
  148. package/dist-server/shared/provider-accounts.js +114 -2
  149. package/dist-server/shared/zoned-time.js +55 -0
  150. package/dist-server/vps-container-mcp.js +165 -93
  151. package/package.json +1 -1
  152. package/dist/assets/channel-DxL_mLhm.js +0 -1
  153. package/dist/assets/index-Bi3hprmz.css +0 -1
  154. package/dist/assets/swimlanesDiagram-TC7HE7FX-gQUGsELo.js +0 -8
  155. package/dist-server/server/agents-token-file.js +0 -26
@@ -0,0 +1,152 @@
1
+ export const COPILOT_CLIENT_ID_ENV = "ATOMIC_GITHUB_COPILOT_CLIENT_ID";
2
+ const DEFAULT_CLIENT_ID = "Iv1.b507a08c87ecfe98";
3
+ export const COPILOT_DEFAULT_API = "https://api.githubcopilot.com";
4
+ const GITHUB = "https://github.com";
5
+ const GITHUB_API = "https://api.github.com";
6
+ /** A Copilot token is renewed this long before GitHub says it expires. */
7
+ const RENEW_EARLY_MS = 5 * 60_000;
8
+ /** The integration headers the Copilot API requires on every request; a
9
+ * Copilot token is scoped to the integration it was minted for. */
10
+ export const COPILOT_HEADERS = Object.freeze({
11
+ "editor-version": "vscode/1.99.0",
12
+ "editor-plugin-version": "copilot-chat/0.26.0",
13
+ "copilot-integration-id": "vscode-chat",
14
+ "user-agent": "GitHubCopilotChat/0.26.0",
15
+ "openai-intent": "conversation-panel",
16
+ });
17
+ export function copilotClientId(env = process.env) {
18
+ return env[COPILOT_CLIENT_ID_ENV]?.trim() || DEFAULT_CLIENT_ID;
19
+ }
20
+ export async function startCopilotDeviceSignIn(fetchImpl = fetch, env = process.env) {
21
+ const response = await fetchImpl(`${GITHUB}/login/device/code`, {
22
+ method: "POST",
23
+ headers: { accept: "application/json", "content-type": "application/json" },
24
+ body: JSON.stringify({ client_id: copilotClientId(env), scope: "read:user" }),
25
+ redirect: "error",
26
+ signal: AbortSignal.timeout(10_000),
27
+ });
28
+ if (!response.ok)
29
+ throw new Error(`GitHub did not start the sign-in (HTTP ${response.status}).`);
30
+ const body = await response.json();
31
+ const deviceCode = typeof body.device_code === "string" ? body.device_code : "";
32
+ const userCode = typeof body.user_code === "string" ? body.user_code : "";
33
+ const verificationUri = typeof body.verification_uri === "string" ? body.verification_uri : "";
34
+ if (!deviceCode || !userCode || !verificationUri.startsWith("https://github.com/")) {
35
+ throw new Error("GitHub gave an unexpected answer when starting the sign-in.");
36
+ }
37
+ return {
38
+ deviceCode, userCode, verificationUri,
39
+ interval: typeof body.interval === "number" && body.interval > 0 ? body.interval : 5,
40
+ expiresIn: typeof body.expires_in === "number" && body.expires_in > 0 ? body.expires_in : 900,
41
+ };
42
+ }
43
+ /** One poll of the device code (RFC 8628). */
44
+ export async function pollCopilotDeviceSignIn(deviceCode, fetchImpl = fetch, env = process.env) {
45
+ let response;
46
+ try {
47
+ response = await fetchImpl(`${GITHUB}/login/oauth/access_token`, {
48
+ method: "POST",
49
+ headers: { accept: "application/json", "content-type": "application/json" },
50
+ body: JSON.stringify({ client_id: copilotClientId(env), device_code: deviceCode, grant_type: "urn:ietf:params:oauth:grant-type:device_code" }),
51
+ redirect: "error",
52
+ signal: AbortSignal.timeout(10_000),
53
+ });
54
+ }
55
+ catch {
56
+ return { state: "pending" }; // a dropped poll is retried on the next tick
57
+ }
58
+ if (!response.ok)
59
+ return { state: "failed", reason: "unexpected" };
60
+ const body = await response.json().catch(() => null);
61
+ if (typeof body?.access_token === "string" && body.access_token)
62
+ return { state: "done", token: body.access_token };
63
+ switch (body?.error) {
64
+ case "authorization_pending": return { state: "pending" };
65
+ case "slow_down": return { state: "pending", interval: typeof body.interval === "number" ? body.interval : undefined };
66
+ case "access_denied": return { state: "failed", reason: "denied" };
67
+ case "expired_token": return { state: "failed", reason: "expired" };
68
+ default: return { state: "failed", reason: "unexpected" };
69
+ }
70
+ }
71
+ export class CopilotAuthError extends Error {
72
+ status;
73
+ constructor(message, status) {
74
+ super(message);
75
+ this.status = status;
76
+ }
77
+ }
78
+ export const COPILOT_NO_PLAN = "This GitHub account has no active Copilot plan. Check github.com/settings/copilot, then sign in again.";
79
+ export const COPILOT_SIGNED_OUT = "GitHub Copilot is signed out. Sign in again in Settings > AI & accounts > Subscriptions.";
80
+ /** Trade a GitHub token for a Copilot token. */
81
+ export async function exchangeCopilotToken(githubToken, fetchImpl = fetch, now = Date.now()) {
82
+ let response;
83
+ try {
84
+ response = await fetchImpl(`${GITHUB_API}/copilot_internal/v2/token`, {
85
+ headers: { ...COPILOT_HEADERS, accept: "application/json", authorization: `token ${githubToken}` },
86
+ redirect: "error",
87
+ signal: AbortSignal.timeout(10_000),
88
+ });
89
+ }
90
+ catch {
91
+ throw new CopilotAuthError("Could not reach GitHub to renew the Copilot sign-in.");
92
+ }
93
+ if (response.status === 401)
94
+ throw new CopilotAuthError(COPILOT_SIGNED_OUT, 401);
95
+ if (response.status === 403 || response.status === 404)
96
+ throw new CopilotAuthError(COPILOT_NO_PLAN, response.status);
97
+ if (!response.ok)
98
+ throw new CopilotAuthError(`GitHub could not renew the Copilot sign-in (HTTP ${response.status}).`, response.status);
99
+ const body = await response.json().catch(() => null);
100
+ const token = typeof body?.token === "string" ? body.token : "";
101
+ if (!token)
102
+ throw new CopilotAuthError("GitHub gave an unexpected answer when renewing the Copilot sign-in.");
103
+ const endpoints = body?.endpoints && typeof body.endpoints === "object" ? body.endpoints : {};
104
+ const api = typeof endpoints.api === "string" && /^https:\/\/[a-z0-9.-]+\.githubcopilot\.com\/?$/i.test(endpoints.api)
105
+ ? endpoints.api.replace(/\/+$/, "") : COPILOT_DEFAULT_API;
106
+ const expiresAt = typeof body?.expires_at === "number" ? body.expires_at * 1000 : now + 25 * 60_000;
107
+ return { token, apiUrl: api, expiresAt };
108
+ }
109
+ /** One account's Copilot token, renewed only when it is close to expiring;
110
+ * concurrent turns share one renewal. */
111
+ export function copilotSessionCache(githubToken, fetchImpl = fetch, clock = Date.now) {
112
+ let current;
113
+ let pending;
114
+ return async () => {
115
+ if (current && current.expiresAt - RENEW_EARLY_MS > clock())
116
+ return current;
117
+ pending ??= exchangeCopilotToken(githubToken, fetchImpl, clock()).then((session) => {
118
+ current = session;
119
+ return session;
120
+ }).finally(() => { pending = undefined; });
121
+ return pending;
122
+ };
123
+ }
124
+ /** The chat models a Copilot plan offers (GET <api>/models): those the
125
+ * Copilot model picker shows and the plan has not switched off. */
126
+ export async function fetchCopilotModels(session, fetchImpl = fetch) {
127
+ const response = await fetchImpl(`${session.apiUrl}/models`, {
128
+ headers: { ...COPILOT_HEADERS, authorization: `Bearer ${session.token}` },
129
+ redirect: "error",
130
+ signal: AbortSignal.timeout(8_000),
131
+ });
132
+ if (!response.ok)
133
+ return [];
134
+ const json = await response.json().catch(() => null);
135
+ const rows = Array.isArray(json?.data) ? json.data : [];
136
+ const seen = new Set();
137
+ const options = [];
138
+ for (const row of rows) {
139
+ const id = typeof row.id === "string" ? row.id : "";
140
+ const capabilities = row.capabilities && typeof row.capabilities === "object" ? row.capabilities : {};
141
+ const policy = row.policy && typeof row.policy === "object" ? row.policy : {};
142
+ if (!id || seen.has(id))
143
+ continue;
144
+ if (capabilities.type !== undefined && capabilities.type !== "chat")
145
+ continue;
146
+ if (row.model_picker_enabled === false || policy.state === "disabled")
147
+ continue;
148
+ seen.add(id);
149
+ options.push({ id, label: typeof row.name === "string" && row.name.trim() ? row.name : id, custom: true });
150
+ }
151
+ return options;
152
+ }
@@ -0,0 +1,68 @@
1
+ // Hermes, and Atomic Engine built on it, refuses a model whose context
2
+ // window is under 64,000 tokens (agent/agent_init.py _enforce_minimum_context
3
+ // in the engine). A local Ollama model such as qwen3:8b (40,960) was still
4
+ // listed in their pickers, so a bot pinned to it hit the refusal on every
5
+ // turn and ran on the engine's default instead (Erick, 2026-11-22). Their
6
+ // catalogs leave such a model out, measured the way the engine measures it.
7
+ import { isOllamaCloudModel } from "../../shared/local-models.js";
8
+ import { anthropicBaseUrl, decodeInjectId, hostApiKey, localHost } from "./local-inject.js";
9
+ /** The engine's MINIMUM_CONTEXT_LENGTH (agent/model_metadata.py). */
10
+ export const HERMES_MIN_CONTEXT = 64_000;
11
+ const OLLAMA_HOSTS = new Set(["ollama", "local_ollama"]);
12
+ /** The window Ollama serves a model at, from its /api/show payload, read as
13
+ * the engine reads it for a local server: the Modelfile's num_ctx, else the
14
+ * model's own context_length. */
15
+ export function ollamaServedWindow(show) {
16
+ if (!show || typeof show !== "object")
17
+ return undefined;
18
+ const { parameters, model_info: info } = show;
19
+ if (typeof parameters === "string") {
20
+ for (const line of parameters.split("\n")) {
21
+ const parts = line.trim().split(/\s+/);
22
+ const value = Number(parts.at(-1));
23
+ if (parts[0] === "num_ctx" && Number.isInteger(value) && value > 0)
24
+ return value;
25
+ }
26
+ }
27
+ if (info && typeof info === "object") {
28
+ for (const [key, value] of Object.entries(info)) {
29
+ if (key.endsWith("context_length") && typeof value === "number" && value > 0)
30
+ return value;
31
+ }
32
+ }
33
+ return undefined;
34
+ }
35
+ async function ollamaShow(host, model, env, fetchImpl) {
36
+ try {
37
+ const response = await fetchImpl(`${anthropicBaseUrl(host)}/api/show`, {
38
+ method: "POST",
39
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${hostApiKey(host, env)}` },
40
+ body: JSON.stringify({ model }),
41
+ signal: AbortSignal.timeout(1500),
42
+ });
43
+ return response.ok ? await response.json() : null;
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ }
49
+ /** The window Hermes would see for a catalog row, when Atomic can tell: an
50
+ * Ollama model's /api/show (/api/ps's figure is only what is loaded now, and
51
+ * the engine asks Ollama for the larger window itself). */
52
+ async function hermesWindow(id, env, fetchImpl) {
53
+ const inject = decodeInjectId(id);
54
+ const host = inject ? localHost(inject.host) : undefined;
55
+ if (!inject || !host || !OLLAMA_HOSTS.has(host.id) || isOllamaCloudModel(inject.model))
56
+ return undefined;
57
+ return ollamaServedWindow(await ollamaShow(host, inject.model, env, fetchImpl));
58
+ }
59
+ /** A Hermes-family catalog without the local models the engine would refuse.
60
+ * A window Atomic cannot read keeps the row: the engine is the judge then. */
61
+ export async function withoutUnderSizedLocalModels(catalog, env = process.env, fetchImpl = fetch) {
62
+ const windows = await Promise.all(catalog.options.map((option) => hermesWindow(option.id, env, fetchImpl)));
63
+ const options = catalog.options.filter((_, index) => (windows[index] ?? HERMES_MIN_CONTEXT) >= HERMES_MIN_CONTEXT);
64
+ if (options.length === catalog.options.length)
65
+ return catalog;
66
+ const kept = new Set(options.map((option) => option.id));
67
+ return { default: kept.has(catalog.default) ? catalog.default : (options[0]?.id ?? ""), options };
68
+ }
@@ -105,3 +105,11 @@ export class ChatToolCalls {
105
105
  return calls;
106
106
  }
107
107
  }
108
+ /** Token totals from an OpenAI-style `usage` block, with the request's price
109
+ * in US dollars when the provider reports one (OpenRouter's `usage.cost`). */
110
+ export function chatUsage(usage) {
111
+ if (!usage)
112
+ return null;
113
+ const cost = typeof usage.cost === "number" && Number.isFinite(usage.cost) && usage.cost >= 0 ? usage.cost : undefined;
114
+ return { input: usage.prompt_tokens ?? 0, output: usage.completion_tokens ?? 0, ...(cost !== undefined ? { cost } : {}) };
115
+ }
@@ -5,13 +5,11 @@ 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, providerError } from "./openai-chat-protocol.js";
8
+ import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, MAX_CHAT_TOOL_CALLS, chatUsage, object, providerError } from "./openai-chat-protocol.js";
9
9
  import { hasImageParts, learnTextOnly, sendableMessages } from "./chat-text-only.js";
10
10
  import { appendNative } from "./native.js";
11
11
  import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS } from "./retry.js";
12
- const usageFrom = (usage) => usage
13
- ? { input: usage.prompt_tokens ?? 0, output: usage.completion_tokens ?? 0 }
14
- : null;
12
+ const usageFrom = (usage) => chatUsage(usage);
15
13
  const asError = (value) => value instanceof Error ? value : new Error(String(value));
16
14
  /** Shared runtime for the three providers that speak OpenAI chat completions. */
17
15
  export function createOpenAIChatRuntime(options) {
@@ -45,11 +43,12 @@ export function createOpenAIChatRuntime(options) {
45
43
  const activeSignal = signal
46
44
  ? AbortSignal.any([signal, timeoutController.signal])
47
45
  : timeoutController.signal;
48
- const sendable = sendableMessages(options.apiUrl, model, messages);
49
- const response = await fetch(`${options.apiUrl}/chat/completions`, {
46
+ const auth = await options.authorize?.();
47
+ const sendable = sendableMessages(auth?.apiUrl ?? options.apiUrl, model, messages);
48
+ const response = await fetch(`${auth?.apiUrl ?? options.apiUrl}/chat/completions`, {
50
49
  method: "POST",
51
50
  ...(hasImageParts(sendable) ? { redirect: "error" } : {}),
52
- headers: { ...options.extraHeaders, authorization: `Bearer ${options.apiKey}`, "content-type": "application/json" },
51
+ headers: { ...options.extraHeaders, ...auth?.headers, authorization: `Bearer ${auth?.apiKey ?? options.apiKey}`, "content-type": "application/json" },
53
52
  body: JSON.stringify({
54
53
  ...options.requestBody(model, sendable, stream),
55
54
  ...(tools.length ? { tools } : {}),
@@ -281,6 +280,7 @@ export function createOpenAIChatRuntime(options) {
281
280
  let tools;
282
281
  const usage = { input: 0, output: 0 };
283
282
  let hasUsage = false;
283
+ let cost = null; // the provider's own price, when it reports one
284
284
  let ok = false;
285
285
  let stopReason = null;
286
286
  let failure;
@@ -354,6 +354,8 @@ export function createOpenAIChatRuntime(options) {
354
354
  }
355
355
  native("in", options.nativeLog.incoming(completion));
356
356
  if (completion.usage) {
357
+ if (completion.usage.cost !== undefined)
358
+ cost = (cost ?? 0) + completion.usage.cost;
357
359
  usage.input += completion.usage.input;
358
360
  usage.output += completion.usage.output;
359
361
  hasUsage = true;
@@ -488,7 +490,7 @@ export function createOpenAIChatRuntime(options) {
488
490
  emit({ ...base(turn.threadId, turnId), type: "runtime.error", message: failure, terminal: !abort.signal.aborted });
489
491
  }
490
492
  active.delete(turn.threadId);
491
- emit({ ...base(turn.threadId, turnId), type: "turn.completed", ok, stopReason, cost: null,
493
+ emit({ ...base(turn.threadId, turnId), type: "turn.completed", ok, stopReason, cost,
492
494
  ...(hasUsage && (options.includeUsageInCompleted || seenCalls.size) ? { usage } : {}),
493
495
  ...(denials.length ? { denials } : {}),
494
496
  });
@@ -1,8 +1,10 @@
1
1
  import { OLLAMA_CLOUD_PREFERRED_MODEL, OLLAMA_CLOUD_URL } from "./ollama-cloud.js";
2
2
  import { createOpenAIChatRuntime } from "./openai-chat.js";
3
3
  import { openAiTeamHeaders } from "../provider-key-check.js";
4
+ import { COPILOT_HEADERS, copilotSessionCache, fetchCopilotModels } from "./github-copilot.js";
5
+ import { gcloudTokenCache } from "./gcloud-token.js";
4
6
  const DRIVER_KIND = "openai-compat";
5
- const DEFAULT_IDLE_TIMEOUT_MS = 180_000;
7
+ export const DEFAULT_IDLE_TIMEOUT_MS = 180_000;
6
8
  const idleTimeoutMs = () => {
7
9
  const raw = process.env.OPENMAUS_OPENAI_COMPAT_IDLE_TIMEOUT_MS;
8
10
  if (!raw)
@@ -14,6 +16,10 @@ const DEFAULT_MODELS = {
14
16
  default: OLLAMA_CLOUD_PREFERRED_MODEL,
15
17
  options: [{ id: OLLAMA_CLOUD_PREFERRED_MODEL, label: `${OLLAMA_CLOUD_PREFERRED_MODEL} (Ollama)`, custom: true }],
16
18
  };
19
+ /** OpenRouter's free models: `:free` ids and the `openrouter/free` router. */
20
+ export function isFreeOpenRouterModel(id) {
21
+ return id.endsWith(":free") || id === "openrouter/free";
22
+ }
17
23
  function isOpenRouterUrl(url) {
18
24
  try {
19
25
  const host = new URL(url).hostname.toLowerCase();
@@ -48,6 +54,10 @@ function decodeConfig(raw) {
48
54
  ? config.provider || undefined
49
55
  : process.env.OPENAI_COMPAT_PROVIDER || undefined,
50
56
  ...(typeof config.organization === "string" && config.organization ? { organization: config.organization } : {}),
57
+ // Accounts added as "OpenRouter (free models)" before the filter existed
58
+ // are known by their key's variable.
59
+ ...(config.modelFilter === "free" || config.apiKeyEnv === "OPENROUTER_FREE_API_KEY" ? { modelFilter: "free" } : {}),
60
+ ...(config.auth === "githubCopilot" || config.auth === "gcloud" ? { auth: config.auth } : {}),
51
61
  ...(typeof config.project === "string" && config.project ? { project: config.project } : {}),
52
62
  };
53
63
  }
@@ -93,11 +103,29 @@ export const OpenAICompatDriver = {
93
103
  : [{ id: config.model, label: config.model, custom: true }, ...DEFAULT_MODELS.options],
94
104
  }
95
105
  : DEFAULT_MODELS;
106
+ const copilot = config.auth === "githubCopilot" && apiKey ? copilotSessionCache(apiKey) : undefined;
107
+ // Vertex AI: the token comes from the person's own gcloud sign-in.
108
+ const gcloud = config.auth === "gcloud" ? gcloudTokenCache() : undefined;
109
+ const useOptions = (options) => {
110
+ if (!options.length)
111
+ return;
112
+ if (config.model && !options.some((model) => model.id === config.model)) {
113
+ options.unshift({ id: config.model, label: config.model, custom: true });
114
+ }
115
+ catalog = { default: config.model || options[0].id, options };
116
+ };
96
117
  const fetchModels = async () => {
97
- if (config.managedModels)
118
+ if (config.managedModels || gcloud)
98
119
  return;
99
120
  if (!apiKey)
100
121
  return;
122
+ if (copilot) {
123
+ try {
124
+ useOptions(await fetchCopilotModels(await copilot()));
125
+ }
126
+ catch { /* the turn reports a sign-in problem */ }
127
+ return;
128
+ }
101
129
  try {
102
130
  const response = await fetch(`${config.url}/models`, {
103
131
  headers: { ...teamHeaders, authorization: `Bearer ${apiKey}` },
@@ -113,6 +141,8 @@ export const OpenAICompatDriver = {
113
141
  const id = typeof row.id === "string" ? row.id : "";
114
142
  if (!id || seen.has(id))
115
143
  continue;
144
+ if (config.modelFilter === "free" && !isFreeOpenRouterModel(id))
145
+ continue;
116
146
  seen.add(id);
117
147
  options.push({
118
148
  id,
@@ -120,12 +150,7 @@ export const OpenAICompatDriver = {
120
150
  custom: true,
121
151
  });
122
152
  }
123
- if (!options.length)
124
- return;
125
- if (config.model && !options.some((model) => model.id === config.model)) {
126
- options.unshift({ id: config.model, label: config.model, custom: true });
127
- }
128
- catalog = { default: config.model ?? options[0].id, options };
153
+ useOptions(options);
129
154
  }
130
155
  catch {
131
156
  // Catalog refresh is opportunistic; keep the seeded options.
@@ -139,6 +164,12 @@ export const OpenAICompatDriver = {
139
164
  apiKey,
140
165
  apiUrl: config.url,
141
166
  extraHeaders: teamHeaders,
167
+ ...(copilot ? {
168
+ authorize: async () => {
169
+ const session = await copilot();
170
+ return { apiKey: session.token, apiUrl: session.apiUrl, headers: { ...COPILOT_HEADERS } };
171
+ },
172
+ } : gcloud ? { authorize: async () => ({ apiKey: await gcloud() }) } : {}),
142
173
  tools: config.tools,
143
174
  computerUse: true,
144
175
  models: () => catalog,
@@ -151,13 +182,17 @@ export const OpenAICompatDriver = {
151
182
  ...(config.provider && isOpenRouterUrl(config.url)
152
183
  ? { provider: { order: [config.provider], allow_fallbacks: false } }
153
184
  : {}),
185
+ // OpenRouter then reports each request's price, which the ledger and
186
+ // the monthly spend limit use instead of an estimate.
187
+ ...(isOpenRouterUrl(config.url) ? { usage: { include: true } } : {}),
154
188
  }),
155
189
  httpErrorLabel: "upstream",
156
190
  missingKeyError: OPENAI_COMPAT_NO_KEY,
157
191
  unavailableReason: OPENAI_COMPAT_NO_KEY,
158
192
  timeoutMs: idleTimeoutMs(),
159
193
  reasoning: true,
160
- billing: "metered",
194
+ // A Copilot plan is a subscription, not metered by the token.
195
+ ...(copilot ? {} : { billing: "metered" }),
161
196
  includeUsageInCompleted: true,
162
197
  nativeLog: {
163
198
  source: "openai-compat.chat.completions",
@@ -1,10 +1,11 @@
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, readFileSync } from "node:fs";
4
+ import { accessSync, constants, existsSync } 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";
8
+ import { turnTokenReader } from "../turn-token.js";
8
9
  const MAX_ADB_OUTPUT = 16 * 1024 * 1024;
9
10
  // Mirrors the shared-computer blockedReason shape: name the holder's
10
11
  // situation, say the call did not happen, and tell the model what beats a
@@ -252,32 +253,18 @@ const textResult = (text, isError = false) => ({ content: [{ type: "text", text
252
253
  // is idempotent; a blocked caller can retry once the holding turn settles.
253
254
  export function createPhoneClaim(env = process.env, fetchImpl = fetch) {
254
255
  const url = env.OMB_HARNESS_URL?.trim();
255
- const spawnToken = env.OMB_PHONE_TOKEN?.trim() ?? "";
256
- const tokenFile = env.OMB_PHONE_TOKEN_FILE?.trim() ?? "";
257
- if (!url || (!spawnToken && !tokenFile)) {
256
+ const currentToken = turnTokenReader(env, "OMB_PHONE_TOKEN");
257
+ if (!url || !currentToken()) {
258
258
  // Spawned outside the harness (development, direct debugging): no
259
259
  // exclusivity to enforce, exactly the behavior this proxy always had.
260
260
  return async () => ({ ok: true });
261
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
- };
275
262
  return async () => {
276
263
  try {
277
264
  const response = await fetchImpl(new URL("/api/internal/phone/claim", url), {
278
265
  method: "POST",
279
266
  redirect: "error",
280
- headers: { authorization: `Bearer ${token()}`, "content-type": "application/json" },
267
+ headers: { authorization: `Bearer ${currentToken()}`, "content-type": "application/json" },
281
268
  body: "{}",
282
269
  signal: AbortSignal.timeout(10_000),
283
270
  });
@@ -7,6 +7,7 @@ import { ATOMIC_AUTO_RUNG, BOT_TIERS, CHIBI_DEFAULT_RUNG, DEFAULT_LADDERS, DEFAU
7
7
  export { DEFAULT_LADDERS };
8
8
  import { expandAnySubscription, orderRungs } from "./ladder-order.js";
9
9
  import { ATOMIC_ENGINE_INSTANCE, engineIntent, freeCandidate, localModel, modelBilling, modelProvider, paidCandidate, perTokenModel } from "./harness-import/engine-policy.js";
10
+ export { needsWiderWalk, takeWider } from "./ladder-pick.js";
10
11
  /** Engines a tier tries first after Atomic Engine (Auto), whatever the
11
12
  * class catalog order says. Without Atomic Engine, Chibi runs on Claude:
12
13
  * Claude's best model graded in its class, then Claude's next (or Claude's
@@ -237,10 +238,9 @@ export function canDriveComputer(candidate, computer) {
237
238
  return candidate.capabilities?.localComputerMcp === true;
238
239
  return candidate.driverKind !== "boxAgent" && candidate.capabilities?.computerMcp === true;
239
240
  }
240
- /** Walk a ladder in two bands. First the subscription engines its rungs
241
- * name, in rung order, and Ollama Cloud whether named or not (after them
242
- * when no rung names it); then, automatically, every key-based engine
243
- * (those the rungs name first, then the rest). A rung on an engine that runs
241
+ /** Walk a ladder in three bands. First the subscription engines its rungs
242
+ * name, in rung order, and flat plans (Ollama Cloud) named or not; then free
243
+ * models; then every key-based engine (named first, then the rest). A rung on an engine that runs
244
244
  * many providers is in the band its model is paid in: a DeepInfra model on
245
245
  * Hermes is a key, a Nous Portal one a subscription. An engine is taken when
246
246
  * it is available, signed in, has a model, can delegate when the bot must,
@@ -263,15 +263,15 @@ export function resolveLadder(ladder, stored, context) {
263
263
  }
264
264
  }
265
265
  const rungOf = (candidate) => {
266
- const step = ladder.findIndex((entry) => matchesEngine(entry, candidate));
266
+ const step = ladder.findIndex((entry) => matchesEngine(entry, candidate) && entryModel(entry, candidate) !== undefined); // only a rung whose model it serves (a catalog run such as gpt-oss-120b must not leave a free account with no model)
267
267
  return step < 0 ? ladder.length : step;
268
268
  };
269
269
  const ownRung = (entry, candidate) => // a same-driver rung naming a model this account lacks: its own default
270
270
  (entry && entryModel(entry, candidate) ? entry : { engine: candidate.instanceId });
271
271
  for (const [index, candidate] of context.candidates.entries()) {
272
- // Ollama Cloud joins every ladder by itself, as it always has: now as the
273
- // flat plan it is, in the subscription band.
274
- if (candidate.driverKind === "ollamaCloud" && !keyBased(candidate) && !subscription.some((attempt) => attempt.candidate === candidate)) {
272
+ // Ollama Cloud and plans on OpenAI-compatible accounts (GitHub Copilot, coding plans) join every ladder's subscription band.
273
+ const planAccount = candidate.driverKind === "openai-compat" && candidate.billing === "subscription";
274
+ if ((candidate.driverKind === "ollamaCloud" || planAccount) && !keyBased(candidate) && !subscription.some((attempt) => attempt.candidate === candidate)) {
275
275
  subscription.push({ step: ladder.length, entry: { engine: candidate.instanceId }, candidate, band: "subscription", index });
276
276
  }
277
277
  // A free-tier account joins every ladder by itself, in its own
@@ -289,7 +289,7 @@ export function resolveLadder(ladder, stored, context) {
289
289
  }
290
290
  subscription.sort((a, b) => atomicFirst(a.candidate) - atomicFirst(b.candidate) || a.step - b.step);
291
291
  key.sort((a, b) => a.step - b.step || storedFirst(a.candidate, b.candidate) || a.index - b.index);
292
- free.sort((a, b) => a.step - b.step || storedFirst(a.candidate, b.candidate) || a.index - b.index);
292
+ free.sort((a, b) => Number(Boolean(a.candidate.keyless)) - Number(Boolean(b.candidate.keyless)) || a.step - b.step || storedFirst(a.candidate, b.candidate) || a.index - b.index);
293
293
  for (const { step, entry, candidate, band } of [...subscription, ...free, ...key]) { // free before pay-per-use (Erick, 2026-11-15)
294
294
  // "paused" names a key kept off this turn by policy alone: a key that could not take it anyway (signed out, resting, refused) keeps its real reason.
295
295
  const reason = band === "free" && !context.includeFree ? "free-off"
@@ -0,0 +1,78 @@
1
+ // A GOD MODE run is a personal goal with a deadline (shared/god-mode-run.ts).
2
+ // This module is what differs from an ordinary goal: the clock instead of a
3
+ // turn budget, and every outcome that would stop an ordinary goal (a failed
4
+ // turn, a question, a blocker, no progress) turned into the next attempt.
5
+ import { godModeRetryDelayMs, godModeRunStop, GOD_MODE_QUESTION_ANSWER, } from "../shared/god-mode-run.js";
6
+ const LOG_LIMIT = 500;
7
+ export function newGodModeRun(now, durationMs) {
8
+ return {
9
+ startedAt: now,
10
+ endsAt: now + durationMs,
11
+ attempts: 0,
12
+ failures: 0,
13
+ log: [{ at: now, stop: "paid-key", action: "approved", detail: "pay-per-use keys are approved for this run (Keep going)." }],
14
+ };
15
+ }
16
+ /** Whether this goal is a GOD MODE run still inside its time. */
17
+ export function godModeRunLive(goal, now) {
18
+ return Boolean(goal?.godMode && goal.status === "working" && now < goal.godMode.endsAt);
19
+ }
20
+ /** Record what the run did in the person's place. */
21
+ export function logGodModeRun(goal, now, entry) {
22
+ goal.godMode.log.push({ at: now, ...entry, detail: entry.detail.slice(0, 400) });
23
+ if (goal.godMode.log.length > LOG_LIMIT)
24
+ goal.godMode.log.splice(0, goal.godMode.log.length - LOG_LIMIT);
25
+ }
26
+ /** Decide a stop for a live run and log it. Undefined when the goal is not a
27
+ * live run: the ordinary behavior applies. */
28
+ export function decideGodModeStop(goal, now, stop) {
29
+ if (!godModeRunLive(goal, now))
30
+ return undefined;
31
+ const decision = godModeRunStop(stop);
32
+ const subject = [stop.tool, stop.question ?? stop.detail].filter(Boolean).join(": ");
33
+ logGodModeRun(goal, now, { stop: stop.kind, action: decision.action, detail: subject ? `${decision.note} [${subject}]` : decision.note });
34
+ return decision;
35
+ }
36
+ /** Before a run's turn: false when its time is up (the goal is closed). */
37
+ export function beginGodModeTurn(goal, now) {
38
+ if (now < goal.godMode.endsAt)
39
+ return true;
40
+ goal.status = "limit-reached";
41
+ goal.detail = "GOD MODE time is up. Start another run to keep going.";
42
+ logGodModeRun(goal, now, { stop: "turn-ended", action: "continued", detail: "time is up; the run ended." });
43
+ return false;
44
+ }
45
+ /** After a run's turn, for every outcome but a verified completion: keep the
46
+ * goal working and say how the next attempt should go. */
47
+ export function settleGodModeTurn(goal, now, result, decision) {
48
+ const run = goal.godMode;
49
+ goal.status = "working";
50
+ if (!result.ok) {
51
+ run.failures += 1;
52
+ run.attempts += 1;
53
+ goal.detail = "The last attempt failed before it finished. Check what is already done, then continue another way (another tool or approach).";
54
+ logGodModeRun(goal, now, { stop: "turn-failed", action: "continued", detail: `started attempt ${run.attempts + 1}.` });
55
+ return;
56
+ }
57
+ run.failures = 0;
58
+ if (decision?.status === "needs-input") {
59
+ goal.detail = `${GOD_MODE_QUESTION_ANSWER} You asked: ${decision.detail}`;
60
+ logGodModeRun(goal, now, { stop: "question", action: "answered", detail: decision.detail });
61
+ }
62
+ else if (decision?.status === "blocked") {
63
+ goal.blockers = 0;
64
+ goal.lastBlocker = "";
65
+ goal.detail = `Blocked: ${decision.detail}. Do not stop: work around it another way, or skip that step and finish everything else.`;
66
+ logGodModeRun(goal, now, { stop: "check-in", action: "continued", detail: decision.detail });
67
+ }
68
+ // No measurable progress is a nudge, never a pause.
69
+ if (goal.missing >= 3 || goal.noProgress >= 3 || goal.repeated >= 3) {
70
+ goal.missing = goal.noProgress = goal.repeated = 0;
71
+ goal.detail = "Three turns without measurable progress. Change approach: inspect the current state, pick a different next step, and act with tools.";
72
+ logGodModeRun(goal, now, { stop: "turn-ended", action: "continued", detail: "no progress; changed approach." });
73
+ }
74
+ }
75
+ /** How long the runtime waits before the run's next attempt. */
76
+ export function godModeNextAttemptDelay(goal) {
77
+ return goal.godMode && goal.status === "working" ? godModeRetryDelayMs(goal.godMode.failures) : 0;
78
+ }