engine7 7.1.133 → 7.1.136

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.
Files changed (42) hide show
  1. package/README.md +1 -0
  2. package/dist/auth-server.mjs +632 -0
  3. package/dist/bg-worker.mjs +31660 -28486
  4. package/dist/cc-desktop.mjs +951 -0
  5. package/dist/cli.mjs +41446 -30183
  6. package/dist/engine-startup.mjs +59137 -46007
  7. package/dist/main.mjs +50062 -36930
  8. package/dist/recall-worker.mjs +20443 -0
  9. package/dist/sqlite-maintenance-worker.mjs +1163 -124
  10. package/dist/stop-history-worker.mjs +180 -0
  11. package/dist/topics-worker.mjs +3350 -1078
  12. package/dist/travel-authority.mjs +1068 -0
  13. package/dist/travel-console.mjs +2205 -0
  14. package/dist/travel-controller.mjs +1883 -0
  15. package/dist/travel-data.mjs +7250 -0
  16. package/dist/travel-gateway.mjs +3258 -0
  17. package/dist/travel-key-service.mjs +483 -0
  18. package/dist/travel-node-data.mjs +4930 -0
  19. package/dist/travel-node.mjs +21233 -0
  20. package/dist/travel-retire.mjs +1094 -0
  21. package/dist/web-console.mjs +2425 -0
  22. package/package.json +32 -17
  23. package/templates/config.template.json +45 -0
  24. package/templates/skills/auth-connect/SKILL.md +22 -0
  25. package/templates/skills/email/SKILL.md +119 -115
  26. package/templates/skills/email/scripts/email-config-path.test.js +52 -0
  27. package/templates/skills/email/scripts/email-config.d.ts +4 -0
  28. package/templates/skills/email/scripts/email-config.js +6 -3
  29. package/templates/skills/pptx/SKILL.md +5 -0
  30. package/templates/skills/pptx/assets/engine7-aurora/field.png +0 -0
  31. package/templates/skills/pptx/assets/engine7-aurora/hero.png +0 -0
  32. package/templates/skills/pptx/assets/engine7-aurora/wordmark.png +0 -0
  33. package/templates/skills/pptx/examples/engine7-aurora.cjs +190 -0
  34. package/templates/skills/pptx/package-lock.json +171 -0
  35. package/templates/skills/pptx/package.json +12 -0
  36. package/templates/skills/pptx/scripts/engine7-aurora.cjs +132 -0
  37. package/templates/skills/pptx/styles/engine7-aurora.md +136 -0
  38. package/templates/skills/pptx/tests/engine7-aurora.test.cjs +116 -0
  39. package/templates/workspace/AGENTS.md +2 -9
  40. package/templates/workspace/RULES.md +22 -0
  41. package/templates/workspace/hooks/loop-detector.mjs +37 -0
  42. package/templates/workspace/souls/unnamed.md +10 -0
@@ -0,0 +1,2205 @@
1
+ const require=(await import('node:module')).createRequire(import.meta.url)
2
+
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";
6
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
7
+
8
+ // src/continuity/key-service-store.ts
9
+ import { DatabaseSync } from "node:sqlite";
10
+ import { constants, lstatSync, mkdirSync, openSync, closeSync, readFileSync, writeSync, fstatSync, fsyncSync, unlinkSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { randomUUID } from "node:crypto";
13
+ function validateKeyIdentity(value) {
14
+ if (!value || ["tenantId", "companionId", "seatId", "keyId"].some((k) => typeof value[k] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value[k])) || !Number.isSafeInteger(value.generation) || value.generation < 1) throw new Error("KEY_SERVICE_INVALID_IDENTITY");
15
+ }
16
+ function identityText(value) {
17
+ validateKeyIdentity(value);
18
+ return JSON.stringify([value.tenantId, value.companionId, value.seatId, value.keyId, value.generation]);
19
+ }
20
+ function watermark(value) {
21
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("KEY_SERVICE_INVALID_WATERMARK");
22
+ }
23
+ function fingerprint(value) {
24
+ if (!/^[A-F0-9]{64}$/.test(value)) throw new Error("KEY_SERVICE_INVALID_CERTIFICATE");
25
+ }
26
+ function assertPrivateStat(stat, directory) {
27
+ if ((directory ? !stat.isDirectory() : !stat.isFile()) || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
28
+ throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
29
+ }
30
+ function privateDirectory(path3) {
31
+ try {
32
+ mkdirSync(path3, { mode: 448 });
33
+ } catch (error) {
34
+ if (error.code !== "EEXIST") throw error;
35
+ }
36
+ assertPrivateStat(lstatSync(path3), true);
37
+ }
38
+ function readPrivateFile(path3, maximumBytes = 65536) {
39
+ assertPrivateStat(lstatSync(path3), false);
40
+ const fd = openSync(path3, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
41
+ try {
42
+ const stat = fstatSync(fd);
43
+ assertPrivateStat(stat, false);
44
+ if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
45
+ return readFileSync(fd);
46
+ } finally {
47
+ closeSync(fd);
48
+ }
49
+ }
50
+ var KeyServiceStore = class {
51
+ constructor(directory) {
52
+ this.directory = directory;
53
+ privateDirectory(directory);
54
+ this.secrets = join(directory, "secrets");
55
+ privateDirectory(this.secrets);
56
+ const path3 = join(directory, "control.sqlite");
57
+ try {
58
+ closeSync(openSync(path3, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 384));
59
+ } catch (error) {
60
+ if (error.code !== "EEXIST") throw error;
61
+ }
62
+ assertPrivateStat(lstatSync(path3), false);
63
+ for (const suffix of ["-wal", "-shm", "-journal"]) {
64
+ try {
65
+ assertPrivateStat(lstatSync(path3 + suffix), false);
66
+ } catch (error) {
67
+ if (error.code !== "ENOENT") throw error;
68
+ }
69
+ }
70
+ this.db = new DatabaseSync(path3);
71
+ try {
72
+ this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
73
+ CREATE TABLE IF NOT EXISTS seat_keys (
74
+ key_id TEXT PRIMARY KEY, identity TEXT NOT NULL, secret_file TEXT NOT NULL,
75
+ state TEXT NOT NULL CHECK(state IN ('active','revoked')), deletion_watermark INTEGER NOT NULL DEFAULT 0);
76
+ CREATE TABLE IF NOT EXISTS certificates (
77
+ fingerprint TEXT PRIMARY KEY, identity TEXT NOT NULL, expires_at INTEGER NOT NULL,
78
+ state TEXT NOT NULL DEFAULT 'active' CHECK(state IN ('active','revoked')));`);
79
+ } catch (error) {
80
+ this.db.close();
81
+ throw error;
82
+ }
83
+ }
84
+ db;
85
+ secrets;
86
+ closed = false;
87
+ transaction(operation) {
88
+ this.db.exec("BEGIN IMMEDIATE");
89
+ try {
90
+ const result = operation();
91
+ this.db.exec("COMMIT");
92
+ return result;
93
+ } catch (error) {
94
+ this.db.exec("ROLLBACK");
95
+ throw error;
96
+ }
97
+ }
98
+ provision(identity3, key) {
99
+ const text = identityText(identity3);
100
+ if (!(key instanceof Uint8Array) || key.byteLength !== 32) throw new Error("KEY_SERVICE_INVALID_KEY");
101
+ this.transaction(() => {
102
+ if (this.db.prepare("SELECT key_id FROM seat_keys WHERE key_id=?").get(identity3.keyId))
103
+ throw new Error("KEY_SERVICE_KEY_EXISTS");
104
+ const filename = `${randomUUID()}.key`, path3 = join(this.secrets, filename);
105
+ assertPrivateStat(lstatSync(this.secrets), true);
106
+ const fd = openSync(path3, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 384);
107
+ try {
108
+ let written = 0;
109
+ while (written < key.byteLength) written += writeSync(fd, key, written, key.byteLength - written);
110
+ fsyncSync(fd);
111
+ } catch (error) {
112
+ closeSync(fd);
113
+ unlinkSync(path3);
114
+ throw error;
115
+ }
116
+ closeSync(fd);
117
+ if (process.platform !== "win32") {
118
+ const dir = openSync(this.secrets, constants.O_RDONLY);
119
+ try {
120
+ fsyncSync(dir);
121
+ } finally {
122
+ closeSync(dir);
123
+ }
124
+ }
125
+ try {
126
+ this.db.prepare("INSERT INTO seat_keys(key_id,identity,secret_file,state) VALUES(?,?,?,'active')").run(identity3.keyId, text, filename);
127
+ } catch (error) {
128
+ unlinkSync(path3);
129
+ throw error;
130
+ }
131
+ });
132
+ }
133
+ authorizeCertificate(certFingerprint, identity3, expiresAt) {
134
+ fingerprint(certFingerprint);
135
+ const text = identityText(identity3);
136
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= Date.now()) throw new Error("KEY_SERVICE_INVALID_EXPIRY");
137
+ this.transaction(() => {
138
+ const seat = this.db.prepare("SELECT identity,state FROM seat_keys WHERE key_id=?").get(identity3.keyId);
139
+ const previous = this.db.prepare("SELECT identity,state FROM certificates WHERE fingerprint=?").get(certFingerprint);
140
+ if (!seat || seat.identity !== text || seat.state !== "active" || previous && (previous.identity !== text || previous.state !== "active"))
141
+ throw new Error("KEY_SERVICE_DENIED");
142
+ this.db.prepare(`INSERT INTO certificates(fingerprint,identity,expires_at) VALUES(?,?,?)
143
+ ON CONFLICT(fingerprint) DO UPDATE SET expires_at=excluded.expires_at`).run(certFingerprint, text, expiresAt);
144
+ });
145
+ }
146
+ readKey(certFingerprint, identity3, minimumDeletionWatermark) {
147
+ fingerprint(certFingerprint);
148
+ const text = identityText(identity3);
149
+ watermark(minimumDeletionWatermark);
150
+ return this.transaction(() => {
151
+ const cert = this.db.prepare("SELECT identity,expires_at,state FROM certificates WHERE fingerprint=?").get(certFingerprint);
152
+ const seat = this.db.prepare("SELECT identity,state,secret_file,deletion_watermark FROM seat_keys WHERE key_id=?").get(identity3.keyId);
153
+ if (!cert || cert.state !== "active" || cert.identity !== text || Number(cert.expires_at) <= Date.now() || !seat || seat.identity !== text || seat.state !== "active")
154
+ throw new Error("KEY_SERVICE_DENIED");
155
+ const current = Number(seat.deletion_watermark);
156
+ watermark(current);
157
+ if (current < minimumDeletionWatermark) throw new Error("KEY_SERVICE_WATERMARK_BEHIND");
158
+ if (typeof seat.secret_file !== "string" || !/^[a-f0-9-]{36}\.key$/.test(seat.secret_file))
159
+ throw new Error("KEY_SERVICE_INVALID_KEY_FILE");
160
+ assertPrivateStat(lstatSync(this.secrets), true);
161
+ const key = readPrivateFile(join(this.secrets, seat.secret_file), 32);
162
+ if (key.length !== 32) {
163
+ key.fill(0);
164
+ throw new Error("KEY_SERVICE_INVALID_KEY_FILE");
165
+ }
166
+ return { key, deletionWatermark: current };
167
+ });
168
+ }
169
+ advanceWatermark(keyId, value) {
170
+ watermark(value);
171
+ this.transaction(() => {
172
+ const row = this.db.prepare("SELECT deletion_watermark FROM seat_keys WHERE key_id=?").get(keyId);
173
+ if (!row) throw new Error("KEY_SERVICE_DENIED");
174
+ if (Number(row.deletion_watermark) > value) throw new Error("KEY_SERVICE_WATERMARK_ROLLBACK");
175
+ this.db.prepare("UPDATE seat_keys SET deletion_watermark=? WHERE key_id=?").run(value, keyId);
176
+ });
177
+ }
178
+ /** Host preflight accepts the original identity even after revocation, so
179
+ * durable exit retries can finish without reenrolling or replacing a key. */
180
+ assertIdentity(identity3) {
181
+ const text = identityText(identity3);
182
+ const row = this.db.prepare("SELECT identity FROM seat_keys WHERE key_id=?").get(identity3.keyId);
183
+ if (!row || row.identity !== text) throw new Error("KEY_SERVICE_DENIED");
184
+ }
185
+ revoke(identity3) {
186
+ this.transaction(() => {
187
+ this.assertIdentity(identity3);
188
+ this.db.prepare("UPDATE seat_keys SET state='revoked' WHERE key_id=? AND identity=?").run(identity3.keyId, identityText(identity3));
189
+ });
190
+ }
191
+ /** Owner management only. Keep the revoked identity tombstone so a retry or
192
+ * old key ID cannot provision a replacement after its secret is removed. */
193
+ destroy(identity3) {
194
+ const text = identityText(identity3);
195
+ const filename = this.transaction(() => {
196
+ const row = this.db.prepare("SELECT identity,secret_file FROM seat_keys WHERE key_id=?").get(identity3.keyId);
197
+ if (!row || row.identity !== text || !/^[-a-f0-9]{36}\.key$/.test(String(row.secret_file))) throw new Error("KEY_SERVICE_DENIED");
198
+ this.db.prepare("UPDATE seat_keys SET state='revoked' WHERE key_id=?").run(identity3.keyId);
199
+ this.db.prepare("UPDATE certificates SET state='revoked' WHERE identity=?").run(text);
200
+ return String(row.secret_file);
201
+ });
202
+ const file = join(this.secrets, filename);
203
+ try {
204
+ assertPrivateStat(lstatSync(file), false);
205
+ unlinkSync(file);
206
+ } catch (error) {
207
+ if (error.code !== "ENOENT") throw error;
208
+ }
209
+ if (process.platform !== "win32") {
210
+ const fd = openSync(this.secrets, constants.O_RDONLY);
211
+ try {
212
+ fsyncSync(fd);
213
+ } finally {
214
+ closeSync(fd);
215
+ }
216
+ }
217
+ return { destroyed: true };
218
+ }
219
+ revokeCertificate(certFingerprint) {
220
+ fingerprint(certFingerprint);
221
+ const result = this.db.prepare("UPDATE certificates SET state='revoked' WHERE fingerprint=?").run(certFingerprint);
222
+ if (result.changes !== 1) throw new Error("KEY_SERVICE_DENIED");
223
+ }
224
+ status() {
225
+ return this.db.prepare("SELECT key_id,state,deletion_watermark FROM seat_keys ORDER BY key_id").all().map((row) => ({ ...row }));
226
+ }
227
+ close() {
228
+ if (!this.closed) {
229
+ this.db.close();
230
+ this.closed = true;
231
+ }
232
+ }
233
+ };
234
+
235
+ // src/continuity/controller-main.ts
236
+ import { readFileSync as readFileSync3 } from "node:fs";
237
+ import { isAbsolute, resolve as resolve2 } from "node:path";
238
+ import { fileURLToPath } from "node:url";
239
+
240
+ // src/continuity/controller.ts
241
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
242
+ import { join as join3 } from "node:path";
243
+ import { randomUUID as randomUUID2 } from "node:crypto";
244
+
245
+ // src/continuity/publication-objects.ts
246
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
247
+ import {
248
+ constants as constants2,
249
+ openSync as openSync2,
250
+ closeSync as closeSync2,
251
+ fstatSync as fstatSync2,
252
+ fsyncSync as fsyncSync2,
253
+ readSync,
254
+ writeSync as writeSync2,
255
+ lstatSync as lstatSync2,
256
+ realpathSync,
257
+ mkdirSync as mkdirSync2,
258
+ readFileSync as readFileSync2,
259
+ writeFileSync,
260
+ linkSync,
261
+ unlinkSync as unlinkSync2
262
+ } from "node:fs";
263
+ import { join as join2, dirname, resolve } from "node:path";
264
+ var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
265
+ var MAGIC = Buffer.from("E7P1");
266
+ var noFollow = constants2.O_NOFOLLOW ?? 0;
267
+ function assertPrivateDirectory(path3) {
268
+ const info = lstatSync2(path3);
269
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(path3) !== resolve(path3) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
270
+ throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
271
+ }
272
+ function syncDir(path3) {
273
+ if (process.platform === "win32") return;
274
+ const fd = openSync2(path3, constants2.O_RDONLY);
275
+ try {
276
+ fsyncSync2(fd);
277
+ } finally {
278
+ closeSync2(fd);
279
+ }
280
+ }
281
+ function preparePrivateDirectory(path3) {
282
+ const missing = [];
283
+ let parent = resolve(path3);
284
+ for (; ; ) {
285
+ try {
286
+ lstatSync2(parent);
287
+ break;
288
+ } catch (error) {
289
+ if (error.code !== "ENOENT") throw error;
290
+ }
291
+ missing.push(parent);
292
+ parent = dirname(parent);
293
+ }
294
+ if (realpathSync(parent) !== parent) throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
295
+ for (const directory of missing.reverse()) {
296
+ try {
297
+ mkdirSync2(directory, { mode: 448 });
298
+ } catch (error) {
299
+ if (error.code !== "EEXIST") throw error;
300
+ }
301
+ assertPrivateDirectory(directory);
302
+ syncDir(dirname(directory));
303
+ }
304
+ assertPrivateDirectory(path3);
305
+ }
306
+ function preparePrivateDatabase(path3) {
307
+ for (const file of [path3, path3 + "-journal", path3 + "-wal", path3 + "-shm"]) {
308
+ try {
309
+ const info2 = lstatSync2(file);
310
+ if (!info2.isFile() || info2.isSymbolicLink() || process.platform !== "win32" && (info2.mode & 63 || info2.uid !== process.getuid()))
311
+ throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
312
+ } catch (error) {
313
+ if (error.code !== "ENOENT") throw error;
314
+ }
315
+ }
316
+ try {
317
+ const fd = openSync2(path3, "wx", 384);
318
+ closeSync2(fd);
319
+ } catch (error) {
320
+ if (error.code !== "EEXIST") throw error;
321
+ }
322
+ const info = lstatSync2(path3);
323
+ if (!info.isFile() || info.isSymbolicLink() || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
324
+ throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
325
+ syncDir(dirname(path3));
326
+ }
327
+
328
+ // src/continuity/controller.ts
329
+ var TravelController = class {
330
+ constructor(options) {
331
+ this.options = options;
332
+ const nodes = Object.values(options.nodes), preferred = options.nodes[options.preferredNodeId];
333
+ if (nodes.length !== 2 || !preferred || nodes.some((node) => options.nodes[node.principal.nodeId] !== node || ["tenantId", "companionId", "seatId"].some((key) => node.principal[key] !== preferred.principal[key])) || new Set(nodes.map((node) => node.principal.role)).size !== 2) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
334
+ this.interval = options.intervalMs ?? 1e3;
335
+ for (const value of [this.interval, options.healthyForMs ?? 12e4, options.handbackCooldownMs ?? 6e5]) if (!Number.isSafeInteger(value) || value < 0 || value > 36e5) throw new Error("TRAVEL_CONTROLLER_TIMING");
336
+ if (this.interval < 100) throw new Error("TRAVEL_CONTROLLER_TIMING");
337
+ this.clock = options.monotonicNow ?? (() => Number(process.hrtime.bigint() / 1000000n));
338
+ preparePrivateDirectory(options.directory);
339
+ const ownerFile = join3(options.directory, "controller-owner.sqlite");
340
+ preparePrivateDatabase(ownerFile);
341
+ this.owner = new DatabaseSync3(ownerFile);
342
+ try {
343
+ this.owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
344
+ } catch {
345
+ this.owner.close();
346
+ throw new Error("TRAVEL_CONTROLLER_BUSY");
347
+ }
348
+ try {
349
+ const file = join3(options.directory, "controller.sqlite");
350
+ preparePrivateDatabase(file);
351
+ this.db = new DatabaseSync3(file);
352
+ this.db.exec(`PRAGMA synchronous=FULL;PRAGMA journal_mode=WAL;
353
+ CREATE TABLE IF NOT EXISTS binding(identity TEXT NOT NULL);
354
+ CREATE TABLE IF NOT EXISTS preferences(id INTEGER PRIMARY KEY CHECK(id=1),node TEXT NOT NULL);
355
+ CREATE TABLE IF NOT EXISTS automatic(id INTEGER PRIMARY KEY CHECK(id=1),enabled INTEGER NOT NULL CHECK(enabled IN (0,1)));
356
+ CREATE TABLE IF NOT EXISTS jobs(id TEXT PRIMARY KEY,source TEXT,target TEXT NOT NULL,state TEXT NOT NULL,checkpoint TEXT);
357
+ CREATE TABLE IF NOT EXISTS abort_recoveries(id TEXT PRIMARY KEY,node TEXT NOT NULL,boot TEXT NOT NULL,authority_boot TEXT NOT NULL,epoch INTEGER NOT NULL,checkpoint TEXT NOT NULL);
358
+ CREATE TABLE IF NOT EXISTS starts(node TEXT NOT NULL,boot TEXT NOT NULL,epoch INTEGER NOT NULL,checkpoint TEXT NOT NULL,PRIMARY KEY(node,boot,epoch));`);
359
+ const identity3 = JSON.stringify(nodes.map((node) => [node.principal.tenantId, node.principal.companionId, node.principal.seatId, node.principal.nodeId, node.principal.role]).sort());
360
+ const binding = this.db.prepare("SELECT identity FROM binding").all();
361
+ if (!binding.length) this.db.prepare("INSERT INTO binding VALUES(?)").run(identity3);
362
+ else if (binding.length !== 1 || binding[0].identity !== identity3) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
363
+ 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)");
365
+ if (!options.nodes[this.preferredNodeId()]) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
366
+ if (this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_CONTROLLER_RECOVERY_REQUIRED");
367
+ } catch (error) {
368
+ this.db?.close();
369
+ this.owner.close();
370
+ throw error;
371
+ }
372
+ }
373
+ db;
374
+ owner;
375
+ active;
376
+ timer;
377
+ running = false;
378
+ closed = false;
379
+ lastError = null;
380
+ healthySince = null;
381
+ lastReturnAt = null;
382
+ clock;
383
+ interval;
384
+ preferredNodeId() {
385
+ return String(this.db.prepare("SELECT node FROM preferences WHERE id=1").get().node);
386
+ }
387
+ status() {
388
+ return { running: this.running, inFlight: !!this.active, lastError: this.lastError, job: this.job(), preferredNodeId: this.preferredNodeId(), automatic: this.db.prepare("SELECT enabled FROM automatic WHERE id=1").get().enabled === 1 };
389
+ }
390
+ setAutomatic(enabled) {
391
+ if (this.closed) throw new Error("TRAVEL_CONTROLLER_CLOSED");
392
+ if (typeof enabled !== "boolean") throw new Error("TRAVEL_CONTROLLER_CONFIG");
393
+ this.db.prepare("UPDATE automatic SET enabled=? WHERE id=1").run(enabled ? 1 : 0);
394
+ }
395
+ job() {
396
+ return this.db.prepare("SELECT * FROM jobs WHERE state NOT IN ('DONE','ABORTED') ORDER BY rowid LIMIT 1").get();
397
+ }
398
+ requestHandback(transferId) {
399
+ this.requestTransfer(this.options.preferredNodeId, transferId);
400
+ }
401
+ /** Explicit owner choice retains its target across restarts. Replaying a
402
+ * completed ID does not overwrite a newer choice or enqueue another move. */
403
+ requestTransfer(targetNodeId, transferId) {
404
+ if (this.closed) throw new Error("TRAVEL_CONTROLLER_CLOSED");
405
+ if (!this.options.nodes[targetNodeId]) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
406
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(transferId)) throw new Error("TRAVEL_INVALID_ID");
407
+ const prior = this.db.prepare("SELECT target FROM jobs WHERE id=?").get(transferId);
408
+ if (prior) {
409
+ if (prior.target !== targetNodeId) throw new Error("TRAVEL_ID_COLLISION");
410
+ return;
411
+ }
412
+ if (this.job()) throw new Error("TRAVEL_HANDOFF_STATE");
413
+ this.db.exec("BEGIN IMMEDIATE");
414
+ try {
415
+ this.db.prepare("INSERT INTO jobs VALUES(?,NULL,?,'REQUESTED',NULL)").run(transferId, targetNodeId);
416
+ this.db.prepare("UPDATE preferences SET node=? WHERE id=1").run(targetNodeId);
417
+ this.db.exec("COMMIT");
418
+ } catch (error) {
419
+ this.db.exec("ROLLBACK");
420
+ throw error;
421
+ }
422
+ }
423
+ tick() {
424
+ if (this.closed) return Promise.reject(new Error("TRAVEL_CONTROLLER_CLOSED"));
425
+ if (this.active) return this.active;
426
+ const operation = this.round().catch((error) => {
427
+ this.lastError = error instanceof Error && /^TRAVEL_[A-Z_]+$/.test(error.message) ? error.message : "TRAVEL_CONTROLLER_OPERATION_FAILED";
428
+ });
429
+ this.active = operation.finally(() => {
430
+ this.active = void 0;
431
+ });
432
+ return this.active;
433
+ }
434
+ async launch(node, permit, checkpoint) {
435
+ const prior = this.db.prepare("SELECT checkpoint FROM starts WHERE node=? AND boot=? AND epoch=?").get(permit.nodeId, permit.bootId, permit.epoch);
436
+ if (prior) {
437
+ if (prior.checkpoint !== checkpoint) throw new Error("TRAVEL_CONTROLLER_GENERATION_COLLISION");
438
+ return;
439
+ }
440
+ await node.start(permit, checkpoint);
441
+ this.db.prepare("INSERT INTO starts VALUES(?,?,?,?)").run(permit.nodeId, permit.bootId, permit.epoch, checkpoint);
442
+ }
443
+ async round() {
444
+ this.lastError = null;
445
+ const job = this.job();
446
+ if (job) {
447
+ await this.advance(job);
448
+ return;
449
+ }
450
+ if (!this.status().automatic) return;
451
+ const preferred = this.options.nodes[this.preferredNodeId()];
452
+ const status = await this.options.authority.status(preferred.principal);
453
+ if (status.activeNodeId && !status.expired) {
454
+ const active = this.options.nodes[status.activeNodeId];
455
+ if (!active) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
456
+ const observed = await active.observe();
457
+ if (!observed.connected) {
458
+ this.healthySince = null;
459
+ return;
460
+ }
461
+ if (!observed.running) {
462
+ await active.stop();
463
+ this.healthySince = null;
464
+ return;
465
+ }
466
+ {
467
+ const standby = Object.values(this.options.nodes).find((node2) => node2 !== active);
468
+ if ((await standby.observe()).connected && !await this.replicate(active, standby)) return;
469
+ }
470
+ if (status.activeNodeId !== preferred.principal.nodeId) {
471
+ const local = await preferred.observe(), now = this.clock();
472
+ if (!local.connected) {
473
+ this.healthySince = null;
474
+ return;
475
+ }
476
+ this.healthySince ??= now;
477
+ if (now - this.healthySince >= (this.options.healthyForMs ?? 12e4) && (!this.lastReturnAt || now - this.lastReturnAt >= (this.options.handbackCooldownMs ?? 6e5))) this.requestTransfer(preferred.principal.nodeId, "return-" + randomUUID2());
478
+ } else this.healthySince = null;
479
+ return;
480
+ }
481
+ this.healthySince = null;
482
+ 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
+ let node;
484
+ for (const candidate of candidates) if ((await candidate.observe()).connected === true) {
485
+ node = candidate;
486
+ break;
487
+ }
488
+ if (!node) return;
489
+ await node.pinBranch(status.checkpointDigest);
490
+ const ready = await node.prepare(status.checkpointDigest);
491
+ const latest = await this.options.authority.status(node.principal);
492
+ if (latest.authorityBootId !== status.authorityBootId || latest.epoch !== status.epoch || latest.checkpointDigest !== status.checkpointDigest || latest.deletionWatermark !== status.deletionWatermark || latest.activeNodeId && !latest.expired) return;
493
+ const permit = await this.options.authority.acquire(node.principal, ready);
494
+ await this.launch(node, permit, status.checkpointDigest);
495
+ }
496
+ async replicate(source, target) {
497
+ if (!source.replicationOffer || !source.connectReplica || !target.replicaProfile || !target.bootstrapReplica) return true;
498
+ const offer = await source.replicationOffer();
499
+ if (!offer) return true;
500
+ if (offer.principal.nodeId !== source.principal.nodeId) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
501
+ const assertSource = async () => {
502
+ const permit = await source.permit();
503
+ if (["nodeId", "bootId", "authorityBootId", "epoch"].some((field) => permit[field] !== offer.permit[field])) throw new Error("TRAVEL_CONTROLLER_COMMIT_SUPERSEDED");
504
+ await this.options.authority.assertPermit(permit, "CONTROL");
505
+ return permit;
506
+ };
507
+ let profile = await target.replicaProfile();
508
+ if (!profile || JSON.stringify(profile) !== JSON.stringify(offer.profile)) {
509
+ await target.stop(await assertSource());
510
+ await target.bootstrapReplica({ ...offer, permitSupplier: () => source.permit() });
511
+ profile = await target.replicaProfile();
512
+ }
513
+ if (!profile || JSON.stringify(profile) !== JSON.stringify(offer.profile)) throw new Error("TRAVEL_CONTROLLER_REPLICA");
514
+ await assertSource();
515
+ await source.connectReplica(profile);
516
+ const recovered = await source.recoverBranches?.();
517
+ return !recovered || recovered.unresolvedCritical === 0;
518
+ }
519
+ async advance(job) {
520
+ const target = this.options.nodes[job.target], control = this.options.authority;
521
+ if (!target) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
522
+ if (job.state === "REQUESTED") {
523
+ const status = await control.status(target.principal);
524
+ if (!status.activeNodeId || status.expired) throw new Error("TRAVEL_CONTROLLER_SOURCE_OFFLINE");
525
+ if (status.activeNodeId === job.target) {
526
+ this.db.prepare("UPDATE jobs SET state='DONE' WHERE id=?").run(job.id);
527
+ return;
528
+ }
529
+ const source2 = this.options.nodes[status.activeNodeId];
530
+ if (!source2) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
531
+ if (!await this.replicate(source2, target)) return;
532
+ this.db.prepare("UPDATE jobs SET source=?,state='PREPARING' WHERE id=?").run(source2.principal.nodeId, job.id);
533
+ await control.beginHandoff(source2.principal, await source2.permit(), job.id, job.target);
534
+ return;
535
+ }
536
+ const source = job.source && this.options.nodes[job.source];
537
+ if (!source) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
538
+ let result;
539
+ try {
540
+ result = await control.handoffStatus(target.principal, job.id);
541
+ } catch (error) {
542
+ if (error instanceof Error && error.message === "TRAVEL_HANDOFF_NOT_FOUND") result = await control.beginHandoff(source.principal, await source.permit(), job.id, job.target);
543
+ else throw error;
544
+ }
545
+ if (result.state === "ABORTED") {
546
+ const recovery = this.db.prepare("SELECT * FROM abort_recoveries WHERE id=?").get(job.id);
547
+ if (!recovery) await source.stop();
548
+ const status = await control.status(source.principal);
549
+ if (recovery) {
550
+ if (status.activeNodeId === recovery.node && status.activeBootId === recovery.boot && status.authorityBootId === recovery.authority_boot && status.epoch === recovery.epoch && !status.expired) {
551
+ const permit = (await source.observe()).running ? await source.permit() : await control.acquire(source.principal, await source.prepare(String(recovery.checkpoint)));
552
+ if (permit.epoch !== recovery.epoch || permit.bootId !== recovery.boot || permit.authorityBootId !== recovery.authority_boot) throw new Error("TRAVEL_CONTROLLER_COMMIT_SUPERSEDED");
553
+ await this.launch(source, permit, String(recovery.checkpoint));
554
+ }
555
+ this.db.prepare("UPDATE jobs SET state='ABORTED' WHERE id=?").run(job.id);
556
+ return;
557
+ }
558
+ if ((!status.activeNodeId || status.expired) && (await source.observe()).connected) {
559
+ await source.pinBranch(status.checkpointDigest);
560
+ const ready = await source.prepare(status.checkpointDigest);
561
+ const latest = await control.status(source.principal);
562
+ if (latest.authorityBootId !== status.authorityBootId || latest.epoch !== status.epoch || latest.checkpointDigest !== status.checkpointDigest || latest.deletionWatermark !== status.deletionWatermark || latest.activeNodeId && !latest.expired) return;
563
+ const permit = await control.acquire(source.principal, ready);
564
+ this.db.prepare("INSERT INTO abort_recoveries VALUES(?,?,?,?,?,?)").run(job.id, permit.nodeId, permit.bootId, permit.authorityBootId, permit.epoch, status.checkpointDigest);
565
+ await this.launch(source, permit, status.checkpointDigest);
566
+ }
567
+ this.db.prepare("UPDATE jobs SET state='ABORTED' WHERE id=?").run(job.id);
568
+ return;
569
+ }
570
+ if (["FROZEN_AT_H", "TARGET_READY"].includes(result.state) && !(await target.observe()).connected) {
571
+ await control.abortHandoff(source.principal, job.id);
572
+ return;
573
+ }
574
+ if (result.state === "PREPARING") {
575
+ const status = await control.status(source.principal);
576
+ if (status.expired || status.activeNodeId !== source.principal.nodeId) {
577
+ await control.abortHandoff(source.principal, job.id);
578
+ this.db.prepare("UPDATE jobs SET state='ABORTED' WHERE id=?").run(job.id);
579
+ await source.stop();
580
+ return;
581
+ }
582
+ const boundary = await source.safeBoundary(job.id);
583
+ if (!boundary || !boundary.safeBoundary || !boundary.effectsSettled) return;
584
+ await target.pinBranch(boundary.checkpointDigest);
585
+ await source.pinBranch(boundary.checkpointDigest);
586
+ result = await control.freezeHandoff(source.principal, await source.permit(), job.id, boundary);
587
+ } else if (result.state === "FROZEN_AT_H") {
588
+ await target.pinBranch(result.checkpointDigest);
589
+ const ready = await target.prepare(result.checkpointDigest);
590
+ result = await control.readyHandoff(target.principal, job.id, ready);
591
+ } else if (result.state === "TARGET_READY") result = await control.commitHandoff(target.principal, job.id);
592
+ else if (result.state === "COMMITTED") {
593
+ const status = await control.status(target.principal), permit = result.permit;
594
+ if (!permit) throw new Error("TRAVEL_CONTROLLER_COMMIT_SUPERSEDED");
595
+ if (status.expired || status.activeNodeId !== target.principal.nodeId || status.activeBootId !== permit.bootId || status.epoch !== permit.epoch || status.authorityBootId !== permit.authorityBootId) {
596
+ this.db.prepare("UPDATE jobs SET state='DONE',checkpoint=? WHERE id=?").run(result.checkpointDigest, job.id);
597
+ return;
598
+ }
599
+ const fresh = await control.acquire(target.principal, await target.prepare(result.checkpointDigest));
600
+ await source.stop(fresh);
601
+ await this.launch(target, fresh, result.checkpointDigest);
602
+ this.db.prepare("UPDATE jobs SET state='DONE',checkpoint=? WHERE id=?").run(result.checkpointDigest, job.id);
603
+ this.lastReturnAt = this.clock();
604
+ return;
605
+ }
606
+ this.db.prepare("UPDATE jobs SET state=?,checkpoint=? WHERE id=?").run(result.state, result.checkpointDigest, job.id);
607
+ }
608
+ start() {
609
+ if (this.running || this.closed) return;
610
+ this.running = true;
611
+ this.schedule(0);
612
+ }
613
+ schedule(delay) {
614
+ if (!this.running) return;
615
+ this.timer = setTimeout(() => {
616
+ this.timer = void 0;
617
+ const started = this.clock();
618
+ void this.tick().finally(() => this.schedule(this.interval - (this.clock() - started) % this.interval));
619
+ }, delay);
620
+ }
621
+ async stop() {
622
+ this.running = false;
623
+ if (this.timer) clearTimeout(this.timer);
624
+ this.timer = void 0;
625
+ await this.active;
626
+ }
627
+ close() {
628
+ if (this.closed) return;
629
+ if (this.active) throw new Error("TRAVEL_CONTROLLER_BUSY");
630
+ this.running = false;
631
+ if (this.timer) clearTimeout(this.timer);
632
+ this.closed = true;
633
+ try {
634
+ this.db.close();
635
+ } finally {
636
+ this.owner.close();
637
+ }
638
+ }
639
+ };
640
+
641
+ // src/continuity/controller-authority-client.ts
642
+ var RemoteTravelControllerAuthority = class {
643
+ constructor(nodes) {
644
+ this.nodes = nodes;
645
+ const entries = Object.entries(nodes), principals = entries.map(([, node]) => node.principal);
646
+ if (entries.length !== 2 || entries.some(([id, node]) => id !== node.principal.nodeId) || new Set(principals.map((node) => node.role)).size !== 2 || principals.some((node) => ["tenantId", "companionId", "seatId"].some((field) => node[field] !== principals[0][field])))
647
+ throw new Error("TRAVEL_CONTROLLER_IDENTITY");
648
+ }
649
+ client(principal) {
650
+ const node = Object.hasOwn(this.nodes, principal.nodeId) ? this.nodes[principal.nodeId] : void 0;
651
+ if (!node || ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].some((field) => node.principal[field] !== principal[field]))
652
+ throw new Error("TRAVEL_AUTH_DENIED");
653
+ return node.client;
654
+ }
655
+ async status(principal) {
656
+ return this.client(principal).status();
657
+ }
658
+ async retirementStatus(principal) {
659
+ return this.client(principal).retirementStatus();
660
+ }
661
+ async assertPermit(permit, operation) {
662
+ const node = Object.hasOwn(this.nodes, permit.nodeId) ? this.nodes[permit.nodeId] : void 0;
663
+ if (!node || ["tenantId", "companionId", "seatId"].some((field) => node.principal[field] !== permit[field])) throw new Error("TRAVEL_AUTH_DENIED");
664
+ await node.client.assertPermit(permit, operation);
665
+ }
666
+ async acquire(principal, ready) {
667
+ return this.client(principal).acquire(ready);
668
+ }
669
+ async beginHandoff(principal, permit, transferId, targetNodeId) {
670
+ return this.client(principal).beginHandoff(permit, transferId, targetNodeId);
671
+ }
672
+ async freezeHandoff(principal, permit, transferId, boundary) {
673
+ return this.client(principal).freezeHandoff(permit, transferId, boundary);
674
+ }
675
+ async readyHandoff(principal, transferId, ready) {
676
+ return this.client(principal).readyHandoff(transferId, ready);
677
+ }
678
+ async commitHandoff(principal, transferId) {
679
+ return this.client(principal).commitHandoff(transferId);
680
+ }
681
+ async handoffStatus(principal, transferId) {
682
+ return this.client(principal).handoffStatus(transferId);
683
+ }
684
+ async abortHandoff(principal, transferId) {
685
+ return this.client(principal).abortHandoff(transferId);
686
+ }
687
+ };
688
+
689
+ // src/continuity/authority-client.ts
690
+ import { Agent, request } from "node:https";
691
+ var publicErrors = /* @__PURE__ */ new Set([
692
+ "TRAVEL_HEARTBEAT_REPLAY",
693
+ "TRAVEL_BOOT_MISMATCH",
694
+ "TRAVEL_BOOT_RETIRED",
695
+ "TRAVEL_LEASE_EXPIRED",
696
+ "TRAVEL_STALE_PERMIT",
697
+ "TRAVEL_DELETION_BARRIER",
698
+ "TRAVEL_BOOT_REQUIRED",
699
+ "TRAVEL_NOT_READY",
700
+ "TRAVEL_READINESS_BARRIER",
701
+ "TRAVEL_LEASE_HELD",
702
+ "TRAVEL_INVALID_PERMIT",
703
+ "TRAVEL_HANDOFF_STATE",
704
+ "TRAVEL_HANDOFF_FROZEN",
705
+ "TRAVEL_HANDOFF_NOT_SAFE",
706
+ "TRAVEL_HANDOFF_NOT_FOUND",
707
+ "TRAVEL_HANDOFF_COMMITTED",
708
+ "TRAVEL_TARGET_OFFLINE",
709
+ "TRAVEL_ID_COLLISION",
710
+ "TRAVEL_ANCESTRY_GAP"
711
+ ]);
712
+ var readActions = /* @__PURE__ */ new Set(["status", "identity", "deletionsSince", "verifyAncestor", "assertPermit", "handoffStatus", "retirementStatus", "recoveryBranchStatus"]);
713
+ var TravelReportClient = class {
714
+ constructor(options) {
715
+ this.options = options;
716
+ try {
717
+ this.url = new URL(options.url);
718
+ } catch {
719
+ throw new Error("TRAVEL_CONTROL_TLS_REQUIRED");
720
+ }
721
+ if (this.url.protocol !== "https:" || !["/api/engine7/report", "/travel/control/v1", "/travel/manage/v1"].includes(this.url.pathname) || this.url.username || this.url.password || this.url.search || this.url.hash) throw new Error("TRAVEL_CONTROL_TLS_REQUIRED");
722
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(options.nodeId) || !/^e7t_[a-f0-9]{64}$/.test(options.credential) || !!options.cert !== !!options.key) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
723
+ this.timeout = options.timeoutMs ?? 8e3;
724
+ if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
725
+ 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 });
727
+ }
728
+ agent;
729
+ key;
730
+ url;
731
+ timeout;
732
+ pending = /* @__PURE__ */ new Set();
733
+ closed = false;
734
+ call(input) {
735
+ return this.attempt(input);
736
+ }
737
+ attempt(input, retryStale = true, deadline = performance.now() + this.timeout, wireBody) {
738
+ if (this.closed) return Promise.reject(new Error("TRAVEL_CONTROL_CLOSED"));
739
+ if (this.pending.size) return Promise.reject(new Error("TRAVEL_CONTROL_BUSY"));
740
+ const body = wireBody ?? Buffer.from(JSON.stringify({ travel: { version: 1, ...input } }));
741
+ if (body.length > (input?.action === "recordRecoveryBranch" ? 40 * 1024 * 1024 : 65536)) return Promise.reject(new Error("TRAVEL_CONTROL_INVALID_REQUEST"));
742
+ const unavailable = () => new Error(this.closed ? "TRAVEL_CONTROL_CLOSED" : "TRAVEL_CONTROL_UNAVAILABLE");
743
+ const remaining = deadline - performance.now();
744
+ if (remaining <= 0) return Promise.reject(unavailable());
745
+ return new Promise((resolve8, reject) => {
746
+ let complete = false, responseStarted = false;
747
+ const finish = (error, value) => {
748
+ if (complete) return;
749
+ complete = true;
750
+ clearTimeout(timer);
751
+ this.pending.delete(req);
752
+ if (error) reject(error);
753
+ else resolve8(value);
754
+ };
755
+ const req = request(this.url, { method: "POST", agent: this.agent, headers: {
756
+ Authorization: "Bearer " + this.options.credential,
757
+ "X-Engine7-Travel-Node": this.options.nodeId,
758
+ "Content-Type": "application/json",
759
+ "Content-Length": body.length
760
+ } }, (res) => {
761
+ responseStarted = true;
762
+ const chunks = [];
763
+ let bytes = 0;
764
+ res.on("data", (chunk) => {
765
+ bytes += chunk.length;
766
+ if (bytes > 65536) {
767
+ finish(new Error("TRAVEL_CONTROL_INVALID_RESPONSE"));
768
+ req.destroy();
769
+ } else chunks.push(chunk);
770
+ });
771
+ res.once("error", () => finish(unavailable()));
772
+ res.once("end", () => {
773
+ if (this.closed) {
774
+ finish(unavailable());
775
+ return;
776
+ }
777
+ let value;
778
+ try {
779
+ value = JSON.parse(Buffer.concat(chunks).toString());
780
+ } catch {
781
+ finish(new Error("TRAVEL_CONTROL_INVALID_RESPONSE"));
782
+ return;
783
+ }
784
+ if (res.statusCode !== 200) {
785
+ finish(new Error(res.statusCode === 401 || res.statusCode === 403 ? "TRAVEL_AUTH_DENIED" : res.statusCode === 503 ? "TRAVEL_CONTROL_BUSY" : publicErrors.has(value?.error) ? value.error : "TRAVEL_CONTROL_REFUSED"));
786
+ return;
787
+ }
788
+ if (!value || typeof value !== "object" || Object.keys(value).length !== 1 || !value.travel || typeof value.travel !== "object" || Array.isArray(value.travel) || value.travel.version !== 1) {
789
+ finish(new Error("TRAVEL_CONTROL_INVALID_RESPONSE"));
790
+ return;
791
+ }
792
+ finish(void 0, value.travel);
793
+ });
794
+ });
795
+ this.pending.add(req);
796
+ const timer = setTimeout(() => {
797
+ finish(unavailable());
798
+ req.destroy();
799
+ }, remaining);
800
+ req.once("error", (error) => {
801
+ if (complete) return;
802
+ if (retryStale && !this.closed && !responseStarted && readActions.has(input?.action) && req.reusedSocket && error.code === "ECONNRESET") {
803
+ complete = true;
804
+ clearTimeout(timer);
805
+ this.pending.delete(req);
806
+ resolve8(this.attempt(input, false, deadline, body));
807
+ } else finish(unavailable());
808
+ });
809
+ req.once("close", () => {
810
+ clearTimeout(timer);
811
+ this.pending.delete(req);
812
+ });
813
+ req.end(body);
814
+ });
815
+ }
816
+ register(bootId2) {
817
+ return this.call({ action: "register", bootId: bootId2 });
818
+ }
819
+ heartbeat(input) {
820
+ return this.call({ action: "heartbeat", ...input });
821
+ }
822
+ status() {
823
+ return this.call({ action: "status" });
824
+ }
825
+ close() {
826
+ if (this.closed) return;
827
+ this.closed = true;
828
+ for (const req of this.pending) req.destroy();
829
+ this.agent.destroy();
830
+ this.key?.fill(0);
831
+ }
832
+ };
833
+ var TravelManagementClient = class extends TravelReportClient {
834
+ tail = Promise.resolve();
835
+ queued = 0;
836
+ call(input) {
837
+ if (this.queued >= 16) return Promise.reject(new Error("TRAVEL_CONTROL_BUSY"));
838
+ this.queued++;
839
+ const operation = this.tail.then(() => super.call(input));
840
+ this.tail = operation.catch(() => {
841
+ });
842
+ return operation.finally(() => {
843
+ this.queued--;
844
+ });
845
+ }
846
+ constructor(options) {
847
+ let url;
848
+ try {
849
+ url = new URL(options.url);
850
+ } catch {
851
+ throw new Error("TRAVEL_CONTROL_TLS_REQUIRED");
852
+ }
853
+ if (url.pathname !== "/travel/manage/v1") throw new Error("TRAVEL_MANAGEMENT_ENDPOINT_REQUIRED");
854
+ super(options);
855
+ }
856
+ async verifyAncestor(ancestor, descendant) {
857
+ await this.call({ action: "verifyAncestor", ancestor, descendant });
858
+ }
859
+ async identity() {
860
+ return this.call({ action: "identity" });
861
+ }
862
+ async deletionsSince(after, maximum = 32) {
863
+ return (await this.call({ action: "deletionsSince", after, maximum })).deletions;
864
+ }
865
+ async publishCheckpoint(permit, digest, parent) {
866
+ await this.call({ action: "publishCheckpoint", permit, digest, parent });
867
+ }
868
+ async recordRecoveryBranch(permit, chain, proof) {
869
+ await this.call({ action: "recordRecoveryBranch", permit, chain, proof });
870
+ }
871
+ async recoveryBranchStatus(common, local) {
872
+ return this.call({ action: "recoveryBranchStatus", common, local });
873
+ }
874
+ async assertPermit(permit, operation) {
875
+ await this.call({ action: "assertPermit", permit, operation });
876
+ }
877
+ async acquire(ready) {
878
+ return (await this.call({ action: "acquire", ready })).permit;
879
+ }
880
+ async retire(jobId) {
881
+ await this.call({ action: "retire", jobId });
882
+ }
883
+ retirementStatus() {
884
+ return this.call({ action: "retirementStatus" });
885
+ }
886
+ beginHandoff(permit, transferId, targetNodeId) {
887
+ return this.call({ action: "beginHandoff", permit, transferId, targetNodeId });
888
+ }
889
+ freezeHandoff(permit, transferId, boundary) {
890
+ return this.call({ action: "freezeHandoff", permit, transferId, boundary });
891
+ }
892
+ readyHandoff(transferId, ready) {
893
+ return this.call({ action: "readyHandoff", transferId, ready });
894
+ }
895
+ commitHandoff(transferId) {
896
+ return this.call({ action: "commitHandoff", transferId });
897
+ }
898
+ handoffStatus(transferId) {
899
+ return this.call({ action: "handoffStatus", transferId });
900
+ }
901
+ abortHandoff(transferId) {
902
+ return this.call({ action: "abortHandoff", transferId });
903
+ }
904
+ };
905
+
906
+ // src/continuity/node-supervisor-client.ts
907
+ import { Agent as Agent2, request as request2 } from "node:https";
908
+
909
+ // src/continuity/publication.ts
910
+ import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
911
+ var PUBLICATION_MANIFEST_BYTES = 4 * 1024 * 1024;
912
+ var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
913
+ var ZERO = "0".repeat(64);
914
+
915
+ // src/continuity/node-supervisor-protocol.ts
916
+ var nodeSupervisorPath = "/travel/node/v1";
917
+ var nodeSupervisorLimit = 2 * 1024 * 1024;
918
+ var nodeSupervisorErrors = /* @__PURE__ */ new Set([
919
+ "TRAVEL_NODE_BUSY",
920
+ "TRAVEL_NODE_CLOSED",
921
+ "TRAVEL_NODE_CANCELLED",
922
+ "TRAVEL_NODE_BOOT_MISMATCH",
923
+ "TRAVEL_NODE_CHECKPOINT",
924
+ "TRAVEL_NODE_GENERATION_COLLISION",
925
+ "TRAVEL_NODE_KEY_UNAVAILABLE",
926
+ "TRAVEL_NODE_KEY_BARRIER",
927
+ "TRAVEL_NODE_IDENTITY",
928
+ "TRAVEL_NODE_REPLICA_NOT_READY",
929
+ "TRAVEL_NODE_RECOVERY_REQUIRED",
930
+ "TRAVEL_NODE_REPLICATION_PEER",
931
+ "TRAVEL_NODE_EFFECT_BARRIER",
932
+ "TRAVEL_PERMIT_REQUIRED",
933
+ "TRAVEL_AUTH_DENIED",
934
+ "TRAVEL_LEASE_EXPIRED",
935
+ "TRAVEL_STALE_PERMIT",
936
+ "TRAVEL_DELETION_BARRIER",
937
+ "TRAVEL_HANDOFF_STATE",
938
+ "TRAVEL_HANDOFF_NOT_FOUND",
939
+ "TRAVEL_INVALID_PERMIT",
940
+ "TRAVEL_CONTROL_BUSY",
941
+ "TRAVEL_CONTROL_UNAVAILABLE"
942
+ ]);
943
+ var nodeSupervisorId = (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value);
944
+ var nodeSupervisorRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
945
+
946
+ // src/continuity/node-supervisor-client.ts
947
+ var RemoteTravelNodeSupervisor = class {
948
+ constructor(options) {
949
+ this.options = options;
950
+ this.principal = Object.freeze({ ...options.principal });
951
+ try {
952
+ this.url = new URL(options.url);
953
+ } catch {
954
+ throw new Error("TRAVEL_NODE_TLS_REQUIRED");
955
+ }
956
+ if (this.url.protocol !== "https:" || this.url.pathname !== nodeSupervisorPath || this.url.username || this.url.password || this.url.search || this.url.hash) throw new Error("TRAVEL_NODE_TLS_REQUIRED");
957
+ if (!nodeSupervisorId(this.principal.nodeId) || !/^e7t_[a-f0-9]{64}$/.test(options.credential) || ![options.ca, options.cert, options.key].every((value) => Buffer.isBuffer(value) && value.length > 0 && value.length <= 65536)) throw new Error("TRAVEL_NODE_CLIENT_CONFIG");
958
+ this.timeout = options.timeoutMs ?? 18e4;
959
+ if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e5) throw new Error("TRAVEL_NODE_CLIENT_CONFIG");
960
+ this.key = Buffer.from(options.key);
961
+ const agent = () => new Agent2({ ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, keepAlive: true, maxSockets: 1 });
962
+ this.agents = { observe: agent(), permit: agent(), operation: agent(), stop: agent() };
963
+ }
964
+ principal;
965
+ url;
966
+ agents;
967
+ key;
968
+ pending = /* @__PURE__ */ new Map();
969
+ timeout;
970
+ bootId;
971
+ observeQuery;
972
+ permitQuery;
973
+ closed = false;
974
+ call(action, args = {}, discover = false) {
975
+ if (this.closed) return Promise.reject(new Error("TRAVEL_NODE_CLOSED"));
976
+ const slot = action === "stop" ? "stop" : action === "observe" ? "observe" : action === "permit" ? "permit" : "operation";
977
+ 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 } }));
979
+ if (body.length > nodeSupervisorLimit) return Promise.reject(new Error("TRAVEL_NODE_INVALID_REQUEST"));
980
+ const unavailable = () => new Error(this.closed ? "TRAVEL_NODE_CLOSED" : "TRAVEL_NODE_UNAVAILABLE");
981
+ return new Promise((resolve8, reject) => {
982
+ const req = request2(this.url, { method: "POST", agent: this.agents[slot], headers: {
983
+ Authorization: "Bearer " + this.options.credential,
984
+ "X-Engine7-Travel-Node": this.principal.nodeId,
985
+ "Content-Type": "application/json",
986
+ "Content-Length": body.length
987
+ } }, (res) => {
988
+ const parts = [];
989
+ let bytes = 0;
990
+ res.on("data", (part) => {
991
+ bytes += part.length;
992
+ if (bytes > nodeSupervisorLimit) {
993
+ req.destroy();
994
+ reject(new Error("TRAVEL_NODE_INVALID_RESPONSE"));
995
+ } else parts.push(part);
996
+ });
997
+ res.once("error", () => reject(unavailable()));
998
+ res.once("end", () => {
999
+ cleanup();
1000
+ if (this.closed) {
1001
+ reject(unavailable());
1002
+ return;
1003
+ }
1004
+ let envelope;
1005
+ try {
1006
+ envelope = JSON.parse(Buffer.concat(parts).toString());
1007
+ } catch {
1008
+ reject(new Error("TRAVEL_NODE_INVALID_RESPONSE"));
1009
+ return;
1010
+ }
1011
+ if (res.statusCode !== 200) {
1012
+ reject(new Error(res.statusCode === 403 || res.statusCode === 401 ? "TRAVEL_AUTH_DENIED" : res.statusCode === 503 ? "TRAVEL_NODE_BUSY" : nodeSupervisorErrors.has(envelope?.error) ? envelope.error : "TRAVEL_NODE_REFUSED"));
1013
+ return;
1014
+ }
1015
+ const response = envelope?.node;
1016
+ if (!nodeSupervisorRecord(envelope) || Object.keys(envelope).length !== 1 || !nodeSupervisorRecord(response) || response.version !== 1 || response.nodeId !== this.principal.nodeId || !nodeSupervisorId(response.bootId) || !Object.hasOwn(response, "result") || !discover && response.bootId !== this.bootId) {
1017
+ reject(new Error("TRAVEL_NODE_INVALID_RESPONSE"));
1018
+ return;
1019
+ }
1020
+ if (discover) this.bootId = response.bootId;
1021
+ resolve8(response.result);
1022
+ });
1023
+ });
1024
+ this.pending.set(req, slot);
1025
+ const timer = setTimeout(() => {
1026
+ req.destroy();
1027
+ reject(unavailable());
1028
+ }, slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
1029
+ const cleanup = () => {
1030
+ clearTimeout(timer);
1031
+ this.pending.delete(req);
1032
+ };
1033
+ req.once("error", () => {
1034
+ cleanup();
1035
+ reject(unavailable());
1036
+ });
1037
+ req.once("close", cleanup);
1038
+ req.end(body);
1039
+ });
1040
+ }
1041
+ async invoke(action, args = {}) {
1042
+ if (!this.bootId) {
1043
+ const observed = await this.observe();
1044
+ if (observed.connected !== true) throw new Error("TRAVEL_NODE_UNAVAILABLE");
1045
+ }
1046
+ return this.call(action, args);
1047
+ }
1048
+ observe() {
1049
+ return this.observeQuery ??= (async () => {
1050
+ try {
1051
+ const result = await this.call("observe", {}, true);
1052
+ if (!result || ["connected", "running", "busy"].some((key) => typeof result[key] !== "boolean")) throw new Error("TRAVEL_NODE_INVALID_RESPONSE");
1053
+ return { connected: result.connected, running: result.running, busy: result.busy };
1054
+ } catch {
1055
+ return { connected: false, running: false, busy: false };
1056
+ }
1057
+ })().finally(() => {
1058
+ this.observeQuery = void 0;
1059
+ });
1060
+ }
1061
+ prepare(checkpointDigest) {
1062
+ return this.invoke("prepare", { checkpointDigest });
1063
+ }
1064
+ async pinBranch(checkpointDigest) {
1065
+ await this.invoke("pinBranch", { checkpointDigest });
1066
+ }
1067
+ permit() {
1068
+ return this.permitQuery ??= this.invoke("permit").finally(() => {
1069
+ this.permitQuery = void 0;
1070
+ });
1071
+ }
1072
+ safeBoundary(transferId) {
1073
+ return this.invoke("safeBoundary", { transferId });
1074
+ }
1075
+ async start(permit, checkpointDigest) {
1076
+ await this.invoke("start", { permit, checkpointDigest });
1077
+ }
1078
+ async stop(expectedSource) {
1079
+ await this.invoke("stop", expectedSource ? { expectedSource } : {});
1080
+ }
1081
+ replicationOffer() {
1082
+ return this.invoke("replicationOffer");
1083
+ }
1084
+ replicaProfile() {
1085
+ return this.invoke("replicaProfile");
1086
+ }
1087
+ async bootstrapReplica(request3) {
1088
+ const wire = {
1089
+ id: request3.id,
1090
+ archiveId: request3.archiveId,
1091
+ archiveDigest: request3.archiveDigest,
1092
+ expectedDigest: request3.expectedDigest,
1093
+ parentCheckpointDigest: request3.parentCheckpointDigest,
1094
+ principal: request3.principal,
1095
+ permit: request3.permit
1096
+ };
1097
+ await this.invoke("bootstrapReplica", { request: wire });
1098
+ }
1099
+ connectReplica(profile) {
1100
+ return this.invoke("connectReplica", { profile });
1101
+ }
1102
+ recoverBranches() {
1103
+ return this.invoke("recoverBranches");
1104
+ }
1105
+ close() {
1106
+ if (this.closed) return;
1107
+ this.closed = true;
1108
+ for (const req of this.pending.keys()) req.destroy();
1109
+ for (const agent of Object.values(this.agents)) agent.destroy();
1110
+ this.key.fill(0);
1111
+ }
1112
+ };
1113
+
1114
+ // src/continuity/publication-transport.ts
1115
+ var BODY_LIMIT = PUBLICATION_MANIFEST_BYTES + 65536;
1116
+
1117
+ // src/continuity/recovery-archive.ts
1118
+ import { DatabaseSync as DatabaseSync5, backup } from "node:sqlite";
1119
+
1120
+ // src/continuity/crypto.ts
1121
+ var MAGIC2 = Buffer.from("E7OBJ001");
1122
+ var HEADER_SIZE = MAGIC2.length + 12;
1123
+
1124
+ // src/continuity/recovery-archive.ts
1125
+ var MAX_METADATA = 16 * 1024 * 1024;
1126
+
1127
+ // src/continuity/recovery-archive-transfer.ts
1128
+ var metadataLimit = 16 * 1024 * 1024;
1129
+
1130
+ // src/continuity/controller-main.ts
1131
+ var path = (value) => {
1132
+ if (typeof value !== "string" || !isAbsolute(value) || resolve2(value) !== value) throw new Error("TRAVEL_CONTROLLER_PATH");
1133
+ return value;
1134
+ };
1135
+ function openTravelController(input) {
1136
+ if (!nodeSupervisorRecord(input) || !nodeSupervisorRecord(input.nodes) || Object.keys(input.nodes).length !== 2 || !nodeSupervisorRecord(input.tls)) throw new Error("TRAVEL_CONTROLLER_CONFIG");
1137
+ const config = input;
1138
+ const nodes = {}, grants = {};
1139
+ const privateKey = readPrivateFile(path(config.tls?.keyFile), 65536);
1140
+ const closeClients = () => {
1141
+ for (const node of Object.values(nodes)) node.close();
1142
+ for (const grant of Object.values(grants)) grant.client.close();
1143
+ privateKey.fill(0);
1144
+ };
1145
+ try {
1146
+ const tls = { ca: readFileSync3(path(config.tls?.caFile)), cert: readFileSync3(path(config.tls?.certFile)), key: privateKey };
1147
+ for (const [nodeId, value] of Object.entries(config.nodes)) {
1148
+ if (!nodeSupervisorId(nodeId) || !nodeSupervisorRecord(value) || !nodeSupervisorRecord(value.principal) || value.principal.nodeId !== nodeId) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
1149
+ const principal = value.principal;
1150
+ nodes[nodeId] = new RemoteTravelNodeSupervisor({ url: value.url, principal, credential: value.credential, ...tls, timeoutMs: config.nodeTimeoutMs });
1151
+ grants[nodeId] = { principal, client: new TravelManagementClient({ url: value.authorityUrl, nodeId, credential: value.credential, ...tls, timeoutMs: config.authorityTimeoutMs }) };
1152
+ }
1153
+ const authority = new RemoteTravelControllerAuthority(grants);
1154
+ const controller = new TravelController({
1155
+ directory: path(config.directory),
1156
+ authority,
1157
+ nodes,
1158
+ preferredNodeId: config.preferredNodeId,
1159
+ intervalMs: config.intervalMs,
1160
+ healthyForMs: config.healthyForMs,
1161
+ handbackCooldownMs: config.handbackCooldownMs
1162
+ });
1163
+ let closing;
1164
+ const close = () => closing ??= (async () => {
1165
+ try {
1166
+ await controller.stop();
1167
+ controller.close();
1168
+ } finally {
1169
+ closeClients();
1170
+ }
1171
+ })();
1172
+ return { controller, nodes, authority, close };
1173
+ } catch (error) {
1174
+ closeClients();
1175
+ throw error;
1176
+ }
1177
+ }
1178
+ async function runTravelControllerCli(args) {
1179
+ if (!args.length || args.length === 1 && args[0] === "--help") return { usage: "travel-controller serve|tick|handback --config /absolute/private-config.json [--transfer-id ID]" };
1180
+ const [action, flag, file, ...rest] = args;
1181
+ if (!["serve", "tick", "handback"].includes(action) || flag !== "--config" || !file) throw new Error("TRAVEL_CONTROLLER_INVALID_COMMAND");
1182
+ if (action === "handback" ? rest.length !== 2 || rest[0] !== "--transfer-id" || !nodeSupervisorId(rest[1]) : rest.length !== 0) throw new Error("TRAVEL_CONTROLLER_INVALID_COMMAND");
1183
+ const service = openTravelController(JSON.parse(readPrivateFile(path(file), 65536).toString()));
1184
+ if (action === "serve") {
1185
+ let closing = false;
1186
+ const stop = () => {
1187
+ if (closing) return;
1188
+ closing = true;
1189
+ void service.close().then(() => process.exit(0), () => process.exit(1));
1190
+ };
1191
+ process.once("SIGTERM", stop);
1192
+ process.once("SIGINT", stop);
1193
+ service.controller.start();
1194
+ return service.controller.status();
1195
+ }
1196
+ try {
1197
+ if (action === "handback") service.controller.requestHandback(rest[1]);
1198
+ else await service.controller.tick();
1199
+ const status = service.controller.status();
1200
+ if (status.lastError) process.exitCode = 1;
1201
+ return status;
1202
+ } finally {
1203
+ await service.close();
1204
+ }
1205
+ }
1206
+ if (process.argv[1] && /[\\/](controller-main\.ts|travel-controller\.mjs)$/.test(fileURLToPath(import.meta.url)) && resolve2(process.argv[1]) === fileURLToPath(import.meta.url)) {
1207
+ runTravelControllerCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch(() => {
1208
+ process.stderr.write("TRAVEL_CONTROLLER_REFUSED\n");
1209
+ process.exitCode = 1;
1210
+ });
1211
+ }
1212
+
1213
+ // src/continuity/console-manager.ts
1214
+ import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
1215
+ import { join as join4 } from "node:path";
1216
+ var travelConsoleActions = ["status", "auto_on", "auto_off", "to_cloud", "to_local", "recover", "finish"];
1217
+ var travelConsoleErrors = /* @__PURE__ */ new Set(["invalid_action", "invalid_request", "wrong_partner", "service_unavailable", "busy", "recovery_required", "recovery_unavailable", "confirmation_required", "not_ready", "retired"]);
1218
+ var TravelConsoleManager = class {
1219
+ constructor(options) {
1220
+ this.options = options;
1221
+ if (!Number.isSafeInteger(options.statusTimeoutMs ?? 5e3) || (options.statusTimeoutMs ?? 5e3) < 1 || (options.statusTimeoutMs ?? 5e3) > 8e3) throw new Error("TRAVEL_CONSOLE_CONFIG");
1222
+ const values = Object.values(options.nodes);
1223
+ if (values.length !== 2 || values.some((node) => ["tenantId", "companionId", "seatId"].some((key) => node.principal[key] !== options.identity[key])) || new Set(values.map((n) => n.principal.role)).size !== 2) throw new Error("TRAVEL_CONSOLE_IDENTITY");
1224
+ this.roles = { local: values.find((node) => node.principal.role === "LOCAL"), cloud: values.find((node) => node.principal.role === "CLOUD") };
1225
+ preparePrivateDirectory(options.directory);
1226
+ const file = join4(options.directory, "console.sqlite");
1227
+ preparePrivateDatabase(file);
1228
+ this.db = new DatabaseSync6(file);
1229
+ try {
1230
+ this.db.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS binding(value TEXT NOT NULL)");
1231
+ const binding = JSON.stringify([options.identity, values.map((n) => [n.principal.nodeId, n.principal.role]).sort()]), prior = this.db.prepare("SELECT value FROM binding").all();
1232
+ if (!prior.length) this.db.prepare("INSERT INTO binding VALUES(?)").run(binding);
1233
+ else if (prior.length !== 1 || prior[0].value !== binding) throw new Error("TRAVEL_CONSOLE_IDENTITY");
1234
+ } catch (error) {
1235
+ this.db.close();
1236
+ throw error;
1237
+ }
1238
+ }
1239
+ db;
1240
+ closed = false;
1241
+ changing = false;
1242
+ roles;
1243
+ role(nodeId) {
1244
+ if (nodeId === this.roles.local.principal.nodeId) return "local";
1245
+ if (nodeId === this.roles.cloud.principal.nodeId) return "cloud";
1246
+ throw new Error("TRAVEL_CONSOLE_IDENTITY");
1247
+ }
1248
+ async snapshot() {
1249
+ if (this.closed) throw new Error("service_unavailable");
1250
+ const peer = (role, observation = { connected: false, running: false, busy: false }) => ({
1251
+ role,
1252
+ label: this.options.labels?.[role] ?? (role === "local" ? "\u6211\u7684\u7535\u8111" : "\u4E91\u7AEF\u968F\u884C\u673A"),
1253
+ connected: observation.connected,
1254
+ running: observation.running,
1255
+ busy: observation.busy
1256
+ });
1257
+ const reads = (async () => {
1258
+ const observations = Promise.all(["local", "cloud"].map(async (role) => peer(
1259
+ role,
1260
+ await this.roles[role].observe().catch(() => ({ connected: false, running: false, busy: false }))
1261
+ )));
1262
+ const retirement2 = await this.options.retirement?.status();
1263
+ const current = retirement2 ? void 0 : await this.options.authority.status(this.roles.local.principal);
1264
+ return { peers: await observations, retirement: retirement2, current };
1265
+ })().catch(() => void 0);
1266
+ let timer;
1267
+ const result = await Promise.race([reads, new Promise((resolve8) => {
1268
+ timer = setTimeout(() => resolve8(void 0), this.options.statusTimeoutMs ?? 5e3);
1269
+ })]);
1270
+ clearTimeout(timer);
1271
+ if (this.closed) throw new Error("service_unavailable");
1272
+ const controller = this.options.controller.status(), retirement = result?.retirement;
1273
+ const peers = result?.peers ?? [peer("local"), peer("cloud")];
1274
+ let active = result ? "none" : "unknown", verified = !!result;
1275
+ if (result?.current?.activeNodeId && !result.current.expired) {
1276
+ const role = this.role(result.current.activeNodeId), observed = peers.find((p) => p.role === role);
1277
+ active = observed.connected && observed.running ? role : "unknown";
1278
+ }
1279
+ const allowedActions = ["status"];
1280
+ if (!retirement) {
1281
+ if (verified && active !== "unknown") allowedActions.push(controller.automatic ? "auto_off" : "auto_on");
1282
+ if (verified && active !== "unknown" && !controller.job && !this.changing) {
1283
+ if (active === "local" && peers[1].connected) allowedActions.push("to_cloud");
1284
+ if (active === "cloud" && peers[0].connected) allowedActions.push("to_local");
1285
+ if (active === "local" && this.options.retirement) allowedActions.push("recover", "finish");
1286
+ }
1287
+ } else if (retirement.state !== "PURGED" && !this.changing) allowedActions.push("recover", "finish");
1288
+ return {
1289
+ version: 1,
1290
+ identity: { ...this.options.identity },
1291
+ enabled: controller.automatic,
1292
+ active,
1293
+ preferred: this.role(controller.preferredNodeId),
1294
+ peers,
1295
+ checkedAt: Date.now(),
1296
+ allowedActions,
1297
+ 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 } } : {}
1300
+ };
1301
+ }
1302
+ async execute(action, payload) {
1303
+ try {
1304
+ if (!travelConsoleActions.includes(action)) throw new Error("invalid_action");
1305
+ if (action === "finish" && payload?.confirmed !== true) throw new Error("confirmation_required");
1306
+ if (action === "status") return { ok: true, connected: true, snapshot: await this.snapshot() };
1307
+ if (this.changing) throw new Error("busy");
1308
+ this.changing = true;
1309
+ try {
1310
+ const snapshot = await this.snapshot();
1311
+ if (snapshot.retirement?.state === "PURGED") {
1312
+ if (action === "finish") return { ok: true, connected: true, snapshot };
1313
+ throw new Error("retired");
1314
+ }
1315
+ if (action === "auto_on" || action === "auto_off") {
1316
+ if (snapshot.retirement) throw new Error("retired");
1317
+ if (snapshot.active === "unknown") throw new Error("not_ready");
1318
+ this.options.controller.setAutomatic(action === "auto_on");
1319
+ } else if (action === "to_cloud" || action === "to_local") {
1320
+ if (snapshot.retirement) throw new Error("retired");
1321
+ const role = action === "to_cloud" ? "cloud" : "local";
1322
+ if (!payload?.requestId || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(payload.requestId)) throw new Error("invalid_request");
1323
+ const job = this.options.controller.status().job;
1324
+ if (job && (job.id !== payload.requestId || job.target !== this.roles[role].principal.nodeId)) throw new Error("busy");
1325
+ if (!job && (snapshot.active === "unknown" || !snapshot.peers.find((p) => p.role === role)?.connected)) throw new Error("not_ready");
1326
+ this.options.controller.requestTransfer(this.roles[role].principal.nodeId, payload.requestId);
1327
+ } else {
1328
+ if (!this.options.retirement) throw new Error("recovery_unavailable");
1329
+ if (this.options.controller.status().job) throw new Error("busy");
1330
+ if (!snapshot.retirement && snapshot.active !== "local") throw new Error("not_ready");
1331
+ await this.options.controller.stop();
1332
+ this.options.controller.setAutomatic(false);
1333
+ if (action === "recover") await this.options.retirement.recover(payload?.receipt);
1334
+ else {
1335
+ if (!(await this.options.retirement.status())?.nodesStopped) {
1336
+ await this.roles.local.stop();
1337
+ await this.roles.cloud.stop();
1338
+ }
1339
+ await this.options.retirement.finish();
1340
+ }
1341
+ }
1342
+ } finally {
1343
+ this.changing = false;
1344
+ }
1345
+ return { ok: true, connected: true, snapshot: await this.snapshot() };
1346
+ } catch (error) {
1347
+ const message = error.message, code = travelConsoleErrors.has(message) ? message : /RECOVERY/.test(message) ? "recovery_required" : /BUSY|HANDOFF_STATE|COLLISION/.test(message) ? "busy" : "service_unavailable";
1348
+ return { ok: false, connected: true, error: code };
1349
+ }
1350
+ }
1351
+ close() {
1352
+ if (this.closed) return;
1353
+ if (this.changing) throw new Error("TRAVEL_CONSOLE_BUSY");
1354
+ this.closed = true;
1355
+ this.db.close();
1356
+ }
1357
+ };
1358
+
1359
+ // src/continuity/console-server.ts
1360
+ import { createServer } from "node:https";
1361
+ import { timingSafeEqual } from "node:crypto";
1362
+ var travelConsolePath = "/travel/console/v1";
1363
+ var exact = (record, allowed) => Object.keys(record).every((key) => allowed.includes(key));
1364
+ var shutdowns = /* @__PURE__ */ new WeakMap();
1365
+ function closeTravelConsoleServer(server) {
1366
+ const close = shutdowns.get(server);
1367
+ if (!close) throw new Error("TRAVEL_CONSOLE_CONFIG");
1368
+ return close();
1369
+ }
1370
+ function createTravelConsoleServer(options) {
1371
+ const { manager, identity: identity3, token, bodyTimeoutMs = 5e3, ...tls } = options;
1372
+ if (!/^e7u_[a-f0-9]{64}$/.test(token) || !Number.isSafeInteger(bodyTimeoutMs) || bodyTimeoutMs < 100 || bodyTimeoutMs > 3e4) throw new Error("TRAVEL_CONSOLE_CONFIG");
1373
+ const expected = Buffer.from("Bearer " + token);
1374
+ let reads = 0, writes = 0;
1375
+ let closing;
1376
+ const pending = /* @__PURE__ */ new Set();
1377
+ const server = createServer({ ...tls, minVersion: "TLSv1.3", requestCert: false }, (req, res) => {
1378
+ if (closing) {
1379
+ req.resume();
1380
+ res.writeHead(503);
1381
+ res.end();
1382
+ return;
1383
+ }
1384
+ const operation = handle(req, res);
1385
+ pending.add(operation);
1386
+ void operation.finally(() => pending.delete(operation));
1387
+ });
1388
+ const handle = async (req, res) => {
1389
+ res.setHeader("Content-Type", "application/json");
1390
+ res.setHeader("Cache-Control", "no-store");
1391
+ const reply = (status, body) => {
1392
+ if (!res.destroyed && !res.writableEnded) {
1393
+ res.statusCode = status;
1394
+ res.end(JSON.stringify(body));
1395
+ }
1396
+ };
1397
+ if (req.method !== "POST" || req.url !== travelConsolePath) {
1398
+ req.resume();
1399
+ reply(404, { ok: false, error: "invalid_request" });
1400
+ return;
1401
+ }
1402
+ const authorization = req.headers.authorization;
1403
+ if (req.headers.origin !== void 0 || typeof authorization !== "string" || Buffer.byteLength(authorization) !== expected.length || req.rawHeaders.filter((v, i) => i % 2 === 0 && v.toLowerCase() === "authorization").length !== 1 || !timingSafeEqual(Buffer.from(authorization), expected)) {
1404
+ req.resume();
1405
+ reply(403, { ok: false, error: "wrong_partner" });
1406
+ return;
1407
+ }
1408
+ const timer = setTimeout(() => req.destroy(), bodyTimeoutMs);
1409
+ timer.unref();
1410
+ let slot;
1411
+ try {
1412
+ const parts = [];
1413
+ let size = 0;
1414
+ for await (const part of req) {
1415
+ size += part.length;
1416
+ if (size > 65536) {
1417
+ reply(400, { ok: false, error: "invalid_request" });
1418
+ return;
1419
+ }
1420
+ parts.push(part);
1421
+ }
1422
+ clearTimeout(timer);
1423
+ let input;
1424
+ try {
1425
+ input = JSON.parse(Buffer.concat(parts).toString());
1426
+ } catch {
1427
+ reply(400, { ok: false, error: "invalid_request" });
1428
+ return;
1429
+ }
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)) {
1431
+ reply(400, { ok: false, error: "invalid_request" });
1432
+ return;
1433
+ }
1434
+ const requestIdentity = input.identity, action = String(input.action);
1435
+ if (["tenantId", "companionId", "seatId"].some((key) => requestIdentity[key] !== identity3[key])) {
1436
+ reply(403, { ok: false, error: "wrong_partner" });
1437
+ return;
1438
+ }
1439
+ const payload = input.payload, allowed = action === "finish" ? ["confirmed"] : action === "recover" ? ["requestId", "receipt"] : action.startsWith("to_") ? ["requestId"] : [];
1440
+ 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
+ reply(400, { ok: false, error: "invalid_request" });
1442
+ return;
1443
+ }
1444
+ if (input.action === "status" ? reads >= 4 : writes >= 1) {
1445
+ reply(503, { ok: false, error: "busy" });
1446
+ return;
1447
+ }
1448
+ slot = input.action === "status" ? "read" : "write";
1449
+ if (slot === "read") reads++;
1450
+ else writes++;
1451
+ const result = await manager.execute(input.action, payload);
1452
+ reply(result.ok ? 200 : 409, result);
1453
+ } catch (error) {
1454
+ reply(409, { ok: false, error: travelConsoleErrors.has(error.message) ? error.message : "service_unavailable" });
1455
+ } finally {
1456
+ clearTimeout(timer);
1457
+ if (slot === "read") reads--;
1458
+ else if (slot === "write") writes--;
1459
+ }
1460
+ };
1461
+ shutdowns.set(server, () => closing ??= (async () => {
1462
+ const stopped = new Promise((resolve8) => server.close(() => resolve8()));
1463
+ server.closeAllConnections();
1464
+ await stopped;
1465
+ await Promise.allSettled([...pending]);
1466
+ })());
1467
+ server.headersTimeout = 5e3;
1468
+ server.requestTimeout = bodyTimeoutMs;
1469
+ server.keepAliveTimeout = 5e3;
1470
+ server.maxConnections = 16;
1471
+ server.on("tlsClientError", () => {
1472
+ });
1473
+ return server;
1474
+ }
1475
+
1476
+ // 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";
1478
+ 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";
1481
+
1482
+ // 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";
1485
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
1486
+ import { execFile } from "node:child_process";
1487
+ import { promisify } from "node:util";
1488
+ import { createHash as createHash5 } from "node:crypto";
1489
+
1490
+ // src/continuity/retirement.ts
1491
+ import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
1492
+ import { createHash } from "node:crypto";
1493
+ 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";
1496
+ var identity = (value) => JSON.stringify([value.tenantId, value.companionId, value.seatId]);
1497
+ var sha = (value) => createHash("sha256").update(value).digest("hex");
1498
+ var LocalSeatResource = class {
1499
+ constructor(path3, identity3) {
1500
+ this.path = path3;
1501
+ this.identity = identity3;
1502
+ if (!isAbsolute2(path3) || resolve3(path3) !== path3 || path3.split("/").filter(Boolean).length < 3) throw new Error("TRAVEL_RETIREMENT_PATH");
1503
+ this.id = "directory-" + sha(path3);
1504
+ }
1505
+ id;
1506
+ check() {
1507
+ if (!existsSync(this.path)) return false;
1508
+ const stat = lstatSync3(this.path);
1509
+ if (!stat.isDirectory() || stat.isSymbolicLink() || realpathSync2(this.path) !== this.path || process.platform !== "win32" && stat.uid !== process.getuid()) throw new Error("TRAVEL_RETIREMENT_PATH");
1510
+ if (identity(JSON.parse(readPrivateFile(join5(this.path, ".travel-seat-resource.json"), 65536).toString())) !== identity(this.identity)) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
1511
+ return true;
1512
+ }
1513
+ async inventory() {
1514
+ return this.inventoryNow();
1515
+ }
1516
+ inventoryNow() {
1517
+ if (!this.check()) return [];
1518
+ const result = [];
1519
+ const visit = (directory) => {
1520
+ for (const item of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1521
+ const path3 = join5(directory, item.name), version = relative(this.path, path3);
1522
+ if (item.isSymbolicLink()) result.push({ version, digest: sha(readlinkSync(path3)) });
1523
+ else if (item.isDirectory()) visit(path3);
1524
+ else if (item.isFile()) {
1525
+ 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)) });
1527
+ } else throw new Error("TRAVEL_RETIREMENT_PATH");
1528
+ if (result.length > 1e6) throw new Error("TRAVEL_RETIREMENT_BUDGET");
1529
+ }
1530
+ };
1531
+ visit(this.path);
1532
+ return result;
1533
+ }
1534
+ async purge(expectedInventory) {
1535
+ const allowed = new Map(expectedInventory.map((item) => [item.version, item.digest]));
1536
+ 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");
1539
+ }
1540
+ };
1541
+ var TravelRetirement = class {
1542
+ constructor(options) {
1543
+ this.options = options;
1544
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(options.jobId) || options.resources.some((resource) => identity(resource.identity) !== identity(options.identity)) || new Set(options.resources.map((resource) => resource.id)).size !== options.resources.length) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
1545
+ preparePrivateDirectory(options.directory);
1546
+ const ownerFile = join5(options.directory, "owner.sqlite");
1547
+ preparePrivateDatabase(ownerFile);
1548
+ this.owner = new DatabaseSync7(ownerFile);
1549
+ try {
1550
+ this.owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER);BEGIN IMMEDIATE");
1551
+ } catch (error) {
1552
+ this.owner.close();
1553
+ throw new Error("TRAVEL_RETIREMENT_BUSY", { cause: error });
1554
+ }
1555
+ const file = join5(options.directory, "retirement.sqlite");
1556
+ preparePrivateDatabase(file);
1557
+ this.db = new DatabaseSync7(file);
1558
+ try {
1559
+ this.db.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS job(id TEXT PRIMARY KEY,binding TEXT NOT NULL,state TEXT NOT NULL,stopped INTEGER NOT NULL DEFAULT 0);CREATE TABLE IF NOT EXISTS resources(id TEXT PRIMARY KEY,inventory TEXT,state TEXT NOT NULL)");
1560
+ const binding = JSON.stringify([identity(options.identity), options.resources.map((resource) => [resource.id, resource.path ?? null]).sort(), options.accountOwnerRequestedKeyDestruction === true]);
1561
+ const prior = this.db.prepare("SELECT * FROM job").all();
1562
+ if (prior.length && (prior.length !== 1 || prior[0].id !== options.jobId || prior[0].binding !== binding)) throw new Error("TRAVEL_RETIREMENT_ID_COLLISION");
1563
+ if (!prior.length) this.db.prepare("INSERT INTO job(id,binding,state) VALUES(?,?,'RETIRING')").run(options.jobId, binding);
1564
+ } catch (error) {
1565
+ this.db.close();
1566
+ this.owner.close();
1567
+ throw error;
1568
+ }
1569
+ }
1570
+ db;
1571
+ owner;
1572
+ active;
1573
+ status() {
1574
+ const row = this.db.prepare("SELECT id,state,stopped FROM job").get();
1575
+ return { jobId: String(row.id), state: String(row.state), nodesStopped: row.stopped === 1 };
1576
+ }
1577
+ run() {
1578
+ return this.active ??= this.execute().finally(() => {
1579
+ this.active = void 0;
1580
+ });
1581
+ }
1582
+ async execute() {
1583
+ let status = this.status();
1584
+ if (status.state === "PURGED") return status;
1585
+ await this.options.retire();
1586
+ if (!status.nodesStopped) {
1587
+ await this.options.stopNodes();
1588
+ this.db.prepare("UPDATE job SET stopped=1").run();
1589
+ }
1590
+ if (status.state === "RETIRING") {
1591
+ this.db.prepare("UPDATE job SET state='RECOVERY_ONLY'").run();
1592
+ status = this.status();
1593
+ }
1594
+ const verifyRecovery = async (required = false) => {
1595
+ const recovered = await this.options.verifyLocalRecovery();
1596
+ if (!recovered) {
1597
+ if (required) throw new Error("TRAVEL_RETIREMENT_RECOVERY_REQUIRED");
1598
+ return null;
1599
+ }
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");
1601
+ for (const resource of this.options.resources) {
1602
+ if (resource.path) {
1603
+ const local = resolve3(recovered.ordinaryStateDir), path3 = resolve3(resource.path), journal = resolve3(this.options.directory);
1604
+ if ([local, journal].some((p) => p === path3 || p.startsWith(path3 + "/") || path3.startsWith(p + "/"))) throw new Error("TRAVEL_RETIREMENT_LOCAL_OVERLAP");
1605
+ }
1606
+ }
1607
+ return recovered;
1608
+ };
1609
+ if (!await verifyRecovery()) return this.status();
1610
+ if (this.status().state === "RECOVERY_ONLY") this.db.prepare("UPDATE job SET state='PURGING'").run();
1611
+ if (this.status().state === "PURGING") {
1612
+ for (const resource of this.options.resources) {
1613
+ const current = await resource.inventory();
1614
+ let row = this.db.prepare("SELECT * FROM resources WHERE id=?").get(resource.id);
1615
+ if (row?.state === "PURGED") {
1616
+ if (current.length) throw new Error("TRAVEL_RETIREMENT_RESOURCE_REAPPEARED");
1617
+ continue;
1618
+ }
1619
+ if (!row) {
1620
+ this.db.prepare("INSERT INTO resources VALUES(?,?,'PURGING')").run(resource.id, JSON.stringify(current));
1621
+ row = this.db.prepare("SELECT * FROM resources WHERE id=?").get(resource.id);
1622
+ }
1623
+ 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");
1625
+ await verifyRecovery(true);
1626
+ await resource.purge(original);
1627
+ if ((await resource.inventory()).length) throw new Error("TRAVEL_RETIREMENT_PROVIDER_PENDING");
1628
+ this.db.prepare("UPDATE resources SET state='PURGED' WHERE id=?").run(resource.id);
1629
+ }
1630
+ this.db.prepare("UPDATE job SET state='KEY_DELETION_PENDING'").run();
1631
+ }
1632
+ await verifyRecovery(true);
1633
+ const revoked = await this.options.revokeKey();
1634
+ if (revoked?.revoked !== true) throw new Error("TRAVEL_RETIREMENT_KEY_PENDING");
1635
+ if (this.options.accountOwnerRequestedKeyDestruction === true) {
1636
+ await verifyRecovery(true);
1637
+ if (!this.options.destroyKey || (await this.options.destroyKey()).destroyed !== true) throw new Error("TRAVEL_RETIREMENT_KEY_PENDING");
1638
+ }
1639
+ this.db.prepare("UPDATE job SET state='PURGED'").run();
1640
+ return this.status();
1641
+ }
1642
+ close() {
1643
+ if (this.active) throw new Error("TRAVEL_RETIREMENT_BUSY");
1644
+ this.db.close();
1645
+ this.owner.close();
1646
+ }
1647
+ };
1648
+
1649
+ // 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";
1651
+ 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";
1654
+
1655
+ // src/continuity/runtime-lock.ts
1656
+ import { randomUUID as randomUUID3 } from "node:crypto";
1657
+ 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";
1659
+ import { join as join6 } from "node:path";
1660
+ import { createRequire } from "node:module";
1661
+ var sqlite;
1662
+ function openSQLite(file, options = {}) {
1663
+ return new (sqlite ??= createRequire(import.meta.url)("node:sqlite")).DatabaseSync(file, options);
1664
+ }
1665
+ var bootId = randomUUID3();
1666
+ var checkpointHandles = /* @__PURE__ */ new Set();
1667
+ var recoveryWriterLocks = new AsyncLocalStorage();
1668
+ function openControl(stateDir, create = true, busyTimeoutMs = 0) {
1669
+ if (create) mkdirSync3(stateDir, { recursive: true });
1670
+ const state = realpathSync3(stateDir);
1671
+ if (process.platform !== "win32" && lstatSync4(state).uid !== process.getuid()) throw new Error("CONTROL_OWNER_MISMATCH: run travel as the engine data owner, without sudo");
1672
+ const directory = join6(state, ".continuity");
1673
+ if (create) mkdirSync3(directory, { recursive: true, mode: 448 });
1674
+ if (lstatSync4(directory).isSymbolicLink()) throw new Error("UNSAFE_CONTROL_DIRECTORY");
1675
+ assertControlPermissions(directory);
1676
+ const file = join6(directory, "runtime.sqlite");
1677
+ if (create) {
1678
+ try {
1679
+ closeSync3(openSync3(file, "wx", 384));
1680
+ } catch (error) {
1681
+ if (error.code !== "EEXIST") throw error;
1682
+ }
1683
+ }
1684
+ assertControlPermissions(file);
1685
+ for (const name of [file, file + "-journal", file + "-wal", file + "-shm"]) {
1686
+ try {
1687
+ if (!lstatSync4(name).isFile() || lstatSync4(name).isSymbolicLink()) throw new Error("UNSAFE_CONTROL_FILE");
1688
+ } catch (error) {
1689
+ if (error.code !== "ENOENT") throw error;
1690
+ }
1691
+ }
1692
+ const db = openSQLite(file);
1693
+ try {
1694
+ db.exec(`PRAGMA busy_timeout=${busyTimeoutMs}; PRAGMA synchronous=FULL;
1695
+ CREATE TABLE IF NOT EXISTS writers (
1696
+ id TEXT PRIMARY KEY, pid INTEGER NOT NULL, boot_id TEXT NOT NULL,
1697
+ kind TEXT NOT NULL, registered_at TEXT NOT NULL
1698
+ )`);
1699
+ return db;
1700
+ } catch (error) {
1701
+ db.close();
1702
+ throw normalize(error);
1703
+ }
1704
+ }
1705
+ function assertControlPermissions(file) {
1706
+ const info = lstatSync4(file);
1707
+ if (process.platform !== "win32" && (info.uid !== process.getuid() || info.mode & 63))
1708
+ throw new Error("CONTROL_PERMISSIONS: use the engine data owner; repair .continuity ownership and private permissions while stopped");
1709
+ }
1710
+ function normalize(error) {
1711
+ return /database is locked|database table is locked|SQLITE_BUSY|SQLITE_LOCKED/i.test(String(error)) ? new Error("CHECKPOINT_BUSY", { cause: error }) : error;
1712
+ }
1713
+ function assertDead(pid, kind = "registered") {
1714
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error(`WRITER_STATE_UNKNOWN: ${kind}; use travel status`);
1715
+ try {
1716
+ process.kill(pid, 0);
1717
+ } catch (error) {
1718
+ if (error.code === "ESRCH") return;
1719
+ throw new Error(`WRITER_STATE_UNKNOWN: ${kind}, pid=${pid}; use travel status`, { cause: error });
1720
+ }
1721
+ throw new Error(`WRITER_ACTIVE: ${kind}, pid=${pid}; use travel status`);
1722
+ }
1723
+ async function withCheckpointLock(stateDir, operation) {
1724
+ const db = openControl(stateDir);
1725
+ try {
1726
+ db.exec("BEGIN IMMEDIATE");
1727
+ checkpointHandles.add(db);
1728
+ for (const row of db.prepare("SELECT pid,kind FROM writers").all()) assertDead(Number(row.pid), String(row.kind));
1729
+ for (const name of [".engine.pid", ".bg-worker.pid"]) {
1730
+ let value;
1731
+ try {
1732
+ value = readFileSync5(join6(stateDir, name), "utf8").trim();
1733
+ } catch (error) {
1734
+ if (error.code === "ENOENT") continue;
1735
+ throw new Error("WRITER_STATE_UNKNOWN", { cause: error });
1736
+ }
1737
+ if (!/^[1-9][0-9]*$/.test(value)) throw new Error(`WRITER_STATE_UNKNOWN: ${name}; use travel status`);
1738
+ assertDead(Number(value), name);
1739
+ }
1740
+ db.exec("DELETE FROM writers");
1741
+ const result = await operation();
1742
+ db.exec("COMMIT");
1743
+ return result;
1744
+ } catch (error) {
1745
+ throw normalize(error);
1746
+ } finally {
1747
+ checkpointHandles.delete(db);
1748
+ db.close();
1749
+ }
1750
+ }
1751
+
1752
+ // src/continuity/local-dedupe.ts
1753
+ import { DatabaseSync as DatabaseSync8 } from "node:sqlite";
1754
+ import { createHash as createHash2 } from "node:crypto";
1755
+ import { dirname as dirname2 } from "node:path";
1756
+ var sha2 = (value) => createHash2("sha256").update(value).digest("hex");
1757
+ var hash = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
1758
+ var PlatformReceiptStore = class {
1759
+ db;
1760
+ constructor(file, namespace) {
1761
+ if (!namespace || namespace.length > 1024) throw new Error("PLATFORM_RECEIPT_IDENTITY");
1762
+ preparePrivateDirectory(dirname2(file));
1763
+ preparePrivateDatabase(file);
1764
+ this.db = new DatabaseSync8(file);
1765
+ try {
1766
+ this.db.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS binding(namespace TEXT NOT NULL);CREATE TABLE IF NOT EXISTS inputs(id TEXT PRIMARY KEY,state TEXT NOT NULL);CREATE TABLE IF NOT EXISTS effects(id TEXT PRIMARY KEY,body TEXT NOT NULL);CREATE TABLE IF NOT EXISTS imports(digest TEXT PRIMARY KEY,identity TEXT NOT NULL)");
1767
+ const binding = this.db.prepare("SELECT namespace FROM binding").all();
1768
+ if (!binding.length) this.db.prepare("INSERT INTO binding VALUES(?)").run(namespace);
1769
+ else if (binding.length !== 1 || binding[0].namespace !== namespace) throw new Error("PLATFORM_RECEIPT_IDENTITY");
1770
+ } catch (error) {
1771
+ this.db.close();
1772
+ throw error;
1773
+ }
1774
+ }
1775
+ has(platformId) {
1776
+ return !!this.db.prepare("SELECT 1 FROM inputs WHERE id=?").get(sha2(platformId));
1777
+ }
1778
+ remember(platformId) {
1779
+ if (!platformId || platformId.length > 512) throw new Error("PLATFORM_RECEIPT_ID");
1780
+ this.db.prepare("INSERT OR IGNORE INTO inputs VALUES(?,'SEEN')").run(sha2(platformId));
1781
+ }
1782
+ effect(id) {
1783
+ const row = this.db.prepare("SELECT body FROM effects WHERE id=?").get(id);
1784
+ return row ? JSON.parse(String(row.body)) : void 0;
1785
+ }
1786
+ importTravelReceipt(receipt) {
1787
+ const { digest, ...body } = receipt;
1788
+ if (receipt.format !== "engine7-travel-exit-dedupe-v1" || sha2(JSON.stringify(body)) !== digest || !hash(receipt.checkpointDigest) || !Number.isSafeInteger(receipt.deletionWatermark) || receipt.deletionWatermark < 0 || !Array.isArray(receipt.inputs) || !Array.isArray(receipt.effects)) throw new Error("PLATFORM_RECEIPT_INVALID");
1789
+ const identity3 = JSON.stringify(receipt.identity);
1790
+ if (this.db.prepare("SELECT 1 FROM imports WHERE identity<>? LIMIT 1").get(identity3)) throw new Error("PLATFORM_RECEIPT_IDENTITY");
1791
+ for (const input of receipt.inputs) {
1792
+ if (["DONE", "CANCELLED"].includes(String(input.state))) continue;
1793
+ const effects = receipt.effects.filter((effect) => effect.eventId === input.id);
1794
+ if (!effects.length || effects.some((effect) => !["SENT", "UNKNOWN", "CANCELLED"].includes(String(effect.state)))) throw new Error("PLATFORM_RECEIPT_PENDING");
1795
+ }
1796
+ this.db.exec("BEGIN IMMEDIATE");
1797
+ try {
1798
+ for (const input of receipt.inputs) {
1799
+ if (!hash(input.platformIdHash) || !hash(input.id)) throw new Error("PLATFORM_RECEIPT_INVALID");
1800
+ this.db.prepare("INSERT OR IGNORE INTO inputs VALUES(?,?)").run(input.platformIdHash, String(input.state));
1801
+ }
1802
+ for (const effect of receipt.effects) {
1803
+ if (!hash(effect.id) || !hash(effect.eventId) || !["PRODUCED", "INTENT", "SENT", "FAILED_NOT_SENT", "UNKNOWN", "CANCELLED"].includes(String(effect.state))) throw new Error("PLATFORM_RECEIPT_INVALID");
1804
+ const prior = this.effect(String(effect.id)), serialized = JSON.stringify(effect);
1805
+ if (prior && JSON.stringify(prior) !== serialized) throw new Error("PLATFORM_RECEIPT_COLLISION");
1806
+ this.db.prepare("INSERT OR IGNORE INTO effects VALUES(?,?)").run(String(effect.id), serialized);
1807
+ }
1808
+ this.db.prepare("INSERT OR IGNORE INTO imports VALUES(?,?)").run(digest, identity3);
1809
+ this.db.exec("COMMIT");
1810
+ } catch (error) {
1811
+ this.db.exec("ROLLBACK");
1812
+ throw error;
1813
+ }
1814
+ return { digest, identity: receipt.identity, loaded: true, unknownEffects: receipt.effects.filter((effect) => effect.state === "UNKNOWN").length };
1815
+ }
1816
+ close() {
1817
+ this.db.close();
1818
+ }
1819
+ };
1820
+
1821
+ // src/continuity/local-exit-proof.ts
1822
+ import { createHash as createHash3, verify } from "node:crypto";
1823
+ import { createReadStream, mkdirSync as mkdirSync4, readdirSync as readdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
1824
+ import { join as join7, relative as relative2 } from "node:path";
1825
+ var hash2 = (value) => createHash3("sha256").update(value).digest("hex");
1826
+ var equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
1827
+ function copyLocalExitPath(source, path3) {
1828
+ const name = relative2(source, path3).replaceAll("\\", "/");
1829
+ return !/^(?:\.travel-|\.runtime-publication)|^(?:\.engine\.pid|\.bg-worker\.pid)$|(?:^|\/)\.continuity\/(?:travel-|runtime\.sqlite|(?:engine|data)-config\.json$|(?:mem7|calendar|proactive|session-events|legacy-memory-[^/]+|topics-vectors-[^/]+)-replication\.json$)/.test(name);
1830
+ }
1831
+ async function localExitFilesDigest(root, ordinary = false) {
1832
+ const files = [];
1833
+ const visit = async (directory) => {
1834
+ for (const entry of readdirSync2(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1835
+ const file = join7(directory, entry.name);
1836
+ if (ordinary ? relative2(root, file).replaceAll("\\", "/") === ".continuity/travel-exit-receipt.json" : !copyLocalExitPath(root, file)) continue;
1837
+ if (entry.isSymbolicLink()) throw new Error("TRAVEL_EXIT_PATH");
1838
+ if (entry.isDirectory()) {
1839
+ await visit(file);
1840
+ continue;
1841
+ }
1842
+ if (!entry.isFile() || files.length >= 1e6) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
1843
+ const digest = createHash3("sha256");
1844
+ for await (const chunk of createReadStream(file)) digest.update(chunk);
1845
+ files.push({ path: relative2(root, file).replaceAll("\\", "/"), sha256: digest.digest("hex") });
1846
+ }
1847
+ };
1848
+ await visit(root);
1849
+ return hash2(JSON.stringify(files));
1850
+ }
1851
+ async function currentBinding(stateDir, authority, principal) {
1852
+ const activation = JSON.parse(readPrivateFile(join7(stateDir, ".travel-active.json"), 4 * 1024 * 1024).toString());
1853
+ const permit = activation.permit, { signature, ...signed } = permit;
1854
+ if (activation.format !== "engine7-runtime-activation-v1" || !verify(null, Buffer.from(JSON.stringify(signed)), authority.publicKey, Buffer.from(signature, "base64")) || permit.nodeId !== principal.nodeId || activation.nodeId !== principal.nodeId || principal.role !== "LOCAL" || ["tenantId", "companionId", "seatId"].some((field) => permit[field] !== principal[field] || activation.identity[field] !== permit[field])) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
1855
+ const control = await authority.status(principal);
1856
+ if (control.activeNodeId !== permit.nodeId || control.activeBootId !== permit.bootId || control.authorityBootId !== permit.authorityBootId || control.epoch !== permit.epoch || control.deletionWatermark !== permit.deletionWatermark) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
1857
+ return {
1858
+ nodeId: permit.nodeId,
1859
+ bootId: permit.bootId,
1860
+ authorityBootId: permit.authorityBootId,
1861
+ epoch: permit.epoch,
1862
+ checkpointDigest: control.checkpointDigest,
1863
+ deletionWatermark: control.deletionWatermark
1864
+ };
1865
+ }
1866
+ async function verifyStoppedLocalExitProof(options) {
1867
+ let proof;
1868
+ try {
1869
+ proof = JSON.parse(readPrivateFile(join7(options.stateDir, ".continuity/travel-exit-source.json"), 65536).toString());
1870
+ } catch {
1871
+ throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
1872
+ }
1873
+ const { digest, ...body } = proof;
1874
+ const binding = await currentBinding(options.stateDir, options.authority, options.principal);
1875
+ if (proof.format !== "engine7-stopped-local-exit-v1" || digest !== hash2(JSON.stringify(body)) || proof.checkpointDigest !== options.checkpointDigest || Object.entries(binding).some(([key, value]) => proof[key] !== value) || proof.filesDigest !== await localExitFilesDigest(options.stateDir)) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
1876
+ return { binding, filesDigest: String(proof.filesDigest), check: async () => {
1877
+ if (!equal(binding, await currentBinding(options.stateDir, options.authority, options.principal)) || proof.filesDigest !== await localExitFilesDigest(options.stateDir)) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
1878
+ } };
1879
+ }
1880
+
1881
+ // src/continuity/local-exit.ts
1882
+ var identity2 = (value) => JSON.stringify([value.tenantId, value.companionId, value.seatId]);
1883
+ var sha3 = (value) => createHash4("sha256").update(value).digest("hex");
1884
+ function detachReplication(directory) {
1885
+ for (const entry of readdirSync3(directory, { withFileTypes: true })) {
1886
+ const file = join8(directory, entry.name);
1887
+ if (entry.isSymbolicLink()) throw new Error("TRAVEL_EXIT_PATH");
1888
+ if (entry.isDirectory()) {
1889
+ detachReplication(file);
1890
+ continue;
1891
+ }
1892
+ if (!entry.isFile()) throw new Error("TRAVEL_EXIT_PATH");
1893
+ if (!/\.(?:db|sqlite)$/.test(entry.name)) continue;
1894
+ const db = new DatabaseSync9(file);
1895
+ try {
1896
+ if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='e7_replication_control'").get()) continue;
1897
+ db.exec("BEGIN IMMEDIATE");
1898
+ try {
1899
+ for (const row of db.prepare("SELECT name FROM sqlite_master WHERE type='trigger' AND name GLOB 'writer_guard_replication_*'").all()) db.exec('DROP TRIGGER "' + String(row.name).replaceAll('"', '""') + '"');
1900
+ db.exec("DROP TABLE e7_replication_outbox;DROP TABLE e7_replication_inbox;DROP TABLE e7_replication_control;COMMIT");
1901
+ } catch (error) {
1902
+ db.exec("ROLLBACK");
1903
+ throw error;
1904
+ }
1905
+ } finally {
1906
+ db.close();
1907
+ }
1908
+ }
1909
+ }
1910
+ async function createOrdinaryLocalRecovery(options) {
1911
+ const source = resolve4(options.stateDir), destination = resolve4(options.destination);
1912
+ 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");
1913
+ const activation = JSON.parse(readFileSync6(join8(source, ".travel-active.json"), "utf8")), permit = activation.permit, { signature, ...signed } = permit;
1914
+ 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");
1915
+ return withCheckpointLock(source, async () => {
1916
+ if (!options.authority || !options.principal || options.authority.publicKey !== options.publicKey) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
1917
+ const proof = await verifyStoppedLocalExitProof({ ...options, stateDir: source });
1918
+ if (existsSync2(destination)) {
1919
+ if (realpathSync4(destination) !== destination) throw new Error("TRAVEL_EXIT_PATH");
1920
+ let receipt;
1921
+ try {
1922
+ receipt = JSON.parse(readPrivateFile(join8(destination, ".continuity/travel-exit-receipt.json"), 65536).toString());
1923
+ } catch {
1924
+ throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
1925
+ }
1926
+ const { digest, ...body } = receipt, generation = receipt.sourceGeneration;
1927
+ if (receipt.format !== "engine7-ordinary-local-recovery-v2" || digest !== sha3(JSON.stringify(body)) || identity2(receipt.identity) !== identity2(options.identity) || receipt.loaded !== true || receipt.ordinaryStateDir !== destination || receipt.checkpointDigest !== proof.binding.checkpointDigest || receipt.deletionWatermark !== proof.binding.deletionWatermark || receipt.sourceFilesDigest !== proof.filesDigest || receipt.channelReceiptsDigest !== options.dedupeReceipt.digest || !generation || generation.nodeId !== proof.binding.nodeId || generation.bootId !== proof.binding.bootId || generation.authorityBootId !== proof.binding.authorityBootId || generation.epoch !== proof.binding.epoch || receipt.ordinaryFilesDigest !== await localExitFilesDigest(destination, true)) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
1928
+ await proof.check();
1929
+ return receipt;
1930
+ }
1931
+ try {
1932
+ mkdirSync5(destination, { mode: 448 });
1933
+ cpSync(source, destination, { recursive: true, force: false, errorOnExist: true, filter: (path3) => copyLocalExitPath(source, path3) });
1934
+ detachReplication(destination);
1935
+ const store = new PlatformReceiptStore(join8(destination, ".continuity/feishu-receipts.sqlite"), options.platformNamespace);
1936
+ try {
1937
+ store.importTravelReceipt(options.dedupeReceipt);
1938
+ } finally {
1939
+ store.close();
1940
+ }
1941
+ const receipt = {
1942
+ format: "engine7-ordinary-local-recovery-v2",
1943
+ identity: options.identity,
1944
+ loaded: true,
1945
+ checkpointDigest: proof.binding.checkpointDigest,
1946
+ deletionWatermark: proof.binding.deletionWatermark,
1947
+ sourceFilesDigest: proof.filesDigest,
1948
+ ordinaryStateDir: destination,
1949
+ channelReceiptsDigest: options.dedupeReceipt.digest,
1950
+ sourceGeneration: { nodeId: proof.binding.nodeId, bootId: proof.binding.bootId, authorityBootId: proof.binding.authorityBootId, epoch: proof.binding.epoch }
1951
+ };
1952
+ await proof.check();
1953
+ const body = { ...receipt, ordinaryFilesDigest: await localExitFilesDigest(destination, true) };
1954
+ const result = { ...body, digest: sha3(JSON.stringify(body)) };
1955
+ writeFileSync3(join8(destination, ".continuity/travel-exit-receipt.json"), JSON.stringify(result), { mode: 384, flag: "wx", flush: true });
1956
+ return result;
1957
+ } catch (error) {
1958
+ if (existsSync2(destination)) rmSync2(destination, { recursive: true });
1959
+ throw error;
1960
+ }
1961
+ });
1962
+ }
1963
+
1964
+ // src/continuity/retirement-main.ts
1965
+ var command = promisify(execFile);
1966
+ var sha4 = (value) => createHash5("sha256").update(value).digest("hex");
1967
+ var path2 = (value) => {
1968
+ if (typeof value !== "string" || !isAbsolute4(value) || resolve5(value) !== value) throw new Error("TRAVEL_RETIREMENT_PATH");
1969
+ return value;
1970
+ };
1971
+ async function runTravelRetirementCli(args) {
1972
+ if (!args.length || args.length === 1 && args[0] === "--help") return { usage: "travel-retire run|recover-local --config /absolute/private-config.json" };
1973
+ if (args.length !== 3 || !["run", "recover-local"].includes(args[0]) || args[1] !== "--config") throw new Error("TRAVEL_RETIREMENT_INVALID_COMMAND");
1974
+ const config = JSON.parse(readPrivateFile(path2(args[2]), 4 * 1024 * 1024).toString());
1975
+ if (args[0] === "recover-local") {
1976
+ 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) });
1977
+ try {
1978
+ const { principal, publicKey } = await client2.retirementStatus();
1979
+ if (publicKey !== config.publicKey) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
1980
+ return await createOrdinaryLocalRecovery({ ...config, principal, authority: { publicKey: config.publicKey, status: async () => {
1981
+ const current = await client2.retirementStatus();
1982
+ if (JSON.stringify(current.principal) !== JSON.stringify(principal) || current.publicKey !== publicKey || !current.source || current.source.checkpointDigest !== current.checkpointDigest || current.source.deletionWatermark !== current.deletionWatermark) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
1983
+ return current.source;
1984
+ } }, dedupeReceipt: JSON.parse(readPrivateFile(path2(config.dedupeReceiptFile), 32 * 1024 * 1024).toString()) });
1985
+ } finally {
1986
+ client2.close();
1987
+ }
1988
+ }
1989
+ 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");
1990
+ if (!config.stopServices.length && config.nodesAlreadyStopped !== true) throw new Error("TRAVEL_RETIREMENT_STOP_REQUIRED");
1991
+ 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) });
1992
+ let job, keys;
1993
+ try {
1994
+ const control = await client.retirementStatus();
1995
+ if (JSON.stringify(control.identity) !== JSON.stringify(config.identity)) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
1996
+ if (config.keyIdentity?.tenantId !== config.identity.tenantId || config.keyIdentity.companionId !== config.identity.companionId || config.keyIdentity.seatId !== config.identity.seatId) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
1997
+ keys = new KeyServiceStore(path2(config.keyStoreDirectory));
1998
+ keys.assertIdentity(config.keyIdentity);
1999
+ const verifyLocalRecovery = async () => {
2000
+ const current = await client.retirementStatus(), source = current.source;
2001
+ if (current.retired !== true || current.jobId !== config.jobId || !source || current.publicKey !== control.publicKey || JSON.stringify(current.identity) !== JSON.stringify(control.identity) || JSON.stringify(current.principal) !== JSON.stringify(control.principal) || source.checkpointDigest !== current.checkpointDigest || source.deletionWatermark !== current.deletionWatermark) throw new Error("TRAVEL_RETIREMENT_RECOVERY_REQUIRED");
2002
+ if (!existsSync3(path2(config.localRecoveryReceiptFile))) return null;
2003
+ const receipt = JSON.parse(readPrivateFile(config.localRecoveryReceiptFile, 65536).toString()), { digest, ...body } = receipt;
2004
+ const generation = receipt.sourceGeneration;
2005
+ if (receipt.format !== "engine7-ordinary-local-recovery-v2" || sha4(JSON.stringify(body)) !== digest || receipt.checkpointDigest !== current.checkpointDigest || JSON.stringify(receipt.identity) !== JSON.stringify(current.identity) || receipt.deletionWatermark !== current.deletionWatermark || !generation || generation.nodeId !== source.activeNodeId || generation.bootId !== source.activeBootId || generation.authorityBootId !== source.authorityBootId || generation.epoch !== source.epoch || typeof generation.nodeId !== "string" || typeof generation.bootId !== "string" || typeof generation.authorityBootId !== "string" || !Number.isSafeInteger(generation.epoch) || receipt.loaded !== true || ![receipt.channelReceiptsDigest, receipt.sourceFilesDigest].every((value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value))) throw new Error("TRAVEL_RETIREMENT_RECOVERY_REQUIRED");
2006
+ return receipt;
2007
+ };
2008
+ job = new TravelRetirement({
2009
+ directory: path2(config.directory),
2010
+ identity: config.identity,
2011
+ jobId: config.jobId,
2012
+ retire: () => client.retire(config.jobId),
2013
+ stopNodes: async () => {
2014
+ if (config.stopServices.length) await command("systemctl", ["stop", ...config.stopServices]);
2015
+ },
2016
+ verifyLocalRecovery,
2017
+ resources: config.resources.map((resource) => new LocalSeatResource(path2(resource.directory), config.identity)),
2018
+ revokeKey: async () => {
2019
+ keys.revoke(config.keyIdentity);
2020
+ return { revoked: true };
2021
+ },
2022
+ accountOwnerRequestedKeyDestruction: config.accountOwnerRequestedKeyDestruction === true,
2023
+ destroyKey: async () => keys.destroy(config.keyIdentity)
2024
+ });
2025
+ return await job.run();
2026
+ } finally {
2027
+ job?.close();
2028
+ keys?.close();
2029
+ client.close();
2030
+ }
2031
+ }
2032
+ if (process.argv[1] && /[\\/](retirement-main\.ts|travel-retire\.mjs)$/.test(fileURLToPath2(import.meta.url)) && resolve5(process.argv[1]) === fileURLToPath2(import.meta.url)) {
2033
+ runTravelRetirementCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch(() => {
2034
+ process.stderr.write("TRAVEL_RETIREMENT_REFUSED\n");
2035
+ process.exitCode = 1;
2036
+ });
2037
+ }
2038
+
2039
+ // src/continuity/console-retirement.ts
2040
+ var hash3 = (value) => createHash6("sha256").update(value).digest("hex");
2041
+ var sameIdentity = (a, b) => a && ["tenantId", "companionId", "seatId"].every((key) => a[key] === b[key]);
2042
+ var sourceBinding = (source) => source ? ["activeNodeId", "activeBootId", "authorityBootId", "epoch", "checkpointDigest", "deletionWatermark"].map((key) => source[key]) : null;
2043
+ function createTravelConsoleRetirement(options) {
2044
+ if (!isAbsolute5(options.configFile) || resolve6(options.configFile) !== options.configFile || realpathSync5(options.configFile) !== options.configFile) throw new Error("TRAVEL_CONSOLE_CONFIG");
2045
+ const config = JSON.parse(readPrivateFile(options.configFile, 4 * 1024 * 1024).toString()), original = readFileSync8(options.configFile);
2046
+ 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");
2047
+ const assertConfig = () => {
2048
+ if (!readFileSync8(options.configFile).equals(original)) throw new Error("TRAVEL_CONSOLE_CONFIG_CHANGED");
2049
+ };
2050
+ preparePrivateDirectory(config.directory);
2051
+ const pendingFile = join9(config.directory, "console-recovery.json");
2052
+ const pending = () => {
2053
+ if (!existsSync4(pendingFile)) return void 0;
2054
+ const value = JSON.parse(readPrivateFile(pendingFile, 65536).toString());
2055
+ if (!sameIdentity(value.identity, options.identity) || value.jobId !== config.jobId || !["RECOVERY_PENDING", "LOCAL_STOPPED"].includes(value.state)) throw new Error("TRAVEL_CONSOLE_CONFIG");
2056
+ return value;
2057
+ };
2058
+ const savePending = (state, source) => {
2059
+ const temp = pendingFile + "." + randomUUID4();
2060
+ try {
2061
+ writeFileSync4(temp, JSON.stringify({ identity: options.identity, jobId: config.jobId, state, source: sourceBinding(source) }), { mode: 384, flag: "wx", flush: true });
2062
+ renameSync(temp, pendingFile);
2063
+ } finally {
2064
+ if (existsSync4(temp)) unlinkSync3(temp);
2065
+ }
2066
+ };
2067
+ const verify3 = async (value) => {
2068
+ const receipt2 = value, current = await options.current(), source = current.source;
2069
+ if (!sameIdentity(current.identity, options.identity) || !source || !receipt2 || receipt2.format !== "engine7-ordinary-local-recovery-v2") throw new Error("TRAVEL_CONSOLE_RECOVERY_REQUIRED");
2070
+ const { digest, ...body } = receipt2, generation = receipt2.sourceGeneration;
2071
+ 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");
2072
+ return receipt2;
2073
+ };
2074
+ const receipt = () => existsSync4(config.localRecoveryReceiptFile) ? JSON.parse(readPrivateFile(config.localRecoveryReceiptFile, 65536).toString()) : void 0;
2075
+ return {
2076
+ async status() {
2077
+ assertConfig();
2078
+ let recovery = "required";
2079
+ try {
2080
+ if (await verify3(receipt())) recovery = "ready";
2081
+ } catch {
2082
+ }
2083
+ const file = join9(config.directory, "retirement.sqlite");
2084
+ if (!existsSync4(file)) {
2085
+ const prepared = pending();
2086
+ return existsSync4(config.localRecoveryReceiptFile) || prepared ? { jobId: config.jobId, state: recovery === "ready" ? "LOCAL_READY" : prepared?.state ?? "RECOVERY_REQUIRED", recovery } : void 0;
2087
+ }
2088
+ const db = new DatabaseSync10(file, { readOnly: true });
2089
+ try {
2090
+ const row = db.prepare("SELECT id,state,stopped FROM job").get();
2091
+ if (!row || row.id !== config.jobId) throw new Error("TRAVEL_CONSOLE_CONFIG");
2092
+ return { jobId: String(row.id), state: String(row.state), recovery, nodesStopped: row.stopped === 1 };
2093
+ } finally {
2094
+ db.close();
2095
+ }
2096
+ },
2097
+ async recover(value) {
2098
+ assertConfig();
2099
+ if (value === void 0) {
2100
+ const prepared = pending(), current = await options.current();
2101
+ if (prepared?.state === "LOCAL_STOPPED") {
2102
+ if (JSON.stringify(prepared.source) !== JSON.stringify(sourceBinding(current.source))) throw new Error("TRAVEL_CONSOLE_RECOVERY_REQUIRED");
2103
+ return;
2104
+ }
2105
+ savePending("RECOVERY_PENDING");
2106
+ if (!(await this.status())?.nodesStopped) await options.stopLocal();
2107
+ const stopped = await options.current();
2108
+ if (!stopped.source) throw new Error("TRAVEL_CONSOLE_RECOVERY_REQUIRED");
2109
+ savePending("LOCAL_STOPPED", stopped.source);
2110
+ return;
2111
+ }
2112
+ const proof = await verify3(value), file = config.localRecoveryReceiptFile, temp = file + "." + randomUUID4();
2113
+ try {
2114
+ writeFileSync4(temp, JSON.stringify(proof), { mode: 384, flag: "wx", flush: true });
2115
+ await verify3(proof);
2116
+ renameSync(temp, file);
2117
+ } finally {
2118
+ if (existsSync4(temp)) {
2119
+ const { unlinkSync: unlinkSync4 } = await import("node:fs");
2120
+ unlinkSync4(temp);
2121
+ }
2122
+ }
2123
+ },
2124
+ async finish() {
2125
+ assertConfig();
2126
+ await runTravelRetirementCli(["run", "--config", options.configFile]);
2127
+ }
2128
+ };
2129
+ }
2130
+
2131
+ // src/continuity/console-main.ts
2132
+ var privatePath = (value) => {
2133
+ if (typeof value !== "string" || !isAbsolute6(value) || resolve7(value) !== value) throw new Error("TRAVEL_CONSOLE_CONFIG");
2134
+ return value;
2135
+ };
2136
+ function openTravelConsole(input) {
2137
+ if (!input || !input.identity || !input.tls || !Number.isSafeInteger(input.port) || input.port < 0 || input.port > 65535 || typeof input.host !== "string") throw new Error("TRAVEL_CONSOLE_CONFIG");
2138
+ const config = JSON.parse(readPrivateFile(privatePath(input.controllerConfigFile), 65536).toString()), service = openTravelController(config);
2139
+ try {
2140
+ const identity3 = input.identity;
2141
+ const local = Object.values(service.nodes).find((node) => node.principal.role === "LOCAL");
2142
+ const retirement = input.retirementConfigFile ? createTravelConsoleRetirement({
2143
+ configFile: privatePath(input.retirementConfigFile),
2144
+ identity: identity3,
2145
+ current: () => service.authority.retirementStatus(local.principal),
2146
+ stopLocal: async () => {
2147
+ await local.stop();
2148
+ }
2149
+ }) : void 0;
2150
+ const manager = new TravelConsoleManager({ directory: privatePath(input.directory), identity: identity3, controller: service.controller, nodes: service.nodes, authority: service.authority, labels: input.labels, retirement });
2151
+ const server = createTravelConsoleServer({
2152
+ manager,
2153
+ identity: identity3,
2154
+ token: readPrivateFile(privatePath(input.tokenFile), 1024).toString().trim(),
2155
+ cert: readFileSync9(privatePath(input.tls.certFile)),
2156
+ key: readPrivateFile(privatePath(input.tls.keyFile), 65536)
2157
+ });
2158
+ let closing;
2159
+ const close = () => closing ??= (async () => {
2160
+ await closeTravelConsoleServer(server);
2161
+ await service.close();
2162
+ manager.close();
2163
+ })();
2164
+ return { manager, server, controller: service.controller, close };
2165
+ } catch (error) {
2166
+ void service.close();
2167
+ throw error;
2168
+ }
2169
+ }
2170
+ async function runTravelConsoleCli(args) {
2171
+ if (args.length === 1 && args[0] === "--help") return { usage: "travel-console serve --config /absolute/private-config.json" };
2172
+ if (args.length !== 3 || args[0] !== "serve" || args[1] !== "--config") throw new Error("TRAVEL_CONSOLE_COMMAND");
2173
+ const config = JSON.parse(readPrivateFile(privatePath(args[2]), 65536).toString()), service = openTravelConsole(config);
2174
+ try {
2175
+ await new Promise((resolve8, reject) => {
2176
+ service.server.once("error", reject);
2177
+ service.server.listen(config.port, config.host, resolve8);
2178
+ });
2179
+ const retiring = await service.manager.snapshot();
2180
+ if (!retiring.retirement) service.controller.start();
2181
+ let closing = false;
2182
+ const stop = () => {
2183
+ if (closing) return;
2184
+ closing = true;
2185
+ void service.close().then(() => process.exit(0), () => process.exit(1));
2186
+ };
2187
+ process.once("SIGTERM", stop);
2188
+ process.once("SIGINT", stop);
2189
+ return { listening: true, port: service.server.address().port };
2190
+ } catch (error) {
2191
+ await service.close();
2192
+ throw error;
2193
+ }
2194
+ }
2195
+ 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(() => {
2196
+ process.stderr.write("TRAVEL_CONSOLE_REFUSED\n");
2197
+ process.exitCode = 1;
2198
+ });
2199
+ export {
2200
+ TravelConsoleManager,
2201
+ createTravelConsoleRetirement,
2202
+ createTravelConsoleServer,
2203
+ openTravelConsole,
2204
+ runTravelConsoleCli
2205
+ };