engine7 7.1.138 → 7.1.140

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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,8 +333,11 @@ 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;
@@ -343,7 +351,7 @@ var TravelController = class {
343
351
  }
344
352
  const source2 = this.options.nodes[status.activeNodeId];
345
353
  if (!source2) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
346
- if (!await this.replicate(source2, target)) return;
354
+ if (!await this.replicate(source2, target, true)) return;
347
355
  this.db.prepare("UPDATE jobs SET source=?,state='PREPARING' WHERE id=?").run(source2.principal.nodeId, job.id);
348
356
  await control.beginHandoff(source2.principal, await source2.permit(), job.id, job.target);
349
357
  return;
@@ -540,9 +548,12 @@ var TravelReportClient = class {
540
548
  this.timeout = options.timeoutMs ?? 8e3;
541
549
  if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
542
550
  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 });
551
+ const tls = { ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, maxSockets: 1 };
552
+ this.agent = new Agent({ ...tls, keepAlive: true });
553
+ this.mutationAgent = new Agent({ ...tls, keepAlive: false });
544
554
  }
545
555
  agent;
556
+ mutationAgent;
546
557
  key;
547
558
  url;
548
559
  timeout;
@@ -559,7 +570,7 @@ var TravelReportClient = class {
559
570
  const unavailable = () => new Error(this.closed ? "TRAVEL_CONTROL_CLOSED" : "TRAVEL_CONTROL_UNAVAILABLE");
560
571
  const remaining = deadline - performance.now();
561
572
  if (remaining <= 0) return Promise.reject(unavailable());
562
- return new Promise((resolve3, reject) => {
573
+ return new Promise((resolve4, reject) => {
563
574
  let complete = false, responseStarted = false;
564
575
  const finish = (error, value) => {
565
576
  if (complete) return;
@@ -567,9 +578,9 @@ var TravelReportClient = class {
567
578
  clearTimeout(timer);
568
579
  this.pending.delete(req);
569
580
  if (error) reject(error);
570
- else resolve3(value);
581
+ else resolve4(value);
571
582
  };
572
- const req = request(this.url, { method: "POST", agent: this.agent, headers: {
583
+ const req = request(this.url, { method: "POST", agent: readActions.has(input?.action) ? this.agent : this.mutationAgent, headers: {
573
584
  Authorization: "Bearer " + this.options.credential,
574
585
  "X-Engine7-Travel-Node": this.options.nodeId,
575
586
  "Content-Type": "application/json",
@@ -620,7 +631,7 @@ var TravelReportClient = class {
620
631
  complete = true;
621
632
  clearTimeout(timer);
622
633
  this.pending.delete(req);
623
- resolve3(this.attempt(input, false, deadline, body));
634
+ resolve4(this.attempt(input, false, deadline, body));
624
635
  } else finish(unavailable());
625
636
  });
626
637
  req.once("close", () => {
@@ -644,6 +655,7 @@ var TravelReportClient = class {
644
655
  this.closed = true;
645
656
  for (const req of this.pending) req.destroy();
646
657
  this.agent.destroy();
658
+ this.mutationAgent.destroy();
647
659
  this.key?.fill(0);
648
660
  }
649
661
  };
@@ -732,7 +744,22 @@ import { Agent as Agent2, request as request2 } from "node:https";
732
744
  // src/continuity/publication.ts
733
745
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
734
746
  import { createHash } from "node:crypto";
735
- var PUBLICATION_MANIFEST_BYTES = 4 * 1024 * 1024;
747
+
748
+ // src/continuity/inventory.ts
749
+ import { isAbsolute, join as join3, relative, resolve as resolve2, sep } from "node:path";
750
+ 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(" "));
751
+ 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(" "));
752
+ 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(" "));
753
+ function validateRelativePath(path2) {
754
+ if (typeof path2 !== "string" || !path2 || path2.length > 2048 || isAbsolute(path2)) throw new Error("INVALID_ARTIFACT_PATH");
755
+ for (const part of path2.split("/")) {
756
+ 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)))
757
+ throw new Error("INVALID_ARTIFACT_PATH");
758
+ }
759
+ }
760
+
761
+ // src/continuity/publication.ts
762
+ var PUBLICATION_MANIFEST_BYTES = 32 * 1024 * 1024;
736
763
  var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
737
764
  var ZERO = "0".repeat(64);
738
765
  var HASH2 = /^[a-f0-9]{64}$/;
@@ -773,8 +800,12 @@ function normalizePublicationProfile(value) {
773
800
  return Object.freeze(profile);
774
801
  }
775
802
  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)))
803
+ if (typeof path2 !== "string" || path2.normalize("NFC") !== path2) throw new Error("PUBLICATION_INVALID_PATH");
804
+ try {
805
+ validateRelativePath(path2);
806
+ } catch {
777
807
  throw new Error("PUBLICATION_INVALID_PATH");
808
+ }
778
809
  }
779
810
  function normalizePublication(value) {
780
811
  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 +881,7 @@ var nodeSupervisorErrors = /* @__PURE__ */ new Set([
850
881
  "TRAVEL_NODE_CANCELLED",
851
882
  "TRAVEL_NODE_BOOT_MISMATCH",
852
883
  "TRAVEL_NODE_CHECKPOINT",
884
+ "TRAVEL_NODE_COMMON_CHECKPOINT",
853
885
  "TRAVEL_NODE_GENERATION_COLLISION",
854
886
  "TRAVEL_NODE_KEY_UNAVAILABLE",
855
887
  "TRAVEL_NODE_KEY_BARRIER",
@@ -941,14 +973,17 @@ var RemoteTravelNodeSupervisor = class {
941
973
  observeQuery;
942
974
  permitQuery;
943
975
  closed = false;
944
- call(action, args = {}, discover = false) {
976
+ call(action, args = {}, discover = false, retryStale = true, deadline, wireBody) {
945
977
  if (this.closed) return Promise.reject(new Error("TRAVEL_NODE_CLOSED"));
946
978
  const slot = action === "stop" ? "stop" : action === "observe" ? "observe" : action === "permit" ? "permit" : "operation";
947
979
  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 } }));
980
+ const body = wireBody ?? Buffer.from(JSON.stringify({ node: { version: 1, nodeId: this.principal.nodeId, ...discover ? {} : { bootId: this.bootId }, action, ...args } }));
949
981
  if (body.length > nodeSupervisorLimit) return Promise.reject(new Error("TRAVEL_NODE_INVALID_REQUEST"));
950
982
  const unavailable = () => new Error(this.closed ? "TRAVEL_NODE_CLOSED" : "TRAVEL_NODE_UNAVAILABLE");
951
- return new Promise((resolve3, reject) => {
983
+ deadline ??= performance.now() + (slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
984
+ const remaining = deadline - performance.now();
985
+ if (remaining <= 0) return Promise.reject(unavailable());
986
+ return new Promise((resolve4, reject) => {
952
987
  const started = performance.now();
953
988
  let responseStarted = false, receivedBytes = 0, reported = false;
954
989
  const lost = (code) => {
@@ -1007,21 +1042,24 @@ var RemoteTravelNodeSupervisor = class {
1007
1042
  return;
1008
1043
  }
1009
1044
  if (discover) this.bootId = response.bootId;
1010
- resolve3(response.result);
1045
+ resolve4(response.result);
1011
1046
  });
1012
1047
  });
1013
1048
  this.pending.set(req, slot);
1014
1049
  const timer = setTimeout(() => {
1015
1050
  lost("TIMEOUT");
1016
1051
  req.destroy();
1017
- }, slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
1052
+ }, remaining);
1018
1053
  const cleanup = () => {
1019
1054
  clearTimeout(timer);
1020
1055
  this.pending.delete(req);
1021
1056
  };
1022
1057
  req.once("error", (error) => {
1023
1058
  cleanup();
1024
- lost(error.code);
1059
+ if (!reported && retryStale && !this.closed && !responseStarted && (slot === "observe" || slot === "permit") && req.reusedSocket && error.code === "ECONNRESET") {
1060
+ reported = true;
1061
+ resolve4(this.call(action, args, discover, false, deadline, body));
1062
+ } else lost(error.code);
1025
1063
  });
1026
1064
  req.once("close", cleanup);
1027
1065
  req.end(body);
@@ -1105,7 +1143,7 @@ var RemoteTravelNodeSupervisor = class {
1105
1143
 
1106
1144
  // src/continuity/key-service-store.ts
1107
1145
  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";
1146
+ 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
1147
  function assertPrivateStat(stat, directory) {
1110
1148
  if ((directory ? !stat.isDirectory() : !stat.isFile()) || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
1111
1149
  throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
@@ -1117,7 +1155,7 @@ function readPrivateFile(path2, maximumBytes = 65536) {
1117
1155
  const stat = fstatSync2(fd);
1118
1156
  assertPrivateStat(stat, false);
1119
1157
  if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
1120
- return readFileSync2(fd);
1158
+ return readFileSync(fd);
1121
1159
  } finally {
1122
1160
  closeSync2(fd);
1123
1161
  }
@@ -1285,9 +1323,12 @@ var RemoteTravelDataAuthority = class {
1285
1323
  this.grants = grants.map((grant) => ({ ...grant, principal: Object.freeze({ ...grant.principal }) }));
1286
1324
  }
1287
1325
  async authenticate(credential) {
1326
+ return Object.freeze({ ...(await this.readIdentity(credential)).principal });
1327
+ }
1328
+ readIdentity(credential) {
1288
1329
  const grant = this.grants.find((grant2) => grant2.credential === credential);
1289
1330
  if (!grant) throw new Error("TRAVEL_AUTH_DENIED");
1290
- return Object.freeze({ ...(await this.read(grant)).principal });
1331
+ return this.read(grant);
1291
1332
  }
1292
1333
  grant(principal) {
1293
1334
  const grant = this.grants.find((grant2) => equal(principal, grant2.principal));
@@ -1337,9 +1378,8 @@ var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteT
1337
1378
  }
1338
1379
  const remote = new _RemoteTravelNodeAuthority(options.publicKey, options.grants);
1339
1380
  for (const grant of options.grants) {
1340
- const identity = await grant.client.identity();
1381
+ const identity = await remote.readIdentity(grant.credential);
1341
1382
  if (identity.publicKey !== options.publicKey) throw new Error("TRAVEL_NODE_SIGNER_MISMATCH");
1342
- await remote.authenticate(grant.credential);
1343
1383
  }
1344
1384
  return remote;
1345
1385
  }
@@ -1486,7 +1526,7 @@ function createPublicationServer(options) {
1486
1526
  };
1487
1527
  switch (value.operation) {
1488
1528
  case "status":
1489
- result = preservePublished ? await mutate(() => receiver.status()) : await receiver.status();
1529
+ result = preservePublished ? await mutate(() => receiver.status(false)) : await receiver.status(false);
1490
1530
  break;
1491
1531
  case "replication-status":
1492
1532
  result = await receiver.replicationStatus();
@@ -1494,7 +1534,6 @@ function createPublicationServer(options) {
1494
1534
  case "missing": {
1495
1535
  if (!Array.isArray(value.refs) || value.refs.length > 128) throw new Error("PUBLICATION_INVALID_OBJECT_LIST");
1496
1536
  const missing = await Promise.all(value.refs.map(async (ref) => {
1497
- await check();
1498
1537
  validateObjectRef(ref);
1499
1538
  return await receiver.objects.has(ref) ? null : ref.sha256;
1500
1539
  }));
@@ -1545,6 +1584,8 @@ function createPublicationServer(options) {
1545
1584
 
1546
1585
  // src/continuity/recovery-archive-transfer.ts
1547
1586
  import { Agent as Agent4, createServer as createServer3, request as request4 } from "node:https";
1587
+ import { gzipSync, gunzipSync, createGunzip, brotliCompressSync, brotliDecompressSync, createBrotliCompress, createBrotliDecompress, constants as constants3 } from "node:zlib";
1588
+ import { pipeline as pipelineAsync } from "node:stream/promises";
1548
1589
 
1549
1590
  // src/continuity/recovery-archive.ts
1550
1591
  import { DatabaseSync as DatabaseSync5, backup } from "node:sqlite";
@@ -1557,7 +1598,8 @@ var HEADER_SIZE = MAGIC2.length + 12;
1557
1598
  import { createHash as createHash4 } from "node:crypto";
1558
1599
  var ID2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
1559
1600
  var FORMAT = "engine7-runtime-recovery-archive-v1";
1560
- var MAX_METADATA = 16 * 1024 * 1024;
1601
+ var RECOVERY_ARCHIVE_METADATA_BYTES = PUBLICATION_MANIFEST_BYTES + 8 * 1024 * 1024;
1602
+ var MAX_METADATA = RECOVERY_ARCHIVE_METADATA_BYTES;
1561
1603
  var same2 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
1562
1604
  function validateRecoveryArchiveEntry(entry, identity) {
1563
1605
  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 +1642,24 @@ async function checkRecoveryDeletionAsync(manifest, current, previous = 0) {
1600
1642
 
1601
1643
  // src/continuity/recovery-archive-transfer.ts
1602
1644
  var endpoint = "/travel/archives/v1";
1603
- var metadataLimit = 16 * 1024 * 1024;
1645
+ var metadataLimit = RECOVERY_ARCHIVE_METADATA_BYTES;
1604
1646
  var requestLimit = 65536;
1605
1647
  var objectGroupLimit = 8;
1606
1648
  var partBodyLimit = 65536;
1649
+ var streamRefLimit = 512;
1650
+ var streamBatchBytes = 8 * 1024 * 1024;
1651
+ var streamBatchObjects = 128;
1652
+ var brotliOptions = { params: { [constants3.BROTLI_PARAM_QUALITY]: 4, [constants3.BROTLI_PARAM_LGWIN]: 22 } };
1653
+ function validateStreamRefs(value) {
1654
+ if (!Array.isArray(value) || value.length < 1 || value.length > streamRefLimit) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
1655
+ const seen = /* @__PURE__ */ new Set();
1656
+ for (const ref of value) {
1657
+ validateObjectRef(ref);
1658
+ if (Object.keys(ref).length !== 2 || seen.has(ref.sha256)) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
1659
+ seen.add(ref.sha256);
1660
+ }
1661
+ return value;
1662
+ }
1607
1663
  var validId = (id2) => typeof id2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(id2);
1608
1664
  function validateObjectParts(value) {
1609
1665
  if (!Array.isArray(value) || value.length < 1 || value.length > objectGroupLimit) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
@@ -1655,7 +1711,7 @@ function refs(entry) {
1655
1711
  return result;
1656
1712
  }
1657
1713
  function createRecoveryArchiveServer(options) {
1658
- const { archive: fixedArchive, resolveArchive, listReceipts, readManifests, readManifestEvidence, identity = options.archive?.objects.identity, authority, allowedPeers, assertAvailable, bodyTimeoutMs = 5e3, ...tls } = options;
1714
+ const { archive: fixedArchive, resolveArchive, listReceipts, readManifests, readManifestEvidence, identity = options.archive?.objects.identity, authority, allowedPeers, assertAvailable, bodyTimeoutMs = 5e3, streaming = true, ...tls } = options;
1659
1715
  if (!identity || !fixedArchive && !resolveArchive || fixedArchive && resolveArchive) throw new Error("RECOVERY_TRANSFER_CONFIG");
1660
1716
  if (typeof assertAvailable !== "function" || !Number.isSafeInteger(bodyTimeoutMs) || bodyTimeoutMs < 10 || bodyTimeoutMs > 3e4) throw new Error("RECOVERY_TRANSFER_CONFIG");
1661
1717
  const peers = new Map(Object.entries(allowedPeers).map(([fingerprint, credential]) => [fingerprint.replaceAll(":", "").toLowerCase(), credential]));
@@ -1664,6 +1720,7 @@ function createRecoveryArchiveServer(options) {
1664
1720
  const server = createServer3({ ...tls, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
1665
1721
  const started = Date.now(), timings = {};
1666
1722
  let phase = "authenticate", action = "unknown", failure;
1723
+ let streamStats;
1667
1724
  const mark = (next) => {
1668
1725
  timings[phase] = Date.now() - started;
1669
1726
  phase = next;
@@ -1671,6 +1728,10 @@ function createRecoveryArchiveServer(options) {
1671
1728
  res.setHeader("Cache-Control", "no-store");
1672
1729
  const refuse = (status, error) => {
1673
1730
  if (!res.writableEnded && !res.destroyed) {
1731
+ if (res.headersSent) {
1732
+ res.destroy();
1733
+ return;
1734
+ }
1674
1735
  res.statusCode = status;
1675
1736
  res.setHeader("Content-Type", "application/json");
1676
1737
  res.end(JSON.stringify({ error }));
@@ -1708,6 +1769,11 @@ function createRecoveryArchiveServer(options) {
1708
1769
  const slot = { archiveDigest };
1709
1770
  slots.add(slot);
1710
1771
  busy.set(fingerprint, slots);
1772
+ const releaseSlot = () => {
1773
+ slots.delete(slot);
1774
+ if (!slots.size && busy.get(fingerprint) === slots) busy.delete(fingerprint);
1775
+ };
1776
+ res.once("close", releaseSlot);
1711
1777
  mark("body");
1712
1778
  const timer = setTimeout(() => {
1713
1779
  refuse(408, "RECOVERY_TRANSFER_REFUSED");
@@ -1723,8 +1789,8 @@ function createRecoveryArchiveServer(options) {
1723
1789
  }
1724
1790
  clearTimeout(timer);
1725
1791
  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";
1792
+ if (archiveDigest && !["parts", "stream"].includes(input?.action)) throw new Error();
1793
+ action = ["list", "read", "object", "objects", "parts", "stream", "manifests", "manifest-page"].includes(input?.action) ? input.action : "invalid";
1728
1794
  mark("resolve");
1729
1795
  if (input?.version === 1 && input.action === "list") {
1730
1796
  if (Object.keys(input).some((key) => !["version", "action"].includes(key))) throw new Error();
@@ -1739,8 +1805,8 @@ function createRecoveryArchiveServer(options) {
1739
1805
  return;
1740
1806
  }
1741
1807
  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)]);
1808
+ 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();
1809
+ await assertAvailable();
1744
1810
  if (ancestry && !validCommon(input.common)) throw new Error();
1745
1811
  const evidence = ancestry && readManifestEvidence ? await readManifestEvidence(input.id, input.common, paged ? 4 : void 0) : void 0;
1746
1812
  const archive = evidence ? void 0 : resolveArchive ? await resolveArchive(input.id) : fixedArchive;
@@ -1756,6 +1822,111 @@ function createRecoveryArchiveServer(options) {
1756
1822
  const floor = (await authority.status(principal)).deletionWatermark;
1757
1823
  await checkRecoveryDeletionAsync(entry.manifest, () => floor);
1758
1824
  mark("content");
1825
+ if (input.action === "stream") {
1826
+ if (!streaming || !archiveDigest) throw new Error();
1827
+ const requested = validateStreamRefs(input.refs), allowed = refs(entry);
1828
+ if (requested.some((ref) => allowed.get(ref.sha256)?.bytes !== ref.bytes)) throw new Error();
1829
+ let currentFloor = floor;
1830
+ const check = async () => {
1831
+ if (res.destroyed) throw new Error("RECOVERY_TRANSFER_UNAVAILABLE");
1832
+ const [control2] = await Promise.all([authority.status(principal), assertAvailable()]);
1833
+ currentFloor = await checkRecoveryDeletionAsync(entry.manifest, () => control2.deletionWatermark, currentFloor);
1834
+ if (res.destroyed) throw new Error("RECOVERY_TRANSFER_UNAVAILABLE");
1835
+ };
1836
+ const accepted2 = String(req.headers["accept-encoding"] ?? "").split(",").map((value) => value.trim());
1837
+ const encoding2 = accepted2.includes("br") ? "br" : accepted2.includes("gzip") ? "gzip" : void 0;
1838
+ streamStats = { encoding: encoding2 ?? "identity", objects: requested.length, batches: 0, rawBytes: 0, wireBytes: 0, readMs: 0, controlMs: 0, encodeAndWriteMs: 0 };
1839
+ const encoder = encoding2 === "br" ? createBrotliCompress(brotliOptions) : void 0, output = encoder ?? res;
1840
+ encoder?.on("data", (body2) => {
1841
+ streamStats.wireBytes += body2.length;
1842
+ });
1843
+ const streamed = encoder ? pipelineAsync(encoder, res) : void 0;
1844
+ void streamed?.catch(() => {
1845
+ });
1846
+ const write = (body2) => new Promise((resolve4, reject) => {
1847
+ if (res.destroyed || output.destroyed) {
1848
+ reject(new Error("RECOVERY_TRANSFER_UNAVAILABLE"));
1849
+ return;
1850
+ }
1851
+ if (!encoder) streamStats.wireBytes += body2.length;
1852
+ if (output.write(body2)) {
1853
+ resolve4();
1854
+ return;
1855
+ }
1856
+ const cleanup = () => {
1857
+ output.off("drain", drain);
1858
+ output.off("close", closed);
1859
+ output.off("error", closed);
1860
+ };
1861
+ const drain = () => {
1862
+ cleanup();
1863
+ resolve4();
1864
+ }, closed = () => {
1865
+ cleanup();
1866
+ reject(new Error("RECOVERY_TRANSFER_UNAVAILABLE"));
1867
+ };
1868
+ output.once("drain", drain);
1869
+ output.once("close", closed);
1870
+ output.once("error", closed);
1871
+ });
1872
+ res.setHeader("Content-Type", "application/octet-stream");
1873
+ if (encoding2) {
1874
+ res.setHeader("Content-Encoding", encoding2);
1875
+ res.setHeader("Vary", "Accept-Encoding");
1876
+ }
1877
+ try {
1878
+ for (let offset = 0; offset < requested.length; ) {
1879
+ let end = offset, bytes2 = 0;
1880
+ while (end < requested.length && end - offset < streamBatchObjects && bytes2 + requested[end].bytes <= streamBatchBytes) {
1881
+ bytes2 += requested[end].bytes;
1882
+ end++;
1883
+ }
1884
+ if (res.destroyed) throw new Error("RECOVERY_TRANSFER_UNAVAILABLE");
1885
+ let step = Date.now();
1886
+ const results = await Promise.allSettled(requested.slice(offset, end).map((ref) => archive.objects.read(ref)));
1887
+ for (const result of results) if (result.status === "rejected") throw result.reason;
1888
+ streamStats.readMs += Date.now() - step;
1889
+ step = Date.now();
1890
+ await check();
1891
+ streamStats.controlMs += Date.now() - step;
1892
+ step = Date.now();
1893
+ const bodies = results.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
1894
+ if (encoder) {
1895
+ await write(Buffer.concat(bodies));
1896
+ await new Promise((resolve4, reject) => {
1897
+ const cleanup = () => {
1898
+ encoder.off("error", failed);
1899
+ encoder.off("close", closed);
1900
+ };
1901
+ const failed = (error) => {
1902
+ cleanup();
1903
+ reject(error);
1904
+ }, closed = () => failed(new Error("RECOVERY_TRANSFER_UNAVAILABLE"));
1905
+ encoder.once("error", failed);
1906
+ encoder.once("close", closed);
1907
+ encoder.flush(constants3.BROTLI_OPERATION_FLUSH, () => {
1908
+ cleanup();
1909
+ resolve4();
1910
+ });
1911
+ });
1912
+ } else if (encoding2 === "gzip") await write(gzipSync(Buffer.concat(bodies), { level: 1 }));
1913
+ else for (const body2 of bodies) await write(body2);
1914
+ streamStats.encodeAndWriteMs += Date.now() - step;
1915
+ streamStats.rawBytes += bytes2;
1916
+ streamStats.batches++;
1917
+ offset = end;
1918
+ }
1919
+ await check();
1920
+ mark("reply");
1921
+ if (encoder) {
1922
+ encoder.end();
1923
+ await streamed;
1924
+ } else res.end();
1925
+ return;
1926
+ } finally {
1927
+ encoder?.destroy();
1928
+ }
1929
+ }
1759
1930
  let body;
1760
1931
  if (ancestry) {
1761
1932
  if (!evidence && !readManifests || entry.kind !== "LOCAL") throw new Error();
@@ -1776,6 +1947,7 @@ function createRecoveryArchiveServer(options) {
1776
1947
  body = Buffer.from(JSON.stringify(entry));
1777
1948
  if (body.length > metadataLimit) throw new Error();
1778
1949
  res.setHeader("Content-Type", "application/json");
1950
+ if (streaming) res.setHeader("X-Engine7-Recovery-Stream", "1");
1779
1951
  } else if (input.action === "parts") {
1780
1952
  const group = validateObjectParts(input.parts), allowed = refs(entry), parts = [];
1781
1953
  if (group.some((part) => allowed.get(part.ref.sha256)?.bytes !== part.ref.bytes)) throw new Error();
@@ -1802,6 +1974,16 @@ function createRecoveryArchiveServer(options) {
1802
1974
  const [control] = await Promise.all([authority.status(principal), assertAvailable()]), latest = control.deletionWatermark;
1803
1975
  await checkRecoveryDeletionAsync(entry.manifest, () => latest, floor);
1804
1976
  mark("reply");
1977
+ const accepted = String(req.headers["accept-encoding"] ?? "").split(",").map((value) => value.trim());
1978
+ const encoding = accepted.includes("br") ? "br" : accepted.includes("gzip") ? "gzip" : void 0;
1979
+ if (encoding) {
1980
+ const compressed = encoding === "br" ? brotliCompressSync(body, brotliOptions) : gzipSync(body, { level: 1 });
1981
+ if (res.getHeader("Content-Type") === "application/json" || compressed.length < body.length) {
1982
+ body = compressed;
1983
+ res.setHeader("Content-Encoding", encoding);
1984
+ res.setHeader("Vary", "Accept-Encoding");
1985
+ }
1986
+ }
1805
1987
  res.setHeader("Content-Length", body.length);
1806
1988
  res.end(body);
1807
1989
  } catch (error) {
@@ -1809,9 +1991,8 @@ function createRecoveryArchiveServer(options) {
1809
1991
  refuse(409, "RECOVERY_TRANSFER_REFUSED");
1810
1992
  } finally {
1811
1993
  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");
1994
+ releaseSlot();
1995
+ 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
1996
  }
1816
1997
  });
1817
1998
  server.headersTimeout = 5e3;
@@ -1875,7 +2056,7 @@ async function createTravelNodeDataServer(options) {
1875
2056
 
1876
2057
  // src/continuity/controller-main.ts
1877
2058
  var path = (value) => {
1878
- if (typeof value !== "string" || !isAbsolute(value) || resolve2(value) !== value) throw new Error("TRAVEL_CONTROLLER_PATH");
2059
+ if (typeof value !== "string" || !isAbsolute2(value) || resolve3(value) !== value) throw new Error("TRAVEL_CONTROLLER_PATH");
1879
2060
  return value;
1880
2061
  };
1881
2062
  function openTravelController(input) {
@@ -1889,7 +2070,7 @@ function openTravelController(input) {
1889
2070
  privateKey.fill(0);
1890
2071
  };
1891
2072
  try {
1892
- const tls = { ca: readFileSync3(path(config.tls?.caFile)), cert: readFileSync3(path(config.tls?.certFile)), key: privateKey };
2073
+ const tls = { ca: readFileSync2(path(config.tls?.caFile)), cert: readFileSync2(path(config.tls?.certFile)), key: privateKey };
1893
2074
  for (const [nodeId, value] of Object.entries(config.nodes)) {
1894
2075
  if (!nodeSupervisorId(nodeId) || !nodeSupervisorRecord(value) || !nodeSupervisorRecord(value.principal) || value.principal.nodeId !== nodeId) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
1895
2076
  const principal = value.principal;
@@ -1950,7 +2131,7 @@ async function runTravelControllerCli(args) {
1950
2131
  await service.close();
1951
2132
  }
1952
2133
  }
1953
- if (process.argv[1] && /[\\/](controller-main\.ts|travel-controller\.mjs)$/.test(fileURLToPath(import.meta.url)) && resolve2(process.argv[1]) === fileURLToPath(import.meta.url)) {
2134
+ if (process.argv[1] && /[\\/](controller-main\.ts|travel-controller\.mjs)$/.test(fileURLToPath(import.meta.url)) && resolve3(process.argv[1]) === fileURLToPath(import.meta.url)) {
1954
2135
  runTravelControllerCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch(() => {
1955
2136
  process.stderr.write("TRAVEL_CONTROLLER_REFUSED\n");
1956
2137
  process.exitCode = 1;