engine7 7.1.138 → 7.1.140

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.
@@ -1,7 +1,7 @@
1
1
  const require=(await import('node:module')).createRequire(import.meta.url)
2
2
 
3
3
  // src/continuity/console-main.ts
4
- import { readFileSync as readFileSync9 } from "node:fs";
4
+ import { readFileSync as readFileSync8 } from "node:fs";
5
5
  import { isAbsolute as isAbsolute7, resolve as resolve8 } from "node:path";
6
6
  import { fileURLToPath as fileURLToPath3 } from "node:url";
7
7
 
@@ -233,7 +233,7 @@ var KeyServiceStore = class {
233
233
  };
234
234
 
235
235
  // src/continuity/controller-main.ts
236
- import { readFileSync as readFileSync3 } from "node:fs";
236
+ import { readFileSync as readFileSync2 } from "node:fs";
237
237
  import { isAbsolute, resolve as resolve2 } from "node:path";
238
238
  import { fileURLToPath } from "node:url";
239
239
 
@@ -251,18 +251,14 @@ import {
251
251
  fstatSync as fstatSync2,
252
252
  fsyncSync as fsyncSync2,
253
253
  readSync,
254
- writeSync as writeSync2,
255
254
  lstatSync as lstatSync2,
256
255
  realpathSync,
257
- mkdirSync as mkdirSync2,
258
- readFileSync as readFileSync2,
259
- writeFileSync,
260
- linkSync,
261
- unlinkSync as unlinkSync2
256
+ mkdirSync as mkdirSync2
262
257
  } from "node:fs";
263
258
  import { join as join2, dirname, resolve } from "node:path";
264
259
  var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
265
260
  var MAGIC = Buffer.from("E7P1");
261
+ var INLINE_BYTES = 64 * 1024;
266
262
  var noFollow = constants2.O_NOFOLLOW ?? 0;
267
263
  function assertPrivateDirectory(path3) {
268
264
  const info = lstatSync2(path3);
@@ -514,19 +510,28 @@ var TravelController = class {
514
510
  this.healthySince = null;
515
511
  const candidates = Object.values(this.options.nodes).sort((a, b) => Number(a.principal.nodeId === status.activeNodeId) - Number(b.principal.nodeId === status.activeNodeId) || Number(a.principal.role !== "CLOUD") - Number(b.principal.role !== "CLOUD"));
516
512
  let node;
513
+ let missingCheckpoint = false;
517
514
  for (const candidate of candidates) if ((await candidate.observe()).connected === true) {
518
- node = candidate;
519
- break;
515
+ try {
516
+ await candidate.pinBranch(status.checkpointDigest);
517
+ node = candidate;
518
+ break;
519
+ } catch (error) {
520
+ if (!(error instanceof Error) || error.message !== "TRAVEL_NODE_COMMON_CHECKPOINT") throw error;
521
+ missingCheckpoint = true;
522
+ }
523
+ }
524
+ if (!node) {
525
+ if (missingCheckpoint) throw new Error("TRAVEL_NODE_COMMON_CHECKPOINT");
526
+ return;
520
527
  }
521
- if (!node) return;
522
- await node.pinBranch(status.checkpointDigest);
523
528
  const ready = await node.prepare(status.checkpointDigest);
524
529
  const latest = await this.options.authority.status(node.principal);
525
530
  if (latest.authorityBootId !== status.authorityBootId || latest.epoch !== status.epoch || latest.checkpointDigest !== status.checkpointDigest || latest.deletionWatermark !== status.deletionWatermark || latest.activeNodeId && !latest.expired) return;
526
531
  const permit = await this.options.authority.acquire(node.principal, ready);
527
532
  await this.launch(node, permit, status.checkpointDigest);
528
533
  }
529
- async replicate(source, target) {
534
+ async replicate(source, target, recheckBranches = false) {
530
535
  if (!source.replicationOffer || !source.connectReplica || !target.replicaProfile || !target.bootstrapReplica) return true;
531
536
  const offer = await source.replicationOffer();
532
537
  if (!offer) return true;
@@ -546,8 +551,11 @@ var TravelController = class {
546
551
  if (!profile || JSON.stringify(profile) !== JSON.stringify(offer.profile)) throw new Error("TRAVEL_CONTROLLER_REPLICA");
547
552
  await assertSource();
548
553
  await source.connectReplica(profile);
549
- const recovered = await source.recoverBranches?.();
550
- return !recovered || recovered.unresolvedCritical === 0;
554
+ if (recheckBranches) {
555
+ const recovered = await source.recoverBranches?.();
556
+ if (recovered && recovered.unresolvedCritical !== 0) return false;
557
+ }
558
+ return true;
551
559
  }
552
560
  async advance(job) {
553
561
  const target = this.options.nodes[job.target], control = this.options.authority;
@@ -561,7 +569,7 @@ var TravelController = class {
561
569
  }
562
570
  const source2 = this.options.nodes[status.activeNodeId];
563
571
  if (!source2) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
564
- if (!await this.replicate(source2, target)) return;
572
+ if (!await this.replicate(source2, target, true)) return;
565
573
  this.db.prepare("UPDATE jobs SET source=?,state='PREPARING' WHERE id=?").run(source2.principal.nodeId, job.id);
566
574
  await control.beginHandoff(source2.principal, await source2.permit(), job.id, job.target);
567
575
  return;
@@ -758,9 +766,12 @@ var TravelReportClient = class {
758
766
  this.timeout = options.timeoutMs ?? 8e3;
759
767
  if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
760
768
  this.key = options.key ? Buffer.from(options.key) : void 0;
761
- this.agent = new Agent({ ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, keepAlive: true, maxSockets: 1 });
769
+ const tls = { ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, maxSockets: 1 };
770
+ this.agent = new Agent({ ...tls, keepAlive: true });
771
+ this.mutationAgent = new Agent({ ...tls, keepAlive: false });
762
772
  }
763
773
  agent;
774
+ mutationAgent;
764
775
  key;
765
776
  url;
766
777
  timeout;
@@ -787,7 +798,7 @@ var TravelReportClient = class {
787
798
  if (error) reject(error);
788
799
  else resolve9(value);
789
800
  };
790
- const req = request(this.url, { method: "POST", agent: this.agent, headers: {
801
+ const req = request(this.url, { method: "POST", agent: readActions.has(input?.action) ? this.agent : this.mutationAgent, headers: {
791
802
  Authorization: "Bearer " + this.options.credential,
792
803
  "X-Engine7-Travel-Node": this.options.nodeId,
793
804
  "Content-Type": "application/json",
@@ -862,6 +873,7 @@ var TravelReportClient = class {
862
873
  this.closed = true;
863
874
  for (const req of this.pending) req.destroy();
864
875
  this.agent.destroy();
876
+ this.mutationAgent.destroy();
865
877
  this.key?.fill(0);
866
878
  }
867
879
  };
@@ -949,7 +961,14 @@ import { Agent as Agent2, request as request2 } from "node:https";
949
961
 
950
962
  // src/continuity/publication.ts
951
963
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
952
- var PUBLICATION_MANIFEST_BYTES = 4 * 1024 * 1024;
964
+
965
+ // src/continuity/inventory.ts
966
+ var STATE = new Set(`workspace agents auth configs cron media mem7 memory runtime session-memory steer tasks teams todos tools topics topics-history .everos .calendar calendar proactive skills prompts goals.json goal-events.jsonl SESSION-STATE.md install-identity.json license.json report-failures.jsonl report-state.json service-suggestions.json weixin cc-driver engines.json settings.json onboarding.json onboarding-tips.json remote-watchers.json plans telegram state`.split(" "));
967
+ var CORE_DIRECTORIES = new Set(`agents auth configs cron mem7 memory runtime session-memory steer tasks teams todos tools .everos .calendar calendar .proactive proactive skills prompts .nudge hooks inner-voice goals plans private scripts state .voice-chat .desktopBuddy body`.split(" "));
968
+ var CORE_OMITTED = new Set(`media images videos audio content content-library docs output outputs dogfood-output backup backups topics-history node_modules .venvs venv .venv asr .cache cache caches tmp temp .playwright-mcp lancedb`.split(" "));
969
+
970
+ // src/continuity/publication.ts
971
+ var PUBLICATION_MANIFEST_BYTES = 32 * 1024 * 1024;
953
972
  var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
954
973
  var ZERO = "0".repeat(64);
955
974
 
@@ -962,6 +981,7 @@ var nodeSupervisorErrors = /* @__PURE__ */ new Set([
962
981
  "TRAVEL_NODE_CANCELLED",
963
982
  "TRAVEL_NODE_BOOT_MISMATCH",
964
983
  "TRAVEL_NODE_CHECKPOINT",
984
+ "TRAVEL_NODE_COMMON_CHECKPOINT",
965
985
  "TRAVEL_NODE_GENERATION_COLLISION",
966
986
  "TRAVEL_NODE_KEY_UNAVAILABLE",
967
987
  "TRAVEL_NODE_KEY_BARRIER",
@@ -1012,13 +1032,16 @@ var RemoteTravelNodeSupervisor = class {
1012
1032
  observeQuery;
1013
1033
  permitQuery;
1014
1034
  closed = false;
1015
- call(action, args = {}, discover = false) {
1035
+ call(action, args = {}, discover = false, retryStale = true, deadline, wireBody) {
1016
1036
  if (this.closed) return Promise.reject(new Error("TRAVEL_NODE_CLOSED"));
1017
1037
  const slot = action === "stop" ? "stop" : action === "observe" ? "observe" : action === "permit" ? "permit" : "operation";
1018
1038
  if ([...this.pending.values()].includes(slot)) return Promise.reject(new Error("TRAVEL_NODE_BUSY"));
1019
- const body = Buffer.from(JSON.stringify({ node: { version: 1, nodeId: this.principal.nodeId, ...discover ? {} : { bootId: this.bootId }, action, ...args } }));
1039
+ const body = wireBody ?? Buffer.from(JSON.stringify({ node: { version: 1, nodeId: this.principal.nodeId, ...discover ? {} : { bootId: this.bootId }, action, ...args } }));
1020
1040
  if (body.length > nodeSupervisorLimit) return Promise.reject(new Error("TRAVEL_NODE_INVALID_REQUEST"));
1021
1041
  const unavailable = () => new Error(this.closed ? "TRAVEL_NODE_CLOSED" : "TRAVEL_NODE_UNAVAILABLE");
1042
+ deadline ??= performance.now() + (slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
1043
+ const remaining = deadline - performance.now();
1044
+ if (remaining <= 0) return Promise.reject(unavailable());
1022
1045
  return new Promise((resolve9, reject) => {
1023
1046
  const started = performance.now();
1024
1047
  let responseStarted = false, receivedBytes = 0, reported = false;
@@ -1085,14 +1108,17 @@ var RemoteTravelNodeSupervisor = class {
1085
1108
  const timer = setTimeout(() => {
1086
1109
  lost("TIMEOUT");
1087
1110
  req.destroy();
1088
- }, slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
1111
+ }, remaining);
1089
1112
  const cleanup = () => {
1090
1113
  clearTimeout(timer);
1091
1114
  this.pending.delete(req);
1092
1115
  };
1093
1116
  req.once("error", (error) => {
1094
1117
  cleanup();
1095
- lost(error.code);
1118
+ if (!reported && retryStale && !this.closed && !responseStarted && (slot === "observe" || slot === "permit") && req.reusedSocket && error.code === "ECONNRESET") {
1119
+ reported = true;
1120
+ resolve9(this.call(action, args, discover, false, deadline, body));
1121
+ } else lost(error.code);
1096
1122
  });
1097
1123
  req.once("close", cleanup);
1098
1124
  req.end(body);
@@ -1177,6 +1203,9 @@ var RemoteTravelNodeSupervisor = class {
1177
1203
  // src/continuity/publication-transport.ts
1178
1204
  var BODY_LIMIT = PUBLICATION_MANIFEST_BYTES + 65536;
1179
1205
 
1206
+ // src/continuity/recovery-archive-transfer.ts
1207
+ import { gzipSync, gunzipSync, createGunzip, brotliCompressSync, brotliDecompressSync, createBrotliCompress, createBrotliDecompress, constants as constants3 } from "node:zlib";
1208
+
1180
1209
  // src/continuity/recovery-archive.ts
1181
1210
  import { DatabaseSync as DatabaseSync5, backup } from "node:sqlite";
1182
1211
 
@@ -1185,10 +1214,11 @@ var MAGIC2 = Buffer.from("E7OBJ001");
1185
1214
  var HEADER_SIZE = MAGIC2.length + 12;
1186
1215
 
1187
1216
  // src/continuity/recovery-archive.ts
1188
- var MAX_METADATA = 16 * 1024 * 1024;
1217
+ var RECOVERY_ARCHIVE_METADATA_BYTES = PUBLICATION_MANIFEST_BYTES + 8 * 1024 * 1024;
1189
1218
 
1190
1219
  // src/continuity/recovery-archive-transfer.ts
1191
- var metadataLimit = 16 * 1024 * 1024;
1220
+ var streamBatchBytes = 8 * 1024 * 1024;
1221
+ var brotliOptions = { params: { [constants3.BROTLI_PARAM_QUALITY]: 4, [constants3.BROTLI_PARAM_LGWIN]: 22 } };
1192
1222
 
1193
1223
  // src/continuity/controller-main.ts
1194
1224
  var path = (value) => {
@@ -1206,7 +1236,7 @@ function openTravelController(input) {
1206
1236
  privateKey.fill(0);
1207
1237
  };
1208
1238
  try {
1209
- const tls = { ca: readFileSync3(path(config.tls?.caFile)), cert: readFileSync3(path(config.tls?.certFile)), key: privateKey };
1239
+ const tls = { ca: readFileSync2(path(config.tls?.caFile)), cert: readFileSync2(path(config.tls?.certFile)), key: privateKey };
1210
1240
  for (const [nodeId, value] of Object.entries(config.nodes)) {
1211
1241
  if (!nodeSupervisorId(nodeId) || !nodeSupervisorRecord(value) || !nodeSupervisorRecord(value.principal) || value.principal.nodeId !== nodeId) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
1212
1242
  const principal = value.principal;
@@ -1277,6 +1307,7 @@ if (process.argv[1] && /[\\/](controller-main\.ts|travel-controller\.mjs)$/.test
1277
1307
  // src/continuity/console-manager.ts
1278
1308
  import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
1279
1309
  import { join as join4 } from "node:path";
1310
+ import { randomUUID as randomUUID3 } from "node:crypto";
1280
1311
  var travelConsoleActions = ["status", "auto_on", "auto_off", "sync", "to_cloud", "to_local", "recover", "finish"];
1281
1312
  var travelConsoleErrors = /* @__PURE__ */ new Set(["invalid_action", "invalid_request", "wrong_partner", "service_unavailable", "busy", "recovery_required", "recovery_unavailable", "confirmation_required", "not_ready", "retired"]);
1282
1313
  var TravelConsoleManager = class {
@@ -1303,6 +1334,7 @@ var TravelConsoleManager = class {
1303
1334
  db;
1304
1335
  closed = false;
1305
1336
  changing = false;
1337
+ operation;
1306
1338
  roles;
1307
1339
  role(nodeId) {
1308
1340
  if (nodeId === this.roles.local.principal.nodeId) return "local";
@@ -1360,11 +1392,13 @@ var TravelConsoleManager = class {
1360
1392
  checkedAt: Date.now(),
1361
1393
  allowedActions,
1362
1394
  recovery: retirement?.recovery ?? "required",
1363
- ...controller.job ? { transfer: { id: controller.job.id, target: this.role(controller.job.target), state: controller.job.state } } : {},
1364
- ...retirement ? { retirement: { jobId: retirement.jobId, state: retirement.state } } : {}
1395
+ ...controller.job ? { transfer: { id: controller.job.id, target: this.role(controller.job.target), state: controller.job.state, ...controller.lastError ? { error: controller.lastError } : {} } } : {},
1396
+ ...retirement ? { retirement: { jobId: retirement.jobId, state: retirement.state } } : {},
1397
+ ...this.operation ? { operation: { ...this.operation } } : {}
1365
1398
  };
1366
1399
  }
1367
1400
  async execute(action, payload) {
1401
+ let operationId;
1368
1402
  try {
1369
1403
  if (!travelConsoleActions.includes(action)) throw new Error("invalid_action");
1370
1404
  if (action === "finish" && payload?.confirmed !== true) throw new Error("confirmation_required");
@@ -1377,6 +1411,10 @@ var TravelConsoleManager = class {
1377
1411
  if (action === "finish") return { ok: true, connected: true, snapshot };
1378
1412
  throw new Error("retired");
1379
1413
  }
1414
+ if (["sync", "recover", "finish"].includes(action)) {
1415
+ operationId = randomUUID3();
1416
+ this.operation = { id: operationId, action, state: "RUNNING", startedAt: Date.now(), updatedAt: Date.now() };
1417
+ }
1380
1418
  if (action === "auto_on" || action === "auto_off") {
1381
1419
  if (snapshot.retirement) throw new Error("retired");
1382
1420
  if (snapshot.active === "unknown") throw new Error("not_ready");
@@ -1408,12 +1446,14 @@ var TravelConsoleManager = class {
1408
1446
  await this.options.retirement.finish();
1409
1447
  }
1410
1448
  }
1449
+ if (this.operation?.id === operationId && this.operation?.state === "RUNNING") this.operation = { ...this.operation, state: "DONE", updatedAt: Date.now() };
1411
1450
  } finally {
1412
1451
  this.changing = false;
1413
1452
  }
1414
1453
  return { ok: true, connected: true, snapshot: await this.snapshot() };
1415
1454
  } catch (error) {
1416
1455
  const message = error.message, code = travelConsoleErrors.has(message) ? message : /RECOVERY/.test(message) ? "recovery_required" : /BUSY|HANDOFF_STATE|COLLISION/.test(message) ? "busy" : "service_unavailable";
1456
+ if (this.operation?.id === operationId && this.operation?.state === "RUNNING") this.operation = { ...this.operation, state: "FAILED", updatedAt: Date.now(), error: code };
1417
1457
  const reason = typeof message === "string" && /^[A-Z][A-Z0-9_]{0,95}$/.test(message) ? message : code;
1418
1458
  process.stderr.write("[travel-console-operation] " + JSON.stringify({ at: Date.now(), action: travelConsoleActions.includes(action) ? action : "OTHER", reason }) + "\n");
1419
1459
  return { ok: false, connected: true, error: code };
@@ -1555,13 +1595,13 @@ function createTravelConsoleServer(options) {
1555
1595
  }
1556
1596
 
1557
1597
  // src/continuity/console-retirement.ts
1558
- import { existsSync as existsSync4, readFileSync as readFileSync8, writeFileSync as writeFileSync4, renameSync, realpathSync as realpathSync5, unlinkSync as unlinkSync3 } from "node:fs";
1598
+ import { existsSync as existsSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync3, renameSync, realpathSync as realpathSync5, unlinkSync as unlinkSync2 } from "node:fs";
1559
1599
  import { DatabaseSync as DatabaseSync10 } from "node:sqlite";
1560
- import { dirname as dirname4, join as join9, isAbsolute as isAbsolute6, resolve as resolve7 } from "node:path";
1561
- import { createHash as createHash7, randomUUID as randomUUID4 } from "node:crypto";
1600
+ import { dirname as dirname5, join as join9, isAbsolute as isAbsolute6, resolve as resolve7 } from "node:path";
1601
+ import { createHash as createHash7, randomUUID as randomUUID5 } from "node:crypto";
1562
1602
 
1563
1603
  // src/continuity/retirement-main.ts
1564
- import { readFileSync as readFileSync7, existsSync as existsSync3 } from "node:fs";
1604
+ import { readFileSync as readFileSync6, existsSync as existsSync3 } from "node:fs";
1565
1605
  import { isAbsolute as isAbsolute5, resolve as resolve6 } from "node:path";
1566
1606
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1567
1607
  import { execFile } from "node:child_process";
@@ -1587,11 +1627,13 @@ var UserSeatResource = class {
1587
1627
  return new Promise((done, reject) => {
1588
1628
  const child = spawn("/usr/bin/sudo", ["-n", "/usr/sbin/runuser", "-u", this.config.runAs.user, "--", this.config.runAs.node, this.config.runAs.entry, action, "--config", this.config.runAs.configFile], { stdio: ["pipe", "pipe", "pipe"] });
1589
1629
  const chunks = [];
1590
- let bytes = 0;
1630
+ let bytes = 0, stderr = "";
1591
1631
  const timer = setTimeout(() => child.kill("SIGKILL"), 12e4);
1592
1632
  child.stdin.on("error", () => {
1593
1633
  });
1594
- child.stderr.resume();
1634
+ child.stderr.on("data", (chunk) => {
1635
+ stderr = (stderr + chunk.toString()).slice(-4096);
1636
+ });
1595
1637
  child.stdout.on("data", (chunk) => {
1596
1638
  bytes += chunk.length;
1597
1639
  if (bytes > 64 * 1024 * 1024) child.kill("SIGKILL");
@@ -1601,7 +1643,9 @@ var UserSeatResource = class {
1601
1643
  child.once("close", (code) => {
1602
1644
  clearTimeout(timer);
1603
1645
  if (code !== 0) {
1604
- reject(new Error("TRAVEL_RETIREMENT_PROVIDER_PENDING"));
1646
+ const reason = stderr.match(/TRAVEL_RETIREMENT_RESOURCE_REFUSED ([A-Z][A-Z0-9_]{0,95})(?:\s|$)/)?.[1];
1647
+ if (reason) process.stderr.write("[travel-retirement-resource] " + JSON.stringify({ action, reason }) + "\n");
1648
+ reject(new Error(reason?.startsWith("TRAVEL_") ? reason : "TRAVEL_RETIREMENT_PROVIDER_PENDING"));
1605
1649
  return;
1606
1650
  }
1607
1651
  try {
@@ -1627,8 +1671,8 @@ var UserSeatResource = class {
1627
1671
  import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
1628
1672
  import { createHash as createHash2 } from "node:crypto";
1629
1673
  import { existsSync } from "node:fs";
1630
- import { lstatSync as lstatSync3, readdirSync, readFileSync as readFileSync4, readlinkSync, realpathSync as realpathSync2, rmSync } from "node:fs";
1631
- import { isAbsolute as isAbsolute3, join as join5, resolve as resolve4, relative } from "node:path";
1674
+ import { accessSync, constants as constants4, lstatSync as lstatSync3, readdirSync, readFileSync as readFileSync3, readlinkSync, realpathSync as realpathSync2, rmSync } from "node:fs";
1675
+ import { dirname as dirname2, isAbsolute as isAbsolute3, join as join5, resolve as resolve4, relative } from "node:path";
1632
1676
  var identity = (value) => JSON.stringify([value.tenantId, value.companionId, value.seatId]);
1633
1677
  var sha = (value) => createHash2("sha256").update(value).digest("hex");
1634
1678
  var LocalSeatResource = class {
@@ -1659,19 +1703,29 @@ var LocalSeatResource = class {
1659
1703
  else if (item.isDirectory()) visit(path3);
1660
1704
  else if (item.isFile()) {
1661
1705
  if (item.name === ".travel-seat-resource.json" && identity(JSON.parse(readPrivateFile(path3, 65536).toString())) !== identity(this.identity)) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
1662
- result.push({ version, digest: sha(readFileSync4(path3)) });
1706
+ result.push({ version, digest: sha(readFileSync3(path3)) });
1663
1707
  } else throw new Error("TRAVEL_RETIREMENT_PATH");
1664
1708
  if (result.length > 1e6) throw new Error("TRAVEL_RETIREMENT_BUDGET");
1665
1709
  }
1666
1710
  };
1667
1711
  visit(this.path);
1668
- return result;
1712
+ return result.length === 1 && result[0].version === ".travel-seat-resource.json" ? [] : result;
1669
1713
  }
1670
1714
  async purge(expectedInventory) {
1671
1715
  const allowed = new Map(expectedInventory.map((item) => [item.version, item.digest]));
1672
1716
  if (this.inventoryNow().some((item) => allowed.get(item.version) !== item.digest)) throw new Error("TRAVEL_RETIREMENT_RESOURCE_CHANGED");
1673
- if (this.check()) rmSync(this.path, { recursive: true });
1674
- if (existsSync(this.path)) throw new Error("TRAVEL_RETIREMENT_PENDING");
1717
+ if (this.check()) {
1718
+ let removeRoot = true;
1719
+ try {
1720
+ accessSync(dirname2(this.path), constants4.W_OK);
1721
+ } catch (error) {
1722
+ if (error.code !== "EACCES") throw error;
1723
+ removeRoot = false;
1724
+ }
1725
+ if (removeRoot) rmSync(this.path, { recursive: true });
1726
+ else for (const name of readdirSync(this.path)) if (name !== ".travel-seat-resource.json") rmSync(join5(this.path, name), { recursive: true });
1727
+ }
1728
+ if (this.inventoryNow().length) throw new Error("TRAVEL_RETIREMENT_PENDING");
1675
1729
  }
1676
1730
  };
1677
1731
  var TravelRetirement = class {
@@ -1757,7 +1811,8 @@ var TravelRetirement = class {
1757
1811
  row = this.db.prepare("SELECT * FROM resources WHERE id=?").get(resource.id);
1758
1812
  }
1759
1813
  const original = JSON.parse(String(row.inventory));
1760
- if (current.some((item) => !original.some((known) => item.version === known.version && item.digest === known.digest))) throw new Error("TRAVEL_RETIREMENT_RESOURCE_CHANGED");
1814
+ const allowed = new Map(original.map((item) => [item.version, item.digest]));
1815
+ if (current.some((item) => allowed.get(item.version) !== item.digest)) throw new Error("TRAVEL_RETIREMENT_RESOURCE_CHANGED");
1761
1816
  await verifyRecovery(true);
1762
1817
  await resource.purge(original);
1763
1818
  if ((await resource.inventory()).length) throw new Error("TRAVEL_RETIREMENT_PROVIDER_PENDING");
@@ -1783,22 +1838,22 @@ var TravelRetirement = class {
1783
1838
  };
1784
1839
 
1785
1840
  // src/continuity/local-exit.ts
1786
- import { cpSync, existsSync as existsSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync6, readdirSync as readdirSync3, realpathSync as realpathSync4, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
1841
+ import { cpSync, existsSync as existsSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync5, readdirSync as readdirSync3, realpathSync as realpathSync4, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
1787
1842
  import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
1788
- import { isAbsolute as isAbsolute4, join as join8, dirname as dirname3, resolve as resolve5 } from "node:path";
1843
+ import { isAbsolute as isAbsolute4, join as join8, dirname as dirname4, resolve as resolve5 } from "node:path";
1789
1844
  import { createHash as createHash5, verify as verify2 } from "node:crypto";
1790
1845
 
1791
1846
  // src/continuity/runtime-lock.ts
1792
- import { randomUUID as randomUUID3 } from "node:crypto";
1847
+ import { randomUUID as randomUUID4 } from "node:crypto";
1793
1848
  import { AsyncLocalStorage } from "node:async_hooks";
1794
- import { closeSync as closeSync3, lstatSync as lstatSync4, mkdirSync as mkdirSync3, openSync as openSync3, readFileSync as readFileSync5, realpathSync as realpathSync3 } from "node:fs";
1849
+ import { closeSync as closeSync3, lstatSync as lstatSync4, mkdirSync as mkdirSync3, openSync as openSync3, readFileSync as readFileSync4, realpathSync as realpathSync3 } from "node:fs";
1795
1850
  import { join as join6 } from "node:path";
1796
1851
  import { createRequire } from "node:module";
1797
1852
  var sqlite;
1798
1853
  function openSQLite(file, options = {}) {
1799
1854
  return new (sqlite ??= createRequire(import.meta.url)("node:sqlite")).DatabaseSync(file, options);
1800
1855
  }
1801
- var bootId = randomUUID3();
1856
+ var bootId = randomUUID4();
1802
1857
  var checkpointHandles = /* @__PURE__ */ new Set();
1803
1858
  var recoveryWriterLocks = new AsyncLocalStorage();
1804
1859
  var initialBaselineAdmission = new AsyncLocalStorage();
@@ -1866,7 +1921,7 @@ async function withCheckpointLock(stateDir, operation) {
1866
1921
  for (const name of [".engine.pid", ".bg-worker.pid"]) {
1867
1922
  let value;
1868
1923
  try {
1869
- value = readFileSync5(join6(stateDir, name), "utf8").trim();
1924
+ value = readFileSync4(join6(stateDir, name), "utf8").trim();
1870
1925
  } catch (error) {
1871
1926
  if (error.code === "ENOENT") continue;
1872
1927
  throw new Error("WRITER_STATE_UNKNOWN", { cause: error });
@@ -1889,14 +1944,14 @@ async function withCheckpointLock(stateDir, operation) {
1889
1944
  // src/continuity/local-dedupe.ts
1890
1945
  import { DatabaseSync as DatabaseSync8 } from "node:sqlite";
1891
1946
  import { createHash as createHash3 } from "node:crypto";
1892
- import { dirname as dirname2 } from "node:path";
1947
+ import { dirname as dirname3 } from "node:path";
1893
1948
  var sha2 = (value) => createHash3("sha256").update(value).digest("hex");
1894
1949
  var hash = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
1895
1950
  var PlatformReceiptStore = class {
1896
1951
  db;
1897
1952
  constructor(file, namespace) {
1898
1953
  if (!namespace || namespace.length > 1024) throw new Error("PLATFORM_RECEIPT_IDENTITY");
1899
- preparePrivateDirectory(dirname2(file));
1954
+ preparePrivateDirectory(dirname3(file));
1900
1955
  preparePrivateDatabase(file);
1901
1956
  this.db = new DatabaseSync8(file);
1902
1957
  try {
@@ -1957,7 +2012,7 @@ var PlatformReceiptStore = class {
1957
2012
 
1958
2013
  // src/continuity/local-exit-proof.ts
1959
2014
  import { createHash as createHash4, verify } from "node:crypto";
1960
- import { createReadStream, mkdirSync as mkdirSync4, readdirSync as readdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
2015
+ import { createReadStream, mkdirSync as mkdirSync4, readdirSync as readdirSync2, writeFileSync } from "node:fs";
1961
2016
  import { join as join7, relative as relative2 } from "node:path";
1962
2017
  var hash2 = (value) => createHash4("sha256").update(value).digest("hex");
1963
2018
  var equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
@@ -2046,8 +2101,8 @@ function detachReplication(directory) {
2046
2101
  }
2047
2102
  async function createOrdinaryLocalRecovery(options) {
2048
2103
  const source = resolve5(options.stateDir), destination = resolve5(options.destination);
2049
- if (!isAbsolute4(options.destination) || source !== options.stateDir || destination !== options.destination || realpathSync4(source) !== source || destination === source || destination.startsWith(source + "/") || source.startsWith(destination + "/") || realpathSync4(dirname3(destination)) !== dirname3(destination)) throw new Error("TRAVEL_EXIT_PATH");
2050
- const activation = JSON.parse(readFileSync6(join8(source, ".travel-active.json"), "utf8")), permit = activation.permit, { signature, ...signed } = permit;
2104
+ if (!isAbsolute4(options.destination) || source !== options.stateDir || destination !== options.destination || realpathSync4(source) !== source || destination === source || destination.startsWith(source + "/") || source.startsWith(destination + "/") || realpathSync4(dirname4(destination)) !== dirname4(destination)) throw new Error("TRAVEL_EXIT_PATH");
2105
+ const activation = JSON.parse(readFileSync5(join8(source, ".travel-active.json"), "utf8")), permit = activation.permit, { signature, ...signed } = permit;
2051
2106
  if (activation.format !== "engine7-runtime-activation-v1" || identity2(activation.identity) !== identity2(options.identity) || identity2(permit) !== identity2(options.identity) || permit.nodeId !== options.localNodeId || activation.nodeId !== options.localNodeId || !verify2(null, Buffer.from(JSON.stringify(signed)), options.publicKey, Buffer.from(signature, "base64")) || identity2(options.dedupeReceipt.identity) !== identity2(options.identity) || options.dedupeReceipt.checkpointDigest !== options.checkpointDigest || options.dedupeReceipt.deletionWatermark !== permit.deletionWatermark) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
2052
2107
  return withCheckpointLock(source, async () => {
2053
2108
  if (!options.authority || !options.principal || options.authority.publicKey !== options.publicKey) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
@@ -2089,7 +2144,7 @@ async function createOrdinaryLocalRecovery(options) {
2089
2144
  await proof.check();
2090
2145
  const body = { ...receipt, ordinaryFilesDigest: await localExitFilesDigest(destination, true) };
2091
2146
  const result = { ...body, digest: sha3(JSON.stringify(body)) };
2092
- writeFileSync3(join8(destination, ".continuity/travel-exit-receipt.json"), JSON.stringify(result), { mode: 384, flag: "wx", flush: true });
2147
+ writeFileSync2(join8(destination, ".continuity/travel-exit-receipt.json"), JSON.stringify(result), { mode: 384, flag: "wx", flush: true });
2093
2148
  return result;
2094
2149
  } catch (error) {
2095
2150
  if (existsSync2(destination)) rmSync2(destination, { recursive: true });
@@ -2110,7 +2165,7 @@ async function runTravelRetirementCli(args) {
2110
2165
  if (args.length !== 3 || !["run", "recover-local"].includes(args[0]) || args[1] !== "--config") throw new Error("TRAVEL_RETIREMENT_INVALID_COMMAND");
2111
2166
  const config = JSON.parse(readPrivateFile(path2(args[2]), 4 * 1024 * 1024).toString());
2112
2167
  if (args[0] === "recover-local") {
2113
- const client2 = new TravelManagementClient({ ...config.control, ca: readFileSync7(path2(config.tls.caFile)), cert: readFileSync7(path2(config.tls.certFile)), key: readPrivateFile(path2(config.tls.keyFile), 65536) });
2168
+ const client2 = new TravelManagementClient({ ...config.control, ca: readFileSync6(path2(config.tls.caFile)), cert: readFileSync6(path2(config.tls.certFile)), key: readPrivateFile(path2(config.tls.keyFile), 65536) });
2114
2169
  try {
2115
2170
  const { principal, publicKey } = await client2.retirementStatus();
2116
2171
  if (publicKey !== config.publicKey) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
@@ -2125,7 +2180,7 @@ async function runTravelRetirementCli(args) {
2125
2180
  }
2126
2181
  if (!Array.isArray(config.resources) || !Array.isArray(config.stopServices) || config.stopServices.some((service) => typeof service !== "string" || !/^engine7-travel[-a-zA-Z0-9_.@]+\.service$/.test(service))) throw new Error("TRAVEL_RETIREMENT_CONFIG");
2127
2182
  if (!config.stopServices.length && config.nodesAlreadyStopped !== true) throw new Error("TRAVEL_RETIREMENT_STOP_REQUIRED");
2128
- const client = new TravelManagementClient({ ...config.control, ca: readFileSync7(path2(config.tls.caFile)), cert: readFileSync7(path2(config.tls.certFile)), key: readPrivateFile(path2(config.tls.keyFile), 65536) });
2183
+ const client = new TravelManagementClient({ ...config.control, ca: readFileSync6(path2(config.tls.caFile)), cert: readFileSync6(path2(config.tls.certFile)), key: readPrivateFile(path2(config.tls.keyFile), 65536) });
2129
2184
  let job, keys;
2130
2185
  try {
2131
2186
  const control = await client.retirementStatus();
@@ -2179,10 +2234,10 @@ var sameIdentity = (a, b) => a && ["tenantId", "companionId", "seatId"].every((k
2179
2234
  var sourceBinding = (source) => source ? ["activeNodeId", "activeBootId", "authorityBootId", "epoch", "checkpointDigest", "deletionWatermark"].map((key) => source[key]) : null;
2180
2235
  function createTravelConsoleRetirement(options) {
2181
2236
  if (!isAbsolute6(options.configFile) || resolve7(options.configFile) !== options.configFile || realpathSync5(options.configFile) !== options.configFile) throw new Error("TRAVEL_CONSOLE_CONFIG");
2182
- const config = JSON.parse(readPrivateFile(options.configFile, 4 * 1024 * 1024).toString()), original = readFileSync8(options.configFile);
2183
- if (!sameIdentity(config.identity, options.identity) || config.accountOwnerRequestedKeyDestruction === true || !isAbsolute6(config.localRecoveryReceiptFile) || realpathSync5(dirname4(config.localRecoveryReceiptFile)) !== dirname4(config.localRecoveryReceiptFile)) throw new Error("TRAVEL_CONSOLE_CONFIG");
2237
+ const config = JSON.parse(readPrivateFile(options.configFile, 4 * 1024 * 1024).toString()), original = readFileSync7(options.configFile);
2238
+ if (!sameIdentity(config.identity, options.identity) || config.accountOwnerRequestedKeyDestruction === true || !isAbsolute6(config.localRecoveryReceiptFile) || realpathSync5(dirname5(config.localRecoveryReceiptFile)) !== dirname5(config.localRecoveryReceiptFile)) throw new Error("TRAVEL_CONSOLE_CONFIG");
2184
2239
  const assertConfig = () => {
2185
- if (!readFileSync8(options.configFile).equals(original)) throw new Error("TRAVEL_CONSOLE_CONFIG_CHANGED");
2240
+ if (!readFileSync7(options.configFile).equals(original)) throw new Error("TRAVEL_CONSOLE_CONFIG_CHANGED");
2186
2241
  };
2187
2242
  preparePrivateDirectory(config.directory);
2188
2243
  const pendingFile = join9(config.directory, "console-recovery.json");
@@ -2193,12 +2248,12 @@ function createTravelConsoleRetirement(options) {
2193
2248
  return value;
2194
2249
  };
2195
2250
  const savePending = (state, source) => {
2196
- const temp = pendingFile + "." + randomUUID4();
2251
+ const temp = pendingFile + "." + randomUUID5();
2197
2252
  try {
2198
- writeFileSync4(temp, JSON.stringify({ identity: options.identity, jobId: config.jobId, state, source: sourceBinding(source) }), { mode: 384, flag: "wx", flush: true });
2253
+ writeFileSync3(temp, JSON.stringify({ identity: options.identity, jobId: config.jobId, state, source: sourceBinding(source) }), { mode: 384, flag: "wx", flush: true });
2199
2254
  renameSync(temp, pendingFile);
2200
2255
  } finally {
2201
- if (existsSync4(temp)) unlinkSync3(temp);
2256
+ if (existsSync4(temp)) unlinkSync2(temp);
2202
2257
  }
2203
2258
  };
2204
2259
  const verify3 = async (value) => {
@@ -2246,15 +2301,15 @@ function createTravelConsoleRetirement(options) {
2246
2301
  savePending("LOCAL_STOPPED", stopped.source);
2247
2302
  return;
2248
2303
  }
2249
- const proof = await verify3(value), file = config.localRecoveryReceiptFile, temp = file + "." + randomUUID4();
2304
+ const proof = await verify3(value), file = config.localRecoveryReceiptFile, temp = file + "." + randomUUID5();
2250
2305
  try {
2251
- writeFileSync4(temp, JSON.stringify(proof), { mode: 384, flag: "wx", flush: true });
2306
+ writeFileSync3(temp, JSON.stringify(proof), { mode: 384, flag: "wx", flush: true });
2252
2307
  await verify3(proof);
2253
2308
  renameSync(temp, file);
2254
2309
  } finally {
2255
2310
  if (existsSync4(temp)) {
2256
- const { unlinkSync: unlinkSync4 } = await import("node:fs");
2257
- unlinkSync4(temp);
2311
+ const { unlinkSync: unlinkSync3 } = await import("node:fs");
2312
+ unlinkSync3(temp);
2258
2313
  }
2259
2314
  }
2260
2315
  },
@@ -2289,7 +2344,7 @@ function openTravelConsole(input) {
2289
2344
  manager,
2290
2345
  identity: identity3,
2291
2346
  token: readPrivateFile(privatePath(input.tokenFile), 1024).toString().trim(),
2292
- cert: readFileSync9(privatePath(input.tls.certFile)),
2347
+ cert: readFileSync8(privatePath(input.tls.certFile)),
2293
2348
  key: readPrivateFile(privatePath(input.tls.keyFile), 65536)
2294
2349
  });
2295
2350
  let closing;