crewly 1.20.176 → 1.20.178

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 (186) hide show
  1. package/config/skills/orchestrator/update-team-member/SKILL.md +1 -1
  2. package/dist/backend/backend/src/constants.d.ts +79 -3
  3. package/dist/backend/backend/src/constants.d.ts.map +1 -1
  4. package/dist/backend/backend/src/constants.js +97 -3
  5. package/dist/backend/backend/src/constants.js.map +1 -1
  6. package/dist/backend/backend/src/controllers/monitoring/terminal.controller.d.ts.map +1 -1
  7. package/dist/backend/backend/src/controllers/monitoring/terminal.controller.js +2 -1
  8. package/dist/backend/backend/src/controllers/monitoring/terminal.controller.js.map +1 -1
  9. package/dist/backend/backend/src/controllers/system/runtime-fallback.controller.d.ts +30 -0
  10. package/dist/backend/backend/src/controllers/system/runtime-fallback.controller.d.ts.map +1 -0
  11. package/dist/backend/backend/src/controllers/system/runtime-fallback.controller.js +100 -0
  12. package/dist/backend/backend/src/controllers/system/runtime-fallback.controller.js.map +1 -0
  13. package/dist/backend/backend/src/controllers/team/team.controller.d.ts.map +1 -1
  14. package/dist/backend/backend/src/controllers/team/team.controller.js +33 -4
  15. package/dist/backend/backend/src/controllers/team/team.controller.js.map +1 -1
  16. package/dist/backend/backend/src/index.d.ts.map +1 -1
  17. package/dist/backend/backend/src/index.js +25 -0
  18. package/dist/backend/backend/src/index.js.map +1 -1
  19. package/dist/backend/backend/src/routes/modules/system.routes.d.ts.map +1 -1
  20. package/dist/backend/backend/src/routes/modules/system.routes.js +3 -0
  21. package/dist/backend/backend/src/routes/modules/system.routes.js.map +1 -1
  22. package/dist/backend/backend/src/services/agent/agent-heartbeat-monitor.service.d.ts.map +1 -1
  23. package/dist/backend/backend/src/services/agent/agent-heartbeat-monitor.service.js +17 -0
  24. package/dist/backend/backend/src/services/agent/agent-heartbeat-monitor.service.js.map +1 -1
  25. package/dist/backend/backend/src/services/agent/agent-registration.service.d.ts +10 -1
  26. package/dist/backend/backend/src/services/agent/agent-registration.service.d.ts.map +1 -1
  27. package/dist/backend/backend/src/services/agent/agent-registration.service.js +103 -7
  28. package/dist/backend/backend/src/services/agent/agent-registration.service.js.map +1 -1
  29. package/dist/backend/backend/src/services/agent/antigravity-runtime.service.d.ts +1 -1
  30. package/dist/backend/backend/src/services/agent/antigravity-runtime.service.d.ts.map +1 -1
  31. package/dist/backend/backend/src/services/agent/antigravity-runtime.service.js +3 -2
  32. package/dist/backend/backend/src/services/agent/antigravity-runtime.service.js.map +1 -1
  33. package/dist/backend/backend/src/services/agent/crewly-agent/crewly-agent-external-runtime.service.d.ts +7 -0
  34. package/dist/backend/backend/src/services/agent/crewly-agent/crewly-agent-external-runtime.service.d.ts.map +1 -1
  35. package/dist/backend/backend/src/services/agent/crewly-agent/crewly-agent-external-runtime.service.js +16 -0
  36. package/dist/backend/backend/src/services/agent/crewly-agent/crewly-agent-external-runtime.service.js.map +1 -1
  37. package/dist/backend/backend/src/services/agent/idle-detection.service.d.ts.map +1 -1
  38. package/dist/backend/backend/src/services/agent/idle-detection.service.js +2 -1
  39. package/dist/backend/backend/src/services/agent/idle-detection.service.js.map +1 -1
  40. package/dist/backend/backend/src/services/agent/oauth-relogin-monitor.service.d.ts.map +1 -1
  41. package/dist/backend/backend/src/services/agent/oauth-relogin-monitor.service.js +7 -0
  42. package/dist/backend/backend/src/services/agent/oauth-relogin-monitor.service.js.map +1 -1
  43. package/dist/backend/backend/src/services/agent/planned-relaunch.registry.d.ts +61 -0
  44. package/dist/backend/backend/src/services/agent/planned-relaunch.registry.d.ts.map +1 -0
  45. package/dist/backend/backend/src/services/agent/planned-relaunch.registry.js +73 -0
  46. package/dist/backend/backend/src/services/agent/planned-relaunch.registry.js.map +1 -0
  47. package/dist/backend/backend/src/services/agent/tmux.service.d.ts.map +1 -1
  48. package/dist/backend/backend/src/services/agent/tmux.service.js +2 -1
  49. package/dist/backend/backend/src/services/agent/tmux.service.js.map +1 -1
  50. package/dist/backend/backend/src/services/harness/harness-status.service.d.ts +17 -0
  51. package/dist/backend/backend/src/services/harness/harness-status.service.d.ts.map +1 -1
  52. package/dist/backend/backend/src/services/harness/harness-status.service.js +25 -1
  53. package/dist/backend/backend/src/services/harness/harness-status.service.js.map +1 -1
  54. package/dist/backend/backend/src/services/messaging/queue-processor.service.d.ts.map +1 -1
  55. package/dist/backend/backend/src/services/messaging/queue-processor.service.js +2 -1
  56. package/dist/backend/backend/src/services/messaging/queue-processor.service.js.map +1 -1
  57. package/dist/backend/backend/src/services/monitoring/activity-monitor.service.d.ts.map +1 -1
  58. package/dist/backend/backend/src/services/monitoring/activity-monitor.service.js +3 -2
  59. package/dist/backend/backend/src/services/monitoring/activity-monitor.service.js.map +1 -1
  60. package/dist/backend/backend/src/services/orchestrator/orchestrator-heartbeat-monitor.service.d.ts.map +1 -1
  61. package/dist/backend/backend/src/services/orchestrator/orchestrator-heartbeat-monitor.service.js +10 -0
  62. package/dist/backend/backend/src/services/orchestrator/orchestrator-heartbeat-monitor.service.js.map +1 -1
  63. package/dist/backend/backend/src/services/orchestrator/orchestrator-restart.service.d.ts +28 -1
  64. package/dist/backend/backend/src/services/orchestrator/orchestrator-restart.service.d.ts.map +1 -1
  65. package/dist/backend/backend/src/services/orchestrator/orchestrator-restart.service.js +48 -3
  66. package/dist/backend/backend/src/services/orchestrator/orchestrator-restart.service.js.map +1 -1
  67. package/dist/backend/backend/src/services/orchestrator/orchestrator-status.service.d.ts.map +1 -1
  68. package/dist/backend/backend/src/services/orchestrator/orchestrator-status.service.js +3 -2
  69. package/dist/backend/backend/src/services/orchestrator/orchestrator-status.service.js.map +1 -1
  70. package/dist/backend/backend/src/services/runtime-fallback/effective-runtime.d.ts +100 -0
  71. package/dist/backend/backend/src/services/runtime-fallback/effective-runtime.d.ts.map +1 -0
  72. package/dist/backend/backend/src/services/runtime-fallback/effective-runtime.js +115 -0
  73. package/dist/backend/backend/src/services/runtime-fallback/effective-runtime.js.map +1 -0
  74. package/dist/backend/backend/src/services/runtime-fallback/reset-time.d.ts +66 -0
  75. package/dist/backend/backend/src/services/runtime-fallback/reset-time.d.ts.map +1 -0
  76. package/dist/backend/backend/src/services/runtime-fallback/reset-time.js +211 -0
  77. package/dist/backend/backend/src/services/runtime-fallback/reset-time.js.map +1 -0
  78. package/dist/backend/backend/src/services/runtime-fallback/runtime-availability.d.ts +39 -0
  79. package/dist/backend/backend/src/services/runtime-fallback/runtime-availability.d.ts.map +1 -0
  80. package/dist/backend/backend/src/services/runtime-fallback/runtime-availability.js +56 -0
  81. package/dist/backend/backend/src/services/runtime-fallback/runtime-availability.js.map +1 -0
  82. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.service.d.ts +417 -0
  83. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.service.d.ts.map +1 -0
  84. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.service.js +974 -0
  85. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.service.js.map +1 -0
  86. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.store.d.ts +53 -0
  87. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.store.d.ts.map +1 -0
  88. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.store.js +109 -0
  89. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.store.js.map +1 -0
  90. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.types.d.ts +134 -0
  91. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.types.d.ts.map +1 -0
  92. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.types.js +152 -0
  93. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.types.js.map +1 -0
  94. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.wiring.d.ts +95 -0
  95. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.wiring.d.ts.map +1 -0
  96. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.wiring.js +286 -0
  97. package/dist/backend/backend/src/services/runtime-fallback/runtime-fallback.wiring.js.map +1 -0
  98. package/dist/backend/backend/src/services/runtime-fallback/runtime-smoke-test.service.d.ts +203 -0
  99. package/dist/backend/backend/src/services/runtime-fallback/runtime-smoke-test.service.d.ts.map +1 -0
  100. package/dist/backend/backend/src/services/runtime-fallback/runtime-smoke-test.service.js +419 -0
  101. package/dist/backend/backend/src/services/runtime-fallback/runtime-smoke-test.service.js.map +1 -0
  102. package/dist/backend/backend/src/services/runtime-fallback/runtime-usage-probe.d.ts +94 -0
  103. package/dist/backend/backend/src/services/runtime-fallback/runtime-usage-probe.d.ts.map +1 -0
  104. package/dist/backend/backend/src/services/runtime-fallback/runtime-usage-probe.js +186 -0
  105. package/dist/backend/backend/src/services/runtime-fallback/runtime-usage-probe.js.map +1 -0
  106. package/dist/backend/backend/src/services/runtime-fallback/usage-limit-rules.d.ts +113 -0
  107. package/dist/backend/backend/src/services/runtime-fallback/usage-limit-rules.d.ts.map +1 -0
  108. package/dist/backend/backend/src/services/runtime-fallback/usage-limit-rules.js +257 -0
  109. package/dist/backend/backend/src/services/runtime-fallback/usage-limit-rules.js.map +1 -0
  110. package/dist/backend/backend/src/services/slack/slack-team-channel.service.d.ts +8 -0
  111. package/dist/backend/backend/src/services/slack/slack-team-channel.service.d.ts.map +1 -1
  112. package/dist/backend/backend/src/services/slack/slack-team-channel.service.js +16 -2
  113. package/dist/backend/backend/src/services/slack/slack-team-channel.service.js.map +1 -1
  114. package/dist/backend/backend/src/services/task-pool/claim.service.d.ts.map +1 -1
  115. package/dist/backend/backend/src/services/task-pool/claim.service.js +3 -1
  116. package/dist/backend/backend/src/services/task-pool/claim.service.js.map +1 -1
  117. package/dist/backend/backend/src/services/workflow/message-scheduler.service.d.ts.map +1 -1
  118. package/dist/backend/backend/src/services/workflow/message-scheduler.service.js +3 -2
  119. package/dist/backend/backend/src/services/workflow/message-scheduler.service.js.map +1 -1
  120. package/dist/backend/backend/src/services/workflow/scheduler.service.d.ts.map +1 -1
  121. package/dist/backend/backend/src/services/workflow/scheduler.service.js +3 -2
  122. package/dist/backend/backend/src/services/workflow/scheduler.service.js.map +1 -1
  123. package/dist/backend/backend/src/types/index.d.ts +14 -0
  124. package/dist/backend/backend/src/types/index.d.ts.map +1 -1
  125. package/dist/backend/backend/src/types/index.js.map +1 -1
  126. package/dist/backend/build-info.json +2 -2
  127. package/dist/cli/backend/src/constants.d.ts +79 -3
  128. package/dist/cli/backend/src/constants.d.ts.map +1 -1
  129. package/dist/cli/backend/src/constants.js +97 -3
  130. package/dist/cli/backend/src/constants.js.map +1 -1
  131. package/dist/cli/backend/src/services/agent/agent-registration.service.d.ts +10 -1
  132. package/dist/cli/backend/src/services/agent/agent-registration.service.d.ts.map +1 -1
  133. package/dist/cli/backend/src/services/agent/agent-registration.service.js +103 -7
  134. package/dist/cli/backend/src/services/agent/agent-registration.service.js.map +1 -1
  135. package/dist/cli/backend/src/services/agent/antigravity-runtime.service.d.ts +1 -1
  136. package/dist/cli/backend/src/services/agent/antigravity-runtime.service.d.ts.map +1 -1
  137. package/dist/cli/backend/src/services/agent/antigravity-runtime.service.js +3 -2
  138. package/dist/cli/backend/src/services/agent/antigravity-runtime.service.js.map +1 -1
  139. package/dist/cli/backend/src/services/agent/crewly-agent/crewly-agent-external-runtime.service.d.ts +7 -0
  140. package/dist/cli/backend/src/services/agent/crewly-agent/crewly-agent-external-runtime.service.d.ts.map +1 -1
  141. package/dist/cli/backend/src/services/agent/crewly-agent/crewly-agent-external-runtime.service.js +16 -0
  142. package/dist/cli/backend/src/services/agent/crewly-agent/crewly-agent-external-runtime.service.js.map +1 -1
  143. package/dist/cli/backend/src/services/agent/oauth-relogin-monitor.service.d.ts.map +1 -1
  144. package/dist/cli/backend/src/services/agent/oauth-relogin-monitor.service.js +7 -0
  145. package/dist/cli/backend/src/services/agent/oauth-relogin-monitor.service.js.map +1 -1
  146. package/dist/cli/backend/src/services/agent/planned-relaunch.registry.d.ts +61 -0
  147. package/dist/cli/backend/src/services/agent/planned-relaunch.registry.d.ts.map +1 -0
  148. package/dist/cli/backend/src/services/agent/planned-relaunch.registry.js +73 -0
  149. package/dist/cli/backend/src/services/agent/planned-relaunch.registry.js.map +1 -0
  150. package/dist/cli/backend/src/services/harness/harness-status.service.d.ts +17 -0
  151. package/dist/cli/backend/src/services/harness/harness-status.service.d.ts.map +1 -1
  152. package/dist/cli/backend/src/services/harness/harness-status.service.js +25 -1
  153. package/dist/cli/backend/src/services/harness/harness-status.service.js.map +1 -1
  154. package/dist/cli/backend/src/services/messaging/queue-processor.service.d.ts.map +1 -1
  155. package/dist/cli/backend/src/services/messaging/queue-processor.service.js +2 -1
  156. package/dist/cli/backend/src/services/messaging/queue-processor.service.js.map +1 -1
  157. package/dist/cli/backend/src/services/monitoring/activity-monitor.service.d.ts.map +1 -1
  158. package/dist/cli/backend/src/services/monitoring/activity-monitor.service.js +3 -2
  159. package/dist/cli/backend/src/services/monitoring/activity-monitor.service.js.map +1 -1
  160. package/dist/cli/backend/src/services/orchestrator/orchestrator-restart.service.d.ts +28 -1
  161. package/dist/cli/backend/src/services/orchestrator/orchestrator-restart.service.d.ts.map +1 -1
  162. package/dist/cli/backend/src/services/orchestrator/orchestrator-restart.service.js +48 -3
  163. package/dist/cli/backend/src/services/orchestrator/orchestrator-restart.service.js.map +1 -1
  164. package/dist/cli/backend/src/services/orchestrator/orchestrator-status.service.d.ts.map +1 -1
  165. package/dist/cli/backend/src/services/orchestrator/orchestrator-status.service.js +3 -2
  166. package/dist/cli/backend/src/services/orchestrator/orchestrator-status.service.js.map +1 -1
  167. package/dist/cli/backend/src/services/runtime-fallback/effective-runtime.d.ts +100 -0
  168. package/dist/cli/backend/src/services/runtime-fallback/effective-runtime.d.ts.map +1 -0
  169. package/dist/cli/backend/src/services/runtime-fallback/effective-runtime.js +115 -0
  170. package/dist/cli/backend/src/services/runtime-fallback/effective-runtime.js.map +1 -0
  171. package/dist/cli/backend/src/services/slack/slack-team-channel.service.d.ts +8 -0
  172. package/dist/cli/backend/src/services/slack/slack-team-channel.service.d.ts.map +1 -1
  173. package/dist/cli/backend/src/services/slack/slack-team-channel.service.js +16 -2
  174. package/dist/cli/backend/src/services/slack/slack-team-channel.service.js.map +1 -1
  175. package/dist/cli/backend/src/services/task-pool/claim.service.d.ts.map +1 -1
  176. package/dist/cli/backend/src/services/task-pool/claim.service.js +3 -1
  177. package/dist/cli/backend/src/services/task-pool/claim.service.js.map +1 -1
  178. package/dist/cli/backend/src/types/index.d.ts +14 -0
  179. package/dist/cli/backend/src/types/index.d.ts.map +1 -1
  180. package/dist/cli/backend/src/types/index.js.map +1 -1
  181. package/dist/cli/cli/src/utils/runtime-auth.d.ts +1 -1
  182. package/dist/cli/cli/src/utils/runtime-auth.js +1 -1
  183. package/frontend/dist/assets/{index-0726afab.js → index-69af46c3.js} +275 -275
  184. package/frontend/dist/assets/{index-0c5449b5.css → index-cdc52122.css} +1 -1
  185. package/frontend/dist/index.html +2 -2
  186. package/package.json +1 -1
@@ -0,0 +1,974 @@
1
+ /**
2
+ * Runtime fallback — when an agent's runtime runs out of usage, run the agent
3
+ * on the next runtime of its fallback chain until the limit resets, then
4
+ * switch it back at an idle boundary.
5
+ *
6
+ * Flow (specs/2026-10-01-runtime-fallback.md):
7
+ *
8
+ * 1. **Detect** ({@link RuntimeFallbackService.reportOutput}): live output or
9
+ * an in-process run error matched a usage-limit rule. Transient rate limits
10
+ * are left to the runtime's own retries unless they keep coming.
11
+ * 2. **Confirm** with the runtime's probe (Claude: a one-line print-mode turn);
12
+ * a probe that answers normally marks the match a false positive.
13
+ * 3. **Mark the runtime exhausted** (account-wide) with its reset time.
14
+ * 4. **Switch** the agent that hit it at its next safe point: handover file,
15
+ * `runtimeOverride` (the configured runtime is not changed), relaunch, then
16
+ * re-deliver what waited for it.
17
+ * 5. Other agents on that runtime switch **when they next get work**
18
+ * ({@link RuntimeFallbackService.beforeDelivery}) or when started
19
+ * ({@link RuntimeFallbackService.resolveLaunch}); idle ones are not woken.
20
+ * 6. **Switch back** ({@link RuntimeFallbackService.tick}) only after the
21
+ * runtime's probe answers normally (at the reset time, or on the probe
22
+ * interval); each agent reverts at its next idle boundary. A runtime that
23
+ * is out of money/credit (`billing`) has no reset time and is probed at
24
+ * most every BILLING_PROBE_INTERVAL_MS. A switch-back that fails (the limit
25
+ * comes straight back) doubles the next probe interval.
26
+ * 7. **Tell the owner once** per event, and once when it is over.
27
+ *
28
+ * Nothing here throws into its callers: delivery and launch fall back to the
29
+ * configured runtime on any error.
30
+ *
31
+ * @module services/runtime-fallback/runtime-fallback.service
32
+ */
33
+ import { ORCHESTRATOR_SESSION_NAME, RUNTIME_FALLBACK_CONSTANTS, RUNTIME_TYPES } from '../../constants.js';
34
+ import { detectUsageLimit } from './usage-limit-rules.js';
35
+ import { applySettingsPatch, runtimeLabel, runtimeShortLabel, } from './runtime-fallback.types.js';
36
+ const C = RUNTIME_FALLBACK_CONSTANTS;
37
+ const SILENT = { info: () => undefined, warn: () => undefined, debug: () => undefined };
38
+ /**
39
+ * "1 agent" / "3 agents".
40
+ *
41
+ * @param n - Count
42
+ * @returns Phrase
43
+ */
44
+ function agents(n) {
45
+ return `${n} agent${n === 1 ? '' : 's'}`;
46
+ }
47
+ /** Runtime fallback coordinator. */
48
+ export class RuntimeFallbackService {
49
+ deps;
50
+ state;
51
+ logger;
52
+ now;
53
+ sleep;
54
+ /** Sessions being switched (messages for them are queued) */
55
+ switching = new Set();
56
+ /** Runtimes whose detection is being confirmed by a probe */
57
+ confirming = new Map();
58
+ /** A probe said the runtime is fine: ignore matches until then */
59
+ mutedUntil = new Map();
60
+ /** Recent transient rate limits per session */
61
+ transients = new Map();
62
+ /** Owner notice due time per exhausted runtime */
63
+ noticeDue = new Map();
64
+ /** Kickoff notes waiting for a session's next launch */
65
+ kickoffNotes = new Map();
66
+ /** Last switch-back per runtime, to recognise one that failed */
67
+ recentRecoveries = new Map();
68
+ availability = null;
69
+ timer = null;
70
+ ticking = false;
71
+ /**
72
+ * @param deps - Dependencies
73
+ */
74
+ constructor(deps) {
75
+ this.deps = deps;
76
+ this.logger = deps.logger ?? SILENT;
77
+ this.now = deps.now ?? (() => Date.now());
78
+ this.sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
79
+ this.state = deps.store.load();
80
+ }
81
+ // ---------------------------------------------------------------- lifecycle
82
+ /** Start the periodic tick (switch-back checks, reverts, notices). */
83
+ start() {
84
+ if (this.timer)
85
+ return;
86
+ this.timer = setInterval(() => void this.tick(), C.TICK_MS);
87
+ this.timer.unref?.();
88
+ // Notices that were due before a restart, and a first availability read.
89
+ void this.tick();
90
+ }
91
+ /** Stop the tick. */
92
+ stop() {
93
+ if (this.timer)
94
+ clearInterval(this.timer);
95
+ this.timer = null;
96
+ }
97
+ // ----------------------------------------------------------------- settings
98
+ /** @returns Current settings (copy) */
99
+ getSettings() {
100
+ return JSON.parse(JSON.stringify(this.state.settings));
101
+ }
102
+ /**
103
+ * Apply a partial settings update.
104
+ *
105
+ * @param patch - Owner's update (validated)
106
+ * @returns New settings
107
+ * @throws RuntimeFallbackSettingsError when invalid
108
+ */
109
+ updateSettings(patch) {
110
+ this.state.settings = applySettingsPatch(this.state.settings, patch);
111
+ this.availability = null;
112
+ this.save();
113
+ return this.getSettings();
114
+ }
115
+ // ------------------------------------------------------------------- hooks
116
+ /**
117
+ * Runtime a session runs on instead of its configured one.
118
+ *
119
+ * @param sessionName - Session
120
+ * @returns Fallback runtime, or null
121
+ */
122
+ overrideFor(sessionName) {
123
+ return this.state.overrides[sessionName]?.runtime ?? null;
124
+ }
125
+ /**
126
+ * Take the note for a session's next kickoff.
127
+ *
128
+ * @param sessionName - Session
129
+ * @returns Note (once) or null
130
+ */
131
+ takeKickoffNote(sessionName) {
132
+ const note = this.kickoffNotes.get(sessionName) ?? null;
133
+ this.kickoffNotes.delete(sessionName);
134
+ return note;
135
+ }
136
+ /**
137
+ * Runtime output / error of a session. A usage limit starts the fallback
138
+ * (asynchronously); everything else is ignored.
139
+ *
140
+ * @param sessionName - Session
141
+ * @param runtime - Runtime it runs on
142
+ * @param text - Output (never logged)
143
+ * @param source - `output` (live chunk), `screen` (sweep, ignored: old scrollback) or `error`
144
+ * @returns True when a usage limit was recognised
145
+ */
146
+ reportOutput(sessionName, runtime, text, source) {
147
+ if (!this.state.settings.enabled || source === 'screen' || this.isExempt(sessionName))
148
+ return false;
149
+ if ((this.mutedUntil.get(runtime) ?? 0) > this.now())
150
+ return false;
151
+ let match = detectUsageLimit(text, runtime, this.now(), this.deps.timeZone);
152
+ if (!match)
153
+ return false;
154
+ if (match.kind === 'transient') {
155
+ match = this.escalateTransient(sessionName, match);
156
+ if (!match)
157
+ return false;
158
+ }
159
+ void this.onUsageLimit(sessionName, runtime, match).catch((err) => this.logger.warn('Runtime fallback failed', { sessionName, runtime, error: err instanceof Error ? err.message : String(err) }));
160
+ return true;
161
+ }
162
+ /**
163
+ * Gate before a message is written into a session.
164
+ *
165
+ * @param sessionName - Session
166
+ * @param runtime - Runtime the caller resolved
167
+ * @returns `queue` while a switch runs or when the session's runtime is out of usage and a fallback exists
168
+ */
169
+ beforeDelivery(sessionName, runtime) {
170
+ if (!this.state.settings.enabled || this.isExempt(sessionName))
171
+ return 'deliver';
172
+ if (this.switching.has(sessionName))
173
+ return 'queue';
174
+ const current = this.state.overrides[sessionName]?.runtime ?? runtime;
175
+ if (!this.state.exhausted[current])
176
+ return 'deliver';
177
+ if (sessionName === ORCHESTRATOR_SESSION_NAME && !this.state.settings.orcFollows)
178
+ return 'deliver';
179
+ if (!this.hasCandidateSync(current))
180
+ return 'deliver';
181
+ this.logger.info('Message for an agent whose runtime is out of usage — switching it first', { sessionName, runtime: current });
182
+ void this.switchSession(sessionName, { waitForSafePoint: true, flushAfter: true });
183
+ return 'queue';
184
+ }
185
+ /**
186
+ * Runtime to launch a session on.
187
+ *
188
+ * @param input - Session, configured runtime
189
+ * @returns The decision
190
+ */
191
+ async resolveLaunch(input) {
192
+ const configured = { runtime: input.configured, overridden: false };
193
+ if (!this.state.settings.enabled || this.isExempt(input.sessionName))
194
+ return configured;
195
+ const existing = this.state.overrides[input.sessionName];
196
+ if (existing) {
197
+ if (existing.primary !== input.configured) {
198
+ // The owner changed the member's runtime: the override is stale.
199
+ delete this.state.overrides[input.sessionName];
200
+ this.save();
201
+ }
202
+ else if (existing.revertPending && !this.state.exhausted[existing.primary]) {
203
+ // A stopped agent being started after its runtime came back.
204
+ this.finishRevertOffline(input.sessionName, existing);
205
+ return configured;
206
+ }
207
+ else {
208
+ return this.decision(existing.runtime);
209
+ }
210
+ }
211
+ if (!this.state.exhausted[input.configured])
212
+ return configured;
213
+ if (input.isOrchestrator && !this.state.settings.orcFollows)
214
+ return configured;
215
+ const agent = (await this.deps.getAgent(input.sessionName).catch(() => null)) ?? {
216
+ sessionName: input.sessionName,
217
+ name: input.sessionName,
218
+ primary: input.configured,
219
+ memberId: input.memberId,
220
+ teamId: input.teamId,
221
+ isOrchestrator: input.isOrchestrator,
222
+ };
223
+ const target = await this.pickFallback(agent, input.configured);
224
+ if (!target) {
225
+ this.markNoFallback(input.configured);
226
+ return configured;
227
+ }
228
+ await this.recordSwitch(agent, input.configured, target);
229
+ this.logger.info('Starting an agent on its fallback runtime (its runtime is out of usage)', {
230
+ sessionName: input.sessionName,
231
+ primary: input.configured,
232
+ runtime: target,
233
+ });
234
+ return this.decision(target);
235
+ }
236
+ // --------------------------------------------------------------- detection
237
+ /**
238
+ * Count a transient rate limit; escalate when they keep coming.
239
+ *
240
+ * @param sessionName - Session
241
+ * @param match - Transient match
242
+ * @returns A usage-limit match when escalated, else null
243
+ */
244
+ escalateTransient(sessionName, match) {
245
+ const now = this.now();
246
+ const recent = (this.transients.get(sessionName) ?? []).filter((t) => now - t < C.TRANSIENT_WINDOW_MS);
247
+ recent.push(now);
248
+ this.transients.set(sessionName, recent);
249
+ if (recent.length < C.TRANSIENT_ESCALATE_COUNT) {
250
+ this.logger.debug('Transient rate limit — the runtime retries it', { sessionName, rule: match.ruleId, count: recent.length });
251
+ return null;
252
+ }
253
+ this.transients.delete(sessionName);
254
+ return { ...match, kind: 'usage_limit', ruleId: `${match.ruleId}+repeated`, resetAt: now + C.TRANSIENT_ESCALATED_HORIZON_MS };
255
+ }
256
+ /**
257
+ * A usage limit was seen in a session.
258
+ *
259
+ * @param sessionName - Session
260
+ * @param runtime - Runtime that is out of usage
261
+ * @param match - The match
262
+ */
263
+ async onUsageLimit(sessionName, runtime, match) {
264
+ const known = this.state.exhausted[runtime];
265
+ const billing = match.kind === 'billing';
266
+ if (known) {
267
+ if (billing && known.kind !== 'billing') {
268
+ // Out of credit trumps a window limit: no reset time to wait for.
269
+ known.kind = 'billing';
270
+ known.ruleId = match.ruleId;
271
+ delete known.until;
272
+ this.save();
273
+ }
274
+ else if (!billing && known.kind !== 'billing' && match.resetAt && known.until !== new Date(match.resetAt).toISOString()) {
275
+ known.until = new Date(match.resetAt).toISOString();
276
+ this.save();
277
+ }
278
+ }
279
+ else {
280
+ const confirmed = await this.confirm(runtime);
281
+ if (!confirmed)
282
+ return;
283
+ if (!this.state.exhausted[runtime]) {
284
+ // The limit came straight back after a switch-back: back off the
285
+ // next probe, and do not tell the owner a second time.
286
+ const recent = this.recentRecoveries.get(runtime);
287
+ const failedRevert = recent !== undefined && this.now() - recent.at < C.FAILED_REVERT_WINDOW_MS;
288
+ this.recentRecoveries.delete(runtime);
289
+ const failedReverts = failedRevert ? recent.failedReverts + 1 : 0;
290
+ this.state.exhausted[runtime] = {
291
+ runtime,
292
+ since: new Date(this.now()).toISOString(),
293
+ ...(match.resetAt && !billing ? { until: new Date(match.resetAt).toISOString() } : {}),
294
+ kind: billing ? 'billing' : 'usage_limit',
295
+ ...(failedReverts > 0 ? { failedReverts } : {}),
296
+ ruleId: match.ruleId,
297
+ switched: [],
298
+ switchedTo: [],
299
+ notified: failedRevert ? recent.notified : false,
300
+ };
301
+ this.save();
302
+ this.logger.info(billing ? 'Runtime is out of credit (no timed retry; probed until it is topped up)' : 'Runtime is out of usage', {
303
+ runtime,
304
+ rule: match.ruleId,
305
+ until: this.state.exhausted[runtime].until ?? null,
306
+ ...(failedReverts > 0 ? { failedReverts } : {}),
307
+ });
308
+ }
309
+ }
310
+ await this.switchSession(sessionName, { waitForSafePoint: true, flushAfter: false });
311
+ }
312
+ /**
313
+ * Confirm a detection with the runtime's probe (one probe per runtime at a time).
314
+ *
315
+ * @param runtime - Runtime
316
+ * @returns False when the probe shows the runtime works (a false positive)
317
+ */
318
+ confirm(runtime) {
319
+ const running = this.confirming.get(runtime);
320
+ if (running)
321
+ return running;
322
+ const run = (async () => {
323
+ const result = await this.deps.probe(runtime).catch(() => 'unknown');
324
+ if (result === 'available') {
325
+ this.mutedUntil.set(runtime, this.now() + C.FALSE_POSITIVE_MUTE_MS);
326
+ this.logger.info('Usage-limit text seen but the runtime answers normally — ignoring it', { runtime });
327
+ return false;
328
+ }
329
+ return true;
330
+ })();
331
+ this.confirming.set(runtime, run);
332
+ void run.finally(() => this.confirming.delete(runtime));
333
+ return run;
334
+ }
335
+ // ------------------------------------------------------------------ switch
336
+ /**
337
+ * Move a session to the next runtime of its chain (or back to its primary).
338
+ *
339
+ * @param sessionName - Session
340
+ * @param opts - Wait for its safe point first; flush queued messages when nothing switched
341
+ * @returns What happened
342
+ */
343
+ async switchSession(sessionName, opts) {
344
+ if (this.switching.has(sessionName))
345
+ return 'skipped';
346
+ this.switching.add(sessionName);
347
+ let outcome = 'skipped';
348
+ try {
349
+ outcome = await this.doSwitch(sessionName, opts.waitForSafePoint);
350
+ return outcome;
351
+ }
352
+ catch (err) {
353
+ this.logger.warn('Runtime switch failed', { sessionName, error: err instanceof Error ? err.message : String(err) });
354
+ outcome = 'failed';
355
+ return outcome;
356
+ }
357
+ finally {
358
+ this.switching.delete(sessionName);
359
+ await this.afterSwitch(sessionName, outcome, opts.flushAfter);
360
+ }
361
+ }
362
+ /**
363
+ * After a switch, once messages are no longer held back: re-deliver what
364
+ * waited for the agent and write out its queue. Messages the gate queued
365
+ * must not wait for an event that will not come, also when nothing switched.
366
+ *
367
+ * @param sessionName - Session
368
+ * @param outcome - How the switch went
369
+ * @param flushAlways - Flush the queue even when nothing switched
370
+ */
371
+ async afterSwitch(sessionName, outcome, flushAlways) {
372
+ const moved = outcome === 'switched' || outcome === 'reverted';
373
+ if (moved)
374
+ await this.deps.redeliver(sessionName).catch(() => undefined);
375
+ if (moved || flushAlways)
376
+ await this.deps.flushQueued(sessionName).catch(() => undefined);
377
+ }
378
+ async doSwitch(sessionName, waitForSafePoint) {
379
+ const agent = await this.deps.getAgent(sessionName);
380
+ if (!agent)
381
+ return 'skipped';
382
+ if (agent.isOrchestrator && !this.state.settings.orcFollows)
383
+ return 'skipped';
384
+ const current = this.state.overrides[sessionName]?.runtime ?? agent.primary;
385
+ if (!this.state.exhausted[current])
386
+ return 'skipped';
387
+ if (waitForSafePoint)
388
+ await this.waitForSafePoint(sessionName);
389
+ const target = await this.pickFallback(agent, current);
390
+ if (!target) {
391
+ this.markNoFallback(current);
392
+ this.logger.warn('No fallback runtime available — the agent waits for its runtime to reset', { sessionName, runtime: current });
393
+ return 'no_fallback';
394
+ }
395
+ const handover = await this.deps
396
+ .writeHandover({
397
+ sessionName,
398
+ from: current,
399
+ to: target,
400
+ direction: 'switch',
401
+ conversationId: this.deps.conversation.get(sessionName) ?? null,
402
+ workItem: await this.deps.getActiveWorkItem(sessionName).catch(() => null),
403
+ })
404
+ .catch(() => null);
405
+ await this.recordSwitch(agent, current, target, handover);
406
+ this.logger.info('Switching agent to its fallback runtime', { sessionName, from: current, to: target, handover });
407
+ const ok = await this.deps.relaunch(agent).catch(() => false);
408
+ if (!ok) {
409
+ this.logger.warn('Relaunch on the fallback runtime failed (the override stays; the next start uses it)', { sessionName, runtime: target });
410
+ return 'failed';
411
+ }
412
+ return 'switched';
413
+ }
414
+ /**
415
+ * Record an override (or clear it when the target is the primary) and
416
+ * prepare the kickoff note.
417
+ *
418
+ * @param agent - Agent
419
+ * @param from - Runtime it leaves (out of usage)
420
+ * @param target - Runtime it goes to
421
+ * @param handover - Handover file, when written
422
+ */
423
+ async recordSwitch(agent, from, target, handover = null) {
424
+ const sessionName = agent.sessionName;
425
+ const existing = this.state.overrides[sessionName];
426
+ const exhausted = this.state.exhausted[from];
427
+ // The primary's conversation is kept for the switch back; the fallback
428
+ // runtime starts fresh.
429
+ const primarySessionId = existing?.primarySessionId ?? (from === agent.primary ? this.deps.conversation.get(sessionName) : undefined);
430
+ this.deps.conversation.clear(sessionName);
431
+ if (target === agent.primary) {
432
+ delete this.state.overrides[sessionName];
433
+ if (primarySessionId)
434
+ this.deps.conversation.set(sessionName, primarySessionId);
435
+ }
436
+ else {
437
+ this.state.overrides[sessionName] = {
438
+ runtime: target,
439
+ primary: agent.primary,
440
+ reason: 'usage_limit',
441
+ since: existing?.since ?? new Date(this.now()).toISOString(),
442
+ ...(this.state.exhausted[agent.primary]?.until ? { until: this.state.exhausted[agent.primary].until } : {}),
443
+ ...(primarySessionId ? { primarySessionId } : {}),
444
+ };
445
+ }
446
+ if (exhausted) {
447
+ if (!exhausted.switched.includes(sessionName))
448
+ exhausted.switched.push(sessionName);
449
+ if (!exhausted.switchedTo.includes(target))
450
+ exhausted.switchedTo.push(target);
451
+ }
452
+ this.save();
453
+ const workItem = await this.deps.getActiveWorkItem(sessionName).catch(() => null);
454
+ this.kickoffNotes.set(sessionName, this.switchNote(from, target, exhausted?.until, handover, workItem));
455
+ this.scheduleNotice(from);
456
+ }
457
+ /**
458
+ * Wait until the agent is not mid-turn (bounded: a usage limit ends the turn anyway).
459
+ *
460
+ * @param sessionName - Session
461
+ */
462
+ async waitForSafePoint(sessionName) {
463
+ const deadline = this.now() + C.SAFE_POINT_MAX_WAIT_MS;
464
+ while (this.now() < deadline) {
465
+ const busy = await this.deps.isBusy(sessionName).catch(() => false);
466
+ if (!busy)
467
+ return;
468
+ await this.sleep(C.SAFE_POINT_POLL_MS);
469
+ }
470
+ }
471
+ /**
472
+ * First runtime of the agent's chain that is not `current`, not out of
473
+ * usage, and installed + signed in.
474
+ *
475
+ * @param agent - Agent
476
+ * @param current - Runtime it is on (out of usage)
477
+ * @returns Runtime, or null
478
+ */
479
+ async pickFallback(agent, current) {
480
+ const available = await this.getAvailability();
481
+ const selectable = new Set(available.filter((a) => a.selectable).map((a) => a.runtime));
482
+ for (const runtime of this.chainFor(agent)) {
483
+ if (runtime === current || this.state.exhausted[runtime])
484
+ continue;
485
+ if (selectable.has(runtime))
486
+ return runtime;
487
+ }
488
+ return null;
489
+ }
490
+ /**
491
+ * The agent's chain: its own, or the global one.
492
+ *
493
+ * @param agent - Agent
494
+ * @returns Chain
495
+ */
496
+ chainFor(agent) {
497
+ const own = agent.memberId ? this.state.settings.memberChains[agent.memberId] : undefined;
498
+ return own && own.length > 0 ? own : this.state.settings.chain;
499
+ }
500
+ /**
501
+ * Whether some runtime could take over (synchronous; uses the cached
502
+ * availability, optimistic when nothing is cached yet).
503
+ *
504
+ * @param current - Runtime out of usage
505
+ * @returns True when a candidate exists
506
+ */
507
+ hasCandidateSync(current) {
508
+ const candidates = this.state.settings.chain.filter((r) => r !== current && !this.state.exhausted[r]);
509
+ const memberCandidates = Object.values(this.state.settings.memberChains).flat().filter((r) => r !== current && !this.state.exhausted[r]);
510
+ const all = [...candidates, ...memberCandidates];
511
+ if (!this.availability)
512
+ return all.length > 0;
513
+ const selectable = new Set(this.availability.list.filter((a) => a.selectable).map((a) => a.runtime));
514
+ return all.some((r) => selectable.has(r));
515
+ }
516
+ /**
517
+ * Availability, cached for 5 minutes.
518
+ *
519
+ * @param force - Ignore the cache
520
+ * @returns List
521
+ */
522
+ async getAvailability(force = false) {
523
+ const ttl = 5 * 60_000;
524
+ if (!force && this.availability && this.now() - this.availability.at < ttl)
525
+ return this.availability.list;
526
+ try {
527
+ const list = await this.deps.getAvailability(this.state.settings);
528
+ this.availability = { at: this.now(), list };
529
+ return list;
530
+ }
531
+ catch (err) {
532
+ this.logger.warn('Could not read runtime availability', { error: err instanceof Error ? err.message : String(err) });
533
+ return this.availability?.list ?? [];
534
+ }
535
+ }
536
+ markNoFallback(runtime) {
537
+ const exhausted = this.state.exhausted[runtime];
538
+ if (!exhausted || exhausted.noFallback)
539
+ return;
540
+ exhausted.noFallback = true;
541
+ this.save();
542
+ this.scheduleNotice(runtime);
543
+ }
544
+ // ------------------------------------------------------------- switch back
545
+ /**
546
+ * Periodic work: owner notices, switch-back checks, idle-boundary reverts.
547
+ */
548
+ async tick() {
549
+ if (this.ticking)
550
+ return;
551
+ this.ticking = true;
552
+ try {
553
+ await this.flushNotices();
554
+ for (const runtime of Object.keys(this.state.exhausted)) {
555
+ await this.checkRecovery(runtime);
556
+ }
557
+ await this.revertIdle();
558
+ }
559
+ catch (err) {
560
+ this.logger.warn('Runtime fallback tick failed', { error: err instanceof Error ? err.message : String(err) });
561
+ }
562
+ finally {
563
+ this.ticking = false;
564
+ }
565
+ }
566
+ /**
567
+ * Is an exhausted runtime back?
568
+ *
569
+ * @param runtime - Runtime
570
+ */
571
+ async checkRecovery(runtime) {
572
+ const entry = this.state.exhausted[runtime];
573
+ if (!entry)
574
+ return;
575
+ const now = this.now();
576
+ if (!this.isRecoveryCheckDue(entry, now))
577
+ return;
578
+ const result = await this.deps.probe(runtime).catch(() => 'unknown');
579
+ entry.lastProbeAt = new Date(now).toISOString();
580
+ const until = entry.until ? Date.parse(entry.until) : null;
581
+ const resetPassed = until !== null && now >= until;
582
+ // Only a probe that answered normally proves the runtime works. A
583
+ // runtime without a probe (`unsupported`) may come back on its parsed
584
+ // reset time; a billing limit has none and never comes back on a clock.
585
+ const back = result === 'available' || (result === 'unsupported' && entry.kind !== 'billing' && resetPassed);
586
+ if (!back) {
587
+ // The reset time passed but it is still limited: probe on the interval from now on.
588
+ if (result === 'limited' && resetPassed)
589
+ delete entry.until;
590
+ this.save();
591
+ this.logger.info(entry.kind === 'billing' ? 'Runtime is still out of credit' : 'Runtime is still out of usage', { runtime, probe: result });
592
+ return;
593
+ }
594
+ await this.recover(runtime);
595
+ }
596
+ /**
597
+ * Whether a switch-back probe is due for an exhausted runtime.
598
+ *
599
+ * - `billing`: every BILLING_PROBE_INTERVAL_MS, whatever any clock says.
600
+ * - With a reset time: once it (plus a grace) passed.
601
+ * - Otherwise: on the owner's probe interval.
602
+ *
603
+ * Each failed switch-back doubles the interval (up to MAX_PROBE_BACKOFF_MS).
604
+ *
605
+ * @param entry - Exhausted runtime
606
+ * @param now - Current time
607
+ * @returns True when a probe should run now
608
+ */
609
+ isRecoveryCheckDue(entry, now) {
610
+ const lastCheck = Date.parse(entry.lastProbeAt ?? entry.since);
611
+ const baseMs = entry.kind === 'billing' ? C.BILLING_PROBE_INTERVAL_MS : this.state.settings.probeIntervalMinutes * 60_000;
612
+ const backoffMs = Math.min(baseMs * 2 ** Math.min(entry.failedReverts ?? 0, 16), Math.max(baseMs, C.MAX_PROBE_BACKOFF_MS));
613
+ const sinceLast = now - lastCheck;
614
+ if (entry.kind === 'billing')
615
+ return sinceLast >= backoffMs;
616
+ const until = entry.until ? Date.parse(entry.until) : null;
617
+ if (until !== null) {
618
+ const minGap = entry.failedReverts ? backoffMs : C.RESET_GRACE_MS;
619
+ return now >= until + C.RESET_GRACE_MS && sinceLast >= minGap;
620
+ }
621
+ return sinceLast >= backoffMs;
622
+ }
623
+ /**
624
+ * A runtime has usage again: mark every agent that left it for revert and tell the owner.
625
+ *
626
+ * @param runtime - Runtime
627
+ */
628
+ async recover(runtime) {
629
+ const entry = this.state.exhausted[runtime];
630
+ if (!entry)
631
+ return;
632
+ delete this.state.exhausted[runtime];
633
+ this.noticeDue.delete(runtime);
634
+ this.recentRecoveries.set(runtime, { at: this.now(), failedReverts: entry.failedReverts ?? 0, notified: entry.notified });
635
+ const reverting = [];
636
+ for (const override of Object.values(this.state.overrides)) {
637
+ if (override.primary === runtime) {
638
+ override.revertPending = true;
639
+ reverting.push(override);
640
+ }
641
+ }
642
+ this.save();
643
+ this.logger.info('Runtime has usage again', { runtime, agentsToRevert: reverting.length });
644
+ if (entry.notified && reverting.length > 0) {
645
+ const fallbacks = [...new Set(reverting.map((o) => this.label(o.runtime)))];
646
+ await this.notify(`${this.label(runtime)} is available again on ${this.deps.machineName()}. ` +
647
+ `${agents(reverting.length)} ${reverting.length === 1 ? 'is' : 'are'} switching back from ${fallbacks.join(' / ')} as ${reverting.length === 1 ? 'it finishes its' : 'they finish their'} current turn.`);
648
+ }
649
+ await this.revertIdle();
650
+ }
651
+ /** Revert every pending override whose agent is idle (or not running). */
652
+ async revertIdle() {
653
+ for (const [sessionName, override] of Object.entries(this.state.overrides)) {
654
+ if (this.state.exhausted[override.primary])
655
+ continue;
656
+ if (!override.revertPending) {
657
+ // State from before a restart whose primary is no longer marked out of usage.
658
+ override.revertPending = true;
659
+ this.save();
660
+ }
661
+ if (this.switching.has(sessionName))
662
+ continue;
663
+ if (!this.deps.isLive(sessionName)) {
664
+ this.finishRevertOffline(sessionName, override);
665
+ continue;
666
+ }
667
+ if (await this.deps.isBusy(sessionName).catch(() => true))
668
+ continue;
669
+ await this.revertSession(sessionName);
670
+ }
671
+ }
672
+ /**
673
+ * Clear the override of an agent that is not running.
674
+ *
675
+ * @param sessionName - Session
676
+ * @param override - Its override
677
+ */
678
+ finishRevertOffline(sessionName, override) {
679
+ delete this.state.overrides[sessionName];
680
+ if (override.primarySessionId)
681
+ this.deps.conversation.set(sessionName, override.primarySessionId);
682
+ else
683
+ this.deps.conversation.clear(sessionName);
684
+ this.save();
685
+ this.logger.info('Fallback ended for a stopped agent (its next start uses its own runtime)', { sessionName, runtime: override.primary });
686
+ }
687
+ /**
688
+ * Move an idle agent back to its configured runtime.
689
+ *
690
+ * @param sessionName - Session
691
+ * @returns Outcome
692
+ */
693
+ async revertSession(sessionName) {
694
+ if (!this.state.overrides[sessionName] || this.switching.has(sessionName))
695
+ return 'skipped';
696
+ this.switching.add(sessionName);
697
+ let outcome = 'skipped';
698
+ try {
699
+ outcome = await this.doRevert(sessionName);
700
+ return outcome;
701
+ }
702
+ finally {
703
+ this.switching.delete(sessionName);
704
+ await this.afterSwitch(sessionName, outcome, false);
705
+ }
706
+ }
707
+ async doRevert(sessionName) {
708
+ const override = this.state.overrides[sessionName];
709
+ if (!override)
710
+ return 'skipped';
711
+ {
712
+ // Last look right before: anything that started since means "not now".
713
+ if (await this.deps.isBusy(sessionName).catch(() => true))
714
+ return 'skipped';
715
+ const agent = (await this.deps.getAgent(sessionName)) ?? null;
716
+ if (!agent)
717
+ return 'skipped';
718
+ const workItem = await this.deps.getActiveWorkItem(sessionName).catch(() => null);
719
+ const handover = await this.deps
720
+ .writeHandover({
721
+ sessionName,
722
+ from: override.runtime,
723
+ to: override.primary,
724
+ direction: 'revert',
725
+ conversationId: this.deps.conversation.get(sessionName) ?? null,
726
+ workItem,
727
+ })
728
+ .catch(() => null);
729
+ delete this.state.overrides[sessionName];
730
+ if (override.primarySessionId)
731
+ this.deps.conversation.set(sessionName, override.primarySessionId);
732
+ else
733
+ this.deps.conversation.clear(sessionName);
734
+ this.save();
735
+ this.kickoffNotes.set(sessionName, this.revertNote(override, handover, workItem));
736
+ this.logger.info('Switching agent back to its own runtime at an idle boundary', { sessionName, from: override.runtime, to: override.primary });
737
+ const ok = await this.deps.relaunch(agent).catch(() => false);
738
+ if (!ok) {
739
+ this.logger.warn('Relaunch on the primary runtime failed (its next start uses it)', { sessionName });
740
+ return 'failed';
741
+ }
742
+ return 'reverted';
743
+ }
744
+ }
745
+ // ----------------------------------------------------------------- notices
746
+ scheduleNotice(runtime) {
747
+ const entry = this.state.exhausted[runtime];
748
+ if (!entry || entry.notified || this.noticeDue.has(runtime))
749
+ return;
750
+ this.noticeDue.set(runtime, this.now() + C.NOTICE_DELAY_MS);
751
+ const t = setTimeout(() => void this.flushNotices(), C.NOTICE_DELAY_MS + 100);
752
+ t.unref?.();
753
+ }
754
+ /** Send every owner notice that is due (once per event). */
755
+ async flushNotices() {
756
+ // Events from before a restart that were never sent.
757
+ for (const entry of Object.values(this.state.exhausted)) {
758
+ if (!entry.notified && !this.noticeDue.has(entry.runtime) && (entry.switched.length > 0 || entry.noFallback)) {
759
+ this.noticeDue.set(entry.runtime, this.now());
760
+ }
761
+ }
762
+ for (const [runtime, due] of [...this.noticeDue]) {
763
+ if (due > this.now())
764
+ continue;
765
+ const entry = this.state.exhausted[runtime];
766
+ if (!entry || entry.notified) {
767
+ this.noticeDue.delete(runtime);
768
+ continue;
769
+ }
770
+ const text = await this.limitNoticeText(entry);
771
+ const sent = await this.notify(text);
772
+ if (sent) {
773
+ entry.notified = true;
774
+ this.noticeDue.delete(runtime);
775
+ this.save();
776
+ }
777
+ }
778
+ }
779
+ async limitNoticeText(entry) {
780
+ if (entry.kind === 'billing')
781
+ return this.billingNoticeText(entry);
782
+ const label = this.label(entry.runtime);
783
+ const reset = entry.until ? ` (resets ~${this.formatTime(Date.parse(entry.until))})` : '';
784
+ const head = `${label} hit its usage limit on ${this.deps.machineName()}${reset}.`;
785
+ const n = entry.switched.length;
786
+ if (n === 0) {
787
+ return `${head} No fallback runtime is available, so its agents wait until it resets. Set one in Settings → Runtimes.`;
788
+ }
789
+ const targets = entry.switchedTo.map((r) => this.label(r)).join(' / ');
790
+ let text = `${head} ${agents(n)} switched to ${targets} until then.`;
791
+ const total = this.deps.countAgentsOnRuntime ? await this.deps.countAgentsOnRuntime(entry.runtime).catch(() => n) : n;
792
+ if (total > n)
793
+ text += ' The others switch when they next get work.';
794
+ if (entry.noFallback)
795
+ text += ' Some agents had no fallback available and wait for the reset.';
796
+ return text;
797
+ }
798
+ /**
799
+ * "DeepSeek is out of credit — top up at platform.deepseek.com. Orc is
800
+ * running on Claude Code meanwhile."
801
+ *
802
+ * @param entry - The billing event
803
+ * @returns Owner message
804
+ */
805
+ async billingNoticeText(entry) {
806
+ const label = this.label(entry.runtime);
807
+ const url = this.topUpUrl(entry);
808
+ const head = `${label} is out of credit — ${url ? `top up at ${url}` : 'top up its account'}.`;
809
+ if (entry.switched.length === 0) {
810
+ return `${head} Its agents wait until it is topped up: no fallback runtime is available (set one in Settings → Runtimes).`;
811
+ }
812
+ const names = [];
813
+ for (const sessionName of entry.switched) {
814
+ const agent = await this.deps.getAgent(sessionName).catch(() => null);
815
+ names.push(agent?.name ?? sessionName);
816
+ }
817
+ const who = names.length <= 2 ? names.join(' and ') : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
818
+ const targets = entry.switchedTo.map((r) => this.label(r)).join(' / ');
819
+ let text = `${head} ${who} ${names.length === 1 ? 'is' : 'are'} running on ${targets} meanwhile.`;
820
+ if (entry.noFallback)
821
+ text += ' Some agents had no fallback available and wait for the top-up.';
822
+ return text;
823
+ }
824
+ /**
825
+ * Where to top up the account behind a billing limit.
826
+ *
827
+ * @param entry - The billing event
828
+ * @returns Host/path, or null when unknown
829
+ */
830
+ topUpUrl(entry) {
831
+ let provider = null;
832
+ if (entry.runtime === RUNTIME_TYPES.CLAUDE_CODE)
833
+ provider = 'anthropic';
834
+ else if (entry.runtime === RUNTIME_TYPES.CODEX_CLI)
835
+ provider = 'openai';
836
+ else if (entry.runtime === RUNTIME_TYPES.CREWLY_AGENT) {
837
+ // "Insufficient Balance" is DeepSeek's wording.
838
+ if (entry.ruleId.endsWith('insufficient_balance'))
839
+ provider = 'deepseek';
840
+ else
841
+ provider = this.state.settings.crewlyAgentModel.split('/')[0] ?? null;
842
+ }
843
+ return provider ? (C.TOP_UP_URLS[provider] ?? null) : null;
844
+ }
845
+ async notify(text) {
846
+ const notifier = this.deps.notifier?.() ?? null;
847
+ if (!notifier)
848
+ return false;
849
+ try {
850
+ const delivered = await notifier.sendToOwner(text);
851
+ return delivered !== false;
852
+ }
853
+ catch {
854
+ return false;
855
+ }
856
+ }
857
+ // -------------------------------------------------------------------- text
858
+ formatTime(epochMs) {
859
+ const tz = this.deps.timeZone;
860
+ const sameDay = new Date(epochMs).toDateString() === new Date(this.now()).toDateString() && epochMs - this.now() < 24 * 3600_000;
861
+ return new Intl.DateTimeFormat('en-US', {
862
+ ...(sameDay ? {} : { month: 'short', day: 'numeric' }),
863
+ hour: 'numeric',
864
+ minute: '2-digit',
865
+ timeZoneName: 'short',
866
+ ...(tz ? { timeZone: tz } : {}),
867
+ }).format(new Date(epochMs));
868
+ }
869
+ switchNote(from, to, until, handover, workItem) {
870
+ const reset = until ? ` (it resets ~${this.formatTime(Date.parse(until))})` : '';
871
+ const billing = this.state.exhausted[from]?.kind === 'billing';
872
+ const parts = [
873
+ billing
874
+ ? `Crewly moved you from ${this.label(from)} to ${this.label(to)} because ${this.label(from)} is out of credit; you will be moved back once it is topped up.`
875
+ : `Crewly moved you from ${this.label(from)} to ${this.label(to)} because ${this.label(from)} hit its usage limit${reset}; you will be moved back when it resets.`,
876
+ handover
877
+ ? `This is a fresh conversation: after registering, read ${handover} once — it holds the end of your previous conversation.`
878
+ : 'This is a fresh conversation: your tasks, teams and wiki are all still in Crewly.',
879
+ ];
880
+ if (workItem)
881
+ parts.push(`Then continue WorkItem ${workItem.id} ("${workItem.title}") where you left off.`);
882
+ return parts.join(' ');
883
+ }
884
+ revertNote(override, handover, workItem) {
885
+ const parts = [
886
+ `${this.label(override.primary)} is available again, so Crewly moved you back from ${this.label(override.runtime)}.`,
887
+ handover
888
+ ? `Work went on while you were away: read ${handover} once for what happened since.`
889
+ : 'Work went on while you were away: check your WorkItems and wiki for what happened since.',
890
+ ];
891
+ if (workItem)
892
+ parts.push(`Then continue WorkItem ${workItem.id} ("${workItem.title}").`);
893
+ return parts.join(' ');
894
+ }
895
+ // ---------------------------------------------------------------- snapshot
896
+ /**
897
+ * Badge data for an agent running on a fallback.
898
+ *
899
+ * @param sessionName - Session
900
+ * @returns Override view, or null
901
+ */
902
+ overrideView(sessionName) {
903
+ const override = this.state.overrides[sessionName];
904
+ if (!override)
905
+ return null;
906
+ const label = this.label(override.runtime);
907
+ return {
908
+ ...override,
909
+ sessionName,
910
+ runtimeLabel: label,
911
+ primaryLabel: this.label(override.primary),
912
+ badge: `on ${label} (${runtimeShortLabel(override.primary)} limit)`,
913
+ };
914
+ }
915
+ /**
916
+ * Everything the API shows.
917
+ *
918
+ * @returns Snapshot
919
+ */
920
+ async snapshot() {
921
+ const runtimes = (await this.getAvailability()).map((a) => ({ ...a, exhausted: Boolean(this.state.exhausted[a.runtime]) }));
922
+ return {
923
+ settings: this.getSettings(),
924
+ runtimes,
925
+ exhausted: Object.values(this.state.exhausted).map((e) => ({ ...e })),
926
+ overrides: Object.keys(this.state.overrides)
927
+ .map((s) => this.overrideView(s))
928
+ .filter((v) => v !== null),
929
+ };
930
+ }
931
+ // ------------------------------------------------------------------ helpers
932
+ label(runtime) {
933
+ return runtimeLabel(runtime, this.state.settings.crewlyAgentModel);
934
+ }
935
+ decision(runtime) {
936
+ return {
937
+ runtime,
938
+ overridden: true,
939
+ ...(runtime === RUNTIME_TYPES.CREWLY_AGENT ? { crewlyAgentModel: this.state.settings.crewlyAgentModel } : {}),
940
+ };
941
+ }
942
+ isExempt(sessionName) {
943
+ if (this.deps.isExempt)
944
+ return this.deps.isExempt(sessionName);
945
+ return sessionName.startsWith(C.SMOKE.TEAM_PREFIX);
946
+ }
947
+ save() {
948
+ try {
949
+ this.deps.store.save(this.state);
950
+ }
951
+ catch (err) {
952
+ this.logger.warn('Could not save runtime-fallback state', { error: err instanceof Error ? err.message : String(err) });
953
+ }
954
+ }
955
+ }
956
+ /** The backend's instance (set by the wiring at boot). */
957
+ let backendInstance = null;
958
+ /**
959
+ * The running backend's runtime-fallback service.
960
+ *
961
+ * @returns The instance, or null before boot wired it (and in tests)
962
+ */
963
+ export function getRuntimeFallbackService() {
964
+ return backendInstance;
965
+ }
966
+ /**
967
+ * Set (or clear) the backend instance.
968
+ *
969
+ * @param service - Instance, or null
970
+ */
971
+ export function setRuntimeFallbackService(service) {
972
+ backendInstance = service;
973
+ }
974
+ //# sourceMappingURL=runtime-fallback.service.js.map