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,8 +1,8 @@
1
1
  const require=(await import('node:module')).createRequire(import.meta.url)
2
2
 
3
3
  // src/continuity/controller-main.ts
4
- import { readFileSync as readFileSync3 } from "node:fs";
5
- import { isAbsolute, resolve as resolve2 } from "node:path";
4
+ import { readFileSync as readFileSync2 } from "node:fs";
5
+ import { isAbsolute as isAbsolute2, resolve as resolve3 } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
 
8
8
  // src/continuity/controller.ts
@@ -19,19 +19,15 @@ import {
19
19
  fstatSync,
20
20
  fsyncSync,
21
21
  readSync,
22
- writeSync,
23
22
  lstatSync,
24
23
  realpathSync,
25
- mkdirSync,
26
- readFileSync,
27
- writeFileSync,
28
- linkSync,
29
- unlinkSync
24
+ mkdirSync
30
25
  } from "node:fs";
31
26
  import { join, dirname, resolve } from "node:path";
32
27
  var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
33
28
  var HASH = /^[a-f0-9]{64}$/;
34
29
  var MAGIC = Buffer.from("E7P1");
30
+ var INLINE_BYTES = 64 * 1024;
35
31
  var noFollow = constants.O_NOFOLLOW ?? 0;
36
32
  function validateObjectRef(ref) {
37
33
  if (!ref || !HASH.test(ref.sha256) || !Number.isSafeInteger(ref.bytes) || ref.bytes < 1 || ref.bytes > PUBLICATION_CHUNK_BYTES)
@@ -296,19 +292,28 @@ var TravelController = class {
296
292
  this.healthySince = null;
297
293
  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"));
298
294
  let node;
295
+ let missingCheckpoint = false;
299
296
  for (const candidate of candidates) if ((await candidate.observe()).connected === true) {
300
- node = candidate;
301
- break;
297
+ try {
298
+ await candidate.pinBranch(status.checkpointDigest);
299
+ node = candidate;
300
+ break;
301
+ } catch (error) {
302
+ if (!(error instanceof Error) || error.message !== "TRAVEL_NODE_COMMON_CHECKPOINT") throw error;
303
+ missingCheckpoint = true;
304
+ }
305
+ }
306
+ if (!node) {
307
+ if (missingCheckpoint) throw new Error("TRAVEL_NODE_COMMON_CHECKPOINT");
308
+ return;
302
309
  }
303
- if (!node) return;
304
- await node.pinBranch(status.checkpointDigest);
305
310
  const ready = await node.prepare(status.checkpointDigest);
306
311
  const latest = await this.options.authority.status(node.principal);
307
312
  if (latest.authorityBootId !== status.authorityBootId || latest.epoch !== status.epoch || latest.checkpointDigest !== status.checkpointDigest || latest.deletionWatermark !== status.deletionWatermark || latest.activeNodeId && !latest.expired) return;
308
313
  const permit = await this.options.authority.acquire(node.principal, ready);
309
314
  await this.launch(node, permit, status.checkpointDigest);
310
315
  }
311
- async replicate(source, target) {
316
+ async replicate(source, target, recheckBranches = false) {
312
317
  if (!source.replicationOffer || !source.connectReplica || !target.replicaProfile || !target.bootstrapReplica) return true;
313
318
  const offer = await source.replicationOffer();
314
319
  if (!offer) return true;
@@ -328,22 +333,29 @@ var TravelController = class {
328
333
  if (!profile || JSON.stringify(profile) !== JSON.stringify(offer.profile)) throw new Error("TRAVEL_CONTROLLER_REPLICA");
329
334
  await assertSource();
330
335
  await source.connectReplica(profile);
331
- const recovered = await source.recoverBranches?.();
332
- return !recovered || recovered.unresolvedCritical === 0;
336
+ if (recheckBranches) {
337
+ const recovered = await source.recoverBranches?.();
338
+ if (recovered && recovered.unresolvedCritical !== 0) return false;
339
+ }
340
+ return true;
333
341
  }
334
342
  async advance(job) {
335
343
  const target = this.options.nodes[job.target], control = this.options.authority;
336
344
  if (!target) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
337
345
  if (job.state === "REQUESTED") {
338
346
  const status = await control.status(target.principal);
339
- if (!status.activeNodeId || status.expired) throw new Error("TRAVEL_CONTROLLER_SOURCE_OFFLINE");
347
+ if (!status.activeNodeId || status.expired) {
348
+ this.db.prepare("UPDATE jobs SET state='ABORTED' WHERE id=?").run(job.id);
349
+ if (status.activeNodeId) await this.options.nodes[status.activeNodeId]?.stop();
350
+ return;
351
+ }
340
352
  if (status.activeNodeId === job.target) {
341
353
  this.db.prepare("UPDATE jobs SET state='DONE' WHERE id=?").run(job.id);
342
354
  return;
343
355
  }
344
356
  const source2 = this.options.nodes[status.activeNodeId];
345
357
  if (!source2) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
346
- if (!await this.replicate(source2, target)) return;
358
+ if (!await this.replicate(source2, target, true)) return;
347
359
  this.db.prepare("UPDATE jobs SET source=?,state='PREPARING' WHERE id=?").run(source2.principal.nodeId, job.id);
348
360
  await control.beginHandoff(source2.principal, await source2.permit(), job.id, job.target);
349
361
  return;
@@ -540,9 +552,12 @@ var TravelReportClient = class {
540
552
  this.timeout = options.timeoutMs ?? 8e3;
541
553
  if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
542
554
  this.key = options.key ? Buffer.from(options.key) : void 0;
543
- this.agent = new Agent({ ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, keepAlive: true, maxSockets: 1 });
555
+ const tls = { ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, maxSockets: 1 };
556
+ this.agent = new Agent({ ...tls, keepAlive: true });
557
+ this.mutationAgent = new Agent({ ...tls, keepAlive: false });
544
558
  }
545
559
  agent;
560
+ mutationAgent;
546
561
  key;
547
562
  url;
548
563
  timeout;
@@ -559,7 +574,7 @@ var TravelReportClient = class {
559
574
  const unavailable = () => new Error(this.closed ? "TRAVEL_CONTROL_CLOSED" : "TRAVEL_CONTROL_UNAVAILABLE");
560
575
  const remaining = deadline - performance.now();
561
576
  if (remaining <= 0) return Promise.reject(unavailable());
562
- return new Promise((resolve3, reject) => {
577
+ return new Promise((resolve4, reject) => {
563
578
  let complete = false, responseStarted = false;
564
579
  const finish = (error, value) => {
565
580
  if (complete) return;
@@ -567,9 +582,9 @@ var TravelReportClient = class {
567
582
  clearTimeout(timer);
568
583
  this.pending.delete(req);
569
584
  if (error) reject(error);
570
- else resolve3(value);
585
+ else resolve4(value);
571
586
  };
572
- const req = request(this.url, { method: "POST", agent: this.agent, headers: {
587
+ const req = request(this.url, { method: "POST", agent: readActions.has(input?.action) ? this.agent : this.mutationAgent, headers: {
573
588
  Authorization: "Bearer " + this.options.credential,
574
589
  "X-Engine7-Travel-Node": this.options.nodeId,
575
590
  "Content-Type": "application/json",
@@ -620,7 +635,7 @@ var TravelReportClient = class {
620
635
  complete = true;
621
636
  clearTimeout(timer);
622
637
  this.pending.delete(req);
623
- resolve3(this.attempt(input, false, deadline, body));
638
+ resolve4(this.attempt(input, false, deadline, body));
624
639
  } else finish(unavailable());
625
640
  });
626
641
  req.once("close", () => {
@@ -644,6 +659,7 @@ var TravelReportClient = class {
644
659
  this.closed = true;
645
660
  for (const req of this.pending) req.destroy();
646
661
  this.agent.destroy();
662
+ this.mutationAgent.destroy();
647
663
  this.key?.fill(0);
648
664
  }
649
665
  };
@@ -732,7 +748,22 @@ import { Agent as Agent2, request as request2 } from "node:https";
732
748
  // src/continuity/publication.ts
733
749
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
734
750
  import { createHash } from "node:crypto";
735
- var PUBLICATION_MANIFEST_BYTES = 4 * 1024 * 1024;
751
+
752
+ // src/continuity/inventory.ts
753
+ import { isAbsolute, join as join3, relative, resolve as resolve2, sep } from "node:path";
754
+ 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(" "));
755
+ 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(" "));
756
+ 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(" "));
757
+ function validateRelativePath(path2) {
758
+ if (typeof path2 !== "string" || !path2 || path2.length > 2048 || isAbsolute(path2)) throw new Error("INVALID_ARTIFACT_PATH");
759
+ for (const part of path2.split("/")) {
760
+ if (!part || part === "." || part === ".." || /[\x00-\x1f]/.test(part) || Buffer.byteLength(part) > 255 || process.platform === "win32" && (/[<>:"|?*\\]/.test(part) || /[. ]$/.test(part) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(part)))
761
+ throw new Error("INVALID_ARTIFACT_PATH");
762
+ }
763
+ }
764
+
765
+ // src/continuity/publication.ts
766
+ var PUBLICATION_MANIFEST_BYTES = 32 * 1024 * 1024;
736
767
  var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
737
768
  var ZERO = "0".repeat(64);
738
769
  var HASH2 = /^[a-f0-9]{64}$/;
@@ -773,8 +804,12 @@ function normalizePublicationProfile(value) {
773
804
  return Object.freeze(profile);
774
805
  }
775
806
  function validatePublicationPath(path2) {
776
- if (typeof path2 !== "string" || !path2 || path2.length > 2048 || path2.normalize("NFC") !== path2 || /[\x00-\x1f<>:"|?*\\]/.test(path2) || path2.split("/").some((p) => !p || p === "." || p === ".." || /[. ]$/.test(p) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(p)))
807
+ if (typeof path2 !== "string" || path2.normalize("NFC") !== path2) throw new Error("PUBLICATION_INVALID_PATH");
808
+ try {
809
+ validateRelativePath(path2);
810
+ } catch {
777
811
  throw new Error("PUBLICATION_INVALID_PATH");
812
+ }
778
813
  }
779
814
  function normalizePublication(value) {
780
815
  if (!value || value.format !== "engine7-publication-v1" || !natural(value.sequence) || !value.sequence || !HASH2.test(value.parentDigest) || !natural(value.deletionWatermark) || !Array.isArray(value.databases) || !Array.isArray(value.trees)) throw new Error("PUBLICATION_INVALID_MANIFEST");
@@ -850,6 +885,7 @@ var nodeSupervisorErrors = /* @__PURE__ */ new Set([
850
885
  "TRAVEL_NODE_CANCELLED",
851
886
  "TRAVEL_NODE_BOOT_MISMATCH",
852
887
  "TRAVEL_NODE_CHECKPOINT",
888
+ "TRAVEL_NODE_COMMON_CHECKPOINT",
853
889
  "TRAVEL_NODE_GENERATION_COLLISION",
854
890
  "TRAVEL_NODE_KEY_UNAVAILABLE",
855
891
  "TRAVEL_NODE_KEY_BARRIER",
@@ -941,14 +977,17 @@ var RemoteTravelNodeSupervisor = class {
941
977
  observeQuery;
942
978
  permitQuery;
943
979
  closed = false;
944
- call(action, args = {}, discover = false) {
980
+ call(action, args = {}, discover = false, retryStale = true, deadline, wireBody) {
945
981
  if (this.closed) return Promise.reject(new Error("TRAVEL_NODE_CLOSED"));
946
982
  const slot = action === "stop" ? "stop" : action === "observe" ? "observe" : action === "permit" ? "permit" : "operation";
947
983
  if ([...this.pending.values()].includes(slot)) return Promise.reject(new Error("TRAVEL_NODE_BUSY"));
948
- const body = Buffer.from(JSON.stringify({ node: { version: 1, nodeId: this.principal.nodeId, ...discover ? {} : { bootId: this.bootId }, action, ...args } }));
984
+ const body = wireBody ?? Buffer.from(JSON.stringify({ node: { version: 1, nodeId: this.principal.nodeId, ...discover ? {} : { bootId: this.bootId }, action, ...args } }));
949
985
  if (body.length > nodeSupervisorLimit) return Promise.reject(new Error("TRAVEL_NODE_INVALID_REQUEST"));
950
986
  const unavailable = () => new Error(this.closed ? "TRAVEL_NODE_CLOSED" : "TRAVEL_NODE_UNAVAILABLE");
951
- return new Promise((resolve3, reject) => {
987
+ deadline ??= performance.now() + (slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
988
+ const remaining = deadline - performance.now();
989
+ if (remaining <= 0) return Promise.reject(unavailable());
990
+ return new Promise((resolve4, reject) => {
952
991
  const started = performance.now();
953
992
  let responseStarted = false, receivedBytes = 0, reported = false;
954
993
  const lost = (code) => {
@@ -1007,21 +1046,24 @@ var RemoteTravelNodeSupervisor = class {
1007
1046
  return;
1008
1047
  }
1009
1048
  if (discover) this.bootId = response.bootId;
1010
- resolve3(response.result);
1049
+ resolve4(response.result);
1011
1050
  });
1012
1051
  });
1013
1052
  this.pending.set(req, slot);
1014
1053
  const timer = setTimeout(() => {
1015
1054
  lost("TIMEOUT");
1016
1055
  req.destroy();
1017
- }, slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
1056
+ }, remaining);
1018
1057
  const cleanup = () => {
1019
1058
  clearTimeout(timer);
1020
1059
  this.pending.delete(req);
1021
1060
  };
1022
1061
  req.once("error", (error) => {
1023
1062
  cleanup();
1024
- lost(error.code);
1063
+ if (!reported && retryStale && !this.closed && !responseStarted && (slot === "observe" || slot === "permit") && req.reusedSocket && error.code === "ECONNRESET") {
1064
+ reported = true;
1065
+ resolve4(this.call(action, args, discover, false, deadline, body));
1066
+ } else lost(error.code);
1025
1067
  });
1026
1068
  req.once("close", cleanup);
1027
1069
  req.end(body);
@@ -1105,7 +1147,7 @@ var RemoteTravelNodeSupervisor = class {
1105
1147
 
1106
1148
  // src/continuity/key-service-store.ts
1107
1149
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
1108
- import { constants as constants2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, closeSync as closeSync2, readFileSync as readFileSync2, writeSync as writeSync2, fstatSync as fstatSync2, fsyncSync as fsyncSync2, unlinkSync as unlinkSync2 } from "node:fs";
1150
+ import { constants as constants2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, closeSync as closeSync2, readFileSync, writeSync, fstatSync as fstatSync2, fsyncSync as fsyncSync2, unlinkSync } from "node:fs";
1109
1151
  function assertPrivateStat(stat, directory) {
1110
1152
  if ((directory ? !stat.isDirectory() : !stat.isFile()) || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
1111
1153
  throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
@@ -1117,7 +1159,7 @@ function readPrivateFile(path2, maximumBytes = 65536) {
1117
1159
  const stat = fstatSync2(fd);
1118
1160
  assertPrivateStat(stat, false);
1119
1161
  if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
1120
- return readFileSync2(fd);
1162
+ return readFileSync(fd);
1121
1163
  } finally {
1122
1164
  closeSync2(fd);
1123
1165
  }
@@ -1285,9 +1327,12 @@ var RemoteTravelDataAuthority = class {
1285
1327
  this.grants = grants.map((grant) => ({ ...grant, principal: Object.freeze({ ...grant.principal }) }));
1286
1328
  }
1287
1329
  async authenticate(credential) {
1330
+ return Object.freeze({ ...(await this.readIdentity(credential)).principal });
1331
+ }
1332
+ readIdentity(credential) {
1288
1333
  const grant = this.grants.find((grant2) => grant2.credential === credential);
1289
1334
  if (!grant) throw new Error("TRAVEL_AUTH_DENIED");
1290
- return Object.freeze({ ...(await this.read(grant)).principal });
1335
+ return this.read(grant);
1291
1336
  }
1292
1337
  grant(principal) {
1293
1338
  const grant = this.grants.find((grant2) => equal(principal, grant2.principal));
@@ -1337,9 +1382,8 @@ var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteT
1337
1382
  }
1338
1383
  const remote = new _RemoteTravelNodeAuthority(options.publicKey, options.grants);
1339
1384
  for (const grant of options.grants) {
1340
- const identity = await grant.client.identity();
1385
+ const identity = await remote.readIdentity(grant.credential);
1341
1386
  if (identity.publicKey !== options.publicKey) throw new Error("TRAVEL_NODE_SIGNER_MISMATCH");
1342
- await remote.authenticate(grant.credential);
1343
1387
  }
1344
1388
  return remote;
1345
1389
  }
@@ -1486,7 +1530,7 @@ function createPublicationServer(options) {
1486
1530
  };
1487
1531
  switch (value.operation) {
1488
1532
  case "status":
1489
- result = preservePublished ? await mutate(() => receiver.status()) : await receiver.status();
1533
+ result = preservePublished ? await mutate(() => receiver.status(false)) : await receiver.status(false);
1490
1534
  break;
1491
1535
  case "replication-status":
1492
1536
  result = await receiver.replicationStatus();
@@ -1494,7 +1538,6 @@ function createPublicationServer(options) {
1494
1538
  case "missing": {
1495
1539
  if (!Array.isArray(value.refs) || value.refs.length > 128) throw new Error("PUBLICATION_INVALID_OBJECT_LIST");
1496
1540
  const missing = await Promise.all(value.refs.map(async (ref) => {
1497
- await check();
1498
1541
  validateObjectRef(ref);
1499
1542
  return await receiver.objects.has(ref) ? null : ref.sha256;
1500
1543
  }));
@@ -1545,10 +1588,20 @@ function createPublicationServer(options) {
1545
1588
 
1546
1589
  // src/continuity/recovery-archive-transfer.ts
1547
1590
  import { Agent as Agent4, createServer as createServer3, request as request4 } from "node:https";
1591
+ import { gzipSync, gunzipSync, createGunzip, brotliCompressSync, brotliDecompressSync, createBrotliCompress, createBrotliDecompress, constants as constants3 } from "node:zlib";
1592
+ import { pipeline as pipelineAsync } from "node:stream/promises";
1548
1593
 
1549
- // src/continuity/recovery-archive.ts
1594
+ // src/continuity/native-database-snapshot.ts
1550
1595
  import { DatabaseSync as DatabaseSync5, backup } from "node:sqlite";
1551
1596
 
1597
+ // src/continuity/native-file-copy.ts
1598
+ import { execFile } from "node:child_process";
1599
+ import { promisify } from "node:util";
1600
+ var exec = promisify(execFile);
1601
+
1602
+ // src/continuity/recovery-archive.ts
1603
+ import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
1604
+
1552
1605
  // src/continuity/crypto.ts
1553
1606
  var MAGIC2 = Buffer.from("E7OBJ001");
1554
1607
  var HEADER_SIZE = MAGIC2.length + 12;
@@ -1557,7 +1610,8 @@ var HEADER_SIZE = MAGIC2.length + 12;
1557
1610
  import { createHash as createHash4 } from "node:crypto";
1558
1611
  var ID2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
1559
1612
  var FORMAT = "engine7-runtime-recovery-archive-v1";
1560
- var MAX_METADATA = 16 * 1024 * 1024;
1613
+ var RECOVERY_ARCHIVE_METADATA_BYTES = PUBLICATION_MANIFEST_BYTES + 8 * 1024 * 1024;
1614
+ var MAX_METADATA = RECOVERY_ARCHIVE_METADATA_BYTES;
1561
1615
  var same2 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
1562
1616
  function validateRecoveryArchiveEntry(entry, identity) {
1563
1617
  if (!entry || Object.keys(entry).some((key) => !["format", "id", "kind", "manifest", "databases", "publication", "receipt"].includes(key)) || entry.format !== FORMAT || !ID2.test(entry.id) || !["COMMON", "LOCAL", "REMOTE"].includes(entry.kind)) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
@@ -1600,10 +1654,24 @@ async function checkRecoveryDeletionAsync(manifest, current, previous = 0) {
1600
1654
 
1601
1655
  // src/continuity/recovery-archive-transfer.ts
1602
1656
  var endpoint = "/travel/archives/v1";
1603
- var metadataLimit = 16 * 1024 * 1024;
1657
+ var metadataLimit = RECOVERY_ARCHIVE_METADATA_BYTES;
1604
1658
  var requestLimit = 65536;
1605
1659
  var objectGroupLimit = 8;
1606
1660
  var partBodyLimit = 65536;
1661
+ var streamRefLimit = 512;
1662
+ var streamBatchBytes = 8 * 1024 * 1024;
1663
+ var streamBatchObjects = 128;
1664
+ var brotliOptions = { params: { [constants3.BROTLI_PARAM_QUALITY]: 4, [constants3.BROTLI_PARAM_LGWIN]: 22 } };
1665
+ function validateStreamRefs(value) {
1666
+ if (!Array.isArray(value) || value.length < 1 || value.length > streamRefLimit) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
1667
+ const seen = /* @__PURE__ */ new Set();
1668
+ for (const ref of value) {
1669
+ validateObjectRef(ref);
1670
+ if (Object.keys(ref).length !== 2 || seen.has(ref.sha256)) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
1671
+ seen.add(ref.sha256);
1672
+ }
1673
+ return value;
1674
+ }
1607
1675
  var validId = (id2) => typeof id2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(id2);
1608
1676
  function validateObjectParts(value) {
1609
1677
  if (!Array.isArray(value) || value.length < 1 || value.length > objectGroupLimit) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
@@ -1655,7 +1723,7 @@ function refs(entry) {
1655
1723
  return result;
1656
1724
  }
1657
1725
  function createRecoveryArchiveServer(options) {
1658
- const { archive: fixedArchive, resolveArchive, listReceipts, readManifests, readManifestEvidence, identity = options.archive?.objects.identity, authority, allowedPeers, assertAvailable, bodyTimeoutMs = 5e3, ...tls } = options;
1726
+ const { archive: fixedArchive, resolveArchive, listReceipts, readManifests, readManifestEvidence, identity = options.archive?.objects.identity, authority, allowedPeers, assertAvailable, bodyTimeoutMs = 5e3, streaming = true, ...tls } = options;
1659
1727
  if (!identity || !fixedArchive && !resolveArchive || fixedArchive && resolveArchive) throw new Error("RECOVERY_TRANSFER_CONFIG");
1660
1728
  if (typeof assertAvailable !== "function" || !Number.isSafeInteger(bodyTimeoutMs) || bodyTimeoutMs < 10 || bodyTimeoutMs > 3e4) throw new Error("RECOVERY_TRANSFER_CONFIG");
1661
1729
  const peers = new Map(Object.entries(allowedPeers).map(([fingerprint, credential]) => [fingerprint.replaceAll(":", "").toLowerCase(), credential]));
@@ -1664,6 +1732,7 @@ function createRecoveryArchiveServer(options) {
1664
1732
  const server = createServer3({ ...tls, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
1665
1733
  const started = Date.now(), timings = {};
1666
1734
  let phase = "authenticate", action = "unknown", failure;
1735
+ let streamStats;
1667
1736
  const mark = (next) => {
1668
1737
  timings[phase] = Date.now() - started;
1669
1738
  phase = next;
@@ -1671,6 +1740,10 @@ function createRecoveryArchiveServer(options) {
1671
1740
  res.setHeader("Cache-Control", "no-store");
1672
1741
  const refuse = (status, error) => {
1673
1742
  if (!res.writableEnded && !res.destroyed) {
1743
+ if (res.headersSent) {
1744
+ res.destroy();
1745
+ return;
1746
+ }
1674
1747
  res.statusCode = status;
1675
1748
  res.setHeader("Content-Type", "application/json");
1676
1749
  res.end(JSON.stringify({ error }));
@@ -1708,6 +1781,11 @@ function createRecoveryArchiveServer(options) {
1708
1781
  const slot = { archiveDigest };
1709
1782
  slots.add(slot);
1710
1783
  busy.set(fingerprint, slots);
1784
+ const releaseSlot = () => {
1785
+ slots.delete(slot);
1786
+ if (!slots.size && busy.get(fingerprint) === slots) busy.delete(fingerprint);
1787
+ };
1788
+ res.once("close", releaseSlot);
1711
1789
  mark("body");
1712
1790
  const timer = setTimeout(() => {
1713
1791
  refuse(408, "RECOVERY_TRANSFER_REFUSED");
@@ -1723,8 +1801,8 @@ function createRecoveryArchiveServer(options) {
1723
1801
  }
1724
1802
  clearTimeout(timer);
1725
1803
  const input = JSON.parse(Buffer.concat(chunks).toString());
1726
- if (archiveDigest && input?.action !== "parts") throw new Error();
1727
- action = ["list", "read", "object", "objects", "parts", "manifests", "manifest-page"].includes(input?.action) ? input.action : "invalid";
1804
+ if (archiveDigest && !["parts", "stream"].includes(input?.action)) throw new Error();
1805
+ action = ["list", "read", "object", "objects", "parts", "stream", "manifests", "manifest-page"].includes(input?.action) ? input.action : "invalid";
1728
1806
  mark("resolve");
1729
1807
  if (input?.version === 1 && input.action === "list") {
1730
1808
  if (Object.keys(input).some((key) => !["version", "action"].includes(key))) throw new Error();
@@ -1739,8 +1817,8 @@ function createRecoveryArchiveServer(options) {
1739
1817
  return;
1740
1818
  }
1741
1819
  const ancestry = ["manifests", "manifest-page"].includes(input?.action), paged = input?.action === "manifest-page";
1742
- if (!input || input.version !== 1 || !["read", "object", "objects", "parts", "manifests", "manifest-page"].includes(input.action) || !validId(input.id) || Object.keys(input).some((key) => !["version", "action", "id", ...input.action === "object" ? ["ref"] : input.action === "objects" ? ["refs"] : input.action === "parts" ? ["parts"] : ancestry ? ["common"] : []].includes(key))) throw new Error();
1743
- await Promise.all([assertAvailable(), authority.status(principal)]);
1820
+ if (!input || input.version !== 1 || !["read", "object", "objects", "parts", "stream", "manifests", "manifest-page"].includes(input.action) || !validId(input.id) || Object.keys(input).some((key) => !["version", "action", "id", ...input.action === "object" ? ["ref"] : ["objects", "stream"].includes(input.action) ? ["refs"] : input.action === "parts" ? ["parts"] : ancestry ? ["common"] : []].includes(key))) throw new Error();
1821
+ await assertAvailable();
1744
1822
  if (ancestry && !validCommon(input.common)) throw new Error();
1745
1823
  const evidence = ancestry && readManifestEvidence ? await readManifestEvidence(input.id, input.common, paged ? 4 : void 0) : void 0;
1746
1824
  const archive = evidence ? void 0 : resolveArchive ? await resolveArchive(input.id) : fixedArchive;
@@ -1756,6 +1834,111 @@ function createRecoveryArchiveServer(options) {
1756
1834
  const floor = (await authority.status(principal)).deletionWatermark;
1757
1835
  await checkRecoveryDeletionAsync(entry.manifest, () => floor);
1758
1836
  mark("content");
1837
+ if (input.action === "stream") {
1838
+ if (!streaming || !archiveDigest) throw new Error();
1839
+ const requested = validateStreamRefs(input.refs), allowed = refs(entry);
1840
+ if (requested.some((ref) => allowed.get(ref.sha256)?.bytes !== ref.bytes)) throw new Error();
1841
+ let currentFloor = floor;
1842
+ const check = async () => {
1843
+ if (res.destroyed) throw new Error("RECOVERY_TRANSFER_UNAVAILABLE");
1844
+ const [control2] = await Promise.all([authority.status(principal), assertAvailable()]);
1845
+ currentFloor = await checkRecoveryDeletionAsync(entry.manifest, () => control2.deletionWatermark, currentFloor);
1846
+ if (res.destroyed) throw new Error("RECOVERY_TRANSFER_UNAVAILABLE");
1847
+ };
1848
+ const accepted2 = String(req.headers["accept-encoding"] ?? "").split(",").map((value) => value.trim());
1849
+ const encoding2 = accepted2.includes("br") ? "br" : accepted2.includes("gzip") ? "gzip" : void 0;
1850
+ streamStats = { encoding: encoding2 ?? "identity", objects: requested.length, batches: 0, rawBytes: 0, wireBytes: 0, readMs: 0, controlMs: 0, encodeAndWriteMs: 0 };
1851
+ const encoder = encoding2 === "br" ? createBrotliCompress(brotliOptions) : void 0, output = encoder ?? res;
1852
+ encoder?.on("data", (body2) => {
1853
+ streamStats.wireBytes += body2.length;
1854
+ });
1855
+ const streamed = encoder ? pipelineAsync(encoder, res) : void 0;
1856
+ void streamed?.catch(() => {
1857
+ });
1858
+ const write = (body2) => new Promise((resolve4, reject) => {
1859
+ if (res.destroyed || output.destroyed) {
1860
+ reject(new Error("RECOVERY_TRANSFER_UNAVAILABLE"));
1861
+ return;
1862
+ }
1863
+ if (!encoder) streamStats.wireBytes += body2.length;
1864
+ if (output.write(body2)) {
1865
+ resolve4();
1866
+ return;
1867
+ }
1868
+ const cleanup = () => {
1869
+ output.off("drain", drain);
1870
+ output.off("close", closed);
1871
+ output.off("error", closed);
1872
+ };
1873
+ const drain = () => {
1874
+ cleanup();
1875
+ resolve4();
1876
+ }, closed = () => {
1877
+ cleanup();
1878
+ reject(new Error("RECOVERY_TRANSFER_UNAVAILABLE"));
1879
+ };
1880
+ output.once("drain", drain);
1881
+ output.once("close", closed);
1882
+ output.once("error", closed);
1883
+ });
1884
+ res.setHeader("Content-Type", "application/octet-stream");
1885
+ if (encoding2) {
1886
+ res.setHeader("Content-Encoding", encoding2);
1887
+ res.setHeader("Vary", "Accept-Encoding");
1888
+ }
1889
+ try {
1890
+ for (let offset = 0; offset < requested.length; ) {
1891
+ let end = offset, bytes2 = 0;
1892
+ while (end < requested.length && end - offset < streamBatchObjects && bytes2 + requested[end].bytes <= streamBatchBytes) {
1893
+ bytes2 += requested[end].bytes;
1894
+ end++;
1895
+ }
1896
+ if (res.destroyed) throw new Error("RECOVERY_TRANSFER_UNAVAILABLE");
1897
+ let step = Date.now();
1898
+ const results = await Promise.allSettled(requested.slice(offset, end).map((ref) => archive.objects.read(ref)));
1899
+ for (const result of results) if (result.status === "rejected") throw result.reason;
1900
+ streamStats.readMs += Date.now() - step;
1901
+ step = Date.now();
1902
+ await check();
1903
+ streamStats.controlMs += Date.now() - step;
1904
+ step = Date.now();
1905
+ const bodies = results.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
1906
+ if (encoder) {
1907
+ await write(Buffer.concat(bodies));
1908
+ await new Promise((resolve4, reject) => {
1909
+ const cleanup = () => {
1910
+ encoder.off("error", failed);
1911
+ encoder.off("close", closed);
1912
+ };
1913
+ const failed = (error) => {
1914
+ cleanup();
1915
+ reject(error);
1916
+ }, closed = () => failed(new Error("RECOVERY_TRANSFER_UNAVAILABLE"));
1917
+ encoder.once("error", failed);
1918
+ encoder.once("close", closed);
1919
+ encoder.flush(constants3.BROTLI_OPERATION_FLUSH, () => {
1920
+ cleanup();
1921
+ resolve4();
1922
+ });
1923
+ });
1924
+ } else if (encoding2 === "gzip") await write(gzipSync(Buffer.concat(bodies), { level: 1 }));
1925
+ else for (const body2 of bodies) await write(body2);
1926
+ streamStats.encodeAndWriteMs += Date.now() - step;
1927
+ streamStats.rawBytes += bytes2;
1928
+ streamStats.batches++;
1929
+ offset = end;
1930
+ }
1931
+ await check();
1932
+ mark("reply");
1933
+ if (encoder) {
1934
+ encoder.end();
1935
+ await streamed;
1936
+ } else res.end();
1937
+ return;
1938
+ } finally {
1939
+ encoder?.destroy();
1940
+ }
1941
+ }
1759
1942
  let body;
1760
1943
  if (ancestry) {
1761
1944
  if (!evidence && !readManifests || entry.kind !== "LOCAL") throw new Error();
@@ -1776,6 +1959,7 @@ function createRecoveryArchiveServer(options) {
1776
1959
  body = Buffer.from(JSON.stringify(entry));
1777
1960
  if (body.length > metadataLimit) throw new Error();
1778
1961
  res.setHeader("Content-Type", "application/json");
1962
+ if (streaming) res.setHeader("X-Engine7-Recovery-Stream", "1");
1779
1963
  } else if (input.action === "parts") {
1780
1964
  const group = validateObjectParts(input.parts), allowed = refs(entry), parts = [];
1781
1965
  if (group.some((part) => allowed.get(part.ref.sha256)?.bytes !== part.ref.bytes)) throw new Error();
@@ -1802,6 +1986,16 @@ function createRecoveryArchiveServer(options) {
1802
1986
  const [control] = await Promise.all([authority.status(principal), assertAvailable()]), latest = control.deletionWatermark;
1803
1987
  await checkRecoveryDeletionAsync(entry.manifest, () => latest, floor);
1804
1988
  mark("reply");
1989
+ const accepted = String(req.headers["accept-encoding"] ?? "").split(",").map((value) => value.trim());
1990
+ const encoding = accepted.includes("br") ? "br" : accepted.includes("gzip") ? "gzip" : void 0;
1991
+ if (encoding) {
1992
+ const compressed = encoding === "br" ? brotliCompressSync(body, brotliOptions) : gzipSync(body, { level: 1 });
1993
+ if (res.getHeader("Content-Type") === "application/json" || compressed.length < body.length) {
1994
+ body = compressed;
1995
+ res.setHeader("Content-Encoding", encoding);
1996
+ res.setHeader("Vary", "Accept-Encoding");
1997
+ }
1998
+ }
1805
1999
  res.setHeader("Content-Length", body.length);
1806
2000
  res.end(body);
1807
2001
  } catch (error) {
@@ -1809,9 +2003,8 @@ function createRecoveryArchiveServer(options) {
1809
2003
  refuse(409, "RECOVERY_TRANSFER_REFUSED");
1810
2004
  } finally {
1811
2005
  clearTimeout(timer);
1812
- slots.delete(slot);
1813
- if (!slots.size) busy.delete(fingerprint);
1814
- if (failure || Date.now() - started >= 5e3) process.stderr.write("[travel-archive] " + JSON.stringify({ at: Date.now(), action, phase, elapsedMs: Date.now() - started, timings, failure }) + "\n");
2006
+ releaseSlot();
2007
+ if (failure || Date.now() - started >= 5e3) process.stderr.write("[travel-archive] " + JSON.stringify({ at: Date.now(), action, phase, elapsedMs: Date.now() - started, timings, stream: streamStats, failure }) + "\n");
1815
2008
  }
1816
2009
  });
1817
2010
  server.headersTimeout = 5e3;
@@ -1875,7 +2068,7 @@ async function createTravelNodeDataServer(options) {
1875
2068
 
1876
2069
  // src/continuity/controller-main.ts
1877
2070
  var path = (value) => {
1878
- if (typeof value !== "string" || !isAbsolute(value) || resolve2(value) !== value) throw new Error("TRAVEL_CONTROLLER_PATH");
2071
+ if (typeof value !== "string" || !isAbsolute2(value) || resolve3(value) !== value) throw new Error("TRAVEL_CONTROLLER_PATH");
1879
2072
  return value;
1880
2073
  };
1881
2074
  function openTravelController(input) {
@@ -1889,7 +2082,7 @@ function openTravelController(input) {
1889
2082
  privateKey.fill(0);
1890
2083
  };
1891
2084
  try {
1892
- const tls = { ca: readFileSync3(path(config.tls?.caFile)), cert: readFileSync3(path(config.tls?.certFile)), key: privateKey };
2085
+ const tls = { ca: readFileSync2(path(config.tls?.caFile)), cert: readFileSync2(path(config.tls?.certFile)), key: privateKey };
1893
2086
  for (const [nodeId, value] of Object.entries(config.nodes)) {
1894
2087
  if (!nodeSupervisorId(nodeId) || !nodeSupervisorRecord(value) || !nodeSupervisorRecord(value.principal) || value.principal.nodeId !== nodeId) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
1895
2088
  const principal = value.principal;
@@ -1950,7 +2143,7 @@ async function runTravelControllerCli(args) {
1950
2143
  await service.close();
1951
2144
  }
1952
2145
  }
1953
- if (process.argv[1] && /[\\/](controller-main\.ts|travel-controller\.mjs)$/.test(fileURLToPath(import.meta.url)) && resolve2(process.argv[1]) === fileURLToPath(import.meta.url)) {
2146
+ if (process.argv[1] && /[\\/](controller-main\.ts|travel-controller\.mjs)$/.test(fileURLToPath(import.meta.url)) && resolve3(process.argv[1]) === fileURLToPath(import.meta.url)) {
1954
2147
  runTravelControllerCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch(() => {
1955
2148
  process.stderr.write("TRAVEL_CONTROLLER_REFUSED\n");
1956
2149
  process.exitCode = 1;