@prestyj/cli 5.38.0 → 5.39.1

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 (229) hide show
  1. package/README.md +92 -42
  2. package/dist/app-sidecar/fleet-adapter.d.ts +138 -0
  3. package/dist/app-sidecar/fleet-adapter.js +356 -0
  4. package/dist/app-sidecar/fleet-adapter.js.map +1 -0
  5. package/dist/app-sidecar/fleet-routes.d.ts +4 -0
  6. package/dist/app-sidecar/fleet-routes.js +109 -0
  7. package/dist/app-sidecar/fleet-routes.js.map +1 -0
  8. package/dist/app-sidecar/goal-routes.d.ts +20 -0
  9. package/dist/app-sidecar/goal-routes.js +42 -1
  10. package/dist/app-sidecar/goal-routes.js.map +1 -1
  11. package/dist/app-sidecar.js +5 -0
  12. package/dist/app-sidecar.js.map +1 -1
  13. package/dist/cli/cloud.d.ts +45 -0
  14. package/dist/cli/cloud.js +241 -0
  15. package/dist/cli/cloud.js.map +1 -0
  16. package/dist/cli/command-routing.d.ts +3 -2
  17. package/dist/cli/command-routing.js +24 -3
  18. package/dist/cli/command-routing.js.map +1 -1
  19. package/dist/cli/fleet.d.ts +19 -3
  20. package/dist/cli/fleet.js +107 -33
  21. package/dist/cli/fleet.js.map +1 -1
  22. package/dist/cli/goals.d.ts +11 -0
  23. package/dist/cli/goals.js +115 -0
  24. package/dist/cli/goals.js.map +1 -0
  25. package/dist/cli/node.d.ts +18 -1
  26. package/dist/cli/node.js +303 -33
  27. package/dist/cli/node.js.map +1 -1
  28. package/dist/cli.js +6 -0
  29. package/dist/cli.js.map +1 -1
  30. package/dist/core/agent-session.d.ts +8 -0
  31. package/dist/core/agent-session.js +18 -1
  32. package/dist/core/agent-session.js.map +1 -1
  33. package/dist/core/cloud/claude.d.ts +128 -0
  34. package/dist/core/cloud/claude.js +836 -0
  35. package/dist/core/cloud/claude.js.map +1 -0
  36. package/dist/core/cloud/cloud-agent.d.ts +136 -0
  37. package/dist/core/cloud/cloud-agent.js +783 -0
  38. package/dist/core/cloud/cloud-agent.js.map +1 -0
  39. package/dist/core/cloud/codex.d.ts +154 -0
  40. package/dist/core/cloud/codex.js +622 -0
  41. package/dist/core/cloud/codex.js.map +1 -0
  42. package/dist/core/cloud/config.d.ts +69 -0
  43. package/dist/core/cloud/config.js +86 -0
  44. package/dist/core/cloud/config.js.map +1 -0
  45. package/dist/core/cloud/git.d.ts +15 -0
  46. package/dist/core/cloud/git.js +33 -0
  47. package/dist/core/cloud/git.js.map +1 -0
  48. package/dist/core/cloud/registry.d.ts +13 -0
  49. package/dist/core/cloud/registry.js +64 -0
  50. package/dist/core/cloud/registry.js.map +1 -0
  51. package/dist/core/cloud/runner.d.ts +46 -0
  52. package/dist/core/cloud/runner.js +99 -0
  53. package/dist/core/cloud/runner.js.map +1 -0
  54. package/dist/core/cloud/snapshot.d.ts +23 -0
  55. package/dist/core/cloud/snapshot.js +98 -0
  56. package/dist/core/cloud/snapshot.js.map +1 -0
  57. package/dist/core/cloud/types.d.ts +139 -0
  58. package/dist/core/cloud/types.js +28 -0
  59. package/dist/core/cloud/types.js.map +1 -0
  60. package/dist/core/fleet/client.d.ts +106 -6
  61. package/dist/core/fleet/client.js +352 -20
  62. package/dist/core/fleet/client.js.map +1 -1
  63. package/dist/core/fleet/cloud-jobs.d.ts +59 -0
  64. package/dist/core/fleet/cloud-jobs.js +131 -0
  65. package/dist/core/fleet/cloud-jobs.js.map +1 -0
  66. package/dist/core/fleet/discovery.d.ts +2 -0
  67. package/dist/core/fleet/discovery.js +3 -1
  68. package/dist/core/fleet/discovery.js.map +1 -1
  69. package/dist/core/fleet/fleet-scheduler.d.ts +4 -0
  70. package/dist/core/fleet/fleet-scheduler.js +11 -1
  71. package/dist/core/fleet/fleet-scheduler.js.map +1 -1
  72. package/dist/core/fleet/git.d.ts +7 -0
  73. package/dist/core/fleet/git.js +22 -1
  74. package/dist/core/fleet/git.js.map +1 -1
  75. package/dist/core/fleet/machines.d.ts +112 -0
  76. package/dist/core/fleet/machines.js +219 -0
  77. package/dist/core/fleet/machines.js.map +1 -0
  78. package/dist/core/fleet/node/agents.d.ts +2 -0
  79. package/dist/core/fleet/node/agents.js +195 -9
  80. package/dist/core/fleet/node/agents.js.map +1 -1
  81. package/dist/core/fleet/node/config.d.ts +37 -3
  82. package/dist/core/fleet/node/config.js +201 -40
  83. package/dist/core/fleet/node/config.js.map +1 -1
  84. package/dist/core/fleet/node/context.d.ts +19 -1
  85. package/dist/core/fleet/node/docker.d.ts +13 -5
  86. package/dist/core/fleet/node/docker.js +132 -66
  87. package/dist/core/fleet/node/docker.js.map +1 -1
  88. package/dist/core/fleet/node/doctor.d.ts +29 -0
  89. package/dist/core/fleet/node/doctor.js +202 -0
  90. package/dist/core/fleet/node/doctor.js.map +1 -0
  91. package/dist/core/fleet/node/env.d.ts +7 -0
  92. package/dist/core/fleet/node/env.js +51 -0
  93. package/dist/core/fleet/node/env.js.map +1 -0
  94. package/dist/core/fleet/node/gc.d.ts +46 -0
  95. package/dist/core/fleet/node/gc.js +140 -0
  96. package/dist/core/fleet/node/gc.js.map +1 -0
  97. package/dist/core/fleet/node/goals.d.ts +43 -0
  98. package/dist/core/fleet/node/goals.js +418 -0
  99. package/dist/core/fleet/node/goals.js.map +1 -0
  100. package/dist/core/fleet/node/jobs.d.ts +37 -2
  101. package/dist/core/fleet/node/jobs.js +236 -15
  102. package/dist/core/fleet/node/jobs.js.map +1 -1
  103. package/dist/core/fleet/node/local-client.d.ts +9 -0
  104. package/dist/core/fleet/node/local-client.js +29 -0
  105. package/dist/core/fleet/node/local-client.js.map +1 -0
  106. package/dist/core/fleet/node/ops-routes.d.ts +15 -0
  107. package/dist/core/fleet/node/ops-routes.js +84 -0
  108. package/dist/core/fleet/node/ops-routes.js.map +1 -0
  109. package/dist/core/fleet/node/pair-code-route.d.ts +14 -0
  110. package/dist/core/fleet/node/pair-code-route.js +76 -0
  111. package/dist/core/fleet/node/pair-code-route.js.map +1 -0
  112. package/dist/core/fleet/node/secrets.d.ts +43 -0
  113. package/dist/core/fleet/node/secrets.js +184 -0
  114. package/dist/core/fleet/node/secrets.js.map +1 -0
  115. package/dist/core/fleet/node/server.d.ts +22 -1
  116. package/dist/core/fleet/node/server.js +210 -21
  117. package/dist/core/fleet/node/server.js.map +1 -1
  118. package/dist/core/fleet/node/state.d.ts +24 -1
  119. package/dist/core/fleet/node/state.js +12 -3
  120. package/dist/core/fleet/node/state.js.map +1 -1
  121. package/dist/core/fleet/node/tls.d.ts +17 -0
  122. package/dist/core/fleet/node/tls.js +49 -0
  123. package/dist/core/fleet/node/tls.js.map +1 -0
  124. package/dist/core/fleet/node/uninstall.d.ts +27 -0
  125. package/dist/core/fleet/node/uninstall.js +100 -0
  126. package/dist/core/fleet/node/uninstall.js.map +1 -0
  127. package/dist/core/fleet/node/update.d.ts +28 -0
  128. package/dist/core/fleet/node/update.js +62 -0
  129. package/dist/core/fleet/node/update.js.map +1 -0
  130. package/dist/core/fleet/node/workspace.d.ts +4 -0
  131. package/dist/core/fleet/node/workspace.js +38 -9
  132. package/dist/core/fleet/node/workspace.js.map +1 -1
  133. package/dist/core/fleet/node-load.d.ts +4 -0
  134. package/dist/core/fleet/node-load.js +62 -0
  135. package/dist/core/fleet/node-load.js.map +1 -0
  136. package/dist/core/fleet/project-config.d.ts +10 -0
  137. package/dist/core/fleet/project-config.js +39 -1
  138. package/dist/core/fleet/project-config.js.map +1 -1
  139. package/dist/core/fleet/prompt-hint.d.ts +11 -0
  140. package/dist/core/fleet/prompt-hint.js +47 -0
  141. package/dist/core/fleet/prompt-hint.js.map +1 -0
  142. package/dist/core/fleet/propose-config.d.ts +26 -0
  143. package/dist/core/fleet/propose-config.js +95 -0
  144. package/dist/core/fleet/propose-config.js.map +1 -0
  145. package/dist/core/fleet/protocol.d.ts +97 -1
  146. package/dist/core/fleet/protocol.js +10 -1
  147. package/dist/core/fleet/protocol.js.map +1 -1
  148. package/dist/core/fleet/registry.d.ts +12 -1
  149. package/dist/core/fleet/registry.js +39 -7
  150. package/dist/core/fleet/registry.js.map +1 -1
  151. package/dist/core/fleet/remote-agent-nodes.d.ts +56 -8
  152. package/dist/core/fleet/remote-agent-nodes.js +162 -22
  153. package/dist/core/fleet/remote-agent-nodes.js.map +1 -1
  154. package/dist/core/fleet/remote-agent.d.ts +52 -1
  155. package/dist/core/fleet/remote-agent.js +220 -40
  156. package/dist/core/fleet/remote-agent.js.map +1 -1
  157. package/dist/core/fleet/service.d.ts +95 -3
  158. package/dist/core/fleet/service.js +762 -35
  159. package/dist/core/fleet/service.js.map +1 -1
  160. package/dist/core/fleet/store.js +22 -5
  161. package/dist/core/fleet/store.js.map +1 -1
  162. package/dist/core/fleet/types.d.ts +36 -1
  163. package/dist/core/fleet/types.js +12 -2
  164. package/dist/core/fleet/types.js.map +1 -1
  165. package/dist/core/goal-controller.d.ts +1 -0
  166. package/dist/core/goal-controller.js +1 -1
  167. package/dist/core/goal-controller.js.map +1 -1
  168. package/dist/core/goal-fleet.d.ts +117 -0
  169. package/dist/core/goal-fleet.js +441 -0
  170. package/dist/core/goal-fleet.js.map +1 -0
  171. package/dist/core/goal-headless.d.ts +45 -0
  172. package/dist/core/goal-headless.js +177 -0
  173. package/dist/core/goal-headless.js.map +1 -0
  174. package/dist/core/goal-remote-worker.d.ts +45 -0
  175. package/dist/core/goal-remote-worker.js +157 -0
  176. package/dist/core/goal-remote-worker.js.map +1 -0
  177. package/dist/core/goal-store.d.ts +36 -0
  178. package/dist/core/goal-store.js +69 -1
  179. package/dist/core/goal-store.js.map +1 -1
  180. package/dist/core/goal-verifier.d.ts +5 -0
  181. package/dist/core/goal-verifier.js +10 -0
  182. package/dist/core/goal-verifier.js.map +1 -1
  183. package/dist/core/goal-worker.d.ts +12 -0
  184. package/dist/core/goal-worker.js +162 -8
  185. package/dist/core/goal-worker.js.map +1 -1
  186. package/dist/core/subagent-manager.d.ts +12 -5
  187. package/dist/core/subagent-manager.js +15 -10
  188. package/dist/core/subagent-manager.js.map +1 -1
  189. package/dist/core/validation/backends.d.ts +34 -5
  190. package/dist/core/validation/backends.js +45 -5
  191. package/dist/core/validation/backends.js.map +1 -1
  192. package/dist/core/validation/cloud-backend.d.ts +77 -0
  193. package/dist/core/validation/cloud-backend.js +343 -0
  194. package/dist/core/validation/cloud-backend.js.map +1 -0
  195. package/dist/core/validation/config.js +9 -2
  196. package/dist/core/validation/config.js.map +1 -1
  197. package/dist/core/validation/node-backend.d.ts +2 -0
  198. package/dist/core/validation/node-backend.js +5 -0
  199. package/dist/core/validation/node-backend.js.map +1 -1
  200. package/dist/core/validation/scheduler.d.ts +11 -0
  201. package/dist/core/validation/scheduler.js +34 -7
  202. package/dist/core/validation/scheduler.js.map +1 -1
  203. package/dist/core/validation/service.d.ts +6 -0
  204. package/dist/core/validation/service.js +51 -13
  205. package/dist/core/validation/service.js.map +1 -1
  206. package/dist/core/validation/types.d.ts +14 -0
  207. package/dist/modes/acp-mode.d.ts +3 -1
  208. package/dist/modes/acp-mode.js +2 -1
  209. package/dist/modes/acp-mode.js.map +1 -1
  210. package/dist/system-prompt.d.ts +5 -0
  211. package/dist/system-prompt.js +3 -0
  212. package/dist/system-prompt.js.map +1 -1
  213. package/dist/tools/fleet.d.ts +40 -4
  214. package/dist/tools/fleet.js +228 -17
  215. package/dist/tools/fleet.js.map +1 -1
  216. package/dist/tools/goals.d.ts +4 -1
  217. package/dist/tools/goals.js +45 -5
  218. package/dist/tools/goals.js.map +1 -1
  219. package/dist/tools/index.d.ts +7 -0
  220. package/dist/tools/index.js +6 -1
  221. package/dist/tools/index.js.map +1 -1
  222. package/dist/tools/steroids.d.ts +1 -1
  223. package/dist/tools/subagent-control.js +1 -1
  224. package/dist/tools/subagent-control.js.map +1 -1
  225. package/dist/tools/validate.js +1 -1
  226. package/dist/tools/validate.js.map +1 -1
  227. package/dist/ui/App.js +2 -0
  228. package/dist/ui/App.js.map +1 -1
  229. package/package.json +6 -4
@@ -7,16 +7,41 @@ import { EventEmitter } from "node:events";
7
7
  import { randomBytes } from "node:crypto";
8
8
  import fs from "node:fs";
9
9
  import path from "node:path";
10
- import { cacheKeyFor } from "../validation/config.js";
10
+ import { benchProvider, cloudAllowedFor, providerSettings, readCloudSettings, recordUtilization, } from "../cloud/config.js";
11
+ import { git as cloudGit, runGit } from "../cloud/git.js";
12
+ import { runnerCommand, runnerPrompt, verifyRunnerResult } from "../cloud/runner.js";
13
+ import { commitSnapshot, workingTreeSnapshot } from "../cloud/snapshot.js";
14
+ import { CloudError, } from "../cloud/types.js";
15
+ import { cacheKeyFor, parseGitHubRepo } from "../validation/config.js";
11
16
  import { defaultExec } from "../validation/exec.js";
12
17
  import { addCustomEndpoint, removeCustomEndpoint, } from "../local-endpoint-store.js";
13
- import { FleetClient, FleetClientError } from "./client.js";
14
- import { chooseNode, } from "./fleet-scheduler.js";
18
+ import { DEFAULT_LOCAL_SLOTS, readBackendsFile } from "../validation/backends.js";
19
+ import { compareVersions, controllerVersion, FleetClient, FleetClientError, protocolProblem, safeArtifactPath, } from "./client.js";
20
+ import { validationInFlightByNode } from "./node-load.js";
21
+ import { CLOUD_JOB_DISALLOWED_TOOLS, CLOUD_JOB_MAX_TURNS, CLOUD_RUNNER_MODEL, cloudIneligibility, cloudJobCommand, cloudNodeName, cloudProviderOfNode, cloudPinProblem, cloudRunId, cloudVerifiable, describeCloudCapacity, isCloudPin, } from "./cloud-jobs.js";
22
+ import { chooseNode, slotsUsed, } from "./fleet-scheduler.js";
15
23
  import { FleetGit } from "./git.js";
16
- import { builtinServices, loadFleetConfig, } from "./project-config.js";
24
+ import { builtinServices, FLEET_CONFIG_FILE, loadFleetConfig, } from "./project-config.js";
17
25
  import { NodeRegistry } from "./registry.js";
18
26
  import { defaultFleetDir, JsonListStore, LeaderLock, readFleetSettings } from "./store.js";
19
- import { FLEET_MAX_ATTEMPTS, isFleetTerminal, REQUEUE_KINDS, } from "./types.js";
27
+ import { FLEET_MAX_ATTEMPTS, isFleetTerminal, canRequeue, } from "./types.js";
28
+ export function defaultFleetCloudHooks() {
29
+ return {
30
+ settings: () => readCloudSettings(),
31
+ // Loaded lazily: the providers pull in auth and HTTP code only when cloud is used.
32
+ availability: async (project, settings) => (await import("../cloud/registry.js")).cloudAvailability("jobs", project, settings),
33
+ provider: async (id) => (await import("../cloud/registry.js")).cloudProvider(id),
34
+ bench: benchProvider,
35
+ recordUtilization,
36
+ };
37
+ }
38
+ /** S7: a notice when the node's CLI is older than this machine's. */
39
+ export function nodeUpdateNotice(name, nodeVersion) {
40
+ const mine = controllerVersion();
41
+ if (!nodeVersion || compareVersions(nodeVersion, mine) >= 0)
42
+ return undefined;
43
+ return `${name} runs EZ Coder ${nodeVersion}, older than this machine's ${mine}; update it with \`ezcoder fleet update ${name}\``;
44
+ }
20
45
  const ACTIVE_JOB = new Set(["queued", "preparing", "running"]);
21
46
  const KEEP_DAYS = 14;
22
47
  const KEEP_MAX = 500;
@@ -50,16 +75,6 @@ function pruneServices(list) {
50
75
  function mapState(s) {
51
76
  return s === "lost" ? "lost" : s;
52
77
  }
53
- /** Safe relative path for an artifact (no traversal, no absolute paths). */
54
- export function safeArtifactPath(p) {
55
- const parts = p
56
- .replace(/\\/g, "/")
57
- .split("/")
58
- .filter((x) => x && x !== ".");
59
- if (!parts.length || parts.some((x) => x === ".."))
60
- return undefined;
61
- return parts.join("/");
62
- }
63
78
  /**
64
79
  * Local file for an artifact under `dir`. Refuses to write through a symlink
65
80
  * (an existing `dir/dist -> /elsewhere` would otherwise redirect the download).
@@ -87,6 +102,7 @@ export class FleetService {
87
102
  jobs;
88
103
  services;
89
104
  registry;
105
+ validationDir;
90
106
  exec;
91
107
  git;
92
108
  fetchImpl;
@@ -98,8 +114,14 @@ export class FleetService {
98
114
  gateFn;
99
115
  localEndpoints;
100
116
  maxConcurrentOverride;
117
+ cloudHooks;
101
118
  events = new EventEmitter();
102
119
  lastInfo = new Map();
120
+ stuckServiceMs;
121
+ cleanupEveryMs;
122
+ lastCleanup = 0;
123
+ /** Nodes that answered 429 with Retry-After: no dispatch there until (ms epoch). */
124
+ busyUntil = new Map();
103
125
  seenJobs = new Map();
104
126
  seenServices = new Map();
105
127
  seeded = false;
@@ -114,12 +136,15 @@ export class FleetService {
114
136
  prune: pruneServices,
115
137
  });
116
138
  this.registry = new NodeRegistry(this.dir);
139
+ this.validationDir = opts.validationDir ?? path.join(path.dirname(this.dir), "validation");
117
140
  this.exec = opts.exec ?? defaultExec;
118
141
  this.git = new FleetGit(this.exec);
119
142
  this.fetchImpl = opts.fetch;
120
143
  this.pollMs = opts.pollMs ?? 15_000;
121
144
  this.clientTimeoutMs = opts.clientTimeoutMs ?? 15_000;
122
145
  this.unreachableMs = (opts.unreachableRequeueMinutes ?? 3) * 60_000;
146
+ this.stuckServiceMs = (opts.stuckServiceMinutes ?? 30) * 60_000;
147
+ this.cleanupEveryMs = (opts.cleanupEveryMinutes ?? 10) * 60_000;
123
148
  this.maxArtifactBytes = opts.maxArtifactBytes ?? 2 * 1024 ** 3;
124
149
  this.leader = new LeaderLock(this.dir, Math.max(90_000, this.pollMs * 4));
125
150
  this.gateFn =
@@ -131,6 +156,7 @@ export class FleetService {
131
156
  this.localEndpoints = opts.localEndpoints ?? {};
132
157
  this.maxConcurrentOverride = opts.maxConcurrent;
133
158
  this.autoStart = opts.autoStart ?? true;
159
+ this.cloudHooks = opts.cloud === false ? undefined : (opts.cloud ?? defaultFleetCloudHooks());
134
160
  this.events.setMaxListeners(100);
135
161
  }
136
162
  /** One service per process. */
@@ -138,8 +164,16 @@ export class FleetService {
138
164
  shared ??= new FleetService();
139
165
  return shared;
140
166
  }
167
+ /**
168
+ * Cap on fleet jobs in flight. Unset (the default): no cap beyond the real
169
+ * capacity, i.e. every free slot on every node is used.
170
+ */
141
171
  get maxConcurrent() {
142
- return Math.max(1, this.maxConcurrentOverride ?? readFleetSettings(this.dir).maxConcurrent ?? 8);
172
+ return Math.max(1, this.maxConcurrentOverride ?? readFleetSettings(this.dir).maxConcurrent ?? Infinity);
173
+ }
174
+ /** Slots of this machine for local validation stages (backends.json localMaxConcurrent). */
175
+ localCapacity() {
176
+ return readBackendsFile(this.validationDir).localMaxConcurrent ?? DEFAULT_LOCAL_SLOTS;
143
177
  }
144
178
  onEvent(listener) {
145
179
  this.events.on("event", listener);
@@ -165,9 +199,33 @@ export class FleetService {
165
199
  try {
166
200
  const info = await this.client(n).info();
167
201
  this.lastInfo.set(n.name, info);
168
- return { name: n.name, online: true, info, labels: n.labels };
202
+ // S3 on every poll: a node we can't talk to safely gets no work.
203
+ const problem = protocolProblem(n.name, info);
204
+ const until = this.busyUntil.get(n.name);
205
+ const wait = until !== undefined ? Math.ceil((until - Date.now()) / 1000) : 0;
206
+ if (until !== undefined && wait <= 0)
207
+ this.busyUntil.delete(n.name);
208
+ return {
209
+ name: n.name,
210
+ online: true,
211
+ info,
212
+ labels: n.labels,
213
+ ...(problem ? { incompatible: problem.message } : {}),
214
+ ...(wait > 0 ? { unavailable: `full; the node asked to retry in ${wait} s` } : {}),
215
+ };
169
216
  }
170
217
  catch (e) {
218
+ if (e instanceof FleetClientError && e.code === "incompatible") {
219
+ const last = this.lastInfo.get(n.name);
220
+ return {
221
+ name: n.name,
222
+ online: true,
223
+ ...(last ? { info: last } : {}),
224
+ labels: n.labels,
225
+ incompatible: e.message,
226
+ error: e.message,
227
+ };
228
+ }
171
229
  const last = this.lastInfo.get(n.name);
172
230
  return {
173
231
  name: n.name,
@@ -192,10 +250,25 @@ export class FleetService {
192
250
  online: v.online,
193
251
  ...(v.online && v.info ? { info: v.info } : {}),
194
252
  ...(v.error ? { error: v.error } : {}),
253
+ ...(v.incompatible ? { incompatible: v.incompatible } : {}),
254
+ ...(v.online && nodeUpdateNotice(node.name, v.info?.version)
255
+ ? { updateNotice: nodeUpdateNotice(node.name, v.info?.version) }
256
+ : {}),
195
257
  active: jobs.filter((j) => j.node === node.name && ACTIVE_JOB.has(j.state)).length,
196
258
  };
197
259
  });
198
260
  }
261
+ /** One line per cloud provider ("cloud: claude-cloud ready, 4 cpu/16 GB, overflow"). */
262
+ async cloudLines(cwd) {
263
+ if (!this.cloudHooks)
264
+ return [];
265
+ const settings = this.cloudHooks.settings();
266
+ const [avail, jobs] = await Promise.all([
267
+ this.cloudHooks.availability(cwd ? { repoRoot: path.resolve(cwd) } : {}, settings),
268
+ this.jobs.read(),
269
+ ]);
270
+ return avail.map((a) => describeCloudCapacity(a, settings, jobs.filter((j) => j.node === cloudNodeName(a.id) && ACTIVE_JOB.has(j.state)).length));
271
+ }
199
272
  // ── jobs ─────────────────────────────────────────────────
200
273
  config(cwd) {
201
274
  return loadFleetConfig(cwd);
@@ -234,6 +307,45 @@ export class FleetService {
234
307
  messages,
235
308
  };
236
309
  }
310
+ /**
311
+ * The code of a job that only cloud will run: the local commit (no push
312
+ * needed, the sandbox gets a bundle) plus, with includeUncommitted, a
313
+ * snapshot commit of the working tree.
314
+ */
315
+ async localSource(cwd, opts) {
316
+ let sha;
317
+ try {
318
+ sha = (await cloudGit(cwd, ["rev-parse", "--verify", `${opts.ref ?? "HEAD"}^{commit}`])).trim();
319
+ }
320
+ catch {
321
+ throw new Error(`"${opts.ref ?? "HEAD"}" is not a commit in ${cwd} (is this a Git repo with commits?)`);
322
+ }
323
+ const origin = await runGit(cwd, ["remote", "get-url", "origin"]);
324
+ const url = origin.code === 0 ? origin.stdout.toString().trim() : "";
325
+ const repo = url ? parseGitHubRepo(url) : undefined;
326
+ const messages = [];
327
+ let snapshot;
328
+ if (opts.includeUncommitted) {
329
+ const snap = await workingTreeSnapshot(cwd);
330
+ snapshot = snap.commit;
331
+ if (snap.withheld.length) {
332
+ messages.push(`Not sent to the cloud (look like credentials): ${snap.withheld.join(", ")}.`);
333
+ }
334
+ }
335
+ return {
336
+ src: { git: url, sha },
337
+ ...(repo ? { repo } : {}),
338
+ ...(snapshot ? { snapshot } : {}),
339
+ messages,
340
+ };
341
+ }
342
+ /** Cloud may pick up jobs without being named (settings allow it, not manual). */
343
+ cloudAuto() {
344
+ if (!this.cloudHooks)
345
+ return false;
346
+ const settings = this.cloudHooks.settings();
347
+ return cloudAllowedFor(settings, "jobs") && (settings.when ?? "overflow") !== "manual";
348
+ }
237
349
  async checkGate(cwd, sha) {
238
350
  let g;
239
351
  try {
@@ -252,7 +364,7 @@ export class FleetService {
252
364
  /** Queue a job from the project config; returns at once. */
253
365
  async run(cwdIn, name, opts = {}) {
254
366
  const cwd = path.resolve(cwdIn);
255
- const config = loadFleetConfig(cwd);
367
+ const config = opts.spec ? { jobs: { [name]: opts.spec } } : loadFleetConfig(cwd);
256
368
  if ("error" in config)
257
369
  throw new Error(config.error);
258
370
  const spec = config.jobs[name];
@@ -260,17 +372,43 @@ export class FleetService {
260
372
  const names = Object.keys(config.jobs);
261
373
  throw new Error(`no fleet job "${name}"; this project has: ${names.join(", ") || "none"} (define jobs in .ezcoder/fleet.json)`);
262
374
  }
263
- if (opts.node && !(await this.registry.get(opts.node))) {
375
+ const cloudPin = isCloudPin(opts.node) ? opts.node : undefined;
376
+ if (opts.node && !cloudPin && !(await this.registry.get(opts.node))) {
264
377
  throw new Error(`no paired node "${opts.node}"`);
265
378
  }
266
- if (!(await this.registry.list()).length) {
267
- throw new Error("no nodes paired; run `ezcoder fleet discover`, then `ezcoder fleet add <pairing>`");
379
+ const cloudWhy = cloudIneligibility({ ...spec, ...(spec.artifacts ? { artifactGlobs: spec.artifacts } : {}) }, { pinned: !!cloudPin });
380
+ if (cloudPin) {
381
+ if (!this.cloudHooks)
382
+ throw new Error("cloud is off in this process");
383
+ const pinWhy = cloudPinProblem(cloudPin) ?? cloudWhy;
384
+ if (pinWhy)
385
+ throw new Error(`job ${name} can't run in the cloud: ${pinWhy}`);
386
+ }
387
+ const noNodes = !(await this.registry.list()).length;
388
+ const cloudOnly = !!cloudPin || (noNodes && !cloudWhy && this.cloudAuto());
389
+ if (noNodes && !cloudOnly) {
390
+ throw new Error("no nodes paired; run `ezcoder fleet discover`, then `ezcoder fleet add <pairing>`" +
391
+ (cloudWhy && this.cloudAuto() ? ` (cloud can't take it: ${cloudWhy})` : ""));
268
392
  }
269
393
  const isDeploy = spec.kind === "deploy";
270
394
  if (isDeploy && opts.includeUncommitted) {
271
395
  throw new Error("deploy runs exact pushed commits only; commit and push, then deploy without --uncommitted");
272
396
  }
273
- const s = await this.source(cwd, opts);
397
+ const s = cloudOnly
398
+ ? await this.localSource(cwd, opts)
399
+ : await this.source(cwd, opts);
400
+ if (!cloudOnly && s.src.patch && !cloudWhy && this.cloudAuto()) {
401
+ // Captured now so the job can still overflow to cloud with the same code.
402
+ s.snapshot = await workingTreeSnapshot(cwd)
403
+ .then((snap) => snap.commit)
404
+ .catch(() => undefined);
405
+ }
406
+ if (cloudOnly && !cloudPin) {
407
+ s.messages.push("No nodes paired: this runs in the cloud (extra capacity) when a provider has room.");
408
+ }
409
+ if (cloudPin && spec.artifacts?.length) {
410
+ s.messages.push("Cloud can't send files back: this job's artifacts stay in the cloud session.");
411
+ }
274
412
  const ungated = isDeploy && spec.gate === false;
275
413
  if (isDeploy && !ungated)
276
414
  await this.checkGate(cwd, s.src.sha);
@@ -293,17 +431,35 @@ export class FleetService {
293
431
  ...(spec.subdir ? { subdir: spec.subdir } : {}),
294
432
  command: spec.command,
295
433
  ...(spec.docker ? { docker: spec.docker } : {}),
296
- ...(spec.env ? { env: spec.env } : {}),
434
+ ...(spec.env || opts.shard
435
+ ? {
436
+ env: {
437
+ ...spec.env,
438
+ ...(opts.shard
439
+ ? {
440
+ EZ_SHARD: String(opts.shard.index),
441
+ EZ_SHARD_TOTAL: String(opts.shard.total),
442
+ }
443
+ : {}),
444
+ },
445
+ }
446
+ : {}),
447
+ ...(opts.spec ? { adhoc: true } : {}),
448
+ ...(opts.shard ? { shard: opts.shard } : {}),
297
449
  ...(spec.secrets ? { secrets: spec.secrets } : {}),
298
450
  ...(spec.resources ? { resources: spec.resources } : {}),
299
451
  ...(spec.artifacts ? { artifactGlobs: spec.artifacts } : {}),
300
452
  cacheKey: spec.cacheKey ?? cacheKeyFor(projectKey),
301
453
  timeoutMinutes: spec.timeoutMinutes,
302
454
  ...(ungated ? { ungated: true } : {}),
455
+ ...(spec.kind === "custom" && spec.retry ? { retry: true } : {}),
303
456
  state: "queued",
304
457
  createdAt: at,
305
458
  updatedAt: at,
306
459
  ...(opts.node ? { node: opts.node, pinned: true } : {}),
460
+ ...(cloudPin ? { cloudPin } : {}),
461
+ ...(cloudOnly ? { cloudOnly: true } : {}),
462
+ ...(s.snapshot ? { snapshot: s.snapshot } : {}),
307
463
  ...(opts.outDir ? { outDir: path.resolve(cwd, opts.outDir) } : {}),
308
464
  attempts: 1,
309
465
  };
@@ -328,13 +484,20 @@ export class FleetService {
328
484
  const j = jobs.find((x) => x.id === id);
329
485
  if (!j || isFleetTerminal(j.state))
330
486
  return j ? { ...j } : undefined;
331
- const wasDispatched = !!j.remoteId && j.state !== "queued";
487
+ const wasDispatched = !!j.remoteId && (j.state !== "queued" || !canRequeue(j));
332
488
  j.state = "cancelled";
333
489
  j.summary = "cancelled by request";
334
490
  j.updatedAt = j.finishedAt = nowIso();
335
491
  return { ...j, wasDispatched };
336
492
  });
337
- if (job && job.wasDispatched && job.node && job.remoteId) {
493
+ const cloudId = cloudProviderOfNode(job?.node);
494
+ if (job && job.wasDispatched && cloudId && job.cloud) {
495
+ await this.stopCloud(cloudId, job.cloud.handle, true);
496
+ }
497
+ else if (job &&
498
+ job.wasDispatched &&
499
+ job.node &&
500
+ job.remoteId) {
338
501
  await this.clientFor(job.node)
339
502
  .then((c) => c.cancelJob(job.remoteId))
340
503
  .catch(() => { });
@@ -351,6 +514,22 @@ export class FleetService {
351
514
  if (!job.node || !job.remoteId || job.state === "queued") {
352
515
  return `Not dispatched yet${job.summary ? ` (${job.summary})` : ""}.`;
353
516
  }
517
+ if (cloudProviderOfNode(job.node)) {
518
+ const where = job.cloud ? ` (${job.cloud.handle.url})` : "";
519
+ let text;
520
+ try {
521
+ text = fs.readFileSync(this.cloudLogFile(job.id), "utf8");
522
+ }
523
+ catch {
524
+ // not finished yet
525
+ }
526
+ if (text === undefined) {
527
+ return `Running on ${job.node}${where}; cloud sends only a verified log tail, when the job finishes.`;
528
+ }
529
+ if (opts.offset !== undefined)
530
+ return text.slice(opts.offset);
531
+ return `[verified log tail from ${job.node}${where}]\n${text || "(no output)"}`;
532
+ }
354
533
  const c = await this.clientFor(job.node);
355
534
  if (opts.offset !== undefined)
356
535
  return (await c.jobLog(job.remoteId, opts.offset)).text;
@@ -369,6 +548,9 @@ export class FleetService {
369
548
  throw new Error(`no job ${id}`);
370
549
  if (!job.node || !job.remoteId)
371
550
  throw new Error(`job ${id} hasn't run yet`);
551
+ if (cloudProviderOfNode(job.node)) {
552
+ throw new Error(`job ${id} ran on ${job.node}; cloud can't send files back, so its artifacts stay in the cloud session${job.cloud ? ` (${job.cloud.handle.url})` : ""}`);
553
+ }
372
554
  const c = await this.clientFor(job.node);
373
555
  const status = await c.job(job.remoteId);
374
556
  const list = status.artifacts ?? job.artifacts ?? [];
@@ -594,7 +776,58 @@ export class FleetService {
594
776
  }
595
777
  return (await this.jobs.read()).some((j) => ACTIVE_JOB.has(j.state));
596
778
  }
779
+ /**
780
+ * R10: controller leftovers. Stored patches of jobs that are finished
781
+ * (cancelled, errored, ...) or forgotten, and services stuck in "error":
782
+ * stopped on their node (best effort) and marked stopped. Runs at the first
783
+ * tick (startup) and then every `cleanupEveryMinutes`.
784
+ */
785
+ async cleanup() {
786
+ this.lastCleanup = Date.now();
787
+ const jobs = await this.jobs.read();
788
+ const keep = new Set(jobs.filter((j) => !isFleetTerminal(j.state)).map((j) => j.id));
789
+ const patches = [];
790
+ const dir = path.join(this.dir, "patches");
791
+ let files = [];
792
+ try {
793
+ files = fs.readdirSync(dir);
794
+ }
795
+ catch {
796
+ // no patches folder
797
+ }
798
+ for (const f of files) {
799
+ if (!f.endsWith(".b64"))
800
+ continue;
801
+ const id = f.slice(0, -4);
802
+ if (keep.has(id))
803
+ continue;
804
+ fs.rmSync(path.join(dir, f), { force: true });
805
+ patches.push(id);
806
+ }
807
+ const retired = [];
808
+ const now = Date.now();
809
+ for (const s of await this.services.read()) {
810
+ if (s.state !== "error" || now - Date.parse(s.updatedAt) < this.stuckServiceMs)
811
+ continue;
812
+ const node = await this.registry.get(s.node);
813
+ if (node)
814
+ await this.client(node)
815
+ .stopService(s.id)
816
+ .catch(() => { });
817
+ const u = await this.patchService(s.id, {
818
+ state: "stopped",
819
+ summary: `cleaned up: stuck in error (${s.summary ?? "no detail"})`.slice(0, 300),
820
+ });
821
+ if (u)
822
+ await this.syncLocalEndpoint(u);
823
+ retired.push(s.id);
824
+ }
825
+ return { patches, services: retired };
826
+ }
597
827
  async tickInner() {
828
+ if (Date.now() - this.lastCleanup >= this.cleanupEveryMs) {
829
+ await this.cleanup().catch(() => { });
830
+ }
598
831
  let jobs = await this.jobs.read();
599
832
  let services = await this.services.read();
600
833
  this.observe(jobs, services);
@@ -624,10 +857,57 @@ export class FleetService {
624
857
  .filter((j) => (j.state === "preparing" || j.state === "running") && j.node)
625
858
  .map((j) => ({ node: j.node, ...(j.resources ? { resources: j.resources } : {}) }));
626
859
  let count = inFlight.length;
860
+ // Validation stages on the same nodes take the same slots (not our cap, though).
861
+ for (const [node, n] of await validationInFlightByNode(this.validationDir)) {
862
+ for (let i = 0; i < n; i++)
863
+ inFlight.push({ node });
864
+ }
627
865
  const views = await this.nodeViews();
866
+ const cloud = this.cloudPass(jobs);
628
867
  for (const j of queued) {
629
868
  if (count >= this.maxConcurrent)
630
869
  break;
870
+ if (!canRequeue(j) && j.node && j.remoteId) {
871
+ const claim = await this.reconcileClaim(j);
872
+ if (claim === "running")
873
+ count++;
874
+ if (claim !== "absent")
875
+ continue;
876
+ delete j.remoteId;
877
+ if (!j.pinned)
878
+ delete j.node;
879
+ }
880
+ if (j.cloudPin) {
881
+ const r = await this.tryCloud(j, cloud, { pinned: true });
882
+ if ("started" in r)
883
+ count++;
884
+ else if ("wait" in r)
885
+ await this.waitJob(j, r.wait);
886
+ else {
887
+ await this.patchJob(j.id, {
888
+ state: "error",
889
+ summary: `can't run in the cloud: ${r.no}`.slice(0, 400),
890
+ finishedAt: nowIso(),
891
+ });
892
+ }
893
+ continue;
894
+ }
895
+ if (j.cloudOnly) {
896
+ // Its source is local only (no origin URL / unpushed commit): nodes can't fetch it.
897
+ const r = await this.tryCloud(j, cloud, { pinned: false });
898
+ if ("started" in r)
899
+ count++;
900
+ else if ("wait" in r)
901
+ await this.waitJob(j, `cloud: ${r.wait}`);
902
+ else {
903
+ await this.patchJob(j.id, {
904
+ state: "error",
905
+ summary: `queued for cloud only (no nodes were paired), and cloud can't run it: ${r.no || "cloud is off"}. Push and run it again to use your machines.`.slice(0, 400),
906
+ finishedAt: nowIso(),
907
+ });
908
+ }
909
+ continue;
910
+ }
631
911
  const last = [...jobs]
632
912
  .reverse()
633
913
  .find((x) => x.id !== j.id && x.dispatchedAt && x.node && x.projectKey === j.projectKey);
@@ -640,7 +920,35 @@ export class FleetService {
640
920
  ...(last?.node ? { affinity: last.node } : {}),
641
921
  takesSlot: true,
642
922
  };
643
- const p = chooseNode(req, views, inFlight);
923
+ let p = chooseNode(req, views, inFlight);
924
+ const pinnedNode = !!(j.pinned && j.node);
925
+ if (!pinnedNode && !("node" in p)) {
926
+ // No self-hosted machine has room (or none fits): cloud is the overflow.
927
+ const r = await this.tryCloud(j, cloud, { pinned: false });
928
+ if ("started" in r) {
929
+ count++;
930
+ continue;
931
+ }
932
+ if ("wait" in r) {
933
+ await this.waitJob(j, `${"wait" in p ? p.wait : p.error}; cloud: ${r.wait}`);
934
+ continue;
935
+ }
936
+ if (!r.quiet) {
937
+ p =
938
+ "wait" in p
939
+ ? { wait: `${p.wait}; cloud: ${r.no}` }
940
+ : { error: `${p.error}; cloud: ${r.no}` };
941
+ }
942
+ }
943
+ else if (!pinnedNode && "node" in p && cloud.settings.when === "always") {
944
+ // Cloud is one more machine: take the job when it is less loaded.
945
+ const ratio = slotsUsed(p.node, inFlight) / Math.max(1, p.node.info?.slots ?? 1);
946
+ const r = await this.tryCloud(j, cloud, { pinned: false, nodeRatio: ratio });
947
+ if ("started" in r) {
948
+ count++;
949
+ continue;
950
+ }
951
+ }
644
952
  if ("error" in p) {
645
953
  await this.patchJob(j.id, {
646
954
  state: "error",
@@ -725,11 +1033,45 @@ export class FleetService {
725
1033
  }
726
1034
  catch (e) {
727
1035
  if (e instanceof FleetClientError &&
728
- (e.code === "busy" || e.code === "unreachable" || e.code === "timeout")) {
729
- // Node full or gone since we looked: stay queued, avoid it this pass.
1036
+ (e.code === "busy" ||
1037
+ e.code === "incompatible" ||
1038
+ e.code === "unreachable" ||
1039
+ e.code === "timeout")) {
1040
+ // Node full, incompatible or gone since we looked: stay queued, avoid it this pass.
730
1041
  const v = views.find((x) => x.name === nodeName);
731
1042
  if (v)
732
1043
  v.online = false;
1044
+ if (e.code === "busy") {
1045
+ // Never an error: wait for a slot, as long as the node asked (Retry-After).
1046
+ if (e.retryAfterMs)
1047
+ this.busyUntil.set(nodeName, Date.now() + e.retryAfterMs);
1048
+ await this.patchJob(j.id, {
1049
+ ...(j.pinned ? {} : { node: undefined }),
1050
+ remoteId: undefined,
1051
+ waitWarned: true,
1052
+ summary: `waiting: ${nodeName} is full` +
1053
+ (e.retryAfterMs ? `; retrying in ${Math.ceil(e.retryAfterMs / 1000)} s` : ""),
1054
+ }, "queued");
1055
+ continue;
1056
+ }
1057
+ if (e.code === "incompatible") {
1058
+ // A 426 answer: the node refused before taking the job.
1059
+ await this.patchJob(j.id, {
1060
+ ...(j.pinned ? {} : { node: undefined }),
1061
+ remoteId: undefined,
1062
+ waitWarned: true,
1063
+ summary: `waiting: ${e.message}`.slice(0, 400),
1064
+ }, "queued");
1065
+ continue;
1066
+ }
1067
+ if (!canRequeue(j)) {
1068
+ // It may have started there: keep the claim and ask that node before placing it again.
1069
+ await this.patchJob(j.id, {
1070
+ waitWarned: true,
1071
+ summary: `waiting: ${nodeName} didn't answer the dispatch; confirming whether it started before trying again`,
1072
+ }, "queued");
1073
+ continue;
1074
+ }
733
1075
  await this.patchJob(j.id, { ...(j.pinned ? {} : { node: undefined }), remoteId: undefined }, "queued");
734
1076
  continue;
735
1077
  }
@@ -741,11 +1083,46 @@ export class FleetService {
741
1083
  }
742
1084
  }
743
1085
  }
1086
+ /** A dispatch whose answer never arrived: ask the claimed node whether it took the job. */
1087
+ async reconcileClaim(j) {
1088
+ const node = await this.registry.get(j.node);
1089
+ if (!node) {
1090
+ await this.patchJob(j.id, {
1091
+ state: "error",
1092
+ summary: `${j.node} was removed before it confirmed the dispatch. ${j.kind} is not retried automatically (it may have run); check the target before deploying again.`,
1093
+ finishedAt: nowIso(),
1094
+ });
1095
+ return "unknown";
1096
+ }
1097
+ try {
1098
+ const status = await this.client(node).job(j.remoteId);
1099
+ const at = nowIso();
1100
+ const state = status.state === "preparing" || status.state === "lost" ? "preparing" : "running";
1101
+ await this.patchJob(j.id, {
1102
+ state,
1103
+ dispatchedAt: at,
1104
+ ...(state === "running" ? { startedAt: status.startedAt ?? at } : {}),
1105
+ summary: `on ${node.name}`,
1106
+ waitWarned: false,
1107
+ }, "queued");
1108
+ return "running";
1109
+ }
1110
+ catch (e) {
1111
+ if (!(e instanceof FleetClientError && e.code === "not_found"))
1112
+ return "unknown";
1113
+ await this.patchJob(j.id, { ...(j.pinned ? {} : { node: undefined }), remoteId: undefined }, "queued");
1114
+ return "absent";
1115
+ }
1116
+ }
744
1117
  async pollJob(j) {
745
1118
  if (!j.node || !j.remoteId) {
746
1119
  await this.patchJob(j.id, { state: "queued" });
747
1120
  return;
748
1121
  }
1122
+ if (cloudProviderOfNode(j.node)) {
1123
+ await this.pollCloudJob(j);
1124
+ return;
1125
+ }
749
1126
  const node = await this.registry.get(j.node);
750
1127
  if (!node) {
751
1128
  await this.nodeLost(j, `node ${j.node} was removed from the fleet`);
@@ -795,8 +1172,12 @@ export class FleetService {
795
1172
  if (status.artifacts)
796
1173
  patch.artifacts = status.artifacts;
797
1174
  patch.summary = status.summary ?? (state === "passed" ? "passed" : state);
798
- if (state === "failed")
1175
+ if (state === "failed") {
799
1176
  patch.summary = await this.failureSummary(node, j, status);
1177
+ const tail = await this.failureTail(node, j);
1178
+ if (tail.length)
1179
+ patch.failTail = tail;
1180
+ }
800
1181
  }
801
1182
  }
802
1183
  if (!Object.keys(patch).length)
@@ -822,6 +1203,18 @@ export class FleetService {
822
1203
  removePatch(id) {
823
1204
  fs.rmSync(this.patchFile(id), { force: true });
824
1205
  }
1206
+ /** A3: the last FAIL_TAIL_LINES lines of the log, cut on the node (older nodes: last 16 KB). */
1207
+ async failureTail(node, j) {
1208
+ const c = this.client(node);
1209
+ const text = await c
1210
+ .logs(j.remoteId, { tail: FAIL_TAIL_LINES })
1211
+ .then((r) => r.text)
1212
+ .catch(() => c
1213
+ .jobLog(j.remoteId, 0)
1214
+ .then((r) => r.text.slice(-16_000))
1215
+ .catch(() => ""));
1216
+ return failTailLines(text);
1217
+ }
825
1218
  async failureSummary(node, j, status) {
826
1219
  const base = status.summary ?? `exited ${status.exitCode ?? "non-zero"}`;
827
1220
  try {
@@ -852,11 +1245,12 @@ export class FleetService {
852
1245
  return;
853
1246
  const attempts = x.attempts ?? 1;
854
1247
  x.updatedAt = at;
855
- if (!REQUEUE_KINDS.has(x.kind)) {
1248
+ if (!canRequeue(x)) {
856
1249
  x.state = "error";
857
1250
  x.finishedAt = at;
858
- x.summary =
859
- `${reason}. ${x.kind} is not retried automatically (it may have partly run); check the target before deploying again.`.slice(0, 480);
1251
+ x.summary = (x.kind === "deploy"
1252
+ ? `${reason}. deploy is not retried automatically (it may have partly run); check the target before deploying again.`
1253
+ : `${reason}. This ${x.kind} job is not retried automatically (it may have partly run); run it again yourself, or mark it "retry": true in ${FLEET_CONFIG_FILE} if it is safe to repeat.`).slice(0, 480);
860
1254
  return;
861
1255
  }
862
1256
  x.requeues = [...(x.requeues ?? []), { at, from, reason }];
@@ -945,6 +1339,321 @@ export class FleetService {
945
1339
  if (u)
946
1340
  await this.syncLocalEndpoint(u);
947
1341
  }
1342
+ // ── cloud ────────────────────────────────────────────────
1343
+ cloudLogFile(id) {
1344
+ return path.join(this.dir, "cloud-logs", `${id}.log`);
1345
+ }
1346
+ cloudPass(jobs) {
1347
+ const active = new Map();
1348
+ for (const j of jobs) {
1349
+ const id = cloudProviderOfNode(j.node);
1350
+ if (id && ACTIVE_JOB.has(j.state) && j.state !== "queued") {
1351
+ active.set(id, (active.get(id) ?? 0) + 1);
1352
+ }
1353
+ }
1354
+ return { settings: this.cloudHooks?.settings() ?? {}, availability: new Map(), active };
1355
+ }
1356
+ async waitJob(j, why) {
1357
+ if (j.waitWarned)
1358
+ return;
1359
+ await this.patchJob(j.id, { waitWarned: true, summary: `waiting: ${why}`.slice(0, 400) }, "queued");
1360
+ }
1361
+ async provider(id) {
1362
+ if (!this.cloudHooks)
1363
+ throw new Error("cloud is off");
1364
+ return this.cloudHooks.provider(id);
1365
+ }
1366
+ /** Interrupt (when asked) and archive a cloud task; best effort. */
1367
+ async stopCloud(id, handle, interrupt) {
1368
+ try {
1369
+ const p = await this.provider(id);
1370
+ if (interrupt)
1371
+ await p.interrupt(handle).catch(() => { });
1372
+ await p.archive(handle).catch(() => { });
1373
+ }
1374
+ catch {
1375
+ // provider gone: nothing to stop
1376
+ }
1377
+ }
1378
+ /**
1379
+ * Run a queued job on the first cloud provider with room. `wait` = it could
1380
+ * run in the cloud later (usage limit, provider full); `no` = it can't.
1381
+ */
1382
+ async tryCloud(j, pass, opts) {
1383
+ const hooks = this.cloudHooks;
1384
+ if (!hooks)
1385
+ return { no: "cloud is off", quiet: true };
1386
+ const settings = pass.settings;
1387
+ if (!opts.pinned) {
1388
+ if (!cloudAllowedFor(settings, "jobs"))
1389
+ return { no: "cloud is off for jobs", quiet: true };
1390
+ const when = settings.when ?? "overflow";
1391
+ if (when === "manual")
1392
+ return { no: "cloud runs only jobs pinned to it", quiet: true };
1393
+ if (opts.nodeRatio !== undefined && when !== "always")
1394
+ return { no: "", quiet: true };
1395
+ }
1396
+ const why = cloudIneligibility(j, { pinned: opts.pinned });
1397
+ if (why)
1398
+ return { no: why };
1399
+ const key = j.project;
1400
+ let avail = pass.availability.get(key);
1401
+ if (!avail) {
1402
+ const repo = /^[\w.-]+\/[\w.-]+$/.test(j.projectKey) ? j.projectKey : undefined;
1403
+ avail = hooks
1404
+ .availability({ repoRoot: j.project, ...(repo ? { repo } : {}) }, settings)
1405
+ .catch((e) => [
1406
+ {
1407
+ id: "claude-cloud",
1408
+ available: false,
1409
+ detail: errText(e),
1410
+ },
1411
+ ]);
1412
+ pass.availability.set(key, avail);
1413
+ }
1414
+ const want = j.cloudPin && j.cloudPin !== "cloud" ? j.cloudPin : undefined;
1415
+ const avoid = new Set(j.avoid ?? []);
1416
+ const reasons = [];
1417
+ let wait;
1418
+ for (const a of await avail) {
1419
+ if (want && a.id !== want)
1420
+ continue;
1421
+ if (!cloudVerifiable(a.id)) {
1422
+ if (want)
1423
+ reasons.push(cloudPinProblem(a.id) ?? `${a.id} can't report verified results`);
1424
+ continue;
1425
+ }
1426
+ if (avoid.has(cloudNodeName(a.id))) {
1427
+ reasons.push(`${a.id} already failed this job`);
1428
+ continue;
1429
+ }
1430
+ if (!a.available) {
1431
+ reasons.push(`${a.id}: ${a.detail}${a.setupHint ? ` (${a.setupHint})` : ""}`);
1432
+ if (a.limitedUntil)
1433
+ wait ??= `${a.id}: ${a.detail}`;
1434
+ continue;
1435
+ }
1436
+ const max = providerSettings(settings, a.id).maxConcurrent;
1437
+ const active = pass.active.get(a.id) ?? 0;
1438
+ if (active >= max) {
1439
+ wait ??= `${a.id} runs ${active}/${max} jobs`;
1440
+ continue;
1441
+ }
1442
+ if (opts.nodeRatio !== undefined && active / max >= opts.nodeRatio)
1443
+ continue;
1444
+ const r = await this.startCloud(j, a.id, settings);
1445
+ if (r === true) {
1446
+ pass.active.set(a.id, active + 1);
1447
+ return { started: true };
1448
+ }
1449
+ if (r.limited)
1450
+ wait ??= `${a.id}: ${r.error}`;
1451
+ reasons.push(`${a.id}: ${r.error}`);
1452
+ }
1453
+ if (wait)
1454
+ return { wait };
1455
+ return { no: reasons.join("; ") || "no cloud provider" };
1456
+ }
1457
+ async startCloud(j, id, settings) {
1458
+ const node = cloudNodeName(id);
1459
+ const remoteId = (j.attempts ?? 1) > 1 ? `${j.id}-${j.attempts}` : j.id;
1460
+ const runId = cloudRunId(remoteId);
1461
+ const claimed = await this.patchJob(j.id, { node, remoteId }, "queued");
1462
+ if (!claimed)
1463
+ return { error: "the job changed meanwhile" };
1464
+ let handle;
1465
+ try {
1466
+ const provider = await this.provider(id);
1467
+ const base = j.snapshot ?? j.sha;
1468
+ const snap = await commitSnapshot(j.project, base);
1469
+ const command = runnerCommand({
1470
+ jobId: runId,
1471
+ tree: snap.tree,
1472
+ command: cloudJobCommand({ ...j, id: runId }),
1473
+ timeoutMinutes: j.timeoutMinutes,
1474
+ ...(j.docker ? { docker: true } : {}),
1475
+ });
1476
+ const model = providerSettings(settings, id).runnerModel ??
1477
+ (id === "claude-cloud" ? CLOUD_RUNNER_MODEL : undefined);
1478
+ const repo = /^[\w.-]+\/[\w.-]+$/.test(j.projectKey) ? j.projectKey : undefined;
1479
+ handle = await provider.start({
1480
+ title: `EZ Coder job ${j.name} (${j.projectKey})`,
1481
+ prompt: runnerPrompt(command, j.timeoutMinutes),
1482
+ source: { repoRoot: j.project, ...(repo ? { repo } : {}), sha: base },
1483
+ ...(model ? { model } : {}),
1484
+ maxTurns: CLOUD_JOB_MAX_TURNS,
1485
+ disallowedTools: [...CLOUD_JOB_DISALLOWED_TOOLS],
1486
+ commandTimeoutMinutes: j.timeoutMinutes,
1487
+ approveCommand: command,
1488
+ runner: true,
1489
+ });
1490
+ const at = nowIso();
1491
+ const started = await this.patchJob(j.id, {
1492
+ state: "preparing",
1493
+ dispatchedAt: at,
1494
+ cloud: { handle, tree: snap.tree, runId },
1495
+ summary: `on ${node}: ${handle.url}`,
1496
+ waitWarned: false,
1497
+ }, "queued");
1498
+ if (!started)
1499
+ await this.stopCloud(id, handle, true); // cancelled meanwhile
1500
+ return true;
1501
+ }
1502
+ catch (e) {
1503
+ const limited = e instanceof CloudError && e.code === "usage_limited";
1504
+ if (limited) {
1505
+ this.cloudHooks?.bench(id, e.until ?? new Date(Date.now() + 3_600_000).toISOString(), "usage limit reached");
1506
+ }
1507
+ await this.patchJob(j.id, {
1508
+ node: j.cloudPin ?? (j.pinned ? j.node : undefined),
1509
+ remoteId: undefined,
1510
+ ...(limited ? {} : { avoid: [...new Set([...(j.avoid ?? []), node])] }),
1511
+ }, "queued");
1512
+ if (!limited)
1513
+ j.avoid = [...new Set([...(j.avoid ?? []), node])];
1514
+ return { error: `couldn't start: ${errText(e)}`.slice(0, 300), limited };
1515
+ }
1516
+ }
1517
+ async pollCloudJob(j) {
1518
+ const id = cloudProviderOfNode(j.node);
1519
+ const c = j.cloud;
1520
+ if (!c) {
1521
+ await this.cloudRetry(j, `no cloud session recorded for ${j.node}`);
1522
+ return;
1523
+ }
1524
+ let status;
1525
+ try {
1526
+ status = await (await this.provider(id)).status(c.handle);
1527
+ }
1528
+ catch (e) {
1529
+ if (e instanceof CloudError && e.code === "not_found") {
1530
+ await this.cloudRetry(j, `${j.node} no longer knows the session`);
1531
+ return;
1532
+ }
1533
+ const since = j.unreachableSince ? Date.parse(j.unreachableSince) : undefined;
1534
+ if (since === undefined)
1535
+ await this.patchJob(j.id, { unreachableSince: nowIso() });
1536
+ else if (Date.now() - since > Math.max(this.unreachableMs, 1)) {
1537
+ await this.stopCloud(id, c.handle, true);
1538
+ await this.cloudRetry(j, `${j.node} unreachable: ${errText(e)}`);
1539
+ }
1540
+ return;
1541
+ }
1542
+ if (status.usage?.utilization !== undefined) {
1543
+ this.cloudHooks?.recordUtilization(id, status.usage.utilization, status.usage.resetsAt);
1544
+ }
1545
+ if (status.state === "starting" || status.state === "running") {
1546
+ const patch = {};
1547
+ if (j.unreachableSince)
1548
+ patch.unreachableSince = undefined;
1549
+ if (status.state === "running" && j.state !== "running") {
1550
+ patch.state = "running";
1551
+ patch.startedAt = nowIso();
1552
+ }
1553
+ const since = Date.parse(j.dispatchedAt ?? j.updatedAt);
1554
+ if (Date.now() - since > (j.timeoutMinutes + 30) * 60_000) {
1555
+ await this.stopCloud(id, c.handle, true);
1556
+ await this.cloudRetry(j, `${j.node} ran past the job's ${j.timeoutMinutes} min timeout`);
1557
+ return;
1558
+ }
1559
+ if (Object.keys(patch).length)
1560
+ await this.patchJob(j.id, patch);
1561
+ return;
1562
+ }
1563
+ // Finished its turn, failed or was stopped: only a verified result counts.
1564
+ await this.stopCloud(id, c.handle, false);
1565
+ if (status.usage?.limited && status.usage.resetsAt) {
1566
+ this.cloudHooks?.bench(id, status.usage.resetsAt, "usage limit reached");
1567
+ }
1568
+ const command = runnerCommand({
1569
+ jobId: c.runId,
1570
+ tree: c.tree,
1571
+ command: cloudJobCommand({ ...j, id: c.runId }),
1572
+ timeoutMinutes: j.timeoutMinutes,
1573
+ ...(j.docker ? { docker: true } : {}),
1574
+ });
1575
+ const result = verifyRunnerResult(status.commands, command, c.runId);
1576
+ if (!result || result.verdict === "wrong-tree") {
1577
+ const reason = !result
1578
+ ? status.state === "failed"
1579
+ ? `cloud session failed${status.error ? `: ${status.error}` : ""}`
1580
+ : "the cloud result could not be verified (the sandbox didn't run the exact command)"
1581
+ : `the cloud sandbox had different code (tree ${short(result.tree ?? "?")}, expected ${short(c.tree)})`;
1582
+ await this.cloudRetry(j, reason);
1583
+ return;
1584
+ }
1585
+ fs.mkdirSync(path.dirname(this.cloudLogFile(j.id)), { recursive: true });
1586
+ fs.writeFileSync(this.cloudLogFile(j.id), result.log);
1587
+ const passed = result.verdict === "done" && result.exitCode === 0;
1588
+ const arts = j.artifactGlobs?.length
1589
+ ? `; artifacts stay in the cloud session ${c.handle.url}`
1590
+ : "";
1591
+ let summary;
1592
+ if (result.verdict === "timeout")
1593
+ summary = `timed out after ${j.timeoutMinutes} min`;
1594
+ else if (passed)
1595
+ summary = "passed";
1596
+ else {
1597
+ const lines = result.log
1598
+ .split("\n")
1599
+ .map((l) => l.trim())
1600
+ .filter((l) => /fail|error|expected|assert|✗|×/i.test(l))
1601
+ .slice(-4);
1602
+ summary = [`exited ${result.exitCode ?? "non-zero"}`, ...lines].join(" | ");
1603
+ }
1604
+ const updated = await this.patchJob(j.id, {
1605
+ state: passed ? "passed" : "failed",
1606
+ finishedAt: nowIso(),
1607
+ ...(result.exitCode !== undefined ? { exitCode: result.exitCode } : {}),
1608
+ ...(j.startedAt ? {} : { startedAt: j.dispatchedAt ?? nowIso() }),
1609
+ unreachableSince: undefined,
1610
+ summary: `${summary}${arts}`.slice(0, 480),
1611
+ });
1612
+ if (updated)
1613
+ this.removePatch(updated.id);
1614
+ }
1615
+ /**
1616
+ * A cloud run gave no verified result: this attempt is an error and the job
1617
+ * goes back to the queue once, away from that provider; a second time ends it.
1618
+ */
1619
+ async cloudRetry(j, reason) {
1620
+ const at = nowIso();
1621
+ const from = j.node ?? "cloud";
1622
+ await this.jobs.update((jobs) => {
1623
+ const x = jobs.find((y) => y.id === j.id);
1624
+ if (!x || (x.state !== "preparing" && x.state !== "running"))
1625
+ return;
1626
+ const attempts = x.attempts ?? 1;
1627
+ const triedCloud = (x.requeues ?? []).some((r) => r.from.startsWith("cloud:"));
1628
+ x.updatedAt = at;
1629
+ x.requeues = [...(x.requeues ?? []), { at, from, reason }];
1630
+ if (triedCloud || attempts >= FLEET_MAX_ATTEMPTS || !canRequeue(x)) {
1631
+ x.state = "error";
1632
+ x.finishedAt = at;
1633
+ x.summary = `${reason} (on ${from})`.slice(0, 400);
1634
+ return;
1635
+ }
1636
+ x.state = "queued";
1637
+ x.attempts = attempts + 1;
1638
+ x.avoid = [...new Set([...(x.avoid ?? []), from])];
1639
+ x.summary = `requeued (attempt ${attempts + 1}/${FLEET_MAX_ATTEMPTS}): ${reason}`.slice(0, 400);
1640
+ if (x.cloudPin)
1641
+ x.node = x.cloudPin;
1642
+ else if (!x.pinned)
1643
+ delete x.node;
1644
+ for (const k of [
1645
+ "remoteId",
1646
+ "dispatchedAt",
1647
+ "startedAt",
1648
+ "unreachableSince",
1649
+ "nodeDownWarned",
1650
+ "waitWarned",
1651
+ "cloud",
1652
+ ]) {
1653
+ delete x[k];
1654
+ }
1655
+ });
1656
+ }
948
1657
  // ── store helpers ────────────────────────────────────────
949
1658
  async patchJob(id, patch, onlyIf, evenIfTerminal = false) {
950
1659
  return this.jobs.update((jobs) => {
@@ -1026,6 +1735,17 @@ export class FleetService {
1026
1735
  }
1027
1736
  }
1028
1737
  // ── plain-words output ─────────────────────────────────────
1738
+ /** A3: how many log lines a failure notification carries. */
1739
+ export const FAIL_TAIL_LINES = 30;
1740
+ /** Last FAIL_TAIL_LINES non-empty lines, each capped at 300 chars. */
1741
+ export function failTailLines(text) {
1742
+ return text
1743
+ .split(/\r?\n/)
1744
+ .map((l) => l.trimEnd())
1745
+ .filter((l) => l.trim())
1746
+ .slice(-FAIL_TAIL_LINES)
1747
+ .map((l) => (l.length > 300 ? `${l.slice(0, 300)}…` : l));
1748
+ }
1029
1749
  export function describeFleetJob(j) {
1030
1750
  const where = j.node ? ` on ${j.node}` : "";
1031
1751
  const src = `${short(j.sha)}${j.hasPatch ? "+patch" : ""}`;
@@ -1041,6 +1761,9 @@ export function describeFleetService(s) {
1041
1761
  }
1042
1762
  export function describeNode(n) {
1043
1763
  const labels = [...new Set([...(n.info?.labels ?? []), ...n.node.labels])];
1764
+ if (n.incompatible) {
1765
+ return `${n.node.name} (${n.node.url}): INCOMPATIBLE — ${n.incompatible}; no work is sent there`;
1766
+ }
1044
1767
  if (!n.online || !n.info) {
1045
1768
  return `${n.node.name} (${n.node.url}): OFFLINE${n.error ? ` — ${n.error}` : ""}`;
1046
1769
  }
@@ -1051,7 +1774,8 @@ export function describeNode(n) {
1051
1774
  return (`${n.node.name} (${i.platform}, ${i.arch}, v${i.version}): online; slots ${i.slotsUsed}/${i.slots}, ` +
1052
1775
  `${i.cpus} cpu, ${i.memoryFreeGb}/${i.memoryGb} GB free, load ${i.load.toFixed(2)}${gpus}` +
1053
1776
  `${i.docker ? "" : "; no docker"}${labels.length ? `; labels ${labels.join(",")}` : ""}` +
1054
- `${i.modelAuth ? "; model login ok" : "; no model login"}${n.active ? `; ${n.active} of our jobs` : ""}`);
1777
+ `${i.modelAuth ? (i.modelProviders?.length ? `; model login: ${i.modelProviders.join(", ")}` : "; model login ok") : "; no model login"}${n.active ? `; ${n.active} of our jobs` : ""}` +
1778
+ `${n.updateNotice ? `\n notice: ${n.updateNotice}` : ""}`);
1055
1779
  }
1056
1780
  /** Notification for a job change, or undefined for routine ones. */
1057
1781
  export function fleetJobNotification(j) {
@@ -1065,7 +1789,10 @@ export function fleetJobNotification(j) {
1065
1789
  };
1066
1790
  case "failed":
1067
1791
  return {
1068
- text: `Fleet job FAILED: ${at}${j.summary ? `: ${j.summary}` : ""}. Read the log with fleet logs ${j.id}.`,
1792
+ text: `Fleet job FAILED: ${at}${j.summary ? `: ${j.summary}` : ""}.` +
1793
+ (j.failTail?.length
1794
+ ? ` Last ${j.failTail.length} log lines:\n${j.failTail.join("\n")}\nMore with fleet logs ${j.id} (tail/grep).`
1795
+ : ` Read the log with fleet logs ${j.id}.`),
1069
1796
  terminal: true,
1070
1797
  urgent: true,
1071
1798
  };
@@ -1079,7 +1806,7 @@ export function fleetJobNotification(j) {
1079
1806
  case "running":
1080
1807
  return j.nodeDownWarned
1081
1808
  ? {
1082
- text: `Fleet node ${j.node} stopped answering while running ${j.name} (${j.id}); ${REQUEUE_KINDS.has(j.kind) ? "it moves to another node if the node stays away" : "a deploy is never retried automatically"}.`,
1809
+ text: `Fleet node ${j.node} stopped answering while running ${j.name} (${j.id}); ${canRequeue(j) ? "it moves to another node if the node stays away" : j.kind === "deploy" ? "a deploy is never retried automatically" : `a ${j.kind} job is not retried automatically (mark it "retry": true in ${FLEET_CONFIG_FILE} if it is safe to repeat)`}.`,
1083
1810
  terminal: false,
1084
1811
  urgent: false,
1085
1812
  }