engine7 7.1.138 → 7.1.141

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,22 +551,29 @@ 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;
554
562
  if (!target) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
555
563
  if (job.state === "REQUESTED") {
556
564
  const status = await control.status(target.principal);
557
- if (!status.activeNodeId || status.expired) throw new Error("TRAVEL_CONTROLLER_SOURCE_OFFLINE");
565
+ if (!status.activeNodeId || status.expired) {
566
+ this.db.prepare("UPDATE jobs SET state='ABORTED' WHERE id=?").run(job.id);
567
+ if (status.activeNodeId) await this.options.nodes[status.activeNodeId]?.stop();
568
+ return;
569
+ }
558
570
  if (status.activeNodeId === job.target) {
559
571
  this.db.prepare("UPDATE jobs SET state='DONE' WHERE id=?").run(job.id);
560
572
  return;
561
573
  }
562
574
  const source2 = this.options.nodes[status.activeNodeId];
563
575
  if (!source2) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
564
- if (!await this.replicate(source2, target)) return;
576
+ if (!await this.replicate(source2, target, true)) return;
565
577
  this.db.prepare("UPDATE jobs SET source=?,state='PREPARING' WHERE id=?").run(source2.principal.nodeId, job.id);
566
578
  await control.beginHandoff(source2.principal, await source2.permit(), job.id, job.target);
567
579
  return;
@@ -758,9 +770,12 @@ var TravelReportClient = class {
758
770
  this.timeout = options.timeoutMs ?? 8e3;
759
771
  if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
760
772
  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 });
773
+ const tls = { ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, maxSockets: 1 };
774
+ this.agent = new Agent({ ...tls, keepAlive: true });
775
+ this.mutationAgent = new Agent({ ...tls, keepAlive: false });
762
776
  }
763
777
  agent;
778
+ mutationAgent;
764
779
  key;
765
780
  url;
766
781
  timeout;
@@ -787,7 +802,7 @@ var TravelReportClient = class {
787
802
  if (error) reject(error);
788
803
  else resolve9(value);
789
804
  };
790
- const req = request(this.url, { method: "POST", agent: this.agent, headers: {
805
+ const req = request(this.url, { method: "POST", agent: readActions.has(input?.action) ? this.agent : this.mutationAgent, headers: {
791
806
  Authorization: "Bearer " + this.options.credential,
792
807
  "X-Engine7-Travel-Node": this.options.nodeId,
793
808
  "Content-Type": "application/json",
@@ -862,6 +877,7 @@ var TravelReportClient = class {
862
877
  this.closed = true;
863
878
  for (const req of this.pending) req.destroy();
864
879
  this.agent.destroy();
880
+ this.mutationAgent.destroy();
865
881
  this.key?.fill(0);
866
882
  }
867
883
  };
@@ -949,7 +965,14 @@ import { Agent as Agent2, request as request2 } from "node:https";
949
965
 
950
966
  // src/continuity/publication.ts
951
967
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
952
- var PUBLICATION_MANIFEST_BYTES = 4 * 1024 * 1024;
968
+
969
+ // src/continuity/inventory.ts
970
+ 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(" "));
971
+ 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(" "));
972
+ 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(" "));
973
+
974
+ // src/continuity/publication.ts
975
+ var PUBLICATION_MANIFEST_BYTES = 32 * 1024 * 1024;
953
976
  var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
954
977
  var ZERO = "0".repeat(64);
955
978
 
@@ -962,6 +985,7 @@ var nodeSupervisorErrors = /* @__PURE__ */ new Set([
962
985
  "TRAVEL_NODE_CANCELLED",
963
986
  "TRAVEL_NODE_BOOT_MISMATCH",
964
987
  "TRAVEL_NODE_CHECKPOINT",
988
+ "TRAVEL_NODE_COMMON_CHECKPOINT",
965
989
  "TRAVEL_NODE_GENERATION_COLLISION",
966
990
  "TRAVEL_NODE_KEY_UNAVAILABLE",
967
991
  "TRAVEL_NODE_KEY_BARRIER",
@@ -1012,13 +1036,16 @@ var RemoteTravelNodeSupervisor = class {
1012
1036
  observeQuery;
1013
1037
  permitQuery;
1014
1038
  closed = false;
1015
- call(action, args = {}, discover = false) {
1039
+ call(action, args = {}, discover = false, retryStale = true, deadline, wireBody) {
1016
1040
  if (this.closed) return Promise.reject(new Error("TRAVEL_NODE_CLOSED"));
1017
1041
  const slot = action === "stop" ? "stop" : action === "observe" ? "observe" : action === "permit" ? "permit" : "operation";
1018
1042
  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 } }));
1043
+ const body = wireBody ?? Buffer.from(JSON.stringify({ node: { version: 1, nodeId: this.principal.nodeId, ...discover ? {} : { bootId: this.bootId }, action, ...args } }));
1020
1044
  if (body.length > nodeSupervisorLimit) return Promise.reject(new Error("TRAVEL_NODE_INVALID_REQUEST"));
1021
1045
  const unavailable = () => new Error(this.closed ? "TRAVEL_NODE_CLOSED" : "TRAVEL_NODE_UNAVAILABLE");
1046
+ deadline ??= performance.now() + (slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
1047
+ const remaining = deadline - performance.now();
1048
+ if (remaining <= 0) return Promise.reject(unavailable());
1022
1049
  return new Promise((resolve9, reject) => {
1023
1050
  const started = performance.now();
1024
1051
  let responseStarted = false, receivedBytes = 0, reported = false;
@@ -1085,14 +1112,17 @@ var RemoteTravelNodeSupervisor = class {
1085
1112
  const timer = setTimeout(() => {
1086
1113
  lost("TIMEOUT");
1087
1114
  req.destroy();
1088
- }, slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
1115
+ }, remaining);
1089
1116
  const cleanup = () => {
1090
1117
  clearTimeout(timer);
1091
1118
  this.pending.delete(req);
1092
1119
  };
1093
1120
  req.once("error", (error) => {
1094
1121
  cleanup();
1095
- lost(error.code);
1122
+ if (!reported && retryStale && !this.closed && !responseStarted && (slot === "observe" || slot === "permit") && req.reusedSocket && error.code === "ECONNRESET") {
1123
+ reported = true;
1124
+ resolve9(this.call(action, args, discover, false, deadline, body));
1125
+ } else lost(error.code);
1096
1126
  });
1097
1127
  req.once("close", cleanup);
1098
1128
  req.end(body);
@@ -1177,18 +1207,30 @@ var RemoteTravelNodeSupervisor = class {
1177
1207
  // src/continuity/publication-transport.ts
1178
1208
  var BODY_LIMIT = PUBLICATION_MANIFEST_BYTES + 65536;
1179
1209
 
1180
- // src/continuity/recovery-archive.ts
1210
+ // src/continuity/recovery-archive-transfer.ts
1211
+ import { gzipSync, gunzipSync, createGunzip, brotliCompressSync, brotliDecompressSync, createBrotliCompress, createBrotliDecompress, constants as constants3 } from "node:zlib";
1212
+
1213
+ // src/continuity/native-database-snapshot.ts
1181
1214
  import { DatabaseSync as DatabaseSync5, backup } from "node:sqlite";
1182
1215
 
1216
+ // src/continuity/native-file-copy.ts
1217
+ import { execFile } from "node:child_process";
1218
+ import { promisify } from "node:util";
1219
+ var exec = promisify(execFile);
1220
+
1221
+ // src/continuity/recovery-archive.ts
1222
+ import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
1223
+
1183
1224
  // src/continuity/crypto.ts
1184
1225
  var MAGIC2 = Buffer.from("E7OBJ001");
1185
1226
  var HEADER_SIZE = MAGIC2.length + 12;
1186
1227
 
1187
1228
  // src/continuity/recovery-archive.ts
1188
- var MAX_METADATA = 16 * 1024 * 1024;
1229
+ var RECOVERY_ARCHIVE_METADATA_BYTES = PUBLICATION_MANIFEST_BYTES + 8 * 1024 * 1024;
1189
1230
 
1190
1231
  // src/continuity/recovery-archive-transfer.ts
1191
- var metadataLimit = 16 * 1024 * 1024;
1232
+ var streamBatchBytes = 8 * 1024 * 1024;
1233
+ var brotliOptions = { params: { [constants3.BROTLI_PARAM_QUALITY]: 4, [constants3.BROTLI_PARAM_LGWIN]: 22 } };
1192
1234
 
1193
1235
  // src/continuity/controller-main.ts
1194
1236
  var path = (value) => {
@@ -1206,7 +1248,7 @@ function openTravelController(input) {
1206
1248
  privateKey.fill(0);
1207
1249
  };
1208
1250
  try {
1209
- const tls = { ca: readFileSync3(path(config.tls?.caFile)), cert: readFileSync3(path(config.tls?.certFile)), key: privateKey };
1251
+ const tls = { ca: readFileSync2(path(config.tls?.caFile)), cert: readFileSync2(path(config.tls?.certFile)), key: privateKey };
1210
1252
  for (const [nodeId, value] of Object.entries(config.nodes)) {
1211
1253
  if (!nodeSupervisorId(nodeId) || !nodeSupervisorRecord(value) || !nodeSupervisorRecord(value.principal) || value.principal.nodeId !== nodeId) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
1212
1254
  const principal = value.principal;
@@ -1275,8 +1317,9 @@ if (process.argv[1] && /[\\/](controller-main\.ts|travel-controller\.mjs)$/.test
1275
1317
  }
1276
1318
 
1277
1319
  // src/continuity/console-manager.ts
1278
- import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
1320
+ import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
1279
1321
  import { join as join4 } from "node:path";
1322
+ import { randomUUID as randomUUID3 } from "node:crypto";
1280
1323
  var travelConsoleActions = ["status", "auto_on", "auto_off", "sync", "to_cloud", "to_local", "recover", "finish"];
1281
1324
  var travelConsoleErrors = /* @__PURE__ */ new Set(["invalid_action", "invalid_request", "wrong_partner", "service_unavailable", "busy", "recovery_required", "recovery_unavailable", "confirmation_required", "not_ready", "retired"]);
1282
1325
  var TravelConsoleManager = class {
@@ -1289,7 +1332,7 @@ var TravelConsoleManager = class {
1289
1332
  preparePrivateDirectory(options.directory);
1290
1333
  const file = join4(options.directory, "console.sqlite");
1291
1334
  preparePrivateDatabase(file);
1292
- this.db = new DatabaseSync6(file);
1335
+ this.db = new DatabaseSync7(file);
1293
1336
  try {
1294
1337
  this.db.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS binding(value TEXT NOT NULL)");
1295
1338
  const binding = JSON.stringify([options.identity, values.map((n) => [n.principal.nodeId, n.principal.role]).sort()]), prior = this.db.prepare("SELECT value FROM binding").all();
@@ -1303,6 +1346,7 @@ var TravelConsoleManager = class {
1303
1346
  db;
1304
1347
  closed = false;
1305
1348
  changing = false;
1349
+ operation;
1306
1350
  roles;
1307
1351
  role(nodeId) {
1308
1352
  if (nodeId === this.roles.local.principal.nodeId) return "local";
@@ -1360,11 +1404,13 @@ var TravelConsoleManager = class {
1360
1404
  checkedAt: Date.now(),
1361
1405
  allowedActions,
1362
1406
  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 } } : {}
1407
+ ...controller.job ? { transfer: { id: controller.job.id, target: this.role(controller.job.target), state: controller.job.state, ...controller.lastError ? { error: controller.lastError } : {} } } : {},
1408
+ ...retirement ? { retirement: { jobId: retirement.jobId, state: retirement.state } } : {},
1409
+ ...this.operation ? { operation: { ...this.operation } } : {}
1365
1410
  };
1366
1411
  }
1367
1412
  async execute(action, payload) {
1413
+ let operationId;
1368
1414
  try {
1369
1415
  if (!travelConsoleActions.includes(action)) throw new Error("invalid_action");
1370
1416
  if (action === "finish" && payload?.confirmed !== true) throw new Error("confirmation_required");
@@ -1377,6 +1423,10 @@ var TravelConsoleManager = class {
1377
1423
  if (action === "finish") return { ok: true, connected: true, snapshot };
1378
1424
  throw new Error("retired");
1379
1425
  }
1426
+ if (["sync", "recover", "finish"].includes(action)) {
1427
+ operationId = randomUUID3();
1428
+ this.operation = { id: operationId, action, state: "RUNNING", startedAt: Date.now(), updatedAt: Date.now() };
1429
+ }
1380
1430
  if (action === "auto_on" || action === "auto_off") {
1381
1431
  if (snapshot.retirement) throw new Error("retired");
1382
1432
  if (snapshot.active === "unknown") throw new Error("not_ready");
@@ -1408,12 +1458,14 @@ var TravelConsoleManager = class {
1408
1458
  await this.options.retirement.finish();
1409
1459
  }
1410
1460
  }
1461
+ if (this.operation?.id === operationId && this.operation?.state === "RUNNING") this.operation = { ...this.operation, state: "DONE", updatedAt: Date.now() };
1411
1462
  } finally {
1412
1463
  this.changing = false;
1413
1464
  }
1414
1465
  return { ok: true, connected: true, snapshot: await this.snapshot() };
1415
1466
  } catch (error) {
1416
1467
  const message = error.message, code = travelConsoleErrors.has(message) ? message : /RECOVERY/.test(message) ? "recovery_required" : /BUSY|HANDOFF_STATE|COLLISION/.test(message) ? "busy" : "service_unavailable";
1468
+ if (this.operation?.id === operationId && this.operation?.state === "RUNNING") this.operation = { ...this.operation, state: "FAILED", updatedAt: Date.now(), error: code };
1417
1469
  const reason = typeof message === "string" && /^[A-Z][A-Z0-9_]{0,95}$/.test(message) ? message : code;
1418
1470
  process.stderr.write("[travel-console-operation] " + JSON.stringify({ at: Date.now(), action: travelConsoleActions.includes(action) ? action : "OTHER", reason }) + "\n");
1419
1471
  return { ok: false, connected: true, error: code };
@@ -1555,17 +1607,17 @@ function createTravelConsoleServer(options) {
1555
1607
  }
1556
1608
 
1557
1609
  // 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";
1559
- 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";
1610
+ import { existsSync as existsSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync3, renameSync, realpathSync as realpathSync5, unlinkSync as unlinkSync2 } from "node:fs";
1611
+ import { DatabaseSync as DatabaseSync11 } from "node:sqlite";
1612
+ import { dirname as dirname5, join as join9, isAbsolute as isAbsolute6, resolve as resolve7 } from "node:path";
1613
+ import { createHash as createHash7, randomUUID as randomUUID5 } from "node:crypto";
1562
1614
 
1563
1615
  // src/continuity/retirement-main.ts
1564
- import { readFileSync as readFileSync7, existsSync as existsSync3 } from "node:fs";
1616
+ import { readFileSync as readFileSync6, existsSync as existsSync3 } from "node:fs";
1565
1617
  import { isAbsolute as isAbsolute5, resolve as resolve6 } from "node:path";
1566
1618
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1567
- import { execFile } from "node:child_process";
1568
- import { promisify } from "node:util";
1619
+ import { execFile as execFile2 } from "node:child_process";
1620
+ import { promisify as promisify2 } from "node:util";
1569
1621
  import { createHash as createHash6 } from "node:crypto";
1570
1622
 
1571
1623
  // src/continuity/user-seat-resource.ts
@@ -1587,11 +1639,13 @@ var UserSeatResource = class {
1587
1639
  return new Promise((done, reject) => {
1588
1640
  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
1641
  const chunks = [];
1590
- let bytes = 0;
1642
+ let bytes = 0, stderr = "";
1591
1643
  const timer = setTimeout(() => child.kill("SIGKILL"), 12e4);
1592
1644
  child.stdin.on("error", () => {
1593
1645
  });
1594
- child.stderr.resume();
1646
+ child.stderr.on("data", (chunk) => {
1647
+ stderr = (stderr + chunk.toString()).slice(-4096);
1648
+ });
1595
1649
  child.stdout.on("data", (chunk) => {
1596
1650
  bytes += chunk.length;
1597
1651
  if (bytes > 64 * 1024 * 1024) child.kill("SIGKILL");
@@ -1601,7 +1655,9 @@ var UserSeatResource = class {
1601
1655
  child.once("close", (code) => {
1602
1656
  clearTimeout(timer);
1603
1657
  if (code !== 0) {
1604
- reject(new Error("TRAVEL_RETIREMENT_PROVIDER_PENDING"));
1658
+ const reason = stderr.match(/TRAVEL_RETIREMENT_RESOURCE_REFUSED ([A-Z][A-Z0-9_]{0,95})(?:\s|$)/)?.[1];
1659
+ if (reason) process.stderr.write("[travel-retirement-resource] " + JSON.stringify({ action, reason }) + "\n");
1660
+ reject(new Error(reason?.startsWith("TRAVEL_") ? reason : "TRAVEL_RETIREMENT_PROVIDER_PENDING"));
1605
1661
  return;
1606
1662
  }
1607
1663
  try {
@@ -1624,11 +1680,11 @@ var UserSeatResource = class {
1624
1680
  };
1625
1681
 
1626
1682
  // src/continuity/retirement.ts
1627
- import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
1683
+ import { DatabaseSync as DatabaseSync8 } from "node:sqlite";
1628
1684
  import { createHash as createHash2 } from "node:crypto";
1629
1685
  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";
1686
+ import { accessSync, constants as constants4, lstatSync as lstatSync3, readdirSync, readFileSync as readFileSync3, readlinkSync, realpathSync as realpathSync2, rmSync } from "node:fs";
1687
+ import { dirname as dirname2, isAbsolute as isAbsolute3, join as join5, resolve as resolve4, relative } from "node:path";
1632
1688
  var identity = (value) => JSON.stringify([value.tenantId, value.companionId, value.seatId]);
1633
1689
  var sha = (value) => createHash2("sha256").update(value).digest("hex");
1634
1690
  var LocalSeatResource = class {
@@ -1659,19 +1715,29 @@ var LocalSeatResource = class {
1659
1715
  else if (item.isDirectory()) visit(path3);
1660
1716
  else if (item.isFile()) {
1661
1717
  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)) });
1718
+ result.push({ version, digest: sha(readFileSync3(path3)) });
1663
1719
  } else throw new Error("TRAVEL_RETIREMENT_PATH");
1664
1720
  if (result.length > 1e6) throw new Error("TRAVEL_RETIREMENT_BUDGET");
1665
1721
  }
1666
1722
  };
1667
1723
  visit(this.path);
1668
- return result;
1724
+ return result.length === 1 && result[0].version === ".travel-seat-resource.json" ? [] : result;
1669
1725
  }
1670
1726
  async purge(expectedInventory) {
1671
1727
  const allowed = new Map(expectedInventory.map((item) => [item.version, item.digest]));
1672
1728
  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");
1729
+ if (this.check()) {
1730
+ let removeRoot = true;
1731
+ try {
1732
+ accessSync(dirname2(this.path), constants4.W_OK);
1733
+ } catch (error) {
1734
+ if (error.code !== "EACCES") throw error;
1735
+ removeRoot = false;
1736
+ }
1737
+ if (removeRoot) rmSync(this.path, { recursive: true });
1738
+ else for (const name of readdirSync(this.path)) if (name !== ".travel-seat-resource.json") rmSync(join5(this.path, name), { recursive: true });
1739
+ }
1740
+ if (this.inventoryNow().length) throw new Error("TRAVEL_RETIREMENT_PENDING");
1675
1741
  }
1676
1742
  };
1677
1743
  var TravelRetirement = class {
@@ -1681,7 +1747,7 @@ var TravelRetirement = class {
1681
1747
  preparePrivateDirectory(options.directory);
1682
1748
  const ownerFile = join5(options.directory, "owner.sqlite");
1683
1749
  preparePrivateDatabase(ownerFile);
1684
- this.owner = new DatabaseSync7(ownerFile);
1750
+ this.owner = new DatabaseSync8(ownerFile);
1685
1751
  try {
1686
1752
  this.owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER);BEGIN IMMEDIATE");
1687
1753
  } catch (error) {
@@ -1690,7 +1756,7 @@ var TravelRetirement = class {
1690
1756
  }
1691
1757
  const file = join5(options.directory, "retirement.sqlite");
1692
1758
  preparePrivateDatabase(file);
1693
- this.db = new DatabaseSync7(file);
1759
+ this.db = new DatabaseSync8(file);
1694
1760
  try {
1695
1761
  this.db.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS job(id TEXT PRIMARY KEY,binding TEXT NOT NULL,state TEXT NOT NULL,stopped INTEGER NOT NULL DEFAULT 0);CREATE TABLE IF NOT EXISTS resources(id TEXT PRIMARY KEY,inventory TEXT,state TEXT NOT NULL)");
1696
1762
  const binding = JSON.stringify([identity(options.identity), options.resources.map((resource) => [resource.id, resource.path ?? null]).sort(), options.accountOwnerRequestedKeyDestruction === true]);
@@ -1757,7 +1823,8 @@ var TravelRetirement = class {
1757
1823
  row = this.db.prepare("SELECT * FROM resources WHERE id=?").get(resource.id);
1758
1824
  }
1759
1825
  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");
1826
+ const allowed = new Map(original.map((item) => [item.version, item.digest]));
1827
+ if (current.some((item) => allowed.get(item.version) !== item.digest)) throw new Error("TRAVEL_RETIREMENT_RESOURCE_CHANGED");
1761
1828
  await verifyRecovery(true);
1762
1829
  await resource.purge(original);
1763
1830
  if ((await resource.inventory()).length) throw new Error("TRAVEL_RETIREMENT_PROVIDER_PENDING");
@@ -1783,22 +1850,22 @@ var TravelRetirement = class {
1783
1850
  };
1784
1851
 
1785
1852
  // 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";
1787
- import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
1788
- import { isAbsolute as isAbsolute4, join as join8, dirname as dirname3, resolve as resolve5 } from "node:path";
1853
+ 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";
1854
+ import { DatabaseSync as DatabaseSync10 } from "node:sqlite";
1855
+ import { isAbsolute as isAbsolute4, join as join8, dirname as dirname4, resolve as resolve5 } from "node:path";
1789
1856
  import { createHash as createHash5, verify as verify2 } from "node:crypto";
1790
1857
 
1791
1858
  // src/continuity/runtime-lock.ts
1792
- import { randomUUID as randomUUID3 } from "node:crypto";
1859
+ import { randomUUID as randomUUID4 } from "node:crypto";
1793
1860
  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";
1861
+ import { closeSync as closeSync3, lstatSync as lstatSync4, mkdirSync as mkdirSync3, openSync as openSync3, readFileSync as readFileSync4, realpathSync as realpathSync3 } from "node:fs";
1795
1862
  import { join as join6 } from "node:path";
1796
1863
  import { createRequire } from "node:module";
1797
1864
  var sqlite;
1798
1865
  function openSQLite(file, options = {}) {
1799
1866
  return new (sqlite ??= createRequire(import.meta.url)("node:sqlite")).DatabaseSync(file, options);
1800
1867
  }
1801
- var bootId = randomUUID3();
1868
+ var bootId = randomUUID4();
1802
1869
  var checkpointHandles = /* @__PURE__ */ new Set();
1803
1870
  var recoveryWriterLocks = new AsyncLocalStorage();
1804
1871
  var initialBaselineAdmission = new AsyncLocalStorage();
@@ -1866,7 +1933,7 @@ async function withCheckpointLock(stateDir, operation) {
1866
1933
  for (const name of [".engine.pid", ".bg-worker.pid"]) {
1867
1934
  let value;
1868
1935
  try {
1869
- value = readFileSync5(join6(stateDir, name), "utf8").trim();
1936
+ value = readFileSync4(join6(stateDir, name), "utf8").trim();
1870
1937
  } catch (error) {
1871
1938
  if (error.code === "ENOENT") continue;
1872
1939
  throw new Error("WRITER_STATE_UNKNOWN", { cause: error });
@@ -1887,18 +1954,18 @@ async function withCheckpointLock(stateDir, operation) {
1887
1954
  }
1888
1955
 
1889
1956
  // src/continuity/local-dedupe.ts
1890
- import { DatabaseSync as DatabaseSync8 } from "node:sqlite";
1957
+ import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
1891
1958
  import { createHash as createHash3 } from "node:crypto";
1892
- import { dirname as dirname2 } from "node:path";
1959
+ import { dirname as dirname3 } from "node:path";
1893
1960
  var sha2 = (value) => createHash3("sha256").update(value).digest("hex");
1894
1961
  var hash = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
1895
1962
  var PlatformReceiptStore = class {
1896
1963
  db;
1897
1964
  constructor(file, namespace) {
1898
1965
  if (!namespace || namespace.length > 1024) throw new Error("PLATFORM_RECEIPT_IDENTITY");
1899
- preparePrivateDirectory(dirname2(file));
1966
+ preparePrivateDirectory(dirname3(file));
1900
1967
  preparePrivateDatabase(file);
1901
- this.db = new DatabaseSync8(file);
1968
+ this.db = new DatabaseSync9(file);
1902
1969
  try {
1903
1970
  this.db.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS binding(namespace TEXT NOT NULL);CREATE TABLE IF NOT EXISTS inputs(id TEXT PRIMARY KEY,state TEXT NOT NULL);CREATE TABLE IF NOT EXISTS effects(id TEXT PRIMARY KEY,body TEXT NOT NULL);CREATE TABLE IF NOT EXISTS imports(digest TEXT PRIMARY KEY,identity TEXT NOT NULL)");
1904
1971
  const binding = this.db.prepare("SELECT namespace FROM binding").all();
@@ -1957,7 +2024,7 @@ var PlatformReceiptStore = class {
1957
2024
 
1958
2025
  // src/continuity/local-exit-proof.ts
1959
2026
  import { createHash as createHash4, verify } from "node:crypto";
1960
- import { createReadStream, mkdirSync as mkdirSync4, readdirSync as readdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
2027
+ import { createReadStream, mkdirSync as mkdirSync4, readdirSync as readdirSync2, writeFileSync } from "node:fs";
1961
2028
  import { join as join7, relative as relative2 } from "node:path";
1962
2029
  var hash2 = (value) => createHash4("sha256").update(value).digest("hex");
1963
2030
  var equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
@@ -2028,7 +2095,7 @@ function detachReplication(directory) {
2028
2095
  }
2029
2096
  if (!entry.isFile()) throw new Error("TRAVEL_EXIT_PATH");
2030
2097
  if (!/\.(?:db|sqlite)$/.test(entry.name)) continue;
2031
- const db = new DatabaseSync9(file);
2098
+ const db = new DatabaseSync10(file);
2032
2099
  try {
2033
2100
  if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='e7_replication_control'").get()) continue;
2034
2101
  db.exec("BEGIN IMMEDIATE");
@@ -2046,8 +2113,8 @@ function detachReplication(directory) {
2046
2113
  }
2047
2114
  async function createOrdinaryLocalRecovery(options) {
2048
2115
  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;
2116
+ 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");
2117
+ const activation = JSON.parse(readFileSync5(join8(source, ".travel-active.json"), "utf8")), permit = activation.permit, { signature, ...signed } = permit;
2051
2118
  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
2119
  return withCheckpointLock(source, async () => {
2053
2120
  if (!options.authority || !options.principal || options.authority.publicKey !== options.publicKey) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
@@ -2089,7 +2156,7 @@ async function createOrdinaryLocalRecovery(options) {
2089
2156
  await proof.check();
2090
2157
  const body = { ...receipt, ordinaryFilesDigest: await localExitFilesDigest(destination, true) };
2091
2158
  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 });
2159
+ writeFileSync2(join8(destination, ".continuity/travel-exit-receipt.json"), JSON.stringify(result), { mode: 384, flag: "wx", flush: true });
2093
2160
  return result;
2094
2161
  } catch (error) {
2095
2162
  if (existsSync2(destination)) rmSync2(destination, { recursive: true });
@@ -2099,7 +2166,7 @@ async function createOrdinaryLocalRecovery(options) {
2099
2166
  }
2100
2167
 
2101
2168
  // src/continuity/retirement-main.ts
2102
- var command = promisify(execFile);
2169
+ var command = promisify2(execFile2);
2103
2170
  var sha4 = (value) => createHash6("sha256").update(value).digest("hex");
2104
2171
  var path2 = (value) => {
2105
2172
  if (typeof value !== "string" || !isAbsolute5(value) || resolve6(value) !== value) throw new Error("TRAVEL_RETIREMENT_PATH");
@@ -2110,7 +2177,7 @@ async function runTravelRetirementCli(args) {
2110
2177
  if (args.length !== 3 || !["run", "recover-local"].includes(args[0]) || args[1] !== "--config") throw new Error("TRAVEL_RETIREMENT_INVALID_COMMAND");
2111
2178
  const config = JSON.parse(readPrivateFile(path2(args[2]), 4 * 1024 * 1024).toString());
2112
2179
  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) });
2180
+ 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
2181
  try {
2115
2182
  const { principal, publicKey } = await client2.retirementStatus();
2116
2183
  if (publicKey !== config.publicKey) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
@@ -2125,7 +2192,7 @@ async function runTravelRetirementCli(args) {
2125
2192
  }
2126
2193
  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
2194
  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) });
2195
+ 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
2196
  let job, keys;
2130
2197
  try {
2131
2198
  const control = await client.retirementStatus();
@@ -2179,10 +2246,10 @@ var sameIdentity = (a, b) => a && ["tenantId", "companionId", "seatId"].every((k
2179
2246
  var sourceBinding = (source) => source ? ["activeNodeId", "activeBootId", "authorityBootId", "epoch", "checkpointDigest", "deletionWatermark"].map((key) => source[key]) : null;
2180
2247
  function createTravelConsoleRetirement(options) {
2181
2248
  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");
2249
+ const config = JSON.parse(readPrivateFile(options.configFile, 4 * 1024 * 1024).toString()), original = readFileSync7(options.configFile);
2250
+ 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
2251
  const assertConfig = () => {
2185
- if (!readFileSync8(options.configFile).equals(original)) throw new Error("TRAVEL_CONSOLE_CONFIG_CHANGED");
2252
+ if (!readFileSync7(options.configFile).equals(original)) throw new Error("TRAVEL_CONSOLE_CONFIG_CHANGED");
2186
2253
  };
2187
2254
  preparePrivateDirectory(config.directory);
2188
2255
  const pendingFile = join9(config.directory, "console-recovery.json");
@@ -2193,12 +2260,12 @@ function createTravelConsoleRetirement(options) {
2193
2260
  return value;
2194
2261
  };
2195
2262
  const savePending = (state, source) => {
2196
- const temp = pendingFile + "." + randomUUID4();
2263
+ const temp = pendingFile + "." + randomUUID5();
2197
2264
  try {
2198
- writeFileSync4(temp, JSON.stringify({ identity: options.identity, jobId: config.jobId, state, source: sourceBinding(source) }), { mode: 384, flag: "wx", flush: true });
2265
+ writeFileSync3(temp, JSON.stringify({ identity: options.identity, jobId: config.jobId, state, source: sourceBinding(source) }), { mode: 384, flag: "wx", flush: true });
2199
2266
  renameSync(temp, pendingFile);
2200
2267
  } finally {
2201
- if (existsSync4(temp)) unlinkSync3(temp);
2268
+ if (existsSync4(temp)) unlinkSync2(temp);
2202
2269
  }
2203
2270
  };
2204
2271
  const verify3 = async (value) => {
@@ -2222,7 +2289,7 @@ function createTravelConsoleRetirement(options) {
2222
2289
  const prepared = pending();
2223
2290
  return existsSync4(config.localRecoveryReceiptFile) || prepared ? { jobId: config.jobId, state: recovery === "ready" ? "LOCAL_READY" : prepared?.state ?? "RECOVERY_REQUIRED", recovery } : void 0;
2224
2291
  }
2225
- const db = new DatabaseSync10(file, { readOnly: true });
2292
+ const db = new DatabaseSync11(file, { readOnly: true });
2226
2293
  try {
2227
2294
  const row = db.prepare("SELECT id,state,stopped FROM job").get();
2228
2295
  if (!row || row.id !== config.jobId) throw new Error("TRAVEL_CONSOLE_CONFIG");
@@ -2246,15 +2313,15 @@ function createTravelConsoleRetirement(options) {
2246
2313
  savePending("LOCAL_STOPPED", stopped.source);
2247
2314
  return;
2248
2315
  }
2249
- const proof = await verify3(value), file = config.localRecoveryReceiptFile, temp = file + "." + randomUUID4();
2316
+ const proof = await verify3(value), file = config.localRecoveryReceiptFile, temp = file + "." + randomUUID5();
2250
2317
  try {
2251
- writeFileSync4(temp, JSON.stringify(proof), { mode: 384, flag: "wx", flush: true });
2318
+ writeFileSync3(temp, JSON.stringify(proof), { mode: 384, flag: "wx", flush: true });
2252
2319
  await verify3(proof);
2253
2320
  renameSync(temp, file);
2254
2321
  } finally {
2255
2322
  if (existsSync4(temp)) {
2256
- const { unlinkSync: unlinkSync4 } = await import("node:fs");
2257
- unlinkSync4(temp);
2323
+ const { unlinkSync: unlinkSync3 } = await import("node:fs");
2324
+ unlinkSync3(temp);
2258
2325
  }
2259
2326
  }
2260
2327
  },
@@ -2289,7 +2356,7 @@ function openTravelConsole(input) {
2289
2356
  manager,
2290
2357
  identity: identity3,
2291
2358
  token: readPrivateFile(privatePath(input.tokenFile), 1024).toString().trim(),
2292
- cert: readFileSync9(privatePath(input.tls.certFile)),
2359
+ cert: readFileSync8(privatePath(input.tls.certFile)),
2293
2360
  key: readPrivateFile(privatePath(input.tls.keyFile), 65536)
2294
2361
  });
2295
2362
  let closing;