@prestyj/cli 5.36.0 → 5.38.0

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 (140) hide show
  1. package/dist/cli/command-routing.d.ts +1 -1
  2. package/dist/cli/command-routing.js +3 -1
  3. package/dist/cli/command-routing.js.map +1 -1
  4. package/dist/cli/fleet.d.ts +6 -0
  5. package/dist/cli/fleet.js +304 -0
  6. package/dist/cli/fleet.js.map +1 -0
  7. package/dist/cli/node.d.ts +5 -0
  8. package/dist/cli/node.js +308 -0
  9. package/dist/cli/node.js.map +1 -0
  10. package/dist/cli/validate.js +31 -7
  11. package/dist/cli/validate.js.map +1 -1
  12. package/dist/cli.js +6 -0
  13. package/dist/cli.js.map +1 -1
  14. package/dist/core/agent-notifications.d.ts +1 -1
  15. package/dist/core/agent-session.d.ts +1 -0
  16. package/dist/core/agent-session.js +6 -0
  17. package/dist/core/agent-session.js.map +1 -1
  18. package/dist/core/fleet/browser.d.ts +13 -0
  19. package/dist/core/fleet/browser.js +50 -0
  20. package/dist/core/fleet/browser.js.map +1 -0
  21. package/dist/core/fleet/client.d.ts +70 -0
  22. package/dist/core/fleet/client.js +240 -0
  23. package/dist/core/fleet/client.js.map +1 -0
  24. package/dist/core/fleet/discovery.d.ts +33 -0
  25. package/dist/core/fleet/discovery.js +82 -0
  26. package/dist/core/fleet/discovery.js.map +1 -0
  27. package/dist/core/fleet/fleet-scheduler.d.ts +44 -0
  28. package/dist/core/fleet/fleet-scheduler.js +108 -0
  29. package/dist/core/fleet/fleet-scheduler.js.map +1 -0
  30. package/dist/core/fleet/git.d.ts +32 -0
  31. package/dist/core/fleet/git.js +113 -0
  32. package/dist/core/fleet/git.js.map +1 -0
  33. package/dist/core/fleet/node/agents.d.ts +15 -0
  34. package/dist/core/fleet/node/agents.js +461 -0
  35. package/dist/core/fleet/node/agents.js.map +1 -0
  36. package/dist/core/fleet/node/config.d.ts +52 -0
  37. package/dist/core/fleet/node/config.js +191 -0
  38. package/dist/core/fleet/node/config.js.map +1 -0
  39. package/dist/core/fleet/node/context.d.ts +43 -0
  40. package/dist/core/fleet/node/context.js +2 -0
  41. package/dist/core/fleet/node/context.js.map +1 -0
  42. package/dist/core/fleet/node/docker.d.ts +23 -0
  43. package/dist/core/fleet/node/docker.js +214 -0
  44. package/dist/core/fleet/node/docker.js.map +1 -0
  45. package/dist/core/fleet/node/exec.d.ts +24 -0
  46. package/dist/core/fleet/node/exec.js +64 -0
  47. package/dist/core/fleet/node/exec.js.map +1 -0
  48. package/dist/core/fleet/node/info.d.ts +36 -0
  49. package/dist/core/fleet/node/info.js +209 -0
  50. package/dist/core/fleet/node/info.js.map +1 -0
  51. package/dist/core/fleet/node/jobs.d.ts +88 -0
  52. package/dist/core/fleet/node/jobs.js +702 -0
  53. package/dist/core/fleet/node/jobs.js.map +1 -0
  54. package/dist/core/fleet/node/server.d.ts +37 -0
  55. package/dist/core/fleet/node/server.js +416 -0
  56. package/dist/core/fleet/node/server.js.map +1 -0
  57. package/dist/core/fleet/node/services.d.ts +71 -0
  58. package/dist/core/fleet/node/services.js +532 -0
  59. package/dist/core/fleet/node/services.js.map +1 -0
  60. package/dist/core/fleet/node/state.d.ts +48 -0
  61. package/dist/core/fleet/node/state.js +43 -0
  62. package/dist/core/fleet/node/state.js.map +1 -0
  63. package/dist/core/fleet/node/workspace.d.ts +41 -0
  64. package/dist/core/fleet/node/workspace.js +153 -0
  65. package/dist/core/fleet/node/workspace.js.map +1 -0
  66. package/dist/core/fleet/project-config.d.ts +52 -0
  67. package/dist/core/fleet/project-config.js +449 -0
  68. package/dist/core/fleet/project-config.js.map +1 -0
  69. package/dist/core/fleet/protocol.d.ts +225 -0
  70. package/dist/core/fleet/protocol.js +11 -0
  71. package/dist/core/fleet/protocol.js.map +1 -0
  72. package/dist/core/fleet/registry.d.ts +34 -0
  73. package/dist/core/fleet/registry.js +79 -0
  74. package/dist/core/fleet/registry.js.map +1 -0
  75. package/dist/core/fleet/remote-agent-nodes.d.ts +31 -0
  76. package/dist/core/fleet/remote-agent-nodes.js +96 -0
  77. package/dist/core/fleet/remote-agent-nodes.js.map +1 -0
  78. package/dist/core/fleet/remote-agent.d.ts +115 -0
  79. package/dist/core/fleet/remote-agent.js +590 -0
  80. package/dist/core/fleet/remote-agent.js.map +1 -0
  81. package/dist/core/fleet/service.d.ts +185 -0
  82. package/dist/core/fleet/service.js +1140 -0
  83. package/dist/core/fleet/service.js.map +1 -0
  84. package/dist/core/fleet/session-hook.d.ts +3 -0
  85. package/dist/core/fleet/session-hook.js +45 -0
  86. package/dist/core/fleet/session-hook.js.map +1 -0
  87. package/dist/core/fleet/store.d.ts +37 -0
  88. package/dist/core/fleet/store.js +115 -0
  89. package/dist/core/fleet/store.js.map +1 -0
  90. package/dist/core/fleet/types.d.ts +88 -0
  91. package/dist/core/fleet/types.js +16 -0
  92. package/dist/core/fleet/types.js.map +1 -0
  93. package/dist/core/mcp/store.d.ts +2 -2
  94. package/dist/core/subagent-manager.d.ts +39 -0
  95. package/dist/core/subagent-manager.js +67 -7
  96. package/dist/core/subagent-manager.js.map +1 -1
  97. package/dist/core/validation/backends.d.ts +5 -2
  98. package/dist/core/validation/backends.js +17 -1
  99. package/dist/core/validation/backends.js.map +1 -1
  100. package/dist/core/validation/config.d.ts +10 -2
  101. package/dist/core/validation/config.js +30 -3
  102. package/dist/core/validation/config.js.map +1 -1
  103. package/dist/core/validation/exec.js +6 -1
  104. package/dist/core/validation/exec.js.map +1 -1
  105. package/dist/core/validation/github-actions-backend.d.ts +49 -2
  106. package/dist/core/validation/github-actions-backend.js +257 -3
  107. package/dist/core/validation/github-actions-backend.js.map +1 -1
  108. package/dist/core/validation/node-backend.d.ts +56 -0
  109. package/dist/core/validation/node-backend.js +184 -0
  110. package/dist/core/validation/node-backend.js.map +1 -0
  111. package/dist/core/validation/scheduler.d.ts +38 -0
  112. package/dist/core/validation/scheduler.js +133 -0
  113. package/dist/core/validation/scheduler.js.map +1 -0
  114. package/dist/core/validation/service.d.ts +53 -3
  115. package/dist/core/validation/service.js +272 -56
  116. package/dist/core/validation/service.js.map +1 -1
  117. package/dist/core/validation/session-hook.js +9 -2
  118. package/dist/core/validation/session-hook.js.map +1 -1
  119. package/dist/core/validation/types.d.ts +52 -1
  120. package/dist/core/validation/types.js +2 -0
  121. package/dist/core/validation/types.js.map +1 -1
  122. package/dist/tools/browser-session.d.ts +24 -1
  123. package/dist/tools/browser-session.js +31 -10
  124. package/dist/tools/browser-session.js.map +1 -1
  125. package/dist/tools/fleet.d.ts +26 -0
  126. package/dist/tools/fleet.js +144 -0
  127. package/dist/tools/fleet.js.map +1 -0
  128. package/dist/tools/index.js +6 -2
  129. package/dist/tools/index.js.map +1 -1
  130. package/dist/tools/prompt-hints.js +2 -0
  131. package/dist/tools/prompt-hints.js.map +1 -1
  132. package/dist/tools/steroids.d.ts +1 -1
  133. package/dist/tools/subagent-control.js +10 -1
  134. package/dist/tools/subagent-control.js.map +1 -1
  135. package/dist/tools/tasks.d.ts +1 -1
  136. package/dist/tools/tool-tiers.js +1 -0
  137. package/dist/tools/tool-tiers.js.map +1 -1
  138. package/dist/tools/validate.js +4 -5
  139. package/dist/tools/validate.js.map +1 -1
  140. package/package.json +7 -5
@@ -0,0 +1,1140 @@
1
+ // The fleet orchestrator on the controller. Sessions and the CLI queue jobs and
2
+ // return at once; one leader process (a session host or `ezcoder fleet daemon`)
3
+ // dispatches them to nodes with bounded concurrency, polls them, downloads
4
+ // artifacts, requeues work lost with a node (never deploys) and records results.
5
+ // Every process watches the shared store and tells its own sessions.
6
+ import { EventEmitter } from "node:events";
7
+ import { randomBytes } from "node:crypto";
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { cacheKeyFor } from "../validation/config.js";
11
+ import { defaultExec } from "../validation/exec.js";
12
+ import { addCustomEndpoint, removeCustomEndpoint, } from "../local-endpoint-store.js";
13
+ import { FleetClient, FleetClientError } from "./client.js";
14
+ import { chooseNode, } from "./fleet-scheduler.js";
15
+ import { FleetGit } from "./git.js";
16
+ import { builtinServices, loadFleetConfig, } from "./project-config.js";
17
+ import { NodeRegistry } from "./registry.js";
18
+ import { defaultFleetDir, JsonListStore, LeaderLock, readFleetSettings } from "./store.js";
19
+ import { FLEET_MAX_ATTEMPTS, isFleetTerminal, REQUEUE_KINDS, } from "./types.js";
20
+ const ACTIVE_JOB = new Set(["queued", "preparing", "running"]);
21
+ const KEEP_DAYS = 14;
22
+ const KEEP_MAX = 500;
23
+ function nowIso() {
24
+ return new Date().toISOString();
25
+ }
26
+ function newId(prefix) {
27
+ return `${prefix}${Date.now().toString(36)}${randomBytes(3).toString("hex")}`;
28
+ }
29
+ export function short(sha) {
30
+ return sha.slice(0, 8);
31
+ }
32
+ function errText(e) {
33
+ return e instanceof Error ? e.message : String(e);
34
+ }
35
+ function pruneJobs(jobs) {
36
+ const cutoff = Date.now() - KEEP_DAYS * 86_400_000;
37
+ let kept = jobs.filter((j) => !isFleetTerminal(j.state) || Date.parse(j.updatedAt) > cutoff);
38
+ if (kept.length > KEEP_MAX) {
39
+ const active = kept.filter((j) => !isFleetTerminal(j.state));
40
+ const done = kept.filter((j) => isFleetTerminal(j.state)).slice(-(KEEP_MAX - active.length));
41
+ kept = [...done, ...active].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
42
+ }
43
+ return kept;
44
+ }
45
+ function pruneServices(list) {
46
+ const cutoff = Date.now() - KEEP_DAYS * 86_400_000;
47
+ return list.filter((s) => s.state !== "stopped" || Date.parse(s.updatedAt) > cutoff);
48
+ }
49
+ /** Map a node job state onto ours. */
50
+ function mapState(s) {
51
+ return s === "lost" ? "lost" : s;
52
+ }
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
+ /**
64
+ * Local file for an artifact under `dir`. Refuses to write through a symlink
65
+ * (an existing `dir/dist -> /elsewhere` would otherwise redirect the download).
66
+ */
67
+ export function safeArtifactDest(dir, rel) {
68
+ fs.mkdirSync(dir, { recursive: true });
69
+ let cur = fs.realpathSync(dir);
70
+ for (const part of rel.split("/")) {
71
+ cur = path.join(cur, part);
72
+ let st;
73
+ try {
74
+ st = fs.lstatSync(cur);
75
+ }
76
+ catch {
77
+ break; // the rest doesn't exist yet: created as plain folders/files
78
+ }
79
+ if (st.isSymbolicLink())
80
+ throw new Error(`refusing to write artifact through a symlink: ${cur}`);
81
+ }
82
+ return path.join(fs.realpathSync(dir), rel);
83
+ }
84
+ let shared;
85
+ export class FleetService {
86
+ dir;
87
+ jobs;
88
+ services;
89
+ registry;
90
+ exec;
91
+ git;
92
+ fetchImpl;
93
+ pollMs;
94
+ clientTimeoutMs;
95
+ unreachableMs;
96
+ maxArtifactBytes;
97
+ leader;
98
+ gateFn;
99
+ localEndpoints;
100
+ maxConcurrentOverride;
101
+ events = new EventEmitter();
102
+ lastInfo = new Map();
103
+ seenJobs = new Map();
104
+ seenServices = new Map();
105
+ seeded = false;
106
+ timer;
107
+ ticking;
108
+ keepAlive = false;
109
+ autoStart;
110
+ constructor(opts = {}) {
111
+ this.dir = opts.dir ?? defaultFleetDir();
112
+ this.jobs = new JsonListStore(this.dir, "jobs.json", "jobs", { prune: pruneJobs });
113
+ this.services = new JsonListStore(this.dir, "services.json", "services", {
114
+ prune: pruneServices,
115
+ });
116
+ this.registry = new NodeRegistry(this.dir);
117
+ this.exec = opts.exec ?? defaultExec;
118
+ this.git = new FleetGit(this.exec);
119
+ this.fetchImpl = opts.fetch;
120
+ this.pollMs = opts.pollMs ?? 15_000;
121
+ this.clientTimeoutMs = opts.clientTimeoutMs ?? 15_000;
122
+ this.unreachableMs = (opts.unreachableRequeueMinutes ?? 3) * 60_000;
123
+ this.maxArtifactBytes = opts.maxArtifactBytes ?? 2 * 1024 ** 3;
124
+ this.leader = new LeaderLock(this.dir, Math.max(90_000, this.pollMs * 4));
125
+ this.gateFn =
126
+ opts.gate ??
127
+ (async (cwd, sha) => {
128
+ const { ValidationService } = await import("../validation/service.js");
129
+ return ValidationService.shared().gate(cwd, sha);
130
+ });
131
+ this.localEndpoints = opts.localEndpoints ?? {};
132
+ this.maxConcurrentOverride = opts.maxConcurrent;
133
+ this.autoStart = opts.autoStart ?? true;
134
+ this.events.setMaxListeners(100);
135
+ }
136
+ /** One service per process. */
137
+ static shared() {
138
+ shared ??= new FleetService();
139
+ return shared;
140
+ }
141
+ get maxConcurrent() {
142
+ return Math.max(1, this.maxConcurrentOverride ?? readFleetSettings(this.dir).maxConcurrent ?? 8);
143
+ }
144
+ onEvent(listener) {
145
+ this.events.on("event", listener);
146
+ return () => this.events.off("event", listener);
147
+ }
148
+ // ── nodes ────────────────────────────────────────────────
149
+ client(node) {
150
+ return FleetClient.forNode(node, {
151
+ timeoutMs: this.clientTimeoutMs,
152
+ ...(this.fetchImpl ? { fetch: this.fetchImpl } : {}),
153
+ });
154
+ }
155
+ async clientFor(name) {
156
+ const node = await this.registry.get(name);
157
+ if (!node)
158
+ throw new Error(`node ${name} is no longer paired`);
159
+ return this.client(node);
160
+ }
161
+ /** Live view of every paired node (info fetched in parallel). */
162
+ async nodeViews() {
163
+ const nodes = await this.registry.list();
164
+ return Promise.all(nodes.map(async (n) => {
165
+ try {
166
+ const info = await this.client(n).info();
167
+ this.lastInfo.set(n.name, info);
168
+ return { name: n.name, online: true, info, labels: n.labels };
169
+ }
170
+ catch (e) {
171
+ const last = this.lastInfo.get(n.name);
172
+ return {
173
+ name: n.name,
174
+ online: false,
175
+ ...(last ? { info: last } : {}),
176
+ labels: n.labels,
177
+ error: errText(e),
178
+ };
179
+ }
180
+ }));
181
+ }
182
+ async nodes() {
183
+ const [views, nodes, jobs] = await Promise.all([
184
+ this.nodeViews(),
185
+ this.registry.list(),
186
+ this.jobs.read(),
187
+ ]);
188
+ return nodes.map((node) => {
189
+ const v = views.find((x) => x.name === node.name);
190
+ return {
191
+ node,
192
+ online: v.online,
193
+ ...(v.online && v.info ? { info: v.info } : {}),
194
+ ...(v.error ? { error: v.error } : {}),
195
+ active: jobs.filter((j) => j.node === node.name && ACTIVE_JOB.has(j.state)).length,
196
+ };
197
+ });
198
+ }
199
+ // ── jobs ─────────────────────────────────────────────────
200
+ config(cwd) {
201
+ return loadFleetConfig(cwd);
202
+ }
203
+ patchFile(id) {
204
+ return path.join(this.dir, "patches", `${id}.b64`);
205
+ }
206
+ /** Resolve the code a job or devenv uses; throws "push first" when the commit isn't on origin. */
207
+ async source(cwd, opts) {
208
+ const g = await this.git.state(cwd, opts.ref ?? "HEAD");
209
+ const messages = [];
210
+ if (opts.includeUncommitted) {
211
+ const p = await this.git.patch(cwd, g.sha);
212
+ if (p.base !== g.sha) {
213
+ messages.push(`Local commits after ${short(p.base)} (the newest pushed one) go as a patch.`);
214
+ }
215
+ if (p.patch)
216
+ messages.push(`Sending ${p.files} changed file(s) as a patch.`);
217
+ return {
218
+ src: { git: g.git, sha: p.base, ...(p.patch ? { patch: p.patch } : {}) },
219
+ ...(g.repo ? { repo: g.repo } : {}),
220
+ dirty: !!p.patch,
221
+ messages,
222
+ };
223
+ }
224
+ if (!g.onRemote) {
225
+ throw new Error(`commit ${short(g.sha)} isn't on origin; push first (or include uncommitted work with --uncommitted / includeUncommitted)`);
226
+ }
227
+ if (g.dirty) {
228
+ messages.push(`Uncommitted changes are not included; this runs commit ${short(g.sha)}. Use --uncommitted to include them.`);
229
+ }
230
+ return {
231
+ src: { git: g.git, sha: g.sha },
232
+ ...(g.repo ? { repo: g.repo } : {}),
233
+ dirty: false,
234
+ messages,
235
+ };
236
+ }
237
+ async checkGate(cwd, sha) {
238
+ let g;
239
+ try {
240
+ g = await this.gateFn(cwd, sha);
241
+ }
242
+ catch (e) {
243
+ throw new Error(`deploy blocked: validation gate could not be checked (${errText(e)})`, {
244
+ cause: e,
245
+ });
246
+ }
247
+ if (!g.ok) {
248
+ const rows = g.rows.map((r) => `${r.stage}: ${r.state}`).join(", ") || "no required stages passed";
249
+ throw new Error(`deploy blocked: required validation hasn't passed at ${short(sha)} (${rows}). Run validate run, wait for it to pass, then deploy again.`);
250
+ }
251
+ }
252
+ /** Queue a job from the project config; returns at once. */
253
+ async run(cwdIn, name, opts = {}) {
254
+ const cwd = path.resolve(cwdIn);
255
+ const config = loadFleetConfig(cwd);
256
+ if ("error" in config)
257
+ throw new Error(config.error);
258
+ const spec = config.jobs[name];
259
+ if (!spec) {
260
+ const names = Object.keys(config.jobs);
261
+ throw new Error(`no fleet job "${name}"; this project has: ${names.join(", ") || "none"} (define jobs in .ezcoder/fleet.json)`);
262
+ }
263
+ if (opts.node && !(await this.registry.get(opts.node))) {
264
+ throw new Error(`no paired node "${opts.node}"`);
265
+ }
266
+ if (!(await this.registry.list()).length) {
267
+ throw new Error("no nodes paired; run `ezcoder fleet discover`, then `ezcoder fleet add <pairing>`");
268
+ }
269
+ const isDeploy = spec.kind === "deploy";
270
+ if (isDeploy && opts.includeUncommitted) {
271
+ throw new Error("deploy runs exact pushed commits only; commit and push, then deploy without --uncommitted");
272
+ }
273
+ const s = await this.source(cwd, opts);
274
+ const ungated = isDeploy && spec.gate === false;
275
+ if (isDeploy && !ungated)
276
+ await this.checkGate(cwd, s.src.sha);
277
+ const id = newId("f");
278
+ if (s.src.patch) {
279
+ fs.mkdirSync(path.dirname(this.patchFile(id)), { recursive: true });
280
+ fs.writeFileSync(this.patchFile(id), s.src.patch, { mode: 0o600 });
281
+ }
282
+ const projectKey = s.repo ?? path.basename(cwd);
283
+ const at = nowIso();
284
+ const job = {
285
+ id,
286
+ name,
287
+ kind: spec.kind,
288
+ project: cwd,
289
+ projectKey,
290
+ git: s.src.git,
291
+ sha: s.src.sha,
292
+ ...(s.src.patch ? { hasPatch: true, base: s.src.sha } : {}),
293
+ ...(spec.subdir ? { subdir: spec.subdir } : {}),
294
+ command: spec.command,
295
+ ...(spec.docker ? { docker: spec.docker } : {}),
296
+ ...(spec.env ? { env: spec.env } : {}),
297
+ ...(spec.secrets ? { secrets: spec.secrets } : {}),
298
+ ...(spec.resources ? { resources: spec.resources } : {}),
299
+ ...(spec.artifacts ? { artifactGlobs: spec.artifacts } : {}),
300
+ cacheKey: spec.cacheKey ?? cacheKeyFor(projectKey),
301
+ timeoutMinutes: spec.timeoutMinutes,
302
+ ...(ungated ? { ungated: true } : {}),
303
+ state: "queued",
304
+ createdAt: at,
305
+ updatedAt: at,
306
+ ...(opts.node ? { node: opts.node, pinned: true } : {}),
307
+ ...(opts.outDir ? { outDir: path.resolve(cwd, opts.outDir) } : {}),
308
+ attempts: 1,
309
+ };
310
+ await this.jobs.update((jobs) => {
311
+ jobs.push(job);
312
+ });
313
+ if (ungated)
314
+ s.messages.push('deploy gate is off for this job ("gate": false).');
315
+ if (this.autoStart)
316
+ this.start();
317
+ return { job, messages: s.messages };
318
+ }
319
+ async list(cwd) {
320
+ const jobs = await this.jobs.read();
321
+ return cwd ? jobs.filter((j) => j.project === path.resolve(cwd)) : jobs;
322
+ }
323
+ async get(id) {
324
+ return (await this.jobs.read()).find((j) => j.id === id);
325
+ }
326
+ async cancel(id) {
327
+ const job = await this.jobs.update((jobs) => {
328
+ const j = jobs.find((x) => x.id === id);
329
+ if (!j || isFleetTerminal(j.state))
330
+ return j ? { ...j } : undefined;
331
+ const wasDispatched = !!j.remoteId && j.state !== "queued";
332
+ j.state = "cancelled";
333
+ j.summary = "cancelled by request";
334
+ j.updatedAt = j.finishedAt = nowIso();
335
+ return { ...j, wasDispatched };
336
+ });
337
+ if (job && job.wasDispatched && job.node && job.remoteId) {
338
+ await this.clientFor(job.node)
339
+ .then((c) => c.cancelJob(job.remoteId))
340
+ .catch(() => { });
341
+ }
342
+ if (job)
343
+ delete job.wasDispatched;
344
+ return job;
345
+ }
346
+ /** Log text from `offset` (default: the last ~24 KB). */
347
+ async logs(id, opts = {}) {
348
+ const job = await this.get(id);
349
+ if (!job)
350
+ return `No job ${id}.`;
351
+ if (!job.node || !job.remoteId || job.state === "queued") {
352
+ return `Not dispatched yet${job.summary ? ` (${job.summary})` : ""}.`;
353
+ }
354
+ const c = await this.clientFor(job.node);
355
+ if (opts.offset !== undefined)
356
+ return (await c.jobLog(job.remoteId, opts.offset)).text;
357
+ const head = await c.jobLog(job.remoteId, 0);
358
+ if (opts.full || head.text.length <= 24_000)
359
+ return head.text || "(no output yet)";
360
+ return `…\n${head.text.slice(-24_000)}`;
361
+ }
362
+ defaultArtifactsDir(job) {
363
+ return job.outDir ?? path.join(job.project, ".ezcoder", "artifacts", job.id);
364
+ }
365
+ /** Download a finished job's artifacts; returns local paths. */
366
+ async downloadArtifacts(id, outDir) {
367
+ const job = await this.get(id);
368
+ if (!job)
369
+ throw new Error(`no job ${id}`);
370
+ if (!job.node || !job.remoteId)
371
+ throw new Error(`job ${id} hasn't run yet`);
372
+ const c = await this.clientFor(job.node);
373
+ const status = await c.job(job.remoteId);
374
+ const list = status.artifacts ?? job.artifacts ?? [];
375
+ const dir = outDir ? path.resolve(outDir) : this.defaultArtifactsDir(job);
376
+ const files = [];
377
+ let total = 0;
378
+ for (const a of list) {
379
+ const rel = safeArtifactPath(a.path);
380
+ if (!rel)
381
+ continue;
382
+ total += a.bytes;
383
+ if (!outDir && total > this.maxArtifactBytes) {
384
+ throw new Error(`artifacts exceed ${Math.round(this.maxArtifactBytes / 1e9)} GB; download with --out <dir>`);
385
+ }
386
+ const dest = safeArtifactDest(dir, rel);
387
+ await c.downloadArtifact(job.remoteId, a.path, dest);
388
+ files.push(dest);
389
+ }
390
+ await this.patchJob(id, { artifacts: list, artifactsDir: dir }, undefined, true);
391
+ return { dir, files };
392
+ }
393
+ // ── services ─────────────────────────────────────────────
394
+ serviceSpec(cwd, name) {
395
+ if (cwd) {
396
+ const config = loadFleetConfig(cwd);
397
+ if ("error" in config)
398
+ throw new Error(config.error);
399
+ const spec = config.services[name];
400
+ if (!spec) {
401
+ throw new Error(`no fleet service "${name}"; available: ${Object.keys(config.services).join(", ")}`);
402
+ }
403
+ return spec;
404
+ }
405
+ const spec = builtinServices()[name];
406
+ if (!spec)
407
+ throw new Error(`no built-in service "${name}" (built-ins: llm, browser)`);
408
+ return spec;
409
+ }
410
+ async serviceList(cwd) {
411
+ const all = await this.services.read();
412
+ return cwd ? all.filter((s) => !s.project || s.project === path.resolve(cwd)) : all;
413
+ }
414
+ /** Find a service by id, `node/name` or name (newest live one, this project first). */
415
+ async findService(ref, cwd) {
416
+ const all = (await this.services.read()).filter((s) => s.state !== "stopped");
417
+ const byId = all.find((s) => s.id === ref);
418
+ if (byId)
419
+ return byId;
420
+ const [node, name] = ref.includes("/") ? ref.split("/", 2) : [undefined, ref];
421
+ const matches = all.filter((s) => s.name === name && (!node || s.node === node));
422
+ const project = cwd ? path.resolve(cwd) : undefined;
423
+ return matches.filter((s) => s.project === project).at(-1) ?? matches.at(-1);
424
+ }
425
+ /** Start a service on a fitting node; returns once the node accepted it. */
426
+ async serviceUp(cwdIn, name, opts = {}) {
427
+ const cwd = cwdIn ? path.resolve(cwdIn) : undefined;
428
+ const spec = this.serviceSpec(cwd, name);
429
+ const existing = (await this.services.read()).find((s) => s.name === name &&
430
+ s.project === cwd &&
431
+ (s.state === "running" || s.state === "starting") &&
432
+ (!opts.node || s.node === opts.node));
433
+ if (existing)
434
+ return { service: existing, messages: [], reused: true };
435
+ const messages = [];
436
+ let source;
437
+ let projectKey;
438
+ if (spec.needsSource) {
439
+ if (!cwd)
440
+ throw new Error(`service ${name} needs a project folder`);
441
+ const s = await this.source(cwd, {
442
+ includeUncommitted: opts.includeUncommitted ?? spec.kind === "devenv",
443
+ });
444
+ source = s.src;
445
+ projectKey = s.repo ?? path.basename(cwd);
446
+ messages.push(...s.messages);
447
+ }
448
+ const views = await this.nodeViews();
449
+ const placement = chooseNode({ resources: spec.resources, docker: true, node: opts.node, takesSlot: false }, views);
450
+ if ("error" in placement)
451
+ throw new Error(`can't start ${name}: ${placement.error}`);
452
+ if ("wait" in placement)
453
+ throw new Error(`can't start ${name} now: ${placement.wait}`);
454
+ const node = (await this.registry.get(placement.node.name));
455
+ const id = `${name}-${randomBytes(3).toString("hex")}`;
456
+ const req = {
457
+ id,
458
+ kind: spec.kind,
459
+ ...(projectKey ? { project: projectKey } : {}),
460
+ ...(source ? { source } : {}),
461
+ docker: spec.docker,
462
+ ...(spec.command ? { command: spec.command } : {}),
463
+ ...(spec.env ? { env: spec.env } : {}),
464
+ ports: spec.ports,
465
+ ...(spec.resources ? { resources: spec.resources } : {}),
466
+ ...(spec.persist ? { persist: spec.persist } : {}),
467
+ ...(spec.idleStopMinutes !== undefined ? { idleStopMinutes: spec.idleStopMinutes } : {}),
468
+ };
469
+ const status = await this.client(node).startService(req);
470
+ const at = nowIso();
471
+ let rec = {
472
+ id: status.id || id,
473
+ name,
474
+ kind: spec.kind,
475
+ node: node.name,
476
+ ...(cwd ? { project: cwd } : {}),
477
+ state: status.state,
478
+ endpoints: status.endpoints ?? [],
479
+ ...(status.summary ? { summary: status.summary } : {}),
480
+ createdAt: at,
481
+ updatedAt: at,
482
+ };
483
+ await this.services.update((list) => {
484
+ list.push(rec);
485
+ });
486
+ rec = (await this.syncLocalEndpoint(rec, messages)) ?? rec;
487
+ if (this.autoStart)
488
+ this.start();
489
+ return { service: rec, messages, reused: false };
490
+ }
491
+ /** Register (or remove) the local model endpoint of an inference service. */
492
+ async syncLocalEndpoint(rec, messages) {
493
+ if (rec.kind !== "inference" || this.localEndpoints === false)
494
+ return undefined;
495
+ const live = rec.state === "running" || rec.state === "starting";
496
+ if (live && !rec.localEndpointId) {
497
+ const ep = rec.endpoints.find((e) => e.name === "openai") ?? rec.endpoints[0];
498
+ if (!ep)
499
+ return undefined;
500
+ try {
501
+ const added = await addCustomEndpoint({ label: `fleet:${rec.node}/${rec.name}`, baseUrl: ep.url }, this.localEndpoints);
502
+ messages?.push(`Registered ${added.baseUrl} as local model endpoint "${added.label}".`);
503
+ return this.patchService(rec.id, { localEndpointId: added.id });
504
+ }
505
+ catch (e) {
506
+ messages?.push(`Could not register the model endpoint: ${errText(e)}`);
507
+ }
508
+ }
509
+ else if (!live && rec.localEndpointId) {
510
+ await removeCustomEndpoint(rec.localEndpointId, this.localEndpoints).catch(() => { });
511
+ return this.patchService(rec.id, { localEndpointId: undefined });
512
+ }
513
+ return undefined;
514
+ }
515
+ async serviceDown(ref, cwd) {
516
+ const rec = await this.findService(ref, cwd);
517
+ if (!rec)
518
+ throw new Error(`no running fleet service "${ref}"`);
519
+ let note;
520
+ try {
521
+ await (await this.clientFor(rec.node)).stopService(rec.id);
522
+ }
523
+ catch (e) {
524
+ if (!(e instanceof FleetClientError && e.code === "not_found")) {
525
+ note = `node didn't confirm the stop: ${errText(e)}`;
526
+ }
527
+ }
528
+ const updated = (await this.patchService(rec.id, {
529
+ state: "stopped",
530
+ ...(note ? { summary: note } : {}),
531
+ })) ?? rec;
532
+ await this.syncLocalEndpoint(updated);
533
+ const { clearSelectedFleetBrowser } = await import("./browser.js");
534
+ clearSelectedFleetBrowser(rec.id);
535
+ return { ...updated, localEndpointId: undefined };
536
+ }
537
+ async serviceLog(ref, tail = 200, cwd) {
538
+ const rec = await this.findService(ref, cwd);
539
+ if (!rec)
540
+ return `No running fleet service "${ref}".`;
541
+ return (await this.clientFor(rec.node)).serviceLog(rec.id, tail);
542
+ }
543
+ async serviceExec(ref, command, opts = {}) {
544
+ const rec = await this.findService(ref, opts.cwd);
545
+ if (!rec)
546
+ throw new Error(`no running fleet service "${ref}"`);
547
+ if (rec.kind !== "devenv" && rec.kind !== "custom") {
548
+ throw new Error(`exec works on devenv/custom services; ${rec.name} is ${rec.kind}`);
549
+ }
550
+ return (await this.clientFor(rec.node)).exec(rec.id, {
551
+ command,
552
+ timeoutSeconds: opts.timeoutSeconds ?? 300,
553
+ });
554
+ }
555
+ // ── scheduling loop ──────────────────────────────────────
556
+ start(opts = {}) {
557
+ if (opts.keepAlive)
558
+ this.keepAlive = true;
559
+ if (this.timer)
560
+ return;
561
+ const loop = () => {
562
+ this.timer = setTimeout(async () => {
563
+ await this.tick().catch(() => { });
564
+ if (this.timer)
565
+ loop();
566
+ }, this.pollMs);
567
+ if (!this.keepAlive)
568
+ this.timer.unref();
569
+ };
570
+ void this.tick().catch(() => { });
571
+ loop();
572
+ }
573
+ stop() {
574
+ if (this.timer)
575
+ clearTimeout(this.timer);
576
+ this.timer = undefined;
577
+ }
578
+ get running() {
579
+ return !!this.timer;
580
+ }
581
+ async leaderAlive() {
582
+ return this.leader.alive();
583
+ }
584
+ /** One pass: observe; if we lead, poll and dispatch. Returns whether jobs remain active. */
585
+ async tick() {
586
+ if (this.ticking) {
587
+ await this.ticking;
588
+ }
589
+ else {
590
+ this.ticking = this.tickInner().finally(() => {
591
+ this.ticking = undefined;
592
+ });
593
+ await this.ticking;
594
+ }
595
+ return (await this.jobs.read()).some((j) => ACTIVE_JOB.has(j.state));
596
+ }
597
+ async tickInner() {
598
+ let jobs = await this.jobs.read();
599
+ let services = await this.services.read();
600
+ this.observe(jobs, services);
601
+ const active = jobs.filter((j) => ACTIVE_JOB.has(j.state));
602
+ const liveServices = services.filter((s) => s.state === "running" || s.state === "starting");
603
+ if (!active.length && !liveServices.length) {
604
+ if (!this.keepAlive)
605
+ this.stop();
606
+ return;
607
+ }
608
+ if (!(await this.leader.lead()))
609
+ return;
610
+ for (const j of active.filter((x) => x.state !== "queued"))
611
+ await this.pollJob(j);
612
+ for (const s of liveServices)
613
+ await this.pollService(s);
614
+ jobs = await this.jobs.read();
615
+ const queued = jobs.filter((j) => j.state === "queued");
616
+ if (queued.length)
617
+ await this.dispatchQueued(jobs, queued);
618
+ jobs = await this.jobs.read();
619
+ services = await this.services.read();
620
+ this.observe(jobs, services);
621
+ }
622
+ async dispatchQueued(jobs, queued) {
623
+ const inFlight = jobs
624
+ .filter((j) => (j.state === "preparing" || j.state === "running") && j.node)
625
+ .map((j) => ({ node: j.node, ...(j.resources ? { resources: j.resources } : {}) }));
626
+ let count = inFlight.length;
627
+ const views = await this.nodeViews();
628
+ for (const j of queued) {
629
+ if (count >= this.maxConcurrent)
630
+ break;
631
+ const last = [...jobs]
632
+ .reverse()
633
+ .find((x) => x.id !== j.id && x.dispatchedAt && x.node && x.projectKey === j.projectKey);
634
+ const req = {
635
+ ...(j.resources ? { resources: j.resources } : {}),
636
+ ...(j.secrets?.length ? { secrets: j.secrets } : {}),
637
+ docker: !!j.docker,
638
+ ...(j.pinned && j.node ? { node: j.node } : {}),
639
+ ...(j.avoid ? { avoid: j.avoid } : {}),
640
+ ...(last?.node ? { affinity: last.node } : {}),
641
+ takesSlot: true,
642
+ };
643
+ const p = chooseNode(req, views, inFlight);
644
+ if ("error" in p) {
645
+ await this.patchJob(j.id, {
646
+ state: "error",
647
+ summary: p.error.slice(0, 400),
648
+ finishedAt: nowIso(),
649
+ });
650
+ continue;
651
+ }
652
+ if ("wait" in p) {
653
+ if (!j.waitWarned) {
654
+ await this.patchJob(j.id, { waitWarned: true, summary: `waiting: ${p.wait}`.slice(0, 400) }, "queued");
655
+ }
656
+ continue;
657
+ }
658
+ const nodeName = p.node.name;
659
+ if (j.kind === "deploy" && !j.ungated) {
660
+ try {
661
+ await this.checkGate(j.project, j.sha);
662
+ }
663
+ catch (e) {
664
+ await this.patchJob(j.id, {
665
+ state: "error",
666
+ summary: errText(e).slice(0, 400),
667
+ finishedAt: nowIso(),
668
+ });
669
+ continue;
670
+ }
671
+ }
672
+ const node = await this.registry.get(nodeName);
673
+ if (!node)
674
+ continue;
675
+ const remoteId = (j.attempts ?? 1) > 1 ? `${j.id}-${j.attempts}` : j.id;
676
+ let patch;
677
+ if (j.hasPatch) {
678
+ try {
679
+ patch = fs.readFileSync(this.patchFile(j.id), "utf8");
680
+ }
681
+ catch {
682
+ await this.patchJob(j.id, {
683
+ state: "error",
684
+ summary: "the stored patch of local changes is missing",
685
+ finishedAt: nowIso(),
686
+ });
687
+ continue;
688
+ }
689
+ }
690
+ const request = {
691
+ id: remoteId,
692
+ kind: j.kind,
693
+ project: j.projectKey,
694
+ source: {
695
+ git: j.git,
696
+ sha: j.sha,
697
+ ...(patch ? { patch } : {}),
698
+ ...(j.subdir ? { subdir: j.subdir } : {}),
699
+ },
700
+ command: j.command,
701
+ ...(j.docker ? { docker: j.docker } : {}),
702
+ ...(j.env ? { env: j.env } : {}),
703
+ ...(j.secrets ? { secrets: j.secrets } : {}),
704
+ timeoutMinutes: j.timeoutMinutes,
705
+ ...(j.resources ? { resources: j.resources } : {}),
706
+ ...(j.artifactGlobs ? { artifacts: j.artifactGlobs } : {}),
707
+ ...(j.cacheKey ? { cacheKey: j.cacheKey } : {}),
708
+ };
709
+ const claimed = await this.patchJob(j.id, { node: nodeName, remoteId }, "queued");
710
+ if (!claimed)
711
+ continue;
712
+ try {
713
+ const status = await this.client(node).submitJob(request);
714
+ const at = nowIso();
715
+ const state = mapState(status.state);
716
+ await this.patchJob(j.id, {
717
+ state: state === "lost" ? "preparing" : state,
718
+ dispatchedAt: at,
719
+ ...(state === "running" ? { startedAt: status.startedAt ?? at } : {}),
720
+ summary: `on ${nodeName}`,
721
+ waitWarned: false,
722
+ }, "queued");
723
+ inFlight.push({ node: nodeName, ...(j.resources ? { resources: j.resources } : {}) });
724
+ count++;
725
+ }
726
+ catch (e) {
727
+ 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.
730
+ const v = views.find((x) => x.name === nodeName);
731
+ if (v)
732
+ v.online = false;
733
+ await this.patchJob(j.id, { ...(j.pinned ? {} : { node: undefined }), remoteId: undefined }, "queued");
734
+ continue;
735
+ }
736
+ await this.patchJob(j.id, {
737
+ state: "error",
738
+ summary: `dispatch to ${nodeName} failed: ${errText(e)}`.slice(0, 400),
739
+ finishedAt: nowIso(),
740
+ });
741
+ }
742
+ }
743
+ }
744
+ async pollJob(j) {
745
+ if (!j.node || !j.remoteId) {
746
+ await this.patchJob(j.id, { state: "queued" });
747
+ return;
748
+ }
749
+ const node = await this.registry.get(j.node);
750
+ if (!node) {
751
+ await this.nodeLost(j, `node ${j.node} was removed from the fleet`);
752
+ return;
753
+ }
754
+ let status;
755
+ try {
756
+ status = await this.client(node).job(j.remoteId);
757
+ }
758
+ catch (e) {
759
+ if (e instanceof FleetClientError && e.code === "not_found") {
760
+ await this.nodeLost(j, `node ${j.node} no longer knows the job`);
761
+ return;
762
+ }
763
+ if (e instanceof FleetClientError && (e.code === "unreachable" || e.code === "timeout")) {
764
+ const since = j.unreachableSince ? Date.parse(j.unreachableSince) : Date.now();
765
+ if (!j.unreachableSince) {
766
+ await this.patchJob(j.id, { unreachableSince: nowIso() });
767
+ }
768
+ else if (Date.now() - since > this.unreachableMs) {
769
+ await this.nodeLost(j, `node ${j.node} unreachable for ${Math.round((Date.now() - since) / 60_000)} min`);
770
+ }
771
+ else if (!j.nodeDownWarned && Date.now() - since > 60_000) {
772
+ await this.patchJob(j.id, { nodeDownWarned: true });
773
+ }
774
+ }
775
+ return;
776
+ }
777
+ const state = mapState(status.state);
778
+ if (state === "lost") {
779
+ await this.nodeLost(j, `node ${j.node} restarted and lost the job`);
780
+ return;
781
+ }
782
+ const patch = {};
783
+ if (j.unreachableSince)
784
+ patch.unreachableSince = undefined;
785
+ if (j.nodeDownWarned)
786
+ patch.nodeDownWarned = undefined;
787
+ if (state !== j.state) {
788
+ patch.state = state;
789
+ if (state === "running")
790
+ patch.startedAt = status.startedAt ?? nowIso();
791
+ if (isFleetTerminal(state)) {
792
+ patch.finishedAt = status.finishedAt ?? nowIso();
793
+ if (status.exitCode !== undefined)
794
+ patch.exitCode = status.exitCode;
795
+ if (status.artifacts)
796
+ patch.artifacts = status.artifacts;
797
+ patch.summary = status.summary ?? (state === "passed" ? "passed" : state);
798
+ if (state === "failed")
799
+ patch.summary = await this.failureSummary(node, j, status);
800
+ }
801
+ }
802
+ if (!Object.keys(patch).length)
803
+ return;
804
+ const updated = await this.patchJob(j.id, patch);
805
+ if (updated && isFleetTerminal(updated.state) && updated.state !== "cancelled") {
806
+ await this.autoDownload(updated);
807
+ this.removePatch(updated.id);
808
+ }
809
+ }
810
+ async autoDownload(j) {
811
+ if (!j.artifacts?.length)
812
+ return;
813
+ try {
814
+ await this.downloadArtifacts(j.id, j.outDir);
815
+ }
816
+ catch (e) {
817
+ await this.patchJob(j.id, {
818
+ summary: `${j.summary ?? j.state}; artifacts not downloaded: ${errText(e)}`.slice(0, 480),
819
+ }, undefined, true);
820
+ }
821
+ }
822
+ removePatch(id) {
823
+ fs.rmSync(this.patchFile(id), { force: true });
824
+ }
825
+ async failureSummary(node, j, status) {
826
+ const base = status.summary ?? `exited ${status.exitCode ?? "non-zero"}`;
827
+ try {
828
+ const size = status.logBytes ?? 0;
829
+ const { text } = await this.client(node).jobLog(j.remoteId, Math.max(0, size - 16_000));
830
+ const lines = text
831
+ .split("\n")
832
+ .map((l) => l.trim())
833
+ .filter((l) => /fail|error|expected|assert|✗|×/i.test(l))
834
+ .slice(-4);
835
+ return [base, ...lines].join(" | ").slice(0, 480);
836
+ }
837
+ catch {
838
+ return base;
839
+ }
840
+ }
841
+ /**
842
+ * The node lost the job (restart, unreachable too long, removed). Safe kinds go
843
+ * back to the queue (max FLEET_MAX_ATTEMPTS), steered away from that node.
844
+ * Deploys are never requeued: they end in error and the user is told.
845
+ */
846
+ async nodeLost(j, reason) {
847
+ const at = nowIso();
848
+ const from = j.node ?? "?";
849
+ await this.jobs.update((jobs) => {
850
+ const x = jobs.find((y) => y.id === j.id);
851
+ if (!x || (x.state !== "preparing" && x.state !== "running"))
852
+ return;
853
+ const attempts = x.attempts ?? 1;
854
+ x.updatedAt = at;
855
+ if (!REQUEUE_KINDS.has(x.kind)) {
856
+ x.state = "error";
857
+ 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);
860
+ return;
861
+ }
862
+ x.requeues = [...(x.requeues ?? []), { at, from, reason }];
863
+ if (attempts >= FLEET_MAX_ATTEMPTS) {
864
+ x.state = "error";
865
+ x.finishedAt = at;
866
+ x.summary = `node lost ${attempts} times; last: ${reason}`.slice(0, 400);
867
+ return;
868
+ }
869
+ x.state = "queued";
870
+ x.attempts = attempts + 1;
871
+ x.avoid = [...new Set([...(x.avoid ?? []), from])];
872
+ x.summary = `requeued (attempt ${attempts + 1}/${FLEET_MAX_ATTEMPTS}): ${reason}`.slice(0, 400);
873
+ if (!x.pinned)
874
+ delete x.node;
875
+ for (const k of [
876
+ "remoteId",
877
+ "dispatchedAt",
878
+ "startedAt",
879
+ "unreachableSince",
880
+ "nodeDownWarned",
881
+ "waitWarned",
882
+ ]) {
883
+ delete x[k];
884
+ }
885
+ });
886
+ // Best effort: stop the old run if the node is reachable after all.
887
+ if (j.node && j.remoteId) {
888
+ const node = await this.registry.get(j.node);
889
+ if (node)
890
+ void this.client(node)
891
+ .cancelJob(j.remoteId)
892
+ .catch(() => { });
893
+ }
894
+ }
895
+ async pollService(s) {
896
+ const node = await this.registry.get(s.node);
897
+ if (!node) {
898
+ const u = await this.patchService(s.id, {
899
+ state: "error",
900
+ summary: `node ${s.node} was removed`,
901
+ });
902
+ if (u)
903
+ await this.syncLocalEndpoint(u);
904
+ return;
905
+ }
906
+ let st;
907
+ try {
908
+ st = await this.client(node).service(s.id);
909
+ }
910
+ catch (e) {
911
+ if (e instanceof FleetClientError && e.code === "not_found") {
912
+ const u = await this.patchService(s.id, {
913
+ state: "stopped",
914
+ summary: "gone from the node",
915
+ });
916
+ if (u)
917
+ await this.syncLocalEndpoint(u);
918
+ return;
919
+ }
920
+ const since = s.unreachableSince ? Date.parse(s.unreachableSince) : undefined;
921
+ if (since === undefined)
922
+ await this.patchService(s.id, { unreachableSince: nowIso() });
923
+ else if (!s.nodeDownWarned && Date.now() - since > 60_000) {
924
+ await this.patchService(s.id, {
925
+ nodeDownWarned: true,
926
+ summary: `node ${s.node} unreachable: ${errText(e)}`.slice(0, 300),
927
+ });
928
+ }
929
+ return;
930
+ }
931
+ const patch = {};
932
+ if (s.unreachableSince)
933
+ patch.unreachableSince = undefined;
934
+ if (s.nodeDownWarned)
935
+ patch.nodeDownWarned = undefined;
936
+ if (st.state !== s.state)
937
+ patch.state = st.state;
938
+ if (st.summary && st.summary !== s.summary)
939
+ patch.summary = st.summary;
940
+ if (JSON.stringify(st.endpoints ?? []) !== JSON.stringify(s.endpoints))
941
+ patch.endpoints = st.endpoints ?? [];
942
+ if (!Object.keys(patch).length && (s.localEndpointId || s.kind !== "inference"))
943
+ return;
944
+ const u = Object.keys(patch).length ? await this.patchService(s.id, patch) : s;
945
+ if (u)
946
+ await this.syncLocalEndpoint(u);
947
+ }
948
+ // ── store helpers ────────────────────────────────────────
949
+ async patchJob(id, patch, onlyIf, evenIfTerminal = false) {
950
+ return this.jobs.update((jobs) => {
951
+ const j = jobs.find((x) => x.id === id);
952
+ if (!j)
953
+ return undefined;
954
+ if (onlyIf && j.state !== onlyIf)
955
+ return undefined;
956
+ if (!evenIfTerminal && isFleetTerminal(j.state))
957
+ return undefined;
958
+ for (const [k, v] of Object.entries(patch)) {
959
+ if (v === undefined)
960
+ delete j[k];
961
+ else
962
+ j[k] = v;
963
+ }
964
+ j.updatedAt = nowIso();
965
+ return { ...j };
966
+ });
967
+ }
968
+ async patchService(id, patch) {
969
+ return this.services.update((list) => {
970
+ const s = list.find((x) => x.id === id);
971
+ if (!s)
972
+ return undefined;
973
+ for (const [k, v] of Object.entries(patch)) {
974
+ if (v === undefined)
975
+ delete s[k];
976
+ else
977
+ s[k] = v;
978
+ }
979
+ s.updatedAt = nowIso();
980
+ return { ...s };
981
+ });
982
+ }
983
+ // ── events ───────────────────────────────────────────────
984
+ observe(jobs, services) {
985
+ const markJobs = [];
986
+ for (const job of jobs) {
987
+ const prev = this.seenJobs.get(job.id);
988
+ const key = `${job.state}|${job.requeues?.length ?? 0}|${job.nodeDownWarned ? 1 : 0}|${job.waitWarned ? 1 : 0}|${job.artifactsDir ? 1 : 0}`;
989
+ if (prev === key)
990
+ continue;
991
+ this.seenJobs.set(job.id, key);
992
+ if (!this.seeded && (!isFleetTerminal(job.state) || job.notifiedState === job.state))
993
+ continue;
994
+ const requeued = !!prev && (job.requeues?.length ?? 0) > Number(prev.split("|")[1] ?? 0);
995
+ const previous = prev ? prev.split("|")[0] : undefined;
996
+ this.events.emit("event", { type: "job", job, previous, requeued });
997
+ if (isFleetTerminal(job.state) && job.notifiedState !== job.state)
998
+ markJobs.push([job.id, job.state]);
999
+ }
1000
+ for (const s of services) {
1001
+ const prev = this.seenServices.get(s.id);
1002
+ const key = `${s.state}|${s.nodeDownWarned ? 1 : 0}`;
1003
+ if (prev === key)
1004
+ continue;
1005
+ this.seenServices.set(s.id, key);
1006
+ if (!this.seeded)
1007
+ continue;
1008
+ this.events.emit("event", {
1009
+ type: "service",
1010
+ service: s,
1011
+ ...(prev ? { previous: prev.split("|")[0] } : {}),
1012
+ });
1013
+ }
1014
+ this.seeded = true;
1015
+ if (markJobs.length && this.events.listenerCount("event") > 0) {
1016
+ void this.jobs
1017
+ .update((all) => {
1018
+ for (const [id, state] of markJobs) {
1019
+ const j = all.find((x) => x.id === id);
1020
+ if (j)
1021
+ j.notifiedState = state;
1022
+ }
1023
+ })
1024
+ .catch(() => { });
1025
+ }
1026
+ }
1027
+ }
1028
+ // ── plain-words output ─────────────────────────────────────
1029
+ export function describeFleetJob(j) {
1030
+ const where = j.node ? ` on ${j.node}` : "";
1031
+ const src = `${short(j.sha)}${j.hasPatch ? "+patch" : ""}`;
1032
+ const extra = j.summary && j.summary !== `on ${j.node}` ? ` — ${j.summary}` : "";
1033
+ const arts = j.artifactsDir ? ` (artifacts: ${j.artifactsDir})` : "";
1034
+ return `${j.id} ${j.name} [${j.kind}] @ ${src}${where}: ${j.state}${extra}${arts}`;
1035
+ }
1036
+ export function describeFleetService(s) {
1037
+ const eps = s.endpoints.map((e) => `${e.name} ${e.url}`).join(", ");
1038
+ return (`${s.id} ${s.name} [${s.kind}] on ${s.node}: ${s.state}` +
1039
+ `${eps ? ` — ${eps}` : ""}${s.summary ? ` (${s.summary})` : ""}` +
1040
+ `${s.localEndpointId ? ` [model endpoint ${s.localEndpointId}]` : ""}`);
1041
+ }
1042
+ export function describeNode(n) {
1043
+ const labels = [...new Set([...(n.info?.labels ?? []), ...n.node.labels])];
1044
+ if (!n.online || !n.info) {
1045
+ return `${n.node.name} (${n.node.url}): OFFLINE${n.error ? ` — ${n.error}` : ""}`;
1046
+ }
1047
+ const i = n.info;
1048
+ const gpus = i.gpus.length
1049
+ ? `; ${i.gpus.map((g) => `${g.name} ${g.memoryGb} GB`).join(", ")}`
1050
+ : "";
1051
+ return (`${n.node.name} (${i.platform}, ${i.arch}, v${i.version}): online; slots ${i.slotsUsed}/${i.slots}, ` +
1052
+ `${i.cpus} cpu, ${i.memoryFreeGb}/${i.memoryGb} GB free, load ${i.load.toFixed(2)}${gpus}` +
1053
+ `${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` : ""}`);
1055
+ }
1056
+ /** Notification for a job change, or undefined for routine ones. */
1057
+ export function fleetJobNotification(j) {
1058
+ const at = `${j.name} at ${short(j.sha)}${j.hasPatch ? "+patch" : ""}${j.node ? ` on ${j.node}` : ""}`;
1059
+ switch (j.state) {
1060
+ case "passed":
1061
+ return {
1062
+ text: `Fleet job passed: ${at}${j.artifactsDir ? `; artifacts in ${j.artifactsDir}` : ""}.`,
1063
+ terminal: true,
1064
+ urgent: false,
1065
+ };
1066
+ case "failed":
1067
+ return {
1068
+ text: `Fleet job FAILED: ${at}${j.summary ? `: ${j.summary}` : ""}. Read the log with fleet logs ${j.id}.`,
1069
+ terminal: true,
1070
+ urgent: true,
1071
+ };
1072
+ case "error":
1073
+ return {
1074
+ text: `Fleet job could not run (not a code failure): ${at}: ${j.summary ?? "unknown error"}. Tell the user if it needs them.`,
1075
+ terminal: true,
1076
+ urgent: true,
1077
+ };
1078
+ case "preparing":
1079
+ case "running":
1080
+ return j.nodeDownWarned
1081
+ ? {
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"}.`,
1083
+ terminal: false,
1084
+ urgent: false,
1085
+ }
1086
+ : undefined;
1087
+ case "queued": {
1088
+ const last = j.requeues?.at(-1);
1089
+ if (last && j.attempts && j.attempts > 1 && !j.waitWarned) {
1090
+ return {
1091
+ text: `Fleet job re-queued: ${j.name} (${j.id}): ${last.reason} (attempt ${j.attempts}/${FLEET_MAX_ATTEMPTS}). Nothing to do.`,
1092
+ terminal: false,
1093
+ urgent: false,
1094
+ };
1095
+ }
1096
+ return j.waitWarned
1097
+ ? {
1098
+ text: `Fleet job ${j.name} (${j.id}) is queued: ${j.summary}.`,
1099
+ terminal: false,
1100
+ urgent: false,
1101
+ }
1102
+ : undefined;
1103
+ }
1104
+ default:
1105
+ return undefined;
1106
+ }
1107
+ }
1108
+ export function fleetServiceNotification(s, previous) {
1109
+ if (s.nodeDownWarned) {
1110
+ return {
1111
+ text: `Fleet node ${s.node} stopped answering; service ${s.name} (${s.id}) may be down.`,
1112
+ terminal: false,
1113
+ urgent: false,
1114
+ };
1115
+ }
1116
+ if (s.state === "running" && previous === "starting") {
1117
+ const eps = s.endpoints.map((e) => `${e.name} ${e.url}`).join(", ");
1118
+ return {
1119
+ text: `Fleet service ${s.name} is up on ${s.node}${eps ? `: ${eps}` : ""}.`,
1120
+ terminal: false,
1121
+ urgent: false,
1122
+ };
1123
+ }
1124
+ if (s.state === "error") {
1125
+ return {
1126
+ text: `Fleet service ${s.name} (${s.id}) on ${s.node} failed: ${s.summary ?? "unknown error"}.`,
1127
+ terminal: true,
1128
+ urgent: true,
1129
+ };
1130
+ }
1131
+ if (s.state === "stopped" && previous && previous !== "stopped") {
1132
+ return {
1133
+ text: `Fleet service ${s.name} (${s.id}) on ${s.node} stopped.`,
1134
+ terminal: true,
1135
+ urgent: false,
1136
+ };
1137
+ }
1138
+ return undefined;
1139
+ }
1140
+ //# sourceMappingURL=service.js.map