@forgezero/agent 0.1.31 → 0.1.33

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.
@@ -2,10 +2,14 @@ import { type Server } from 'node:net';
2
2
  import { type AgentRelease, type StagedAgentRelease, type UpdateCommand, type UpdateCommandResult } from './agent-update';
3
3
  export declare const AGENT_UPDATE_GROUP = "forgezero-update";
4
4
  export declare const AGENT_UPDATE_HELPER_UNIT_PATH = "/etc/systemd/system/forgezero-agent-update-helper.service";
5
- export declare const AGENT_UPDATE_RECEIPT = "/var/lib/forgezero/agent-update.json";
5
+ /** Root-private crash transaction. Existing 0.1.31 hosts may contain its legacy success receipt here. */
6
+ export declare const AGENT_UPDATE_JOURNAL = "/var/lib/forgezero/agent-update.json";
7
+ /** Bounded, group-readable evidence consumed by the unprivileged Agent heartbeat. */
8
+ export declare const AGENT_UPDATE_RECEIPT = "/var/lib/forgezero/agent-update-receipt.json";
6
9
  export type AgentUpdateRequest = {
7
10
  op: 'apply';
8
11
  target: 'compute' | 'metal';
12
+ attemptId?: string;
9
13
  currentVersion: string;
10
14
  release: AgentRelease;
11
15
  };
@@ -13,6 +17,7 @@ export type AgentUpdateResponse = {
13
17
  ok: true;
14
18
  status: 'staged';
15
19
  version: string;
20
+ attemptId: string;
16
21
  } | {
17
22
  ok: false;
18
23
  error: {
@@ -20,6 +25,24 @@ export type AgentUpdateResponse = {
20
25
  message: string;
21
26
  };
22
27
  };
28
+ export type AgentUpdateOutcome = 'activating' | 'active' | 'rolled-back' | 'failed';
29
+ /** Bounded, non-secret update evidence included in the next signed heartbeat. */
30
+ export interface AgentUpdateReceipt {
31
+ attemptId: string;
32
+ fromVersion: string;
33
+ targetVersion: string;
34
+ outcome: AgentUpdateOutcome;
35
+ startedAtTs: number;
36
+ updatedAtTs: number;
37
+ retryAfterTs?: number;
38
+ rollbackHealthy?: boolean;
39
+ reason?: {
40
+ code: string;
41
+ message: string;
42
+ };
43
+ }
44
+ /** Read only the bounded evidence safe to send to the control plane. */
45
+ export declare function readAgentUpdateReceipt(path?: string): AgentUpdateReceipt | undefined;
23
46
  /** Prove a newly started Agent process answers, not merely that PID 1 holds its socket. */
24
47
  export declare function probeAgentSocket(socketPath?: string, timeoutMs?: number): Promise<boolean>;
25
48
  export declare function activateAgentRelease(staged: StagedAgentRelease, options?: {
@@ -27,6 +50,8 @@ export declare function activateAgentRelease(staged: StagedAgentRelease, options
27
50
  run?: (input: UpdateCommand) => Promise<UpdateCommandResult>;
28
51
  probe?: () => Promise<boolean>;
29
52
  receiptPath?: string;
53
+ journalPath?: string;
54
+ attemptId?: string;
30
55
  now?: () => number;
31
56
  }): Promise<{
32
57
  ok: true;
@@ -34,12 +59,26 @@ export declare function activateAgentRelease(staged: StagedAgentRelease, options
34
59
  } | {
35
60
  ok: false;
36
61
  rolledBack: boolean;
62
+ rollbackHealthy: boolean;
37
63
  reason: string;
38
64
  }>;
65
+ /** Restore a transaction that lost power or the helper before its health verdict became durable. */
66
+ export declare function recoverInterruptedAgentUpdate(options?: {
67
+ root?: string;
68
+ receiptPath?: string;
69
+ journalPath?: string;
70
+ run?: (input: UpdateCommand) => Promise<UpdateCommandResult>;
71
+ probe?: () => Promise<boolean>;
72
+ now?: () => number;
73
+ }): Promise<AgentUpdateReceipt | undefined>;
39
74
  export declare function startAgentUpdateHelper(options?: {
40
75
  socketPath?: string;
41
76
  root?: string;
42
- activate?: (staged: StagedAgentRelease, target: AgentUpdateRequest['target']) => Promise<unknown>;
77
+ activate?: (staged: StagedAgentRelease, target: AgentUpdateRequest['target'], attemptId: string) => Promise<unknown>;
78
+ receiptPath?: string;
79
+ journalPath?: string;
80
+ recover?: () => Promise<unknown>;
81
+ now?: () => number;
43
82
  setTimer?: (callback: () => void, ms: number) => unknown;
44
83
  }): Server;
45
84
  export declare function requestAgentUpdate(request: AgentUpdateRequest, socketPath?: string, timeoutMs?: number): Promise<AgentUpdateResponse>;
@@ -2,8 +2,11 @@
2
2
  import { createHash, timingSafeEqual, randomUUID } from "node:crypto";
3
3
  import {
4
4
  chmodSync,
5
+ closeSync,
5
6
  existsSync,
7
+ fsyncSync,
6
8
  mkdirSync,
9
+ openSync,
7
10
  readFileSync,
8
11
  readlinkSync,
9
12
  renameSync,
@@ -17,6 +20,25 @@ var DEFAULT_AGENT_UPDATE_SOCKET = "/run/forgezero-update/helper.sock";
17
20
  var MAX_AGENT_TARBALL_BYTES = 32 * 1024 * 1024;
18
21
  var VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
19
22
  var REGISTRY = "registry.npmjs.org";
23
+ var syncPath = (path) => {
24
+ const descriptor = openSync(path, "r");
25
+ try {
26
+ fsyncSync(descriptor);
27
+ } finally {
28
+ closeSync(descriptor);
29
+ }
30
+ };
31
+ var syncReleaseDirectory = (directory) => {
32
+ for (const path of [
33
+ join(directory, "package.json"),
34
+ join(directory, "dist", "fz-agent.js"),
35
+ join(directory, "dist", "fz.js"),
36
+ join(directory, "dist"),
37
+ directory,
38
+ dirname(directory)
39
+ ])
40
+ syncPath(path);
41
+ };
20
42
  function validateAgentRelease(release) {
21
43
  if (release?.package !== "@forgezero/agent")
22
44
  throw new Error("agent update package is fixed");
@@ -135,16 +157,24 @@ async function stageAgentRelease(releaseInput, options) {
135
157
  ]
136
158
  }, "agent update extraction");
137
159
  await validateReleaseDirectory(unpacked, release, run);
138
- if (!existsSync(finalDirectory))
160
+ if (!existsSync(finalDirectory)) {
139
161
  renameSync(unpacked, finalDirectory);
140
- else
162
+ syncReleaseDirectory(finalDirectory);
163
+ } else
141
164
  await validateReleaseDirectory(finalDirectory, release, run);
142
165
  if (!existsSync(currentLink)) {
143
166
  throw new Error("agent update requires an active immutable release to roll back to");
144
167
  }
145
168
  const previousTarget = readlinkSync(currentLink);
169
+ if (previousTarget !== join("versions", options.currentVersion)) {
170
+ throw new Error("agent update current release does not match the running version");
171
+ }
172
+ if (!existsSync(join(root, previousTarget))) {
173
+ throw new Error("agent update rollback release is missing");
174
+ }
146
175
  return {
147
176
  version: release.version,
177
+ fromVersion: options.currentVersion,
148
178
  directory: finalDirectory,
149
179
  previousTarget,
150
180
  nextTarget: join("versions", release.version),
@@ -159,6 +189,7 @@ function selectAgentRelease(staged) {
159
189
  try {
160
190
  symlinkSync(staged.nextTarget, next);
161
191
  renameSync(next, staged.currentLink);
192
+ syncPath(dirname(staged.currentLink));
162
193
  } finally {
163
194
  rmSync(next, { force: true });
164
195
  }
@@ -168,25 +199,189 @@ function restoreAgentRelease(staged) {
168
199
  try {
169
200
  symlinkSync(staged.previousTarget, next);
170
201
  renameSync(next, staged.currentLink);
202
+ syncPath(dirname(staged.currentLink));
171
203
  } finally {
172
204
  rmSync(next, { force: true });
173
205
  }
174
206
  }
175
207
 
176
208
  // src/agent-update-helper.ts
177
- import { chmodSync as chmodSync2, existsSync as existsSync2, mkdirSync as mkdirSync2, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
209
+ import { randomUUID as randomUUID2 } from "node:crypto";
210
+ import {
211
+ chmodSync as chmodSync2,
212
+ closeSync as closeSync2,
213
+ existsSync as existsSync2,
214
+ fsyncSync as fsyncSync2,
215
+ mkdirSync as mkdirSync2,
216
+ openSync as openSync2,
217
+ readFileSync as readFileSync2,
218
+ renameSync as renameSync2,
219
+ rmSync as rmSync2,
220
+ unlinkSync,
221
+ writeFileSync as writeFileSync2
222
+ } from "node:fs";
178
223
  import { connect, createServer } from "node:net";
179
- import { dirname as dirname2 } from "node:path";
224
+ import { dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";
180
225
  import { DEFAULT_SOCKET } from "@forgezero/vault";
181
226
  var AGENT_UPDATE_GROUP = "forgezero-update";
182
227
  var AGENT_UPDATE_HELPER_UNIT_PATH = "/etc/systemd/system/forgezero-agent-update-helper.service";
183
- var AGENT_UPDATE_RECEIPT = "/var/lib/forgezero/agent-update.json";
228
+ var AGENT_UPDATE_JOURNAL = "/var/lib/forgezero/agent-update.json";
229
+ var AGENT_UPDATE_RECEIPT = "/var/lib/forgezero/agent-update-receipt.json";
184
230
  var MAX_REQUEST_BYTES = 8 * 1024;
185
231
  var COMPUTE_HELPER_UNITS = [
232
+ "forgezero-agent-egress.service",
186
233
  "forgezero-deploy-runner.service",
187
234
  "forgezero-lifecycle-helper.service",
188
235
  "forgezero-software-helper.service"
189
236
  ];
237
+ var VERSION2 = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
238
+ var ATTEMPT_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
239
+ var REASON_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
240
+ var MAX_REASON_BYTES = 512;
241
+ var UPDATE_RETRY_BASE_MS = 5 * 60000;
242
+ var UPDATE_RETRY_MAX_MS = 24 * 60 * 60000;
243
+ var boundedMessage = (value) => {
244
+ let message = value.replace(/[\r\n]+/g, " ").trim();
245
+ while (Buffer.byteLength(message, "utf8") > MAX_REASON_BYTES)
246
+ message = message.slice(0, -1);
247
+ return message;
248
+ };
249
+ var reason = (code, message) => ({
250
+ code: REASON_CODE.test(code) ? code : "UPDATE_FAILED",
251
+ message: boundedMessage(message) || "Agent update failed"
252
+ });
253
+ var validTime = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
254
+ function validateReceipt(value) {
255
+ if (!value || typeof value !== "object")
256
+ throw new Error("Agent update receipt is malformed");
257
+ const receipt = value;
258
+ if (!receipt.attemptId || !ATTEMPT_ID.test(receipt.attemptId))
259
+ throw new Error("Agent update attempt ID is invalid");
260
+ if (!receipt.fromVersion || !VERSION2.test(receipt.fromVersion))
261
+ throw new Error("Agent update source version is invalid");
262
+ if (!receipt.targetVersion || !VERSION2.test(receipt.targetVersion))
263
+ throw new Error("Agent update target version is invalid");
264
+ if (!["activating", "active", "rolled-back", "failed"].includes(receipt.outcome ?? "")) {
265
+ throw new Error("Agent update outcome is invalid");
266
+ }
267
+ if (!validTime(receipt.startedAtTs) || !validTime(receipt.updatedAtTs)) {
268
+ throw new Error("Agent update timestamps are invalid");
269
+ }
270
+ if (receipt.retryAfterTs !== undefined && !validTime(receipt.retryAfterTs)) {
271
+ throw new Error("Agent update retry timestamp is invalid");
272
+ }
273
+ if (receipt.rollbackHealthy !== undefined && typeof receipt.rollbackHealthy !== "boolean") {
274
+ throw new Error("Agent update rollback health is invalid");
275
+ }
276
+ if (receipt.reason && (!REASON_CODE.test(receipt.reason.code) || typeof receipt.reason.message !== "string" || Buffer.byteLength(receipt.reason.message, "utf8") > MAX_REASON_BYTES))
277
+ throw new Error("Agent update failure reason is invalid");
278
+ return {
279
+ attemptId: receipt.attemptId,
280
+ fromVersion: receipt.fromVersion,
281
+ targetVersion: receipt.targetVersion,
282
+ outcome: receipt.outcome,
283
+ startedAtTs: receipt.startedAtTs,
284
+ updatedAtTs: receipt.updatedAtTs,
285
+ ...receipt.retryAfterTs === undefined ? {} : { retryAfterTs: receipt.retryAfterTs },
286
+ ...receipt.rollbackHealthy === undefined ? {} : { rollbackHealthy: receipt.rollbackHealthy },
287
+ ...receipt.reason === undefined ? {} : { reason: receipt.reason }
288
+ };
289
+ }
290
+ function validateJournal(value, root) {
291
+ if (!value || typeof value !== "object")
292
+ throw new Error("Agent update journal is malformed");
293
+ const legacy = value;
294
+ if (legacy.schemaVersion === undefined) {
295
+ if (typeof legacy.version === "string" && VERSION2.test(legacy.version) && legacy.outcome === "active" && validTime(legacy.updatedAtTs) && Object.keys(value).every((key) => ["version", "outcome", "updatedAtTs"].includes(key)))
296
+ return;
297
+ throw new Error("Agent update legacy receipt is malformed");
298
+ }
299
+ const journal = value;
300
+ const receipt = validateReceipt(journal);
301
+ if (journal.schemaVersion !== 1)
302
+ throw new Error("Agent update journal schema is unsupported");
303
+ if (journal.target !== "compute" && journal.target !== "metal")
304
+ throw new Error("Agent update target is invalid");
305
+ if (!Number.isSafeInteger(journal.failureCount) || (journal.failureCount ?? -1) < 0) {
306
+ throw new Error("Agent update failure count is invalid");
307
+ }
308
+ const releaseRoot = resolve2(root);
309
+ if (journal.currentLink !== join2(releaseRoot, "current"))
310
+ throw new Error("Agent update current link is invalid");
311
+ if (journal.previousTarget !== join2("versions", receipt.fromVersion)) {
312
+ throw new Error("Agent update rollback target is invalid");
313
+ }
314
+ if (journal.nextTarget !== join2("versions", receipt.targetVersion)) {
315
+ throw new Error("Agent update next target is invalid");
316
+ }
317
+ return journal;
318
+ }
319
+ function readJournal(path, root) {
320
+ if (!existsSync2(path))
321
+ return;
322
+ return validateJournal(JSON.parse(readFileSync2(path, "utf8")), root);
323
+ }
324
+ function writeAtomic(path, value, mode) {
325
+ mkdirSync2(dirname2(path), { recursive: true, mode: 493 });
326
+ const next = `${path}.${randomUUID2()}.next`;
327
+ let file;
328
+ try {
329
+ file = openSync2(next, "wx", mode);
330
+ writeFileSync2(file, `${JSON.stringify(value)}
331
+ `);
332
+ fsyncSync2(file);
333
+ closeSync2(file);
334
+ file = undefined;
335
+ renameSync2(next, path);
336
+ const directory = openSync2(dirname2(path), "r");
337
+ try {
338
+ fsyncSync2(directory);
339
+ } finally {
340
+ closeSync2(directory);
341
+ }
342
+ } finally {
343
+ if (file !== undefined)
344
+ closeSync2(file);
345
+ rmSync2(next, { force: true });
346
+ }
347
+ }
348
+ var publicReceipt = (journal) => {
349
+ const {
350
+ attemptId,
351
+ fromVersion,
352
+ targetVersion,
353
+ outcome,
354
+ startedAtTs,
355
+ updatedAtTs,
356
+ retryAfterTs,
357
+ rollbackHealthy,
358
+ reason: failureReason
359
+ } = journal;
360
+ return {
361
+ attemptId,
362
+ fromVersion,
363
+ targetVersion,
364
+ outcome,
365
+ startedAtTs,
366
+ updatedAtTs,
367
+ ...retryAfterTs === undefined ? {} : { retryAfterTs },
368
+ ...rollbackHealthy === undefined ? {} : { rollbackHealthy },
369
+ ...failureReason === undefined ? {} : { reason: failureReason }
370
+ };
371
+ };
372
+ function writeUpdateState(journalPath, receiptPath, journal) {
373
+ writeAtomic(journalPath, journal, 384);
374
+ writeAtomic(receiptPath, publicReceipt(journal), 416);
375
+ }
376
+ function readAgentUpdateReceipt(path = AGENT_UPDATE_RECEIPT) {
377
+ try {
378
+ if (!existsSync2(path))
379
+ return;
380
+ return validateReceipt(JSON.parse(readFileSync2(path, "utf8")));
381
+ } catch {
382
+ return;
383
+ }
384
+ }
190
385
  var runCommand = async (input) => {
191
386
  const child = Bun.spawn([input.command, ...input.args], {
192
387
  cwd: input.cwd,
@@ -202,8 +397,27 @@ var runCommand = async (input) => {
202
397
  return { exitCode, output: `${stdout}${stderr}` };
203
398
  };
204
399
  var runOk = async (run, command2, args) => (await run({ command: command2, args })).exitCode === 0;
400
+ var retryAfter = (now, failures) => now + Math.min(UPDATE_RETRY_MAX_MS, UPDATE_RETRY_BASE_MS * 2 ** Math.min(16, Math.max(0, failures - 1)));
401
+ var stagedFromJournal = (journal, root) => ({
402
+ version: journal.targetVersion,
403
+ fromVersion: journal.fromVersion,
404
+ directory: join2(resolve2(root), journal.nextTarget),
405
+ previousTarget: journal.previousTarget,
406
+ nextTarget: journal.nextTarget,
407
+ currentLink: journal.currentLink
408
+ });
409
+ var restartAgent = async (target, run) => {
410
+ const helpers = target === "compute" ? COMPUTE_HELPER_UNITS : ["forgezero-metal-helper.service"];
411
+ for (const unit of helpers)
412
+ await run({ command: "/usr/bin/systemctl", args: ["try-restart", unit] });
413
+ const service = target === "compute" ? "forgezero-agent.service" : "forgezero-metal-agent.service";
414
+ if (!await runOk(run, "/usr/bin/systemctl", ["restart", service])) {
415
+ throw new Error(`systemd could not restart ${service}`);
416
+ }
417
+ };
418
+ var targetProbe = (target, run) => target === "compute" ? () => probeAgentSocket() : async () => await runOk(run, "/usr/bin/systemctl", ["is-active", "--quiet", "forgezero-metal-agent.service"]) && await runOk(run, "/usr/bin/systemctl", ["is-active", "--quiet", "forgezero-metal-helper.service"]);
205
419
  function probeAgentSocket(socketPath = DEFAULT_SOCKET, timeoutMs = 5000) {
206
- return new Promise((resolve2) => {
420
+ return new Promise((resolve3) => {
207
421
  const socket = connect(socketPath);
208
422
  let settled = false;
209
423
  let buffer = "";
@@ -213,7 +427,7 @@ function probeAgentSocket(socketPath = DEFAULT_SOCKET, timeoutMs = 5000) {
213
427
  settled = true;
214
428
  clearTimeout(timer);
215
429
  socket.destroy();
216
- resolve2(value);
430
+ resolve3(value);
217
431
  };
218
432
  const timer = setTimeout(() => finish(false), timeoutMs);
219
433
  socket.on("connect", () => socket.write(`{"op":"identity"}
@@ -237,55 +451,136 @@ function probeAgentSocket(socketPath = DEFAULT_SOCKET, timeoutMs = 5000) {
237
451
  async function activateAgentRelease(staged, options = {}) {
238
452
  const run = options.run ?? runCommand;
239
453
  const target = options.target ?? "compute";
240
- const probe = options.probe ?? (target === "compute" ? () => probeAgentSocket() : async () => await runOk(run, "/usr/bin/systemctl", ["is-active", "--quiet", "forgezero-metal-agent.service"]) && await runOk(run, "/usr/bin/systemctl", ["is-active", "--quiet", "forgezero-metal-helper.service"]));
241
- const restart = async () => {
242
- const helpers = target === "compute" ? COMPUTE_HELPER_UNITS : ["forgezero-metal-helper.service"];
243
- for (const unit of helpers) {
244
- await run({ command: "/usr/bin/systemctl", args: ["try-restart", unit] });
245
- }
246
- const service = target === "compute" ? "forgezero-agent.service" : "forgezero-metal-agent.service";
247
- const restarted = await runOk(run, "/usr/bin/systemctl", ["restart", service]);
248
- if (!restarted)
249
- throw new Error(`systemd could not restart ${service}`);
454
+ const probe = options.probe ?? targetProbe(target, run);
455
+ const now = options.now ?? Date.now;
456
+ const journalPath = options.journalPath ?? AGENT_UPDATE_JOURNAL;
457
+ const receiptPath = options.receiptPath ?? AGENT_UPDATE_RECEIPT;
458
+ const previous = readJournal(journalPath, dirname2(staged.currentLink));
459
+ const attemptId = options.attemptId ?? randomUUID2();
460
+ if (!ATTEMPT_ID.test(attemptId))
461
+ throw new Error("Agent update attempt ID is invalid");
462
+ const startedAtTs = now();
463
+ const failureCount = previous?.targetVersion === staged.version ? previous.failureCount : 0;
464
+ let journal = {
465
+ schemaVersion: 1,
466
+ attemptId,
467
+ target,
468
+ fromVersion: staged.fromVersion,
469
+ targetVersion: staged.version,
470
+ outcome: "activating",
471
+ startedAtTs,
472
+ updatedAtTs: startedAtTs,
473
+ currentLink: staged.currentLink,
474
+ previousTarget: staged.previousTarget,
475
+ nextTarget: staged.nextTarget,
476
+ failureCount
250
477
  };
251
- let selected = false;
478
+ writeUpdateState(journalPath, receiptPath, journal);
479
+ let selectionAttempted = false;
252
480
  try {
481
+ selectionAttempted = true;
253
482
  selectAgentRelease(staged);
254
- selected = true;
255
- await restart();
483
+ await restartAgent(target, run);
256
484
  if (!await probe())
257
485
  throw new Error("the replacement Agent did not answer its retained Vault socket");
258
- const receipt = options.receiptPath ?? AGENT_UPDATE_RECEIPT;
259
- mkdirSync2(dirname2(receipt), { recursive: true, mode: 493 });
260
- const next = `${receipt}.next`;
261
- writeFileSync2(next, JSON.stringify({
262
- version: staged.version,
263
- outcome: "active",
264
- updatedAtTs: (options.now ?? Date.now)()
265
- }) + `
266
- `, { mode: 420 });
267
- renameSync2(next, receipt);
486
+ journal = { ...journal, outcome: "active", updatedAtTs: now(), rollbackHealthy: undefined };
487
+ writeUpdateState(journalPath, receiptPath, journal);
268
488
  run({
269
489
  command: "/usr/bin/systemctl",
270
490
  args: ["try-restart", "--no-block", "forgezero-agent-update-helper.service"]
271
491
  });
272
492
  return { ok: true, version: staged.version };
273
493
  } catch (cause) {
274
- const reason = cause instanceof Error ? cause.message : String(cause);
275
- if (selected) {
276
- restoreAgentRelease(staged);
277
- await restart();
494
+ const message = cause instanceof Error ? cause.message : String(cause);
495
+ let rollbackHealthy = false;
496
+ let restored = false;
497
+ if (selectionAttempted) {
498
+ try {
499
+ restoreAgentRelease(staged);
500
+ restored = true;
501
+ await restartAgent(target, run);
502
+ rollbackHealthy = await probe();
503
+ } catch {
504
+ rollbackHealthy = false;
505
+ }
278
506
  }
279
- return { ok: false, rolledBack: selected, reason };
507
+ const failures = failureCount + 1;
508
+ const updatedAtTs = now();
509
+ journal = {
510
+ ...journal,
511
+ outcome: rollbackHealthy ? "rolled-back" : "failed",
512
+ updatedAtTs,
513
+ retryAfterTs: retryAfter(updatedAtTs, failures),
514
+ rollbackHealthy,
515
+ reason: reason(rollbackHealthy ? "REPLACEMENT_UNHEALTHY" : "ROLLBACK_UNHEALTHY", rollbackHealthy ? message : `${message}; the restored Agent did not pass its health probe`),
516
+ failureCount: failures
517
+ };
518
+ writeUpdateState(journalPath, receiptPath, journal);
519
+ return { ok: false, rolledBack: restored, rollbackHealthy, reason: message };
280
520
  }
281
521
  }
522
+ async function recoverInterruptedAgentUpdate(options = {}) {
523
+ const root = resolve2(options.root ?? DEFAULT_AGENT_RELEASE_ROOT);
524
+ const journalPath = options.journalPath ?? AGENT_UPDATE_JOURNAL;
525
+ const receiptPath = options.receiptPath ?? AGENT_UPDATE_RECEIPT;
526
+ const journal = readJournal(journalPath, root);
527
+ if (!journal)
528
+ return;
529
+ if (journal.outcome !== "activating") {
530
+ writeAtomic(receiptPath, publicReceipt(journal), 416);
531
+ return publicReceipt(journal);
532
+ }
533
+ const staged = stagedFromJournal(journal, root);
534
+ if (!existsSync2(join2(root, journal.previousTarget))) {
535
+ throw new Error("Agent update rollback release is missing");
536
+ }
537
+ const run = options.run ?? runCommand;
538
+ const probe = options.probe ?? targetProbe(journal.target, run);
539
+ restoreAgentRelease(staged);
540
+ let rollbackHealthy = false;
541
+ let failureMessage = "activation was interrupted before its health verdict became durable";
542
+ try {
543
+ await restartAgent(journal.target, run);
544
+ rollbackHealthy = await probe();
545
+ } catch (cause) {
546
+ failureMessage = `${failureMessage}; ${cause instanceof Error ? cause.message : String(cause)}`;
547
+ }
548
+ const failures = journal.failureCount + 1;
549
+ const updatedAtTs = (options.now ?? Date.now)();
550
+ const recovered = {
551
+ ...journal,
552
+ outcome: rollbackHealthy ? "rolled-back" : "failed",
553
+ updatedAtTs,
554
+ retryAfterTs: retryAfter(updatedAtTs, failures),
555
+ rollbackHealthy,
556
+ reason: reason(rollbackHealthy ? "ACTIVATION_INTERRUPTED" : "ROLLBACK_UNHEALTHY", failureMessage),
557
+ failureCount: failures
558
+ };
559
+ writeUpdateState(journalPath, receiptPath, recovered);
560
+ return readAgentUpdateReceipt(receiptPath);
561
+ }
282
562
  function startAgentUpdateHelper(options = {}) {
283
563
  const socketPath = options.socketPath ?? DEFAULT_AGENT_UPDATE_SOCKET;
284
564
  if (existsSync2(socketPath))
285
565
  unlinkSync(socketPath);
286
566
  mkdirSync2(dirname2(socketPath), { recursive: true, mode: 488 });
287
567
  const setTimer = options.setTimer ?? ((callback, ms) => setTimeout(callback, ms));
288
- const activate = options.activate ?? ((staged, target) => activateAgentRelease(staged, { target }));
568
+ const receiptPath = options.receiptPath ?? AGENT_UPDATE_RECEIPT;
569
+ const journalPath = options.journalPath ?? AGENT_UPDATE_JOURNAL;
570
+ const releaseRoot = options.root ?? DEFAULT_AGENT_RELEASE_ROOT;
571
+ const activate = options.activate ?? ((staged, target, attemptId) => activateAgentRelease(staged, { target, attemptId, journalPath, receiptPath, now: options.now }));
572
+ let busy = true;
573
+ let blocked;
574
+ (options.recover ?? (() => recoverInterruptedAgentUpdate({
575
+ root: releaseRoot,
576
+ journalPath,
577
+ receiptPath,
578
+ now: options.now
579
+ })))().catch((cause) => {
580
+ blocked = cause instanceof Error ? cause.message : String(cause);
581
+ }).finally(() => {
582
+ busy = false;
583
+ });
289
584
  const server = createServer((socket) => {
290
585
  let buffer = "";
291
586
  socket.on("data", (chunk) => {
@@ -301,22 +596,42 @@ function startAgentUpdateHelper(options = {}) {
301
596
  return;
302
597
  const line = buffer.slice(0, newline);
303
598
  buffer = "";
599
+ let ownsBusy = false;
304
600
  Promise.resolve().then(() => JSON.parse(line)).then(async (request) => {
601
+ if (blocked)
602
+ throw new Error(`update journal needs operator recovery: ${blocked}`);
603
+ if (busy)
604
+ throw new Error("another Agent update or recovery is already active");
305
605
  if (request.op !== "apply")
306
606
  throw new Error("unknown update operation");
307
607
  if (request.target !== "compute" && request.target !== "metal") {
308
608
  throw new Error("agent update target is invalid");
309
609
  }
610
+ const attemptId = request.attemptId ?? randomUUID2();
611
+ if (!ATTEMPT_ID.test(attemptId))
612
+ throw new Error("Agent update attempt ID is invalid");
613
+ const prior = readJournal(journalPath, releaseRoot);
614
+ const now = (options.now ?? Date.now)();
615
+ if (prior?.targetVersion === request.release.version && (prior.outcome === "rolled-back" || prior.outcome === "failed") && (prior.retryAfterTs ?? 0) > now)
616
+ throw new Error(`Agent update ${request.release.version} is quarantined until ${prior.retryAfterTs}`);
617
+ busy = true;
618
+ ownsBusy = true;
310
619
  const staged = await stageAgentRelease(request.release, {
311
620
  currentVersion: request.currentVersion,
312
- root: options.root ?? DEFAULT_AGENT_RELEASE_ROOT
621
+ root: releaseRoot
313
622
  });
314
- const response = { ok: true, status: "staged", version: staged.version };
623
+ const response = { ok: true, status: "staged", version: staged.version, attemptId };
315
624
  socket.end(`${JSON.stringify(response)}
316
- `, () => {
317
- setTimer(() => void activate(staged, request.target), 100);
318
- });
625
+ `);
626
+ setTimer(() => void activate(staged, request.target, attemptId).catch((cause) => {
627
+ blocked = cause instanceof Error ? cause.message : String(cause);
628
+ }).finally(() => {
629
+ busy = false;
630
+ }), 100);
631
+ ownsBusy = false;
319
632
  }).catch((cause) => {
633
+ if (ownsBusy)
634
+ busy = false;
320
635
  const response = {
321
636
  ok: false,
322
637
  error: { code: "UPDATE_REFUSED", message: cause instanceof Error ? cause.message : String(cause) }
@@ -331,7 +646,7 @@ function startAgentUpdateHelper(options = {}) {
331
646
  return server;
332
647
  }
333
648
  function requestAgentUpdate(request, socketPath = DEFAULT_AGENT_UPDATE_SOCKET, timeoutMs = 90000) {
334
- return new Promise((resolve2, reject) => {
649
+ return new Promise((resolve3, reject) => {
335
650
  const socket = connect(socketPath, () => socket.write(`${JSON.stringify(request)}
336
651
  `));
337
652
  let buffer = "";
@@ -347,7 +662,7 @@ function requestAgentUpdate(request, socketPath = DEFAULT_AGENT_UPDATE_SOCKET, t
347
662
  return;
348
663
  socket.end();
349
664
  try {
350
- resolve2(JSON.parse(buffer.slice(0, newline)));
665
+ resolve3(JSON.parse(buffer.slice(0, newline)));
351
666
  } catch (cause) {
352
667
  reject(cause);
353
668
  }
@@ -358,9 +673,12 @@ function requestAgentUpdate(request, socketPath = DEFAULT_AGENT_UPDATE_SOCKET, t
358
673
  export {
359
674
  startAgentUpdateHelper,
360
675
  requestAgentUpdate,
676
+ recoverInterruptedAgentUpdate,
677
+ readAgentUpdateReceipt,
361
678
  probeAgentSocket,
362
679
  activateAgentRelease,
363
680
  AGENT_UPDATE_RECEIPT,
681
+ AGENT_UPDATE_JOURNAL,
364
682
  AGENT_UPDATE_HELPER_UNIT_PATH,
365
683
  AGENT_UPDATE_GROUP
366
684
  };
@@ -16,6 +16,7 @@ export interface UpdateCommandResult {
16
16
  }
17
17
  export interface StagedAgentRelease {
18
18
  version: string;
19
+ fromVersion: string;
19
20
  directory: string;
20
21
  previousTarget: string;
21
22
  nextTarget: string;