engine7 7.1.137 → 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,8 +1,8 @@
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";
5
- import { isAbsolute as isAbsolute6, resolve as resolve7 } from "node:path";
4
+ import { readFileSync as readFileSync8 } from "node:fs";
5
+ import { isAbsolute as isAbsolute7, resolve as resolve8 } from "node:path";
6
6
  import { fileURLToPath as fileURLToPath3 } from "node:url";
7
7
 
8
8
  // src/continuity/key-service-store.ts
@@ -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);
@@ -361,7 +357,7 @@ var TravelController = class {
361
357
  if (!binding.length) this.db.prepare("INSERT INTO binding VALUES(?)").run(identity3);
362
358
  else if (binding.length !== 1 || binding[0].identity !== identity3) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
363
359
  this.db.prepare("INSERT OR IGNORE INTO preferences VALUES(1,?)").run(options.preferredNodeId);
364
- this.db.exec("INSERT OR IGNORE INTO automatic VALUES(1,1)");
360
+ this.db.prepare("INSERT OR IGNORE INTO automatic VALUES(1,?)").run(options.initialAutomatic === false ? 0 : 1);
365
361
  if (!options.nodes[this.preferredNodeId()]) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
366
362
  if (this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_CONTROLLER_RECOVERY_REQUIRED");
367
363
  } catch (error) {
@@ -431,6 +427,39 @@ var TravelController = class {
431
427
  });
432
428
  return this.active;
433
429
  }
430
+ /** Manual synchronization shares the controller's mutation slot with ticks
431
+ * and handoffs, and leaves the owner's automatic preference untouched. */
432
+ synchronize() {
433
+ if (this.closed) return Promise.reject(new Error("TRAVEL_CONTROLLER_CLOSED"));
434
+ if (this.active || this.job()) return Promise.reject(new Error("TRAVEL_NODE_BUSY"));
435
+ const operation = (async () => {
436
+ const reference = this.options.nodes[this.preferredNodeId()];
437
+ const current = await this.options.authority.status(reference.principal);
438
+ const source = current.activeNodeId ? this.options.nodes[current.activeNodeId] : void 0;
439
+ if (current.expired || !source || !source.synchronize) throw new Error("not_ready");
440
+ const target = Object.values(this.options.nodes).find((node) => node !== source);
441
+ const observations = await Promise.all([source.observe(), target.observe()]);
442
+ if (observations.some((node) => !node.connected || node.busy) || !observations[0].running) throw new Error("not_ready");
443
+ const permit = await source.permit();
444
+ await this.options.authority.assertPermit(permit, "CONTROL");
445
+ const assertSource = async () => {
446
+ const renewed = await source.permit();
447
+ if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((field) => renewed[field] !== permit[field])) throw new Error("TRAVEL_CONTROLLER_COMMIT_SUPERSEDED");
448
+ await this.options.authority.assertPermit(renewed, "CONTROL");
449
+ };
450
+ if (!await this.replicate(source, target)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
451
+ await assertSource();
452
+ await source.synchronize();
453
+ await assertSource();
454
+ })();
455
+ this.active = operation.catch((error) => {
456
+ this.lastError = error instanceof Error && /^TRAVEL_[A-Z_]+$/.test(error.message) ? error.message : "TRAVEL_CONTROLLER_OPERATION_FAILED";
457
+ throw error;
458
+ }).finally(() => {
459
+ this.active = void 0;
460
+ });
461
+ return this.active;
462
+ }
434
463
  async launch(node, permit, checkpoint) {
435
464
  const prior = this.db.prepare("SELECT checkpoint FROM starts WHERE node=? AND boot=? AND epoch=?").get(permit.nodeId, permit.bootId, permit.epoch);
436
465
  if (prior) {
@@ -481,19 +510,28 @@ var TravelController = class {
481
510
  this.healthySince = null;
482
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"));
483
512
  let node;
513
+ let missingCheckpoint = false;
484
514
  for (const candidate of candidates) if ((await candidate.observe()).connected === true) {
485
- node = candidate;
486
- 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;
487
527
  }
488
- if (!node) return;
489
- await node.pinBranch(status.checkpointDigest);
490
528
  const ready = await node.prepare(status.checkpointDigest);
491
529
  const latest = await this.options.authority.status(node.principal);
492
530
  if (latest.authorityBootId !== status.authorityBootId || latest.epoch !== status.epoch || latest.checkpointDigest !== status.checkpointDigest || latest.deletionWatermark !== status.deletionWatermark || latest.activeNodeId && !latest.expired) return;
493
531
  const permit = await this.options.authority.acquire(node.principal, ready);
494
532
  await this.launch(node, permit, status.checkpointDigest);
495
533
  }
496
- async replicate(source, target) {
534
+ async replicate(source, target, recheckBranches = false) {
497
535
  if (!source.replicationOffer || !source.connectReplica || !target.replicaProfile || !target.bootstrapReplica) return true;
498
536
  const offer = await source.replicationOffer();
499
537
  if (!offer) return true;
@@ -513,8 +551,11 @@ var TravelController = class {
513
551
  if (!profile || JSON.stringify(profile) !== JSON.stringify(offer.profile)) throw new Error("TRAVEL_CONTROLLER_REPLICA");
514
552
  await assertSource();
515
553
  await source.connectReplica(profile);
516
- const recovered = await source.recoverBranches?.();
517
- 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;
518
559
  }
519
560
  async advance(job) {
520
561
  const target = this.options.nodes[job.target], control = this.options.authority;
@@ -528,7 +569,7 @@ var TravelController = class {
528
569
  }
529
570
  const source2 = this.options.nodes[status.activeNodeId];
530
571
  if (!source2) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
531
- if (!await this.replicate(source2, target)) return;
572
+ if (!await this.replicate(source2, target, true)) return;
532
573
  this.db.prepare("UPDATE jobs SET source=?,state='PREPARING' WHERE id=?").run(source2.principal.nodeId, job.id);
533
574
  await control.beginHandoff(source2.principal, await source2.permit(), job.id, job.target);
534
575
  return;
@@ -615,14 +656,16 @@ var TravelController = class {
615
656
  this.timer = setTimeout(() => {
616
657
  this.timer = void 0;
617
658
  const started = this.clock();
618
- void this.tick().finally(() => this.schedule(this.interval - (this.clock() - started) % this.interval));
659
+ void this.tick().catch(() => {
660
+ }).finally(() => this.schedule(this.interval - (this.clock() - started) % this.interval));
619
661
  }, delay);
620
662
  }
621
663
  async stop() {
622
664
  this.running = false;
623
665
  if (this.timer) clearTimeout(this.timer);
624
666
  this.timer = void 0;
625
- await this.active;
667
+ await this.active?.catch(() => {
668
+ });
626
669
  }
627
670
  close() {
628
671
  if (this.closed) return;
@@ -723,9 +766,12 @@ var TravelReportClient = class {
723
766
  this.timeout = options.timeoutMs ?? 8e3;
724
767
  if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
725
768
  this.key = options.key ? Buffer.from(options.key) : void 0;
726
- 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 });
727
772
  }
728
773
  agent;
774
+ mutationAgent;
729
775
  key;
730
776
  url;
731
777
  timeout;
@@ -742,7 +788,7 @@ var TravelReportClient = class {
742
788
  const unavailable = () => new Error(this.closed ? "TRAVEL_CONTROL_CLOSED" : "TRAVEL_CONTROL_UNAVAILABLE");
743
789
  const remaining = deadline - performance.now();
744
790
  if (remaining <= 0) return Promise.reject(unavailable());
745
- return new Promise((resolve8, reject) => {
791
+ return new Promise((resolve9, reject) => {
746
792
  let complete = false, responseStarted = false;
747
793
  const finish = (error, value) => {
748
794
  if (complete) return;
@@ -750,9 +796,9 @@ var TravelReportClient = class {
750
796
  clearTimeout(timer);
751
797
  this.pending.delete(req);
752
798
  if (error) reject(error);
753
- else resolve8(value);
799
+ else resolve9(value);
754
800
  };
755
- 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: {
756
802
  Authorization: "Bearer " + this.options.credential,
757
803
  "X-Engine7-Travel-Node": this.options.nodeId,
758
804
  "Content-Type": "application/json",
@@ -803,7 +849,7 @@ var TravelReportClient = class {
803
849
  complete = true;
804
850
  clearTimeout(timer);
805
851
  this.pending.delete(req);
806
- resolve8(this.attempt(input, false, deadline, body));
852
+ resolve9(this.attempt(input, false, deadline, body));
807
853
  } else finish(unavailable());
808
854
  });
809
855
  req.once("close", () => {
@@ -827,6 +873,7 @@ var TravelReportClient = class {
827
873
  this.closed = true;
828
874
  for (const req of this.pending) req.destroy();
829
875
  this.agent.destroy();
876
+ this.mutationAgent.destroy();
830
877
  this.key?.fill(0);
831
878
  }
832
879
  };
@@ -853,6 +900,9 @@ var TravelManagementClient = class extends TravelReportClient {
853
900
  if (url.pathname !== "/travel/manage/v1") throw new Error("TRAVEL_MANAGEMENT_ENDPOINT_REQUIRED");
854
901
  super(options);
855
902
  }
903
+ async bindInitialCheckpoint(digest, buildManifestId) {
904
+ await this.call({ action: "bindInitialCheckpoint", digest, buildManifestId });
905
+ }
856
906
  async verifyAncestor(ancestor, descendant) {
857
907
  await this.call({ action: "verifyAncestor", ancestor, descendant });
858
908
  }
@@ -874,6 +924,9 @@ var TravelManagementClient = class extends TravelReportClient {
874
924
  async assertPermit(permit, operation) {
875
925
  await this.call({ action: "assertPermit", permit, operation });
876
926
  }
927
+ async assertPermitWithStatus(permit, operation) {
928
+ return (await this.call({ action: "assertPermit", permit, operation })).status;
929
+ }
877
930
  async acquire(ready) {
878
931
  return (await this.call({ action: "acquire", ready })).permit;
879
932
  }
@@ -908,7 +961,14 @@ import { Agent as Agent2, request as request2 } from "node:https";
908
961
 
909
962
  // src/continuity/publication.ts
910
963
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
911
- 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;
912
972
  var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
913
973
  var ZERO = "0".repeat(64);
914
974
 
@@ -921,6 +981,7 @@ var nodeSupervisorErrors = /* @__PURE__ */ new Set([
921
981
  "TRAVEL_NODE_CANCELLED",
922
982
  "TRAVEL_NODE_BOOT_MISMATCH",
923
983
  "TRAVEL_NODE_CHECKPOINT",
984
+ "TRAVEL_NODE_COMMON_CHECKPOINT",
924
985
  "TRAVEL_NODE_GENERATION_COLLISION",
925
986
  "TRAVEL_NODE_KEY_UNAVAILABLE",
926
987
  "TRAVEL_NODE_KEY_BARRIER",
@@ -971,31 +1032,53 @@ var RemoteTravelNodeSupervisor = class {
971
1032
  observeQuery;
972
1033
  permitQuery;
973
1034
  closed = false;
974
- call(action, args = {}, discover = false) {
1035
+ call(action, args = {}, discover = false, retryStale = true, deadline, wireBody) {
975
1036
  if (this.closed) return Promise.reject(new Error("TRAVEL_NODE_CLOSED"));
976
1037
  const slot = action === "stop" ? "stop" : action === "observe" ? "observe" : action === "permit" ? "permit" : "operation";
977
1038
  if ([...this.pending.values()].includes(slot)) return Promise.reject(new Error("TRAVEL_NODE_BUSY"));
978
- 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 } }));
979
1040
  if (body.length > nodeSupervisorLimit) return Promise.reject(new Error("TRAVEL_NODE_INVALID_REQUEST"));
980
1041
  const unavailable = () => new Error(this.closed ? "TRAVEL_NODE_CLOSED" : "TRAVEL_NODE_UNAVAILABLE");
981
- return new Promise((resolve8, reject) => {
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());
1045
+ return new Promise((resolve9, reject) => {
1046
+ const started = performance.now();
1047
+ let responseStarted = false, receivedBytes = 0, reported = false;
1048
+ const lost = (code) => {
1049
+ if (!reported && slot !== "observe") process.stderr.write("[travel-node-client] " + JSON.stringify({
1050
+ at: Date.now(),
1051
+ action,
1052
+ nodeId: this.principal.nodeId,
1053
+ phase: responseStarted ? "response" : "request",
1054
+ elapsedMs: Math.round(performance.now() - started),
1055
+ receivedBytes,
1056
+ reusedSocket: req.reusedSocket,
1057
+ code: typeof code === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : "OTHER"
1058
+ }) + "\n");
1059
+ reported = true;
1060
+ reject(unavailable());
1061
+ };
982
1062
  const req = request2(this.url, { method: "POST", agent: this.agents[slot], headers: {
983
1063
  Authorization: "Bearer " + this.options.credential,
984
1064
  "X-Engine7-Travel-Node": this.principal.nodeId,
985
1065
  "Content-Type": "application/json",
986
1066
  "Content-Length": body.length
987
1067
  } }, (res) => {
1068
+ responseStarted = true;
988
1069
  const parts = [];
989
1070
  let bytes = 0;
990
1071
  res.on("data", (part) => {
991
1072
  bytes += part.length;
1073
+ receivedBytes = bytes;
992
1074
  if (bytes > nodeSupervisorLimit) {
993
1075
  req.destroy();
994
1076
  reject(new Error("TRAVEL_NODE_INVALID_RESPONSE"));
995
1077
  } else parts.push(part);
996
1078
  });
997
- res.once("error", () => reject(unavailable()));
1079
+ res.once("error", (error) => lost(error.code));
998
1080
  res.once("end", () => {
1081
+ reported = true;
999
1082
  cleanup();
1000
1083
  if (this.closed) {
1001
1084
  reject(unavailable());
@@ -1018,21 +1101,24 @@ var RemoteTravelNodeSupervisor = class {
1018
1101
  return;
1019
1102
  }
1020
1103
  if (discover) this.bootId = response.bootId;
1021
- resolve8(response.result);
1104
+ resolve9(response.result);
1022
1105
  });
1023
1106
  });
1024
1107
  this.pending.set(req, slot);
1025
1108
  const timer = setTimeout(() => {
1109
+ lost("TIMEOUT");
1026
1110
  req.destroy();
1027
- reject(unavailable());
1028
- }, slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
1111
+ }, remaining);
1029
1112
  const cleanup = () => {
1030
1113
  clearTimeout(timer);
1031
1114
  this.pending.delete(req);
1032
1115
  };
1033
- req.once("error", () => {
1116
+ req.once("error", (error) => {
1034
1117
  cleanup();
1035
- reject(unavailable());
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);
1036
1122
  });
1037
1123
  req.once("close", cleanup);
1038
1124
  req.end(body);
@@ -1102,6 +1188,9 @@ var RemoteTravelNodeSupervisor = class {
1102
1188
  recoverBranches() {
1103
1189
  return this.invoke("recoverBranches");
1104
1190
  }
1191
+ synchronize() {
1192
+ return this.invoke("synchronize");
1193
+ }
1105
1194
  close() {
1106
1195
  if (this.closed) return;
1107
1196
  this.closed = true;
@@ -1114,6 +1203,9 @@ var RemoteTravelNodeSupervisor = class {
1114
1203
  // src/continuity/publication-transport.ts
1115
1204
  var BODY_LIMIT = PUBLICATION_MANIFEST_BYTES + 65536;
1116
1205
 
1206
+ // src/continuity/recovery-archive-transfer.ts
1207
+ import { gzipSync, gunzipSync, createGunzip, brotliCompressSync, brotliDecompressSync, createBrotliCompress, createBrotliDecompress, constants as constants3 } from "node:zlib";
1208
+
1117
1209
  // src/continuity/recovery-archive.ts
1118
1210
  import { DatabaseSync as DatabaseSync5, backup } from "node:sqlite";
1119
1211
 
@@ -1122,10 +1214,11 @@ var MAGIC2 = Buffer.from("E7OBJ001");
1122
1214
  var HEADER_SIZE = MAGIC2.length + 12;
1123
1215
 
1124
1216
  // src/continuity/recovery-archive.ts
1125
- var MAX_METADATA = 16 * 1024 * 1024;
1217
+ var RECOVERY_ARCHIVE_METADATA_BYTES = PUBLICATION_MANIFEST_BYTES + 8 * 1024 * 1024;
1126
1218
 
1127
1219
  // src/continuity/recovery-archive-transfer.ts
1128
- 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 } };
1129
1222
 
1130
1223
  // src/continuity/controller-main.ts
1131
1224
  var path = (value) => {
@@ -1143,7 +1236,7 @@ function openTravelController(input) {
1143
1236
  privateKey.fill(0);
1144
1237
  };
1145
1238
  try {
1146
- 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 };
1147
1240
  for (const [nodeId, value] of Object.entries(config.nodes)) {
1148
1241
  if (!nodeSupervisorId(nodeId) || !nodeSupervisorRecord(value) || !nodeSupervisorRecord(value.principal) || value.principal.nodeId !== nodeId) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
1149
1242
  const principal = value.principal;
@@ -1156,6 +1249,7 @@ function openTravelController(input) {
1156
1249
  authority,
1157
1250
  nodes,
1158
1251
  preferredNodeId: config.preferredNodeId,
1252
+ initialAutomatic: config.initialAutomatic,
1159
1253
  intervalMs: config.intervalMs,
1160
1254
  healthyForMs: config.healthyForMs,
1161
1255
  handbackCooldownMs: config.handbackCooldownMs
@@ -1213,7 +1307,8 @@ if (process.argv[1] && /[\\/](controller-main\.ts|travel-controller\.mjs)$/.test
1213
1307
  // src/continuity/console-manager.ts
1214
1308
  import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
1215
1309
  import { join as join4 } from "node:path";
1216
- var travelConsoleActions = ["status", "auto_on", "auto_off", "to_cloud", "to_local", "recover", "finish"];
1310
+ import { randomUUID as randomUUID3 } from "node:crypto";
1311
+ var travelConsoleActions = ["status", "auto_on", "auto_off", "sync", "to_cloud", "to_local", "recover", "finish"];
1217
1312
  var travelConsoleErrors = /* @__PURE__ */ new Set(["invalid_action", "invalid_request", "wrong_partner", "service_unavailable", "busy", "recovery_required", "recovery_unavailable", "confirmation_required", "not_ready", "retired"]);
1218
1313
  var TravelConsoleManager = class {
1219
1314
  constructor(options) {
@@ -1239,6 +1334,7 @@ var TravelConsoleManager = class {
1239
1334
  db;
1240
1335
  closed = false;
1241
1336
  changing = false;
1337
+ operation;
1242
1338
  roles;
1243
1339
  role(nodeId) {
1244
1340
  if (nodeId === this.roles.local.principal.nodeId) return "local";
@@ -1264,8 +1360,8 @@ var TravelConsoleManager = class {
1264
1360
  return { peers: await observations, retirement: retirement2, current };
1265
1361
  })().catch(() => void 0);
1266
1362
  let timer;
1267
- const result = await Promise.race([reads, new Promise((resolve8) => {
1268
- timer = setTimeout(() => resolve8(void 0), this.options.statusTimeoutMs ?? 5e3);
1363
+ const result = await Promise.race([reads, new Promise((resolve9) => {
1364
+ timer = setTimeout(() => resolve9(void 0), this.options.statusTimeoutMs ?? 5e3);
1269
1365
  })]);
1270
1366
  clearTimeout(timer);
1271
1367
  if (this.closed) throw new Error("service_unavailable");
@@ -1280,6 +1376,7 @@ var TravelConsoleManager = class {
1280
1376
  if (!retirement) {
1281
1377
  if (verified && active !== "unknown") allowedActions.push(controller.automatic ? "auto_off" : "auto_on");
1282
1378
  if (verified && active !== "unknown" && !controller.job && !this.changing) {
1379
+ if ((active === "local" || active === "cloud") && peers.every((peer2) => peer2.connected && !peer2.busy) && this.roles[active].synchronize) allowedActions.push("sync");
1283
1380
  if (active === "local" && peers[1].connected) allowedActions.push("to_cloud");
1284
1381
  if (active === "cloud" && peers[0].connected) allowedActions.push("to_local");
1285
1382
  if (active === "local" && this.options.retirement) allowedActions.push("recover", "finish");
@@ -1295,11 +1392,13 @@ var TravelConsoleManager = class {
1295
1392
  checkedAt: Date.now(),
1296
1393
  allowedActions,
1297
1394
  recovery: retirement?.recovery ?? "required",
1298
- ...controller.job ? { transfer: { id: controller.job.id, target: this.role(controller.job.target), state: controller.job.state } } : {},
1299
- ...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 } } : {}
1300
1398
  };
1301
1399
  }
1302
1400
  async execute(action, payload) {
1401
+ let operationId;
1303
1402
  try {
1304
1403
  if (!travelConsoleActions.includes(action)) throw new Error("invalid_action");
1305
1404
  if (action === "finish" && payload?.confirmed !== true) throw new Error("confirmation_required");
@@ -1312,10 +1411,18 @@ var TravelConsoleManager = class {
1312
1411
  if (action === "finish") return { ok: true, connected: true, snapshot };
1313
1412
  throw new Error("retired");
1314
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
+ }
1315
1418
  if (action === "auto_on" || action === "auto_off") {
1316
1419
  if (snapshot.retirement) throw new Error("retired");
1317
1420
  if (snapshot.active === "unknown") throw new Error("not_ready");
1318
1421
  this.options.controller.setAutomatic(action === "auto_on");
1422
+ } else if (action === "sync") {
1423
+ if (snapshot.retirement) throw new Error("retired");
1424
+ if (!["local", "cloud"].includes(snapshot.active) || snapshot.peers.some((peer) => !peer.connected || peer.busy)) throw new Error("not_ready");
1425
+ await this.options.controller.synchronize();
1319
1426
  } else if (action === "to_cloud" || action === "to_local") {
1320
1427
  if (snapshot.retirement) throw new Error("retired");
1321
1428
  const role = action === "to_cloud" ? "cloud" : "local";
@@ -1339,12 +1446,16 @@ var TravelConsoleManager = class {
1339
1446
  await this.options.retirement.finish();
1340
1447
  }
1341
1448
  }
1449
+ if (this.operation?.id === operationId && this.operation?.state === "RUNNING") this.operation = { ...this.operation, state: "DONE", updatedAt: Date.now() };
1342
1450
  } finally {
1343
1451
  this.changing = false;
1344
1452
  }
1345
1453
  return { ok: true, connected: true, snapshot: await this.snapshot() };
1346
1454
  } catch (error) {
1347
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 };
1457
+ const reason = typeof message === "string" && /^[A-Z][A-Z0-9_]{0,95}$/.test(message) ? message : code;
1458
+ process.stderr.write("[travel-console-operation] " + JSON.stringify({ at: Date.now(), action: travelConsoleActions.includes(action) ? action : "OTHER", reason }) + "\n");
1348
1459
  return { ok: false, connected: true, error: code };
1349
1460
  }
1350
1461
  }
@@ -1368,7 +1479,7 @@ function closeTravelConsoleServer(server) {
1368
1479
  return close();
1369
1480
  }
1370
1481
  function createTravelConsoleServer(options) {
1371
- const { manager, identity: identity3, token, bodyTimeoutMs = 5e3, ...tls } = options;
1482
+ const { manager, identity: identity3, token, bodyTimeoutMs = 5e3, startInitial, ...tls } = options;
1372
1483
  if (!/^e7u_[a-f0-9]{64}$/.test(token) || !Number.isSafeInteger(bodyTimeoutMs) || bodyTimeoutMs < 100 || bodyTimeoutMs > 3e4) throw new Error("TRAVEL_CONSOLE_CONFIG");
1373
1484
  const expected = Buffer.from("Bearer " + token);
1374
1485
  let reads = 0, writes = 0;
@@ -1427,7 +1538,7 @@ function createTravelConsoleServer(options) {
1427
1538
  reply(400, { ok: false, error: "invalid_request" });
1428
1539
  return;
1429
1540
  }
1430
- if (!nodeSupervisorRecord(input) || !exact(input, ["version", "identity", "action", "payload"]) || input.version !== 1 || !nodeSupervisorRecord(input.identity) || !exact(input.identity, ["tenantId", "companionId", "seatId"]) || !travelConsoleActions.includes(input.action)) {
1541
+ if (!nodeSupervisorRecord(input) || !exact(input, ["version", "identity", "action", "payload"]) || input.version !== 1 || !nodeSupervisorRecord(input.identity) || !exact(input.identity, ["tenantId", "companionId", "seatId"]) || !(travelConsoleActions.includes(input.action) || input.action === "start_initial" && startInitial)) {
1431
1542
  reply(400, { ok: false, error: "invalid_request" });
1432
1543
  return;
1433
1544
  }
@@ -1436,7 +1547,7 @@ function createTravelConsoleServer(options) {
1436
1547
  reply(403, { ok: false, error: "wrong_partner" });
1437
1548
  return;
1438
1549
  }
1439
- const payload = input.payload, allowed = action === "finish" ? ["confirmed"] : action === "recover" ? ["requestId", "receipt"] : action.startsWith("to_") ? ["requestId"] : [];
1550
+ const payload = input.payload, allowed = action === "finish" ? ["confirmed"] : action === "recover" ? ["requestId", "receipt"] : action.startsWith("to_") || action === "start_initial" ? ["requestId"] : [];
1440
1551
  if (payload !== void 0 && (!nodeSupervisorRecord(payload) || !exact(payload, allowed) || Object.hasOwn(payload, "requestId") && !nodeSupervisorId(payload.requestId) || Object.hasOwn(payload, "confirmed") && typeof payload.confirmed !== "boolean" || Object.hasOwn(payload, "receipt") && !nodeSupervisorRecord(payload.receipt))) {
1441
1552
  reply(400, { ok: false, error: "invalid_request" });
1442
1553
  return;
@@ -1448,7 +1559,17 @@ function createTravelConsoleServer(options) {
1448
1559
  slot = input.action === "status" ? "read" : "write";
1449
1560
  if (slot === "read") reads++;
1450
1561
  else writes++;
1562
+ if (action === "start_initial") {
1563
+ if (!payload || !nodeSupervisorId(payload.requestId)) {
1564
+ reply(400, { ok: false, error: "invalid_request" });
1565
+ return;
1566
+ }
1567
+ startInitial(payload.requestId);
1568
+ reply(200, { ok: true });
1569
+ return;
1570
+ }
1451
1571
  const result = await manager.execute(input.action, payload);
1572
+ if (result.ok && startInitial && nodeSupervisorId(result.initialRequestId) && req.headers["x-engine7-first-acknowledgement"] !== "1") startInitial(result.initialRequestId);
1452
1573
  reply(result.ok ? 200 : 409, result);
1453
1574
  } catch (error) {
1454
1575
  reply(409, { ok: false, error: travelConsoleErrors.has(error.message) ? error.message : "service_unavailable" });
@@ -1459,7 +1580,7 @@ function createTravelConsoleServer(options) {
1459
1580
  }
1460
1581
  };
1461
1582
  shutdowns.set(server, () => closing ??= (async () => {
1462
- const stopped = new Promise((resolve8) => server.close(() => resolve8()));
1583
+ const stopped = new Promise((resolve9) => server.close(() => resolve9()));
1463
1584
  server.closeAllConnections();
1464
1585
  await stopped;
1465
1586
  await Promise.allSettled([...pending]);
@@ -1474,32 +1595,91 @@ function createTravelConsoleServer(options) {
1474
1595
  }
1475
1596
 
1476
1597
  // src/continuity/console-retirement.ts
1477
- 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";
1478
1599
  import { DatabaseSync as DatabaseSync10 } from "node:sqlite";
1479
- import { dirname as dirname4, join as join9, isAbsolute as isAbsolute5, resolve as resolve6 } from "node:path";
1480
- import { createHash as createHash6, 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";
1481
1602
 
1482
1603
  // src/continuity/retirement-main.ts
1483
- import { readFileSync as readFileSync7, existsSync as existsSync3 } from "node:fs";
1484
- import { isAbsolute as isAbsolute4, resolve as resolve5 } from "node:path";
1604
+ import { readFileSync as readFileSync6, existsSync as existsSync3 } from "node:fs";
1605
+ import { isAbsolute as isAbsolute5, resolve as resolve6 } from "node:path";
1485
1606
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1486
1607
  import { execFile } from "node:child_process";
1487
1608
  import { promisify } from "node:util";
1488
- import { createHash as createHash5 } from "node:crypto";
1609
+ import { createHash as createHash6 } from "node:crypto";
1610
+
1611
+ // src/continuity/user-seat-resource.ts
1612
+ import { spawn } from "node:child_process";
1613
+ import { createHash } from "node:crypto";
1614
+ import { isAbsolute as isAbsolute2, resolve as resolve3 } from "node:path";
1615
+ var UserSeatResource = class {
1616
+ constructor(config) {
1617
+ this.config = config;
1618
+ if (!/^[a-z_][a-z0-9_-]{0,31}$/.test(config.runAs.user) || [config.directory, config.runAs.node, config.runAs.entry, config.runAs.configFile].some((path3) => !isAbsolute2(path3) || resolve3(path3) !== path3 || /[\r\n\0]/.test(path3))) throw new Error("TRAVEL_RETIREMENT_CONFIG");
1619
+ this.identity = config.identity;
1620
+ this.path = config.directory;
1621
+ this.id = "directory-" + createHash("sha256").update(this.path).digest("hex");
1622
+ }
1623
+ id;
1624
+ path;
1625
+ identity;
1626
+ call(action, input) {
1627
+ return new Promise((done, reject) => {
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"] });
1629
+ const chunks = [];
1630
+ let bytes = 0, stderr = "";
1631
+ const timer = setTimeout(() => child.kill("SIGKILL"), 12e4);
1632
+ child.stdin.on("error", () => {
1633
+ });
1634
+ child.stderr.on("data", (chunk) => {
1635
+ stderr = (stderr + chunk.toString()).slice(-4096);
1636
+ });
1637
+ child.stdout.on("data", (chunk) => {
1638
+ bytes += chunk.length;
1639
+ if (bytes > 64 * 1024 * 1024) child.kill("SIGKILL");
1640
+ else chunks.push(chunk);
1641
+ });
1642
+ child.once("error", reject);
1643
+ child.once("close", (code) => {
1644
+ clearTimeout(timer);
1645
+ if (code !== 0) {
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"));
1649
+ return;
1650
+ }
1651
+ try {
1652
+ done(JSON.parse(Buffer.concat(chunks).toString()));
1653
+ } catch {
1654
+ reject(new Error("TRAVEL_RETIREMENT_PROVIDER_PENDING"));
1655
+ }
1656
+ });
1657
+ child.stdin.end(input === void 0 ? "" : JSON.stringify(input));
1658
+ });
1659
+ }
1660
+ async inventory() {
1661
+ const rows = await this.call("inventory");
1662
+ if (!Array.isArray(rows) || rows.length > 1e6) throw new Error("TRAVEL_RETIREMENT_BUDGET");
1663
+ return rows;
1664
+ }
1665
+ async purge(inventory) {
1666
+ if ((await this.call("purge", inventory)).purged !== true) throw new Error("TRAVEL_RETIREMENT_PROVIDER_PENDING");
1667
+ }
1668
+ };
1489
1669
 
1490
1670
  // src/continuity/retirement.ts
1491
1671
  import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
1492
- import { createHash } from "node:crypto";
1672
+ import { createHash as createHash2 } from "node:crypto";
1493
1673
  import { existsSync } from "node:fs";
1494
- import { lstatSync as lstatSync3, readdirSync, readFileSync as readFileSync4, readlinkSync, realpathSync as realpathSync2, rmSync } from "node:fs";
1495
- import { isAbsolute as isAbsolute2, join as join5, resolve as resolve3, 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";
1496
1676
  var identity = (value) => JSON.stringify([value.tenantId, value.companionId, value.seatId]);
1497
- var sha = (value) => createHash("sha256").update(value).digest("hex");
1677
+ var sha = (value) => createHash2("sha256").update(value).digest("hex");
1498
1678
  var LocalSeatResource = class {
1499
1679
  constructor(path3, identity3) {
1500
1680
  this.path = path3;
1501
1681
  this.identity = identity3;
1502
- if (!isAbsolute2(path3) || resolve3(path3) !== path3 || path3.split("/").filter(Boolean).length < 3) throw new Error("TRAVEL_RETIREMENT_PATH");
1682
+ if (!isAbsolute3(path3) || resolve4(path3) !== path3 || path3.split("/").filter(Boolean).length < 3) throw new Error("TRAVEL_RETIREMENT_PATH");
1503
1683
  this.id = "directory-" + sha(path3);
1504
1684
  }
1505
1685
  id;
@@ -1523,19 +1703,29 @@ var LocalSeatResource = class {
1523
1703
  else if (item.isDirectory()) visit(path3);
1524
1704
  else if (item.isFile()) {
1525
1705
  if (item.name === ".travel-seat-resource.json" && identity(JSON.parse(readPrivateFile(path3, 65536).toString())) !== identity(this.identity)) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
1526
- result.push({ version, digest: sha(readFileSync4(path3)) });
1706
+ result.push({ version, digest: sha(readFileSync3(path3)) });
1527
1707
  } else throw new Error("TRAVEL_RETIREMENT_PATH");
1528
1708
  if (result.length > 1e6) throw new Error("TRAVEL_RETIREMENT_BUDGET");
1529
1709
  }
1530
1710
  };
1531
1711
  visit(this.path);
1532
- return result;
1712
+ return result.length === 1 && result[0].version === ".travel-seat-resource.json" ? [] : result;
1533
1713
  }
1534
1714
  async purge(expectedInventory) {
1535
1715
  const allowed = new Map(expectedInventory.map((item) => [item.version, item.digest]));
1536
1716
  if (this.inventoryNow().some((item) => allowed.get(item.version) !== item.digest)) throw new Error("TRAVEL_RETIREMENT_RESOURCE_CHANGED");
1537
- if (this.check()) rmSync(this.path, { recursive: true });
1538
- 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");
1539
1729
  }
1540
1730
  };
1541
1731
  var TravelRetirement = class {
@@ -1597,10 +1787,10 @@ var TravelRetirement = class {
1597
1787
  if (required) throw new Error("TRAVEL_RETIREMENT_RECOVERY_REQUIRED");
1598
1788
  return null;
1599
1789
  }
1600
- if (recovered.loaded !== true || identity(recovered.identity) !== identity(this.options.identity) || !isAbsolute2(recovered.ordinaryStateDir) || ![recovered.checkpointDigest, recovered.channelReceiptsDigest].every((value) => /^[a-f0-9]{64}$/.test(value))) throw new Error("TRAVEL_RETIREMENT_RECOVERY_REQUIRED");
1790
+ if (recovered.loaded !== true || identity(recovered.identity) !== identity(this.options.identity) || !isAbsolute3(recovered.ordinaryStateDir) || ![recovered.checkpointDigest, recovered.channelReceiptsDigest].every((value) => /^[a-f0-9]{64}$/.test(value))) throw new Error("TRAVEL_RETIREMENT_RECOVERY_REQUIRED");
1601
1791
  for (const resource of this.options.resources) {
1602
1792
  if (resource.path) {
1603
- const local = resolve3(recovered.ordinaryStateDir), path3 = resolve3(resource.path), journal = resolve3(this.options.directory);
1793
+ const local = resolve4(recovered.ordinaryStateDir), path3 = resolve4(resource.path), journal = resolve4(this.options.directory);
1604
1794
  if ([local, journal].some((p) => p === path3 || p.startsWith(path3 + "/") || path3.startsWith(p + "/"))) throw new Error("TRAVEL_RETIREMENT_LOCAL_OVERLAP");
1605
1795
  }
1606
1796
  }
@@ -1621,7 +1811,8 @@ var TravelRetirement = class {
1621
1811
  row = this.db.prepare("SELECT * FROM resources WHERE id=?").get(resource.id);
1622
1812
  }
1623
1813
  const original = JSON.parse(String(row.inventory));
1624
- 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");
1625
1816
  await verifyRecovery(true);
1626
1817
  await resource.purge(original);
1627
1818
  if ((await resource.inventory()).length) throw new Error("TRAVEL_RETIREMENT_PROVIDER_PENDING");
@@ -1647,22 +1838,22 @@ var TravelRetirement = class {
1647
1838
  };
1648
1839
 
1649
1840
  // src/continuity/local-exit.ts
1650
- 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";
1651
1842
  import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
1652
- import { isAbsolute as isAbsolute3, join as join8, dirname as dirname3, resolve as resolve4 } from "node:path";
1653
- import { createHash as createHash4, verify as verify2 } from "node:crypto";
1843
+ import { isAbsolute as isAbsolute4, join as join8, dirname as dirname4, resolve as resolve5 } from "node:path";
1844
+ import { createHash as createHash5, verify as verify2 } from "node:crypto";
1654
1845
 
1655
1846
  // src/continuity/runtime-lock.ts
1656
- import { randomUUID as randomUUID3 } from "node:crypto";
1847
+ import { randomUUID as randomUUID4 } from "node:crypto";
1657
1848
  import { AsyncLocalStorage } from "node:async_hooks";
1658
- 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";
1659
1850
  import { join as join6 } from "node:path";
1660
1851
  import { createRequire } from "node:module";
1661
1852
  var sqlite;
1662
1853
  function openSQLite(file, options = {}) {
1663
1854
  return new (sqlite ??= createRequire(import.meta.url)("node:sqlite")).DatabaseSync(file, options);
1664
1855
  }
1665
- var bootId = randomUUID3();
1856
+ var bootId = randomUUID4();
1666
1857
  var checkpointHandles = /* @__PURE__ */ new Set();
1667
1858
  var recoveryWriterLocks = new AsyncLocalStorage();
1668
1859
  var initialBaselineAdmission = new AsyncLocalStorage();
@@ -1730,7 +1921,7 @@ async function withCheckpointLock(stateDir, operation) {
1730
1921
  for (const name of [".engine.pid", ".bg-worker.pid"]) {
1731
1922
  let value;
1732
1923
  try {
1733
- value = readFileSync5(join6(stateDir, name), "utf8").trim();
1924
+ value = readFileSync4(join6(stateDir, name), "utf8").trim();
1734
1925
  } catch (error) {
1735
1926
  if (error.code === "ENOENT") continue;
1736
1927
  throw new Error("WRITER_STATE_UNKNOWN", { cause: error });
@@ -1752,15 +1943,15 @@ async function withCheckpointLock(stateDir, operation) {
1752
1943
 
1753
1944
  // src/continuity/local-dedupe.ts
1754
1945
  import { DatabaseSync as DatabaseSync8 } from "node:sqlite";
1755
- import { createHash as createHash2 } from "node:crypto";
1756
- import { dirname as dirname2 } from "node:path";
1757
- var sha2 = (value) => createHash2("sha256").update(value).digest("hex");
1946
+ import { createHash as createHash3 } from "node:crypto";
1947
+ import { dirname as dirname3 } from "node:path";
1948
+ var sha2 = (value) => createHash3("sha256").update(value).digest("hex");
1758
1949
  var hash = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
1759
1950
  var PlatformReceiptStore = class {
1760
1951
  db;
1761
1952
  constructor(file, namespace) {
1762
1953
  if (!namespace || namespace.length > 1024) throw new Error("PLATFORM_RECEIPT_IDENTITY");
1763
- preparePrivateDirectory(dirname2(file));
1954
+ preparePrivateDirectory(dirname3(file));
1764
1955
  preparePrivateDatabase(file);
1765
1956
  this.db = new DatabaseSync8(file);
1766
1957
  try {
@@ -1820,10 +2011,10 @@ var PlatformReceiptStore = class {
1820
2011
  };
1821
2012
 
1822
2013
  // src/continuity/local-exit-proof.ts
1823
- import { createHash as createHash3, verify } from "node:crypto";
1824
- import { createReadStream, mkdirSync as mkdirSync4, readdirSync as readdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
2014
+ import { createHash as createHash4, verify } from "node:crypto";
2015
+ import { createReadStream, mkdirSync as mkdirSync4, readdirSync as readdirSync2, writeFileSync } from "node:fs";
1825
2016
  import { join as join7, relative as relative2 } from "node:path";
1826
- var hash2 = (value) => createHash3("sha256").update(value).digest("hex");
2017
+ var hash2 = (value) => createHash4("sha256").update(value).digest("hex");
1827
2018
  var equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
1828
2019
  function copyLocalExitPath(source, path3) {
1829
2020
  const name = relative2(source, path3).replaceAll("\\", "/");
@@ -1841,7 +2032,7 @@ async function localExitFilesDigest(root, ordinary = false) {
1841
2032
  continue;
1842
2033
  }
1843
2034
  if (!entry.isFile() || files.length >= 1e6) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
1844
- const digest = createHash3("sha256");
2035
+ const digest = createHash4("sha256");
1845
2036
  for await (const chunk of createReadStream(file)) digest.update(chunk);
1846
2037
  files.push({ path: relative2(root, file).replaceAll("\\", "/"), sha256: digest.digest("hex") });
1847
2038
  }
@@ -1881,7 +2072,7 @@ async function verifyStoppedLocalExitProof(options) {
1881
2072
 
1882
2073
  // src/continuity/local-exit.ts
1883
2074
  var identity2 = (value) => JSON.stringify([value.tenantId, value.companionId, value.seatId]);
1884
- var sha3 = (value) => createHash4("sha256").update(value).digest("hex");
2075
+ var sha3 = (value) => createHash5("sha256").update(value).digest("hex");
1885
2076
  function detachReplication(directory) {
1886
2077
  for (const entry of readdirSync3(directory, { withFileTypes: true })) {
1887
2078
  const file = join8(directory, entry.name);
@@ -1909,9 +2100,9 @@ function detachReplication(directory) {
1909
2100
  }
1910
2101
  }
1911
2102
  async function createOrdinaryLocalRecovery(options) {
1912
- const source = resolve4(options.stateDir), destination = resolve4(options.destination);
1913
- if (!isAbsolute3(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");
1914
- const activation = JSON.parse(readFileSync6(join8(source, ".travel-active.json"), "utf8")), permit = activation.permit, { signature, ...signed } = permit;
2103
+ const source = resolve5(options.stateDir), destination = resolve5(options.destination);
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;
1915
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");
1916
2107
  return withCheckpointLock(source, async () => {
1917
2108
  if (!options.authority || !options.principal || options.authority.publicKey !== options.publicKey) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
@@ -1953,7 +2144,7 @@ async function createOrdinaryLocalRecovery(options) {
1953
2144
  await proof.check();
1954
2145
  const body = { ...receipt, ordinaryFilesDigest: await localExitFilesDigest(destination, true) };
1955
2146
  const result = { ...body, digest: sha3(JSON.stringify(body)) };
1956
- 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 });
1957
2148
  return result;
1958
2149
  } catch (error) {
1959
2150
  if (existsSync2(destination)) rmSync2(destination, { recursive: true });
@@ -1964,9 +2155,9 @@ async function createOrdinaryLocalRecovery(options) {
1964
2155
 
1965
2156
  // src/continuity/retirement-main.ts
1966
2157
  var command = promisify(execFile);
1967
- var sha4 = (value) => createHash5("sha256").update(value).digest("hex");
2158
+ var sha4 = (value) => createHash6("sha256").update(value).digest("hex");
1968
2159
  var path2 = (value) => {
1969
- if (typeof value !== "string" || !isAbsolute4(value) || resolve5(value) !== value) throw new Error("TRAVEL_RETIREMENT_PATH");
2160
+ if (typeof value !== "string" || !isAbsolute5(value) || resolve6(value) !== value) throw new Error("TRAVEL_RETIREMENT_PATH");
1970
2161
  return value;
1971
2162
  };
1972
2163
  async function runTravelRetirementCli(args) {
@@ -1974,7 +2165,7 @@ async function runTravelRetirementCli(args) {
1974
2165
  if (args.length !== 3 || !["run", "recover-local"].includes(args[0]) || args[1] !== "--config") throw new Error("TRAVEL_RETIREMENT_INVALID_COMMAND");
1975
2166
  const config = JSON.parse(readPrivateFile(path2(args[2]), 4 * 1024 * 1024).toString());
1976
2167
  if (args[0] === "recover-local") {
1977
- 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) });
1978
2169
  try {
1979
2170
  const { principal, publicKey } = await client2.retirementStatus();
1980
2171
  if (publicKey !== config.publicKey) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
@@ -1989,7 +2180,7 @@ async function runTravelRetirementCli(args) {
1989
2180
  }
1990
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");
1991
2182
  if (!config.stopServices.length && config.nodesAlreadyStopped !== true) throw new Error("TRAVEL_RETIREMENT_STOP_REQUIRED");
1992
- 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) });
1993
2184
  let job, keys;
1994
2185
  try {
1995
2186
  const control = await client.retirementStatus();
@@ -2012,10 +2203,10 @@ async function runTravelRetirementCli(args) {
2012
2203
  jobId: config.jobId,
2013
2204
  retire: () => client.retire(config.jobId),
2014
2205
  stopNodes: async () => {
2015
- if (config.stopServices.length) await command("systemctl", ["stop", ...config.stopServices]);
2206
+ if (config.stopServices.length) await command(config.stopViaSudo === true ? "/usr/bin/sudo" : "systemctl", config.stopViaSudo === true ? ["-n", "/usr/bin/systemctl", "stop", ...config.stopServices] : ["stop", ...config.stopServices]);
2016
2207
  },
2017
2208
  verifyLocalRecovery,
2018
- resources: config.resources.map((resource) => new LocalSeatResource(path2(resource.directory), config.identity)),
2209
+ resources: config.resources.map((resource) => resource.runAs ? new UserSeatResource({ ...resource, identity: config.identity }) : new LocalSeatResource(path2(resource.directory), config.identity)),
2019
2210
  revokeKey: async () => {
2020
2211
  keys.revoke(config.keyIdentity);
2021
2212
  return { revoked: true };
@@ -2030,7 +2221,7 @@ async function runTravelRetirementCli(args) {
2030
2221
  client.close();
2031
2222
  }
2032
2223
  }
2033
- if (process.argv[1] && /[\\/](retirement-main\.ts|travel-retire\.mjs)$/.test(fileURLToPath2(import.meta.url)) && resolve5(process.argv[1]) === fileURLToPath2(import.meta.url)) {
2224
+ if (process.argv[1] && /[\\/](retirement-main\.ts|travel-retire\.mjs)$/.test(fileURLToPath2(import.meta.url)) && resolve6(process.argv[1]) === fileURLToPath2(import.meta.url)) {
2034
2225
  runTravelRetirementCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch(() => {
2035
2226
  process.stderr.write("TRAVEL_RETIREMENT_REFUSED\n");
2036
2227
  process.exitCode = 1;
@@ -2038,15 +2229,15 @@ if (process.argv[1] && /[\\/](retirement-main\.ts|travel-retire\.mjs)$/.test(fil
2038
2229
  }
2039
2230
 
2040
2231
  // src/continuity/console-retirement.ts
2041
- var hash3 = (value) => createHash6("sha256").update(value).digest("hex");
2232
+ var hash3 = (value) => createHash7("sha256").update(value).digest("hex");
2042
2233
  var sameIdentity = (a, b) => a && ["tenantId", "companionId", "seatId"].every((key) => a[key] === b[key]);
2043
2234
  var sourceBinding = (source) => source ? ["activeNodeId", "activeBootId", "authorityBootId", "epoch", "checkpointDigest", "deletionWatermark"].map((key) => source[key]) : null;
2044
2235
  function createTravelConsoleRetirement(options) {
2045
- if (!isAbsolute5(options.configFile) || resolve6(options.configFile) !== options.configFile || realpathSync5(options.configFile) !== options.configFile) throw new Error("TRAVEL_CONSOLE_CONFIG");
2046
- const config = JSON.parse(readPrivateFile(options.configFile, 4 * 1024 * 1024).toString()), original = readFileSync8(options.configFile);
2047
- if (!sameIdentity(config.identity, options.identity) || config.accountOwnerRequestedKeyDestruction === true || !isAbsolute5(config.localRecoveryReceiptFile) || realpathSync5(dirname4(config.localRecoveryReceiptFile)) !== dirname4(config.localRecoveryReceiptFile)) throw new Error("TRAVEL_CONSOLE_CONFIG");
2236
+ if (!isAbsolute6(options.configFile) || resolve7(options.configFile) !== options.configFile || realpathSync5(options.configFile) !== options.configFile) 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");
2048
2239
  const assertConfig = () => {
2049
- 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");
2050
2241
  };
2051
2242
  preparePrivateDirectory(config.directory);
2052
2243
  const pendingFile = join9(config.directory, "console-recovery.json");
@@ -2057,19 +2248,19 @@ function createTravelConsoleRetirement(options) {
2057
2248
  return value;
2058
2249
  };
2059
2250
  const savePending = (state, source) => {
2060
- const temp = pendingFile + "." + randomUUID4();
2251
+ const temp = pendingFile + "." + randomUUID5();
2061
2252
  try {
2062
- 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 });
2063
2254
  renameSync(temp, pendingFile);
2064
2255
  } finally {
2065
- if (existsSync4(temp)) unlinkSync3(temp);
2256
+ if (existsSync4(temp)) unlinkSync2(temp);
2066
2257
  }
2067
2258
  };
2068
2259
  const verify3 = async (value) => {
2069
2260
  const receipt2 = value, current = await options.current(), source = current.source;
2070
2261
  if (!sameIdentity(current.identity, options.identity) || !source || !receipt2 || receipt2.format !== "engine7-ordinary-local-recovery-v2") throw new Error("TRAVEL_CONSOLE_RECOVERY_REQUIRED");
2071
2262
  const { digest, ...body } = receipt2, generation = receipt2.sourceGeneration;
2072
- if (hash3(JSON.stringify(body)) !== digest || !sameIdentity(receipt2.identity, options.identity) || receipt2.loaded !== true || receipt2.checkpointDigest !== current.checkpointDigest || receipt2.deletionWatermark !== current.deletionWatermark || source.checkpointDigest !== current.checkpointDigest || source.deletionWatermark !== current.deletionWatermark || !generation || generation.nodeId !== source.activeNodeId || generation.bootId !== source.activeBootId || generation.authorityBootId !== source.authorityBootId || generation.epoch !== source.epoch || !isAbsolute5(receipt2.ordinaryStateDir) || ![receipt2.channelReceiptsDigest, receipt2.sourceFilesDigest].every((v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v))) throw new Error("TRAVEL_CONSOLE_RECOVERY_REQUIRED");
2263
+ if (hash3(JSON.stringify(body)) !== digest || !sameIdentity(receipt2.identity, options.identity) || receipt2.loaded !== true || receipt2.checkpointDigest !== current.checkpointDigest || receipt2.deletionWatermark !== current.deletionWatermark || source.checkpointDigest !== current.checkpointDigest || source.deletionWatermark !== current.deletionWatermark || !generation || generation.nodeId !== source.activeNodeId || generation.bootId !== source.activeBootId || generation.authorityBootId !== source.authorityBootId || generation.epoch !== source.epoch || !isAbsolute6(receipt2.ordinaryStateDir) || ![receipt2.channelReceiptsDigest, receipt2.sourceFilesDigest].every((v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v))) throw new Error("TRAVEL_CONSOLE_RECOVERY_REQUIRED");
2073
2264
  return receipt2;
2074
2265
  };
2075
2266
  const receipt = () => existsSync4(config.localRecoveryReceiptFile) ? JSON.parse(readPrivateFile(config.localRecoveryReceiptFile, 65536).toString()) : void 0;
@@ -2110,15 +2301,15 @@ function createTravelConsoleRetirement(options) {
2110
2301
  savePending("LOCAL_STOPPED", stopped.source);
2111
2302
  return;
2112
2303
  }
2113
- const proof = await verify3(value), file = config.localRecoveryReceiptFile, temp = file + "." + randomUUID4();
2304
+ const proof = await verify3(value), file = config.localRecoveryReceiptFile, temp = file + "." + randomUUID5();
2114
2305
  try {
2115
- writeFileSync4(temp, JSON.stringify(proof), { mode: 384, flag: "wx", flush: true });
2306
+ writeFileSync3(temp, JSON.stringify(proof), { mode: 384, flag: "wx", flush: true });
2116
2307
  await verify3(proof);
2117
2308
  renameSync(temp, file);
2118
2309
  } finally {
2119
2310
  if (existsSync4(temp)) {
2120
- const { unlinkSync: unlinkSync4 } = await import("node:fs");
2121
- unlinkSync4(temp);
2311
+ const { unlinkSync: unlinkSync3 } = await import("node:fs");
2312
+ unlinkSync3(temp);
2122
2313
  }
2123
2314
  }
2124
2315
  },
@@ -2131,7 +2322,7 @@ function createTravelConsoleRetirement(options) {
2131
2322
 
2132
2323
  // src/continuity/console-main.ts
2133
2324
  var privatePath = (value) => {
2134
- if (typeof value !== "string" || !isAbsolute6(value) || resolve7(value) !== value) throw new Error("TRAVEL_CONSOLE_CONFIG");
2325
+ if (typeof value !== "string" || !isAbsolute7(value) || resolve8(value) !== value) throw new Error("TRAVEL_CONSOLE_CONFIG");
2135
2326
  return value;
2136
2327
  };
2137
2328
  function openTravelConsole(input) {
@@ -2153,7 +2344,7 @@ function openTravelConsole(input) {
2153
2344
  manager,
2154
2345
  identity: identity3,
2155
2346
  token: readPrivateFile(privatePath(input.tokenFile), 1024).toString().trim(),
2156
- cert: readFileSync9(privatePath(input.tls.certFile)),
2347
+ cert: readFileSync8(privatePath(input.tls.certFile)),
2157
2348
  key: readPrivateFile(privatePath(input.tls.keyFile), 65536)
2158
2349
  });
2159
2350
  let closing;
@@ -2173,9 +2364,9 @@ async function runTravelConsoleCli(args) {
2173
2364
  if (args.length !== 3 || args[0] !== "serve" || args[1] !== "--config") throw new Error("TRAVEL_CONSOLE_COMMAND");
2174
2365
  const config = JSON.parse(readPrivateFile(privatePath(args[2]), 65536).toString()), service = openTravelConsole(config);
2175
2366
  try {
2176
- await new Promise((resolve8, reject) => {
2367
+ await new Promise((resolve9, reject) => {
2177
2368
  service.server.once("error", reject);
2178
- service.server.listen(config.port, config.host, resolve8);
2369
+ service.server.listen(config.port, config.host, resolve9);
2179
2370
  });
2180
2371
  const retiring = await service.manager.snapshot();
2181
2372
  if (!retiring.retirement) service.controller.start();
@@ -2193,7 +2384,7 @@ async function runTravelConsoleCli(args) {
2193
2384
  throw error;
2194
2385
  }
2195
2386
  }
2196
- if (process.argv[1] && resolve7(process.argv[1]) === fileURLToPath3(import.meta.url)) runTravelConsoleCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch(() => {
2387
+ if (process.argv[1] && resolve8(process.argv[1]) === fileURLToPath3(import.meta.url)) runTravelConsoleCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch(() => {
2197
2388
  process.stderr.write("TRAVEL_CONSOLE_REFUSED\n");
2198
2389
  process.exitCode = 1;
2199
2390
  });