engine7 7.1.142 → 7.1.144
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.
- package/dist/bg-worker.mjs +90 -15
- package/dist/cc-desktop.mjs +9 -0
- package/dist/cli.mjs +2045 -825
- package/dist/engine-startup.mjs +1049 -578
- package/dist/main.mjs +1049 -578
- package/dist/recall-worker.mjs +89 -15
- package/dist/topics-worker.mjs +166 -48
- package/dist/travel-gateway.mjs +186 -65
- package/dist/travel-host.mjs +600 -460
- package/dist/travel-node.mjs +29 -0
- package/dist/travel-oss-pull.mjs +389 -0
- package/dist/travel-oss-return.mjs +563 -0
- package/dist/travel-pairing.mjs +206 -85
- package/dist/web-console.mjs +448 -265
- package/package.json +1 -1
package/dist/travel-host.mjs
CHANGED
|
@@ -1230,6 +1230,8 @@ var init_features = __esm({
|
|
|
1230
1230
|
installer: true,
|
|
1231
1231
|
agentTeams: true,
|
|
1232
1232
|
autoDream: true,
|
|
1233
|
+
/** 1122:cc_ask/cc_progress 默认开(存量配置 loader 就地补全);边缘功能,垫底 */
|
|
1234
|
+
"cc-driver": true,
|
|
1233
1235
|
processOutput: "verbose",
|
|
1234
1236
|
interrupt: "command",
|
|
1235
1237
|
/** 1105:主 query 运行中用户消息的处理——'steer'(默认,注入当前 query)| 'queue'(旧行为,排队) */
|
|
@@ -3212,15 +3214,15 @@ var init_context_time = __esm({
|
|
|
3212
3214
|
});
|
|
3213
3215
|
|
|
3214
3216
|
// src/mem7/core/state/knowledge-history.ts
|
|
3215
|
-
function knowledgeCutoff(db2, scope,
|
|
3216
|
-
if (
|
|
3217
|
-
if (
|
|
3217
|
+
function knowledgeCutoff(db2, scope, request9) {
|
|
3218
|
+
if (request9.knownAt === void 0 && request9.knownAtRevision === void 0) return void 0;
|
|
3219
|
+
if (request9.knownAt !== void 0 && request9.knownAtRevision !== void 0) throw new Error("AMBIGUOUS_KNOWLEDGE_TIME");
|
|
3218
3220
|
const id2 = scopeId(scope);
|
|
3219
|
-
const time =
|
|
3220
|
-
const checkpoint =
|
|
3221
|
+
const time = request9.knownAt === void 0 ? null : instant(request9.knownAt);
|
|
3222
|
+
const checkpoint = request9.knownAtRevision === void 0 ? void 0 : db2.prepare("SELECT history_id FROM memory_knowledge_checkpoints WHERE scope_id=? AND fact_revision=?").get(id2, request9.knownAtRevision);
|
|
3221
3223
|
const historyId = time ? Number(db2.prepare("SELECT COALESCE(MAX(history_id),0) history_id FROM memory_knowledge_history WHERE scope_id=? AND recorded_at<=?").get(id2, time).history_id) : Number(checkpoint?.history_id ?? 0);
|
|
3222
3224
|
const baseline = db2.prepare("SELECT history_id FROM memory_knowledge_history WHERE scope_id=? AND target_kind='coverage' ORDER BY history_id LIMIT 1").get(id2);
|
|
3223
|
-
return { historyId, time, complete: (!baseline || historyId >= baseline.history_id) && (
|
|
3225
|
+
return { historyId, time, complete: (!baseline || historyId >= baseline.history_id) && (request9.knownAtRevision === void 0 || request9.knownAtRevision === 0 || Boolean(checkpoint)) };
|
|
3224
3226
|
}
|
|
3225
3227
|
function journalEntityCutoff(db2, scope, revision) {
|
|
3226
3228
|
const row = db2.prepare("SELECT history_id FROM memory_entity_checkpoints WHERE scope_id=? AND entity_revision<=? ORDER BY entity_revision DESC LIMIT 1").get(scopeId(scope), revision);
|
|
@@ -7471,13 +7473,13 @@ CREATE TABLE memory_relationship_receipts (
|
|
|
7471
7473
|
JOIN memory_relationship_versions r ON r.scope_id=h.scope_id AND r.relationship_id=h.relationship_id AND r.semantic_version=h.semantic_version
|
|
7472
7474
|
JOIN fact_assertions a ON a.scope_id=r.scope_id AND a.assertion_id=r.assertion_id
|
|
7473
7475
|
WHERE h.scope_id=? AND h.perspective_entity_id=? AND h.subject_id=? AND h.object_id=?`);
|
|
7474
|
-
for (const
|
|
7475
|
-
const endpoints = [[
|
|
7476
|
-
if (
|
|
7476
|
+
for (const request9 of requests) {
|
|
7477
|
+
const endpoints = [[request9.subjectId, request9.objectId]];
|
|
7478
|
+
if (request9.direction === "symmetric") endpoints.push([request9.objectId, request9.subjectId]);
|
|
7477
7479
|
for (const [subject, object4] of endpoints) {
|
|
7478
|
-
for (const row of query.all(scopeId(scope),
|
|
7480
|
+
for (const row of query.all(scopeId(scope), request9.perspectiveEntityId, subject, object4)) {
|
|
7479
7481
|
const value2 = JSON.parse(row.value_json);
|
|
7480
|
-
if (value2.contentKind ===
|
|
7482
|
+
if (value2.contentKind === request9.contentKind && value2.temporalScope === request9.temporalScope) ids.add(row.relationship_id);
|
|
7481
7483
|
}
|
|
7482
7484
|
}
|
|
7483
7485
|
}
|
|
@@ -10511,8 +10513,8 @@ CREATE TABLE IF NOT EXISTS cluster_members (
|
|
|
10511
10513
|
socialInterpretations;
|
|
10512
10514
|
relationshipCognition;
|
|
10513
10515
|
relationshipNotices;
|
|
10514
|
-
knowledgeCutoff(scope,
|
|
10515
|
-
return knowledgeCutoff(this.db, scope,
|
|
10516
|
+
knowledgeCutoff(scope, request9) {
|
|
10517
|
+
return knowledgeCutoff(this.db, scope, request9);
|
|
10516
10518
|
}
|
|
10517
10519
|
knowledgeSnapshot(scope, cutoff) {
|
|
10518
10520
|
return historicalRows(this.db, scope, "scope", cutoff)[0] ?? { entityRevision: 0, factRevision: 0, contextRevision: 0, sourceSeq: 0, interpretedSeq: 0 };
|
|
@@ -10745,6 +10747,35 @@ CREATE TABLE IF NOT EXISTS cluster_members (
|
|
|
10745
10747
|
};
|
|
10746
10748
|
}, scope, version);
|
|
10747
10749
|
}
|
|
10750
|
+
/** 1123 跨轮去重(md):entry id 由正文决定、所在文件由日期决定——日期判定跨轮漂移时新块落到
|
|
10751
|
+
* 另一个日期文件,appendMd 的原位替换只扫目标文件,旧块留成孤儿(妹妹 1122 重洗 44 处双份)。
|
|
10752
|
+
* 单遍扫 episodes:id 在本轮写入表里、但所在文件 ≠ 本轮目标日期的块删掉,entry_count 同步。
|
|
10753
|
+
* 不在本轮写入表里的条目不碰(别的来源/原生记忆)。 */
|
|
10754
|
+
purgeEpisodeEntries(ownerId, targetDateById) {
|
|
10755
|
+
if (!targetDateById.size) return 0;
|
|
10756
|
+
const dir = join16(this.root, "users", ownerId, "episodes");
|
|
10757
|
+
if (!existsSync6(dir)) return 0;
|
|
10758
|
+
let removed = 0;
|
|
10759
|
+
for (const name of readdirSync2(dir)) {
|
|
10760
|
+
const fileDate = /^episode-(\d{4}-\d{2}-\d{2})\.md$/.exec(name)?.[1];
|
|
10761
|
+
if (!fileDate) continue;
|
|
10762
|
+
const file2 = join16(dir, name);
|
|
10763
|
+
let text2 = readFileSync10(file2, "utf8"), hit = false;
|
|
10764
|
+
for (const m of text2.matchAll(/<!-- entry:(\S+) -->/g)) {
|
|
10765
|
+
const target = targetDateById.get(m[1]);
|
|
10766
|
+
if (target === void 0 || target === fileDate) continue;
|
|
10767
|
+
text2 = text2.replace(new RegExp(`\\n*<!-- entry:${m[1]} -->[\\s\\S]*?<!-- /entry:${m[1]} -->`), "");
|
|
10768
|
+
removed++;
|
|
10769
|
+
hit = true;
|
|
10770
|
+
}
|
|
10771
|
+
if (!hit) continue;
|
|
10772
|
+
text2 = text2.replace(/entry_count: \d+/, `entry_count: ${(text2.match(/<!-- entry:/g) ?? []).length}`);
|
|
10773
|
+
const tmp = `${file2}.${process.pid}.tmp`;
|
|
10774
|
+
writeFileSync8(tmp, text2);
|
|
10775
|
+
renameSync3(tmp, file2);
|
|
10776
|
+
}
|
|
10777
|
+
return removed;
|
|
10778
|
+
}
|
|
10748
10779
|
appendAtomicFacts(ownerId, dateStr, entries, scope, version) {
|
|
10749
10780
|
const flat = [];
|
|
10750
10781
|
for (const e of entries) {
|
|
@@ -13202,8 +13233,11 @@ var init_capacity_fuse = __esm({
|
|
|
13202
13233
|
function hasImage(m) {
|
|
13203
13234
|
return "role" in m && Array.isArray(m.content) && m.content.some((b) => b.type === "image_ref" || b.type === "image");
|
|
13204
13235
|
}
|
|
13236
|
+
function hasMedia(m) {
|
|
13237
|
+
return hasImage(m) || "role" in m && Array.isArray(m.content) && m.content.some((b) => b.type === "video");
|
|
13238
|
+
}
|
|
13205
13239
|
function unobservedImageIndex(messages) {
|
|
13206
|
-
return messages.findIndex((m) =>
|
|
13240
|
+
return messages.findIndex((m) => hasMedia(m) && !("role" in m && m.imageInput?.observed === true));
|
|
13207
13241
|
}
|
|
13208
13242
|
function splitProtectedImages(messages, budget) {
|
|
13209
13243
|
const index = unobservedImageIndex(messages);
|
|
@@ -14738,6 +14772,52 @@ var init_project_sessions = __esm({
|
|
|
14738
14772
|
}
|
|
14739
14773
|
});
|
|
14740
14774
|
|
|
14775
|
+
// src/cc-driver/long-http.ts
|
|
14776
|
+
import { request } from "node:http";
|
|
14777
|
+
function longPostJson(url, body, headers = {}, signal) {
|
|
14778
|
+
const data = Buffer.from(JSON.stringify(body));
|
|
14779
|
+
return new Promise((resolve47, reject) => {
|
|
14780
|
+
const req = request(url, { method: "POST", headers: { ...headers, "Content-Length": String(data.byteLength) } }, (res) => {
|
|
14781
|
+
const chunks = [];
|
|
14782
|
+
res.on("data", (chunk) => chunks.push(chunk));
|
|
14783
|
+
res.on("error", reject);
|
|
14784
|
+
res.on("end", () => {
|
|
14785
|
+
cleanup();
|
|
14786
|
+
const text2 = Buffer.concat(chunks).toString("utf8");
|
|
14787
|
+
try {
|
|
14788
|
+
resolve47({ status: res.statusCode ?? 0, json: JSON.parse(text2) });
|
|
14789
|
+
} catch {
|
|
14790
|
+
reject(new Error(`\u5BF9\u7AEF\u8FD4\u56DE\u4E86\u975E JSON\uFF08HTTP ${res.statusCode}\uFF09\uFF1A${text2.slice(0, 200)}`));
|
|
14791
|
+
}
|
|
14792
|
+
});
|
|
14793
|
+
});
|
|
14794
|
+
req.on("error", (err) => {
|
|
14795
|
+
cleanup();
|
|
14796
|
+
reject(err);
|
|
14797
|
+
});
|
|
14798
|
+
const onAbort = () => {
|
|
14799
|
+
req.destroy();
|
|
14800
|
+
reject(signal.reason instanceof Error ? signal.reason : new Error("\u8BF7\u6C42\u5DF2\u53D6\u6D88"));
|
|
14801
|
+
};
|
|
14802
|
+
const cleanup = () => {
|
|
14803
|
+
signal?.removeEventListener("abort", onAbort);
|
|
14804
|
+
};
|
|
14805
|
+
if (signal) {
|
|
14806
|
+
if (signal.aborted) {
|
|
14807
|
+
onAbort();
|
|
14808
|
+
return;
|
|
14809
|
+
}
|
|
14810
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
14811
|
+
}
|
|
14812
|
+
req.end(data);
|
|
14813
|
+
});
|
|
14814
|
+
}
|
|
14815
|
+
var init_long_http = __esm({
|
|
14816
|
+
"src/cc-driver/long-http.ts"() {
|
|
14817
|
+
"use strict";
|
|
14818
|
+
}
|
|
14819
|
+
});
|
|
14820
|
+
|
|
14741
14821
|
// src/cc-driver/desktop.ts
|
|
14742
14822
|
import fs9 from "node:fs";
|
|
14743
14823
|
import os2 from "node:os";
|
|
@@ -14789,14 +14869,13 @@ async function findDesktopTargets(workDir, sessionId) {
|
|
|
14789
14869
|
return targets;
|
|
14790
14870
|
}
|
|
14791
14871
|
async function askDesktop(target, prompt, source, signal) {
|
|
14792
|
-
const
|
|
14793
|
-
|
|
14794
|
-
|
|
14795
|
-
|
|
14796
|
-
|
|
14797
|
-
|
|
14798
|
-
|
|
14799
|
-
if (!response.ok) throw failure(result.error || `Desktop CC HTTP ${response.status}`, response.status);
|
|
14872
|
+
const { status, json: result } = await longPostJson(
|
|
14873
|
+
`http://127.0.0.1:${target.port}/ask`,
|
|
14874
|
+
{ prompt, source, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
|
|
14875
|
+
{ authorization: `Bearer ${target.token}` },
|
|
14876
|
+
signal
|
|
14877
|
+
);
|
|
14878
|
+
if (status !== 200) throw failure(result?.error || `Desktop CC HTTP ${status}`, status);
|
|
14800
14879
|
if (result.sessionId !== target.sessionId || typeof result.text !== "string" || typeof result.isError !== "boolean") {
|
|
14801
14880
|
throw failure("Desktop CC returned an invalid result");
|
|
14802
14881
|
}
|
|
@@ -14806,6 +14885,7 @@ var registryDir, canonical3, failure, alive;
|
|
|
14806
14885
|
var init_desktop = __esm({
|
|
14807
14886
|
"src/cc-driver/desktop.ts"() {
|
|
14808
14887
|
"use strict";
|
|
14888
|
+
init_long_http();
|
|
14809
14889
|
registryDir = () => process.env.CC_DESKTOP_REGISTRY_DIR || path11.join(os2.homedir(), ".engine7", "cc-driver", "desktops");
|
|
14810
14890
|
canonical3 = (dir) => {
|
|
14811
14891
|
try {
|
|
@@ -16437,6 +16517,8 @@ var init_dep_downloader = __esm({
|
|
|
16437
16517
|
});
|
|
16438
16518
|
|
|
16439
16519
|
// src/cc-driver/driver.ts
|
|
16520
|
+
import { mkdirSync as mkdirSync16, writeFileSync as writeFileSync17 } from "node:fs";
|
|
16521
|
+
import { extname as extname2, join as join28 } from "node:path";
|
|
16440
16522
|
function requestError(message, status = 409) {
|
|
16441
16523
|
return Object.assign(new Error(message), { status });
|
|
16442
16524
|
}
|
|
@@ -17046,14 +17128,16 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
|
|
|
17046
17128
|
return task;
|
|
17047
17129
|
}
|
|
17048
17130
|
};
|
|
17049
|
-
CcDriverHub = class {
|
|
17131
|
+
CcDriverHub = class _CcDriverHub {
|
|
17050
17132
|
map;
|
|
17051
17133
|
sessions = /* @__PURE__ */ new Map();
|
|
17052
17134
|
cfg;
|
|
17053
17135
|
cm;
|
|
17136
|
+
stateDir;
|
|
17054
17137
|
constructor(cfg, cm, stateDir, predecessor) {
|
|
17055
17138
|
this.cfg = cfg;
|
|
17056
17139
|
this.cm = cm;
|
|
17140
|
+
this.stateDir = stateDir;
|
|
17057
17141
|
this.map = new CcSessionMapStore(stateDir);
|
|
17058
17142
|
for (const b of cfg.bindings) {
|
|
17059
17143
|
this.sessions.set(bindingKey(b), new CcDriverSession(b, cm, this.map, predecessor));
|
|
@@ -17063,15 +17147,49 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
|
|
|
17063
17147
|
matches(inbound) {
|
|
17064
17148
|
return findBinding(inbound, this.cfg) !== null;
|
|
17065
17149
|
}
|
|
17066
|
-
/**
|
|
17150
|
+
/** 落盘附件的体积上限:这条通道只收图/文档,不让大视频把 stateDir 撑爆 */
|
|
17151
|
+
static MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;
|
|
17152
|
+
/**
|
|
17153
|
+
* 入站附件落盘(1123 翀哥:「我给你发图片你现在收不到」):CC 会话靠工具读文件——
|
|
17154
|
+
* 图片用 Read 工具直接看,文档走对应 skill。只做落盘+正文附路径,不改 CC 的输入协议。
|
|
17155
|
+
* 落在 <stateDir>/media/inbound(与 my-eyes 等同目录惯例);单个附件失败不影响其它附件和正文。
|
|
17156
|
+
*/
|
|
17157
|
+
async saveAttachments(inbound) {
|
|
17158
|
+
const lines = [];
|
|
17159
|
+
const dir = join28(this.stateDir, "media", "inbound");
|
|
17160
|
+
for (const [i, a] of (inbound.attachments ?? []).entries()) {
|
|
17161
|
+
const label = a.filename || `\u9644\u4EF6${i + 1}`;
|
|
17162
|
+
try {
|
|
17163
|
+
if (!a.loadBytes) throw new Error("\u9002\u914D\u5668\u672A\u63D0\u4F9B\u4E0B\u8F7D\u80FD\u529B");
|
|
17164
|
+
if (a.size > _CcDriverHub.MAX_ATTACHMENT_BYTES) throw new Error(`\u6587\u4EF6\u8FC7\u5927\uFF08${a.size} \u5B57\u8282\uFF09\uFF0C\u672A\u843D\u76D8`);
|
|
17165
|
+
const bytes = await a.loadBytes();
|
|
17166
|
+
const ext = extname2(a.filename || "").toLowerCase().replace(/[^.a-z0-9]/g, "") || (a.contentType.startsWith("image/") ? "." + a.contentType.slice(6).replace("jpeg", "jpg") : "");
|
|
17167
|
+
const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
|
|
17168
|
+
const tail = (inbound.messageId || "msg").replace(/\W/g, "").slice(-8);
|
|
17169
|
+
const file2 = join28(dir, `${stamp2}-${tail}-${i + 1}${ext}`);
|
|
17170
|
+
mkdirSync16(dir, { recursive: true });
|
|
17171
|
+
writeFileSync17(file2, bytes);
|
|
17172
|
+
const how = a.contentType.startsWith("image/") ? "\u56FE\u7247\u2014\u2014\u7528 Read \u5DE5\u5177\u6253\u5F00\u8FD9\u4E2A\u8DEF\u5F84\u5373\u53EF\u770B\u5230" : `\u6587\u4EF6\uFF08${a.contentType || "\u672A\u77E5\u7C7B\u578B"}\uFF09`;
|
|
17173
|
+
lines.push(`${i + 1}. ${label}\uFF0C${how}\uFF1A${file2}`);
|
|
17174
|
+
} catch (err) {
|
|
17175
|
+
lines.push(`${i + 1}. ${label} \u843D\u76D8\u5931\u8D25\uFF1A${err?.message || String(err)}`);
|
|
17176
|
+
}
|
|
17177
|
+
}
|
|
17178
|
+
return `\uFF08\u6536\u5230 ${lines.length} \u4E2A\u9644\u4EF6\uFF0C\u5DF2\u4FDD\u5B58\u5230\u672C\u673A\uFF1A
|
|
17179
|
+
${lines.join("\n")}\uFF09`;
|
|
17180
|
+
}
|
|
17181
|
+
/** 路由一条命中消息(调用方已 matches 过)。附件先落盘,路径随正文一起进会话(1123)。 */
|
|
17067
17182
|
route(inbound) {
|
|
17068
17183
|
const binding = findBinding(inbound, this.cfg);
|
|
17069
17184
|
if (!binding) return;
|
|
17070
17185
|
const session = this.sessions.get(bindingKey(binding));
|
|
17071
17186
|
if (!session) return;
|
|
17072
17187
|
if (inbound.attachments?.length) {
|
|
17073
|
-
void session.enqueue(`${inbound.content}
|
|
17074
|
-
|
|
17188
|
+
void this.saveAttachments(inbound).then((note) => session.enqueue(inbound.content.trim() ? `${inbound.content}
|
|
17189
|
+
|
|
17190
|
+
${note}` : note)).catch((err) => session.enqueue(`${inbound.content}
|
|
17191
|
+
|
|
17192
|
+
\uFF08\u9644\u4EF6\u5904\u7406\u5931\u8D25\uFF1A${err?.message || String(err)}\uFF09`));
|
|
17075
17193
|
return;
|
|
17076
17194
|
}
|
|
17077
17195
|
session.enqueue(inbound.content);
|
|
@@ -17177,11 +17295,9 @@ async function findBoundCcTargets(workDir, key2) {
|
|
|
17177
17295
|
return lists.flat();
|
|
17178
17296
|
}
|
|
17179
17297
|
async function askBoundCc(target, prompt, source, signal) {
|
|
17180
|
-
const
|
|
17181
|
-
|
|
17182
|
-
|
|
17183
|
-
signal,
|
|
17184
|
-
body: JSON.stringify({
|
|
17298
|
+
const { status, json: result } = await longPostJson(
|
|
17299
|
+
`http://127.0.0.1:${target.endpoint.port}/api/cc-driver/ask`,
|
|
17300
|
+
{
|
|
17185
17301
|
key: target.key,
|
|
17186
17302
|
workDir: target.workDir,
|
|
17187
17303
|
prompt,
|
|
@@ -17189,16 +17305,28 @@ async function askBoundCc(target, prompt, source, signal) {
|
|
|
17189
17305
|
expectedSessionId: target.sessionId,
|
|
17190
17306
|
expectedPid: target.endpoint.pid,
|
|
17191
17307
|
expectedStateDir: target.endpoint.stateDir
|
|
17192
|
-
}
|
|
17193
|
-
|
|
17194
|
-
|
|
17195
|
-
|
|
17308
|
+
},
|
|
17309
|
+
{ "x-engine-console": "1" },
|
|
17310
|
+
signal
|
|
17311
|
+
);
|
|
17312
|
+
if (status !== 200) throw new Error(result?.error || `CC hub handoff failed (HTTP ${status})`);
|
|
17196
17313
|
if (typeof result.text !== "string" || typeof result.isError !== "boolean" || result.sessionId !== null && typeof result.sessionId !== "string") throw new Error("CC hub returned an invalid result");
|
|
17197
17314
|
return result;
|
|
17198
17315
|
}
|
|
17316
|
+
async function stopBoundCc(target) {
|
|
17317
|
+
const { status, json } = await longPostJson(
|
|
17318
|
+
`http://127.0.0.1:${target.endpoint.port}/api/cc-driver/stop`,
|
|
17319
|
+
{ key: target.key, workDir: target.workDir, expectedPid: target.endpoint.pid, expectedStateDir: target.endpoint.stateDir },
|
|
17320
|
+
{ "x-engine-console": "1" },
|
|
17321
|
+
AbortSignal.timeout(5e3)
|
|
17322
|
+
);
|
|
17323
|
+
if (status !== 200) throw new Error(json?.error || `CC hub stop failed (HTTP ${status})`);
|
|
17324
|
+
return json?.stopped === true;
|
|
17325
|
+
}
|
|
17199
17326
|
var init_handoff = __esm({
|
|
17200
17327
|
"src/cc-driver/handoff.ts"() {
|
|
17201
17328
|
"use strict";
|
|
17329
|
+
init_long_http();
|
|
17202
17330
|
init_router();
|
|
17203
17331
|
}
|
|
17204
17332
|
});
|
|
@@ -17665,8 +17793,16 @@ ${[...desktops, ...targets].map((t) => `${t.key} \u2192 ${t.workDir}`).join("\n"
|
|
|
17665
17793
|
return { content: `[CC @ ${path17.basename(target.workDir)}] ${result.text}
|
|
17666
17794
|
\uFF08\u5DF2\u8FDB\u5165 ${target.key} \u7684 CC \u7ED1\u5B9A\u4F1A\u8BDD ${result.sessionId?.slice(0, 8) ?? "new"}\uFF0C\u98DE\u4E66\uFF0F\u5FAE\u4FE1\u540E\u7EED\u5BF9\u8BDD\u5171\u4EAB\u8FD9\u6BB5\u4E0A\u4E0B\u6587\uFF09`, isError: result.isError };
|
|
17667
17795
|
} catch (error) {
|
|
17668
|
-
if (
|
|
17669
|
-
|
|
17796
|
+
if (signal?.aborted) {
|
|
17797
|
+
let stopped = false;
|
|
17798
|
+
try {
|
|
17799
|
+
stopped = await stopBoundCc(target);
|
|
17800
|
+
} catch {
|
|
17801
|
+
stopped = false;
|
|
17802
|
+
}
|
|
17803
|
+
return { content: stopped ? "CC \u7ED1\u5B9A\u8BF7\u6C42\u5DF2\u53D6\u6D88\uFF0C\u5E76\u5DF2\u901A\u77E5 CC \u505C\u6B62\u5F53\u524D\u4EFB\u52A1\u3002" : "CC \u7ED1\u5B9A\u8BF7\u6C42\u5DF2\u53D6\u6D88\uFF08\u505C\u6B62\u901A\u77E5\u672A\u9001\u8FBE\u2014\u2014\u5F53\u524D\u56DE\u5408\u53EF\u80FD\u4ECD\u5728\u7EE7\u7EED\uFF0C\u53EF\u7528 cc_progress \u67E5\u770B\u8FDB\u5C55\uFF09\u3002", isError: true };
|
|
17804
|
+
}
|
|
17805
|
+
if (timeout.signal.aborted) return { content: `\u7B49\u5F85\u8D85\u65F6\uFF08>${Math.round(timeoutMs2 / 1e3)}s\uFF09\u5DF2\u5148\u8FD4\u56DE\uFF1BCC \u91CC\u7684\u4EFB\u52A1\u6CA1\u6709\u88AB\u53D6\u6D88\u3001\u4ECD\u5728\u7EE7\u7EED\u8DD1\u5B8C\u2014\u2014\u7A0D\u540E\u7528 cc_progress \u67E5\u770B\u7ED3\u679C\uFF0C\u4E0D\u8981\u91CD\u590D\u53D1\u9001\u3002`, isError: true };
|
|
17670
17806
|
throw error;
|
|
17671
17807
|
} finally {
|
|
17672
17808
|
clearTimeout(timer2);
|
|
@@ -18151,7 +18287,7 @@ var init_db = __esm({
|
|
|
18151
18287
|
});
|
|
18152
18288
|
|
|
18153
18289
|
// src/tools/notification-state.ts
|
|
18154
|
-
import { join as
|
|
18290
|
+
import { join as join30, resolve as resolve23 } from "node:path";
|
|
18155
18291
|
function createNotificationStateReader() {
|
|
18156
18292
|
const databases = /* @__PURE__ */ new Map();
|
|
18157
18293
|
const checkers = /* @__PURE__ */ new Map();
|
|
@@ -18198,7 +18334,7 @@ function readNotificationState(route, queueStateDir, open6, relationshipChecker)
|
|
|
18198
18334
|
let proactive;
|
|
18199
18335
|
let calendar;
|
|
18200
18336
|
try {
|
|
18201
|
-
memory = open6(
|
|
18337
|
+
memory = open6(join30(runtime.stateDir, "mem7", "index", "mem7.db"));
|
|
18202
18338
|
const scope = memory.prepare("SELECT * FROM memory_scopes WHERE scope_id=?").get(context.scopeId);
|
|
18203
18339
|
if (!scope) {
|
|
18204
18340
|
return { state: "blocked", reason: "MEMORY_NOTIFICATION_SCOPE_MISSING", redact: true };
|
|
@@ -18225,7 +18361,7 @@ function readNotificationState(route, queueStateDir, open6, relationshipChecker)
|
|
|
18225
18361
|
}
|
|
18226
18362
|
if (context.actionVersions && Object.keys(context.actionVersions).length) {
|
|
18227
18363
|
const ledgerDependencies = new MemoryDependencies(memory, (operation) => operation());
|
|
18228
|
-
proactive = open6(
|
|
18364
|
+
proactive = open6(join30(runtime.workspace, ".proactive", "proactive.db"));
|
|
18229
18365
|
for (const id2 of Object.keys(context.actionVersions)) {
|
|
18230
18366
|
const action = proactive.prepare("SELECT scope_id,intent_id FROM actions WHERE id=?").get(id2);
|
|
18231
18367
|
if (!action || action.scope_id !== context.scopeId) return { state: "blocked", reason: "MEMORY_NOTIFICATION_ACTION_MISMATCH", redact: true };
|
|
@@ -18279,7 +18415,7 @@ function readNotificationState(route, queueStateDir, open6, relationshipChecker)
|
|
|
18279
18415
|
}
|
|
18280
18416
|
if (route.hostDelivery) {
|
|
18281
18417
|
if (!proactive) {
|
|
18282
|
-
proactive = open6(
|
|
18418
|
+
proactive = open6(join30(runtime.workspace, ".proactive", "proactive.db"));
|
|
18283
18419
|
}
|
|
18284
18420
|
const receipt2 = proactive.prepare("SELECT * FROM proactive_host_deliveries WHERE delivery_key=?").get(route.hostDelivery.key);
|
|
18285
18421
|
if (!receipt2 || contextIdentity(JSON.parse(receipt2.context_json)) !== contextIdentity(context)) {
|
|
@@ -18290,7 +18426,7 @@ function readNotificationState(route, queueStateDir, open6, relationshipChecker)
|
|
|
18290
18426
|
if (["blocked", "delivery_unknown"].includes(receipt2.state)) return { state: receipt2.state, reason: receipt2.reason ?? receipt2.state };
|
|
18291
18427
|
}
|
|
18292
18428
|
if (context.calendarBinding) {
|
|
18293
|
-
calendar = open6(
|
|
18429
|
+
calendar = open6(join30(runtime.workspace, ".calendar", "calendar.db"));
|
|
18294
18430
|
const binding = context.calendarBinding;
|
|
18295
18431
|
const rows = calendar.prepare("SELECT state,closure FROM calendar_dispatches WHERE scope_id=? AND event_id=? AND occurrence_id=?").all(context.scopeId, binding.eventId, binding.occurrenceId);
|
|
18296
18432
|
if (rows.some((row) => ["started", "delivery_unknown"].includes(row.state) && !row.closure)) {
|
|
@@ -19721,14 +19857,14 @@ var init_provider_errors = __esm({
|
|
|
19721
19857
|
});
|
|
19722
19858
|
|
|
19723
19859
|
// src/memory/execution-guard.ts
|
|
19724
|
-
import { join as
|
|
19860
|
+
import { join as join33 } from "node:path";
|
|
19725
19861
|
function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
|
|
19726
19862
|
let memory;
|
|
19727
19863
|
let proactive;
|
|
19728
19864
|
let calendar;
|
|
19729
19865
|
try {
|
|
19730
19866
|
if (!stateDir || !context.scopeId || !Array.isArray(context.basisRefs)) return { ok: false, reason: "EXECUTION_CONTEXT_INVALID" };
|
|
19731
|
-
memory = new DatabaseSync16(
|
|
19867
|
+
memory = new DatabaseSync16(join33(stateDir, "mem7", "index", "mem7.db"), { readOnly: true });
|
|
19732
19868
|
memory.exec("PRAGMA query_only=ON; BEGIN");
|
|
19733
19869
|
const schema5 = readSchemaVersion(memory);
|
|
19734
19870
|
if (schema5?.component !== "mem7" || schema5.version !== MEM7_SCHEMA_VERSION) return { ok: false, reason: "MEMORY_SCHEMA_UNSUPPORTED" };
|
|
@@ -19743,7 +19879,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
|
|
|
19743
19879
|
if (!result.ok) return result;
|
|
19744
19880
|
}
|
|
19745
19881
|
if (context.calendarBinding) {
|
|
19746
|
-
calendar = new DatabaseSync16(
|
|
19882
|
+
calendar = new DatabaseSync16(join33(workspace, ".calendar", "calendar.db"), { readOnly: true });
|
|
19747
19883
|
calendar.exec("PRAGMA query_only=ON; BEGIN");
|
|
19748
19884
|
const binding = calendar.prepare(`SELECT b.*,e.status event_status,e.memory_version current_event_version FROM calendar_memory_bindings b
|
|
19749
19885
|
JOIN events e ON e.id=b.event_id WHERE b.event_id=?`).get(context.calendarBinding.eventId);
|
|
@@ -19761,7 +19897,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
|
|
|
19761
19897
|
if (!bound.ok) return bound;
|
|
19762
19898
|
}
|
|
19763
19899
|
if (context.actionVersions && Object.keys(context.actionVersions).length) {
|
|
19764
|
-
proactive = new DatabaseSync16(
|
|
19900
|
+
proactive = new DatabaseSync16(join33(workspace, ".proactive", "proactive.db"), { readOnly: true });
|
|
19765
19901
|
proactive.exec("PRAGMA query_only=ON; BEGIN");
|
|
19766
19902
|
for (const [id2, version] of Object.entries(context.actionVersions)) {
|
|
19767
19903
|
const action = proactive.prepare("SELECT * FROM actions WHERE id=?").get(id2);
|
|
@@ -22809,7 +22945,7 @@ __export(memdir_exports, {
|
|
|
22809
22945
|
truncateEntrypointContent: () => truncateEntrypointContent
|
|
22810
22946
|
});
|
|
22811
22947
|
import { readFileSync as readFileSync19 } from "node:fs";
|
|
22812
|
-
import { join as
|
|
22948
|
+
import { join as join36 } from "node:path";
|
|
22813
22949
|
function truncateEntrypointContent(raw) {
|
|
22814
22950
|
const trimmed = raw.trim();
|
|
22815
22951
|
const contentLines = trimmed.split("\n");
|
|
@@ -22902,7 +23038,7 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
|
|
|
22902
23038
|
}
|
|
22903
23039
|
function buildMemoryPrompt(params) {
|
|
22904
23040
|
const { displayName, memoryDir, extraGuidelines } = params;
|
|
22905
|
-
const entrypoint =
|
|
23041
|
+
const entrypoint = join36(memoryDir, ENTRYPOINT_NAME);
|
|
22906
23042
|
let entrypointContent = "";
|
|
22907
23043
|
try {
|
|
22908
23044
|
entrypointContent = readFileSync19(entrypoint, { encoding: "utf-8" });
|
|
@@ -23586,7 +23722,7 @@ var init_query = __esm({
|
|
|
23586
23722
|
this.compactConfig.systemOverheadTokens = overhead ?? this.compactConfig.systemOverheadTokens;
|
|
23587
23723
|
}
|
|
23588
23724
|
const activeSystemStable = perTurnSystemStable || this.resolveOpt(this.options.systemStable) || this.resolveOpt(this.options.systemPrompt);
|
|
23589
|
-
for (const m of messages) if ("role" in m &&
|
|
23725
|
+
for (const m of messages) if ("role" in m && hasMedia(m) && !m.imageInput) m.imageInput = { id: randomUUID14(), observed: hasImage(m) };
|
|
23590
23726
|
let currentMessages = [...messages];
|
|
23591
23727
|
const oldGatePattern = /^Tool "([^"]+)" is permanently unavailable in this channel\. Do NOT retry it or any other tool — answer the user directly in plain speech now\.$/;
|
|
23592
23728
|
const historicalGateTools = new Set(currentMessages.flatMap((m) => {
|
|
@@ -23977,9 +24113,13 @@ var init_query = __esm({
|
|
|
23977
24113
|
try {
|
|
23978
24114
|
wholeQueryAbort.signal.throwIfAborted();
|
|
23979
24115
|
const view = normalizeMessagesForAPI(currentMessages).map((m) => {
|
|
23980
|
-
if (!Array.isArray(m.content) || !m.imageInput?.observed ||
|
|
23981
|
-
const blocks = m.content.filter((b) =>
|
|
23982
|
-
|
|
24116
|
+
if (!Array.isArray(m.content) || !m.imageInput?.observed || !queryModelRef) return m;
|
|
24117
|
+
const blocks = m.content.filter((b) => {
|
|
24118
|
+
if (b.type === "image" || b.type === "image_ref") return !!queryInputs?.includes("image");
|
|
24119
|
+
if (b.type === "video") return !!queryInputs?.includes("video");
|
|
24120
|
+
return true;
|
|
24121
|
+
});
|
|
24122
|
+
return { ...m, content: blocks.length ? blocks : "[previous media omitted]" };
|
|
23983
24123
|
});
|
|
23984
24124
|
const apiMessages = await materializeImageMessages(view, this.options.imageAssets, wholeQueryAbort.signal);
|
|
23985
24125
|
wholeQueryAbort.signal.throwIfAborted();
|
|
@@ -24140,7 +24280,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
|
|
|
24140
24280
|
}
|
|
24141
24281
|
});
|
|
24142
24282
|
if (!requestComplete || (toolCalls.length ? !validToolCalls : !textContent.trim()) || ["length", "max_tokens", "MAX_TOKENS", "incomplete", "content_filter"].includes(responseStopReason ?? "")) return;
|
|
24143
|
-
const inputs = currentMessages.filter((m) => "role" in m &&
|
|
24283
|
+
const inputs = currentMessages.filter((m) => "role" in m && hasMedia(m) && !m.imageInput?.observed);
|
|
24144
24284
|
if (!inputs.length) return;
|
|
24145
24285
|
return {
|
|
24146
24286
|
type: "image_observed",
|
|
@@ -25461,26 +25601,26 @@ __export(teamHelpers_exports, {
|
|
|
25461
25601
|
writeTeamFile: () => writeTeamFile,
|
|
25462
25602
|
writeTeamFileAsync: () => writeTeamFileAsync
|
|
25463
25603
|
});
|
|
25464
|
-
import { mkdirSync as
|
|
25604
|
+
import { mkdirSync as mkdirSync21, readFileSync as readFileSync21, writeFileSync as writeFileSync21 } from "node:fs";
|
|
25465
25605
|
import { mkdir, readFile, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
|
|
25466
|
-
import { join as
|
|
25606
|
+
import { join as join38 } from "node:path";
|
|
25467
25607
|
function initTeamDirs(stateDir) {
|
|
25468
25608
|
_stateDir = stateDir;
|
|
25469
25609
|
}
|
|
25470
25610
|
function getTeamsDir() {
|
|
25471
|
-
return
|
|
25611
|
+
return join38(_stateDir, "teams");
|
|
25472
25612
|
}
|
|
25473
25613
|
function getTasksDir() {
|
|
25474
|
-
return
|
|
25614
|
+
return join38(_stateDir, "tasks");
|
|
25475
25615
|
}
|
|
25476
25616
|
function sanitizeName(name) {
|
|
25477
25617
|
return name.replace(/[^a-zA-Z0-9_-]/g, "-").toLowerCase();
|
|
25478
25618
|
}
|
|
25479
25619
|
function getTeamDir(teamName) {
|
|
25480
|
-
return
|
|
25620
|
+
return join38(getTeamsDir(), sanitizeName(teamName));
|
|
25481
25621
|
}
|
|
25482
25622
|
function getTeamFilePath(teamName) {
|
|
25483
|
-
return
|
|
25623
|
+
return join38(getTeamDir(teamName), "config.json");
|
|
25484
25624
|
}
|
|
25485
25625
|
function readTeamFile(teamName) {
|
|
25486
25626
|
try {
|
|
@@ -25504,8 +25644,8 @@ async function readTeamFileAsync(teamName) {
|
|
|
25504
25644
|
}
|
|
25505
25645
|
function writeTeamFile(teamName, teamFile) {
|
|
25506
25646
|
const teamDir = getTeamDir(teamName);
|
|
25507
|
-
|
|
25508
|
-
|
|
25647
|
+
mkdirSync21(teamDir, { recursive: true });
|
|
25648
|
+
writeFileSync21(getTeamFilePath(teamName), JSON.stringify(teamFile, null, 2));
|
|
25509
25649
|
}
|
|
25510
25650
|
async function writeTeamFileAsync(teamName, teamFile) {
|
|
25511
25651
|
const teamDir = getTeamDir(teamName);
|
|
@@ -25585,7 +25725,7 @@ async function cleanupTeamDirectories(teamName) {
|
|
|
25585
25725
|
} catch (error) {
|
|
25586
25726
|
console.warn(`[teamHelpers] Failed to clean up team directory ${teamDir}: ${error.message}`);
|
|
25587
25727
|
}
|
|
25588
|
-
const tasksDir =
|
|
25728
|
+
const tasksDir = join38(getTasksDir(), sanitizedName);
|
|
25589
25729
|
try {
|
|
25590
25730
|
await rm2(tasksDir, { recursive: true, force: true });
|
|
25591
25731
|
console.log(`[teamHelpers] Cleaned up tasks directory: ${tasksDir}`);
|
|
@@ -25594,8 +25734,8 @@ async function cleanupTeamDirectories(teamName) {
|
|
|
25594
25734
|
}
|
|
25595
25735
|
}
|
|
25596
25736
|
function ensureTasksDir(taskListId) {
|
|
25597
|
-
const dir =
|
|
25598
|
-
|
|
25737
|
+
const dir = join38(getTasksDir(), taskListId);
|
|
25738
|
+
mkdirSync21(dir, { recursive: true });
|
|
25599
25739
|
}
|
|
25600
25740
|
function setLeaderTeamName(name) {
|
|
25601
25741
|
_leaderTeamName = name;
|
|
@@ -25775,9 +25915,9 @@ The user interacts primarily with the team lead. Your work is coordinated throug
|
|
|
25775
25915
|
|
|
25776
25916
|
// src/swarm/teammateMailbox.ts
|
|
25777
25917
|
import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile4 } from "node:fs/promises";
|
|
25778
|
-
import { join as
|
|
25918
|
+
import { join as join39 } from "node:path";
|
|
25779
25919
|
function getTeamsDir2() {
|
|
25780
|
-
return
|
|
25920
|
+
return join39(process.env.ENGINE_STATE_DIR || ".", "teams");
|
|
25781
25921
|
}
|
|
25782
25922
|
function sanitizePathComponent(s) {
|
|
25783
25923
|
return s.replace(/[^a-zA-Z0-9_-]/g, "-");
|
|
@@ -25786,12 +25926,12 @@ function getInboxPath(agentName, teamName) {
|
|
|
25786
25926
|
const team = teamName || "default";
|
|
25787
25927
|
const safeTeam = sanitizePathComponent(team);
|
|
25788
25928
|
const safeAgentName = sanitizePathComponent(agentName);
|
|
25789
|
-
return
|
|
25929
|
+
return join39(getTeamsDir2(), safeTeam, "inboxes", `${safeAgentName}.json`);
|
|
25790
25930
|
}
|
|
25791
25931
|
async function ensureInboxDir(teamName) {
|
|
25792
25932
|
const team = teamName || "default";
|
|
25793
25933
|
const safeTeam = sanitizePathComponent(team);
|
|
25794
|
-
const inboxDir =
|
|
25934
|
+
const inboxDir = join39(getTeamsDir2(), safeTeam, "inboxes");
|
|
25795
25935
|
await mkdir2(inboxDir, { recursive: true });
|
|
25796
25936
|
}
|
|
25797
25937
|
async function sleep2(ms) {
|
|
@@ -30706,7 +30846,7 @@ var init_tools = __esm({
|
|
|
30706
30846
|
|
|
30707
30847
|
// src/tools/wechat/wx-query.ts
|
|
30708
30848
|
var wx_query_exports = {};
|
|
30709
|
-
import { join as
|
|
30849
|
+
import { join as join45 } from "node:path";
|
|
30710
30850
|
function getDescription() {
|
|
30711
30851
|
return `\u67E5\u8BE2\u7FC0\u54E5\u7684\u5FAE\u4FE1\u6D88\u606F\uFF08\u7F13\u5B58\u89E3\u5BC6\u540E\u7684\u672C\u5730\u6570\u636E\u5E93\uFF09\u3002
|
|
30712
30852
|
|
|
@@ -30741,8 +30881,8 @@ var init_wx_query = __esm({
|
|
|
30741
30881
|
"use strict";
|
|
30742
30882
|
init_registry();
|
|
30743
30883
|
init_live();
|
|
30744
|
-
STATE_DIR = process.env.ENGINE7_STATE_DIR ||
|
|
30745
|
-
SCRIPT =
|
|
30884
|
+
STATE_DIR = process.env.ENGINE7_STATE_DIR || join45(process.env.HOME || process.env.USERPROFILE || ".", ".engine7");
|
|
30885
|
+
SCRIPT = join45("/Users/chongzhang/work/twinsun-hearth/engine", "src", "tools", "wechat", "wx_query.py");
|
|
30746
30886
|
PYTHON = "python3";
|
|
30747
30887
|
registry.register({
|
|
30748
30888
|
name: "wx_query",
|
|
@@ -30816,15 +30956,15 @@ var init_wx_query = __esm({
|
|
|
30816
30956
|
init_publication_objects();
|
|
30817
30957
|
init_key_service_store();
|
|
30818
30958
|
import { DatabaseSync as DatabaseSync41 } from "node:sqlite";
|
|
30819
|
-
import { existsSync as existsSync42, readFileSync as readFileSync36, writeFileSync as
|
|
30820
|
-
import { join as
|
|
30959
|
+
import { existsSync as existsSync42, readFileSync as readFileSync36, writeFileSync as writeFileSync42, renameSync as renameSync12, realpathSync as realpathSync30, openSync as openSync21, closeSync as closeSync20 } from "node:fs";
|
|
30960
|
+
import { join as join73, resolve as resolve46 } from "node:path";
|
|
30821
30961
|
import { fileURLToPath as fileURLToPath9, pathToFileURL as pathToFileURL2 } from "node:url";
|
|
30822
30962
|
import { spawn as spawn7 } from "node:child_process";
|
|
30823
|
-
import { request as
|
|
30963
|
+
import { request as request8 } from "node:https";
|
|
30824
30964
|
|
|
30825
30965
|
// src/continuity/pairing-setup.ts
|
|
30826
|
-
import { existsSync as existsSync26, mkdirSync as
|
|
30827
|
-
import { join as
|
|
30966
|
+
import { existsSync as existsSync26, mkdirSync as mkdirSync24, readFileSync as readFileSync26, writeFileSync as writeFileSync23, readdirSync as readdirSync11, cpSync, realpathSync as realpathSync13, symlinkSync, lstatSync as lstatSync18 } from "node:fs";
|
|
30967
|
+
import { join as join46 } from "node:path";
|
|
30828
30968
|
import { homedir as homedir3 } from "node:os";
|
|
30829
30969
|
import { randomBytes as randomBytes4, createHash as createHash35, X509Certificate } from "node:crypto";
|
|
30830
30970
|
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
@@ -33858,7 +33998,7 @@ function resolveRequiredTools(features, licensedFeatures) {
|
|
|
33858
33998
|
|
|
33859
33999
|
// src/continuity/pairing-setup.ts
|
|
33860
34000
|
var sha6 = (value2) => createHash35("sha256").update(value2).digest("hex");
|
|
33861
|
-
var write = (file2, value2) =>
|
|
34001
|
+
var write = (file2, value2) => writeFileSync23(file2, JSON.stringify(value2), { mode: 384, flush: true });
|
|
33862
34002
|
var free = () => new Promise((done, reject) => {
|
|
33863
34003
|
const server = createServer();
|
|
33864
34004
|
server.once("error", reject);
|
|
@@ -33869,19 +34009,19 @@ var free = () => new Promise((done, reject) => {
|
|
|
33869
34009
|
});
|
|
33870
34010
|
var names = ["authority", "gateway", "key", "pairing", "localManagement", "cloudManagement", "localData", "cloudData", "console", "localApi", "cloudApi", "hostControl"];
|
|
33871
34011
|
var archivePairing = (directory2) => {
|
|
33872
|
-
const stage =
|
|
33873
|
-
execFileSync2("/usr/bin/tar", ["--exclude=setup/node_modules", "-czf",
|
|
33874
|
-
execFileSync2("/usr/bin/tar", ["--exclude=setup/node_modules", "--exclude=setup/dist", "-czf",
|
|
33875
|
-
const manifest = JSON.parse(readFileSync26(
|
|
33876
|
-
write(
|
|
34012
|
+
const stage = join46(directory2, "stage");
|
|
34013
|
+
execFileSync2("/usr/bin/tar", ["--exclude=setup/node_modules", "-czf", join46(directory2, "pairing.tgz"), "-C", stage, "setup", "control"], { stdio: "ignore" });
|
|
34014
|
+
execFileSync2("/usr/bin/tar", ["--exclude=setup/node_modules", "--exclude=setup/dist", "-czf", join46(directory2, "pairing-reuse.tgz"), "-C", stage, "setup", "control"], { stdio: "ignore" });
|
|
34015
|
+
const manifest = JSON.parse(readFileSync26(join46(stage, "setup/manifest.json"), "utf8"));
|
|
34016
|
+
write(join46(directory2, "pairing-environment.json"), { dependenciesSha256: manifest.dependenciesSha256 });
|
|
33877
34017
|
};
|
|
33878
34018
|
async function preparePairingMaterial(input) {
|
|
33879
|
-
const hostStorage = input.hostStorage ? realpathSync13(input.hostStorage) :
|
|
34019
|
+
const hostStorage = input.hostStorage ? realpathSync13(input.hostStorage) : join46(homedir3(), ".engine7-travel-test/hosts");
|
|
33880
34020
|
const engineDir = realpathSync13(input.engineDir), stateDir = realpathSync13(input.stateDir), configPath = realpathSync13(input.configPath);
|
|
33881
34021
|
const environmentDir = input.environmentDir ? realpathSync13(input.environmentDir) : engineDir;
|
|
33882
|
-
const pkg = JSON.parse(readFileSync26(
|
|
34022
|
+
const pkg = JSON.parse(readFileSync26(join46(environmentDir, "package.json"), "utf8"));
|
|
33883
34023
|
if (input.environmentDir) {
|
|
33884
|
-
const lock = JSON.parse(readFileSync26(
|
|
34024
|
+
const lock = JSON.parse(readFileSync26(join46(environmentDir, "package-lock.json"), "utf8"));
|
|
33885
34025
|
if (pkg.name !== "engine7" || lock.name !== pkg.name || lock.version !== pkg.version || lock.lockfileVersion !== 3 || lock.packages?.[""]?.version !== pkg.version || JSON.stringify(lock.packages[""].dependencies) !== JSON.stringify(pkg.dependencies)) throw Error("TRAVEL_PAIRING_ENVIRONMENT");
|
|
33886
34026
|
}
|
|
33887
34027
|
if (!/^[a-f0-9-]{36}$/.test(input.taskId) || input.remoteRoot !== "/srv/engine7-self-hosted/" + input.taskId) throw new Error("TRAVEL_PAIRING_CONFIG");
|
|
@@ -33889,10 +34029,10 @@ async function preparePairingMaterial(input) {
|
|
|
33889
34029
|
loadSecretsEnvForConfig(configPath);
|
|
33890
34030
|
const parsed = loadConfig(configPath);
|
|
33891
34031
|
if (realpathSync13(parsed.stateDir) !== stateDir) throw new Error("TRAVEL_PAIRING_IDENTITY");
|
|
33892
|
-
const companion = JSON.parse(readPrivateFile(
|
|
33893
|
-
const directory2 =
|
|
33894
|
-
|
|
33895
|
-
const receiptFile =
|
|
34032
|
+
const companion = JSON.parse(readPrivateFile(join46(stateDir, ".continuity/travel-companion-id.json"), 16384).toString()).companionId;
|
|
34033
|
+
const directory2 = join46(homedir3(), ".engine7-travel-test", "tasks", input.taskId);
|
|
34034
|
+
mkdirSync24(join46(homedir3(), ".engine7-travel-test", "tasks"), { recursive: true, mode: 448 });
|
|
34035
|
+
const receiptFile = join46(directory2, "material.json");
|
|
33896
34036
|
if (existsSync26(receiptFile)) {
|
|
33897
34037
|
const prior = JSON.parse(readPrivateFile(receiptFile, 65536).toString());
|
|
33898
34038
|
if (prior.stateDir !== stateDir || prior.configPath !== configPath || prior.host !== input.host || prior.hostFingerprint !== input.hostFingerprint || prior.identity.companionId !== companion) throw new Error("TRAVEL_PAIRING_IDENTITY");
|
|
@@ -33900,20 +34040,20 @@ async function preparePairingMaterial(input) {
|
|
|
33900
34040
|
if (!prior.hostStorage) {
|
|
33901
34041
|
prior.hostStorage = hostStorage;
|
|
33902
34042
|
write(receiptFile, prior);
|
|
33903
|
-
if (existsSync26(
|
|
34043
|
+
if (existsSync26(join46(directory2, "host.json"))) write(join46(directory2, "host.json"), prior);
|
|
33904
34044
|
}
|
|
33905
34045
|
if (input.environmentDir) {
|
|
33906
|
-
const setup2 =
|
|
34046
|
+
const setup2 = join46(directory2, "stage/setup"), manifestFile = join46(setup2, "manifest.json");
|
|
33907
34047
|
const manifest = JSON.parse(readPrivateFile(manifestFile, 4 * 1024 * 1024).toString()), dependenciesSha256 = sha6(JSON.stringify(pkg.dependencies));
|
|
33908
34048
|
if (manifest.taskId !== input.taskId || JSON.stringify(manifest.identity) !== JSON.stringify(prior.identity) || manifest.buildManifestId !== prior.buildManifestId) throw Error("TRAVEL_PAIRING_IDENTITY");
|
|
33909
34049
|
if (manifest.dependenciesSha256 !== dependenciesSha256) {
|
|
33910
|
-
if (existsSync26(
|
|
33911
|
-
for (const name of ["package.json", "package-lock.json"]) cpSync(
|
|
34050
|
+
if (existsSync26(join46(directory2, "binding.json")) || existsSync26(join46(directory2, "host-ready.json"))) throw Error("TRAVEL_PAIRING_ENVIRONMENT");
|
|
34051
|
+
for (const name of ["package.json", "package-lock.json"]) cpSync(join46(environmentDir, name), join46(setup2, name));
|
|
33912
34052
|
write(manifestFile, { ...manifest, dependenciesSha256 });
|
|
33913
34053
|
}
|
|
33914
|
-
const archivedFile =
|
|
34054
|
+
const archivedFile = join46(directory2, "pairing-environment.json");
|
|
33915
34055
|
const archived = existsSync26(archivedFile) ? JSON.parse(readPrivateFile(archivedFile, 4096).toString()) : void 0;
|
|
33916
|
-
if (!existsSync26(
|
|
34056
|
+
if (!existsSync26(join46(directory2, "binding.json")) && archived?.dependenciesSha256 !== dependenciesSha256) archivePairing(directory2);
|
|
33917
34057
|
}
|
|
33918
34058
|
return prior;
|
|
33919
34059
|
}
|
|
@@ -33924,25 +34064,25 @@ async function preparePairingMaterial(input) {
|
|
|
33924
34064
|
const layout = await describeInitialRuntimeLayout(stateDir, realpathSync13(parsed.workspace), "core");
|
|
33925
34065
|
preparePrivateDirectory(directory2);
|
|
33926
34066
|
const identity3 = { tenantId: "self-hosted-" + sha6(homedir3()).slice(0, 20), companionId: companion, seatId: input.taskId };
|
|
33927
|
-
const tlsDirectory =
|
|
34067
|
+
const tlsDirectory = join46(directory2, "tls");
|
|
33928
34068
|
createPairingTLS(tlsDirectory, input.host);
|
|
33929
34069
|
const key2 = randomBytes4(32);
|
|
33930
|
-
|
|
34070
|
+
writeFileSync23(join46(directory2, "data.key"), key2, { mode: 384 });
|
|
33931
34071
|
const keySha256 = sha6(key2);
|
|
33932
34072
|
key2.fill(0);
|
|
33933
34073
|
const ports = {};
|
|
33934
34074
|
for (const name of names) ports[name] = await free();
|
|
33935
|
-
execFileSync2("/usr/bin/ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-f",
|
|
33936
|
-
const stage =
|
|
34075
|
+
execFileSync2("/usr/bin/ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-f", join46(directory2, "relay.key")], { stdio: "ignore" });
|
|
34076
|
+
const stage = join46(directory2, "stage");
|
|
33937
34077
|
preparePrivateDirectory(stage);
|
|
33938
|
-
const setup =
|
|
34078
|
+
const setup = join46(stage, "setup");
|
|
33939
34079
|
preparePrivateDirectory(setup);
|
|
33940
|
-
cpSync(
|
|
33941
|
-
symlinkSync(
|
|
33942
|
-
for (const name of ["package.json", "package-lock.json"]) cpSync(
|
|
34080
|
+
cpSync(join46(engineDir, "dist"), join46(setup, "dist"), { recursive: true });
|
|
34081
|
+
symlinkSync(join46(engineDir, "node_modules"), join46(setup, "node_modules"), "dir");
|
|
34082
|
+
for (const name of ["package.json", "package-lock.json"]) cpSync(join46(environmentDir, name), join46(setup, name));
|
|
33943
34083
|
const runtimeHashes = [];
|
|
33944
34084
|
const collect = (name) => {
|
|
33945
|
-
const file2 =
|
|
34085
|
+
const file2 = join46(setup, name), stat3 = lstatSync18(file2);
|
|
33946
34086
|
if (stat3.isSymbolicLink() || !stat3.isDirectory() && !stat3.isFile() || /[\r\n\\]/.test(name)) throw Error("TRAVEL_PAIRING_CONFIG");
|
|
33947
34087
|
if (stat3.isDirectory()) {
|
|
33948
34088
|
for (const child of readdirSync11(file2).sort()) collect(name + "/" + child);
|
|
@@ -33951,17 +34091,17 @@ async function preparePairingMaterial(input) {
|
|
|
33951
34091
|
if (!/\.(?:mjs|js)\.map$/.test(name)) runtimeHashes.push([name, sha6(readFileSync26(file2))]);
|
|
33952
34092
|
};
|
|
33953
34093
|
collect("dist");
|
|
33954
|
-
const overlayHashes = readdirSync11(
|
|
34094
|
+
const overlayHashes = readdirSync11(join46(setup, "dist")).filter((name) => name.endsWith(".mjs")).sort().map((name) => [name, sha6(readFileSync26(join46(setup, "dist", name)))]);
|
|
33955
34095
|
const buildManifestId = "setup-" + sha6(JSON.stringify(overlayHashes)).slice(0, 40);
|
|
33956
|
-
write(
|
|
33957
|
-
const control2 =
|
|
34096
|
+
write(join46(setup, "manifest.json"), { taskId: input.taskId, identity: identity3, buildManifestId, dependenciesSha256: sha6(JSON.stringify(pkg.dependencies)), overlayHashes, runtimeHashes });
|
|
34097
|
+
const control2 = join46(stage, "control");
|
|
33958
34098
|
preparePrivateDirectory(control2);
|
|
33959
|
-
for (const name of ["ca.pem", "server.pem", "server.key", "local.pem", "cloud.pem", "manager.pem", "manager.key"]) cpSync(
|
|
33960
|
-
cpSync(
|
|
33961
|
-
|
|
34099
|
+
for (const name of ["ca.pem", "server.pem", "server.key", "local.pem", "cloud.pem", "manager.pem", "manager.key"]) cpSync(join46(tlsDirectory, name), join46(control2, name));
|
|
34100
|
+
cpSync(join46(directory2, "data.key"), join46(control2, "data.key"));
|
|
34101
|
+
writeFileSync23(join46(control2, "pair-token"), "e7p_" + randomBytes4(32).toString("hex"), { mode: 384 });
|
|
33962
34102
|
const feishu = channels.feishu ?? {}, feishuAccount = feishu.accounts?.default ?? {};
|
|
33963
34103
|
const remoteControl = input.remoteRoot + "/pair-control";
|
|
33964
|
-
write(
|
|
34104
|
+
write(join46(control2, "config.json"), {
|
|
33965
34105
|
directory: remoteControl,
|
|
33966
34106
|
identity: identity3,
|
|
33967
34107
|
buildManifestId,
|
|
@@ -33970,8 +34110,8 @@ async function preparePairingMaterial(input) {
|
|
|
33970
34110
|
channels,
|
|
33971
34111
|
feishu: { ...feishu, appId: feishu.appId ?? feishuAccount.appId ?? "no-feishu", appSecret: feishu.appSecret ?? feishuAccount.appSecret ?? "no-feishu" }
|
|
33972
34112
|
});
|
|
33973
|
-
write(
|
|
33974
|
-
const tls2 = (role) => ({ caFile:
|
|
34113
|
+
write(join46(directory2, "engine-config.json"), effective);
|
|
34114
|
+
const tls2 = (role) => ({ caFile: join46(tlsDirectory, "ca.pem"), certFile: join46(tlsDirectory, role + ".pem"), keyFile: join46(tlsDirectory, role + ".key") });
|
|
33975
34115
|
const material = {
|
|
33976
34116
|
layout,
|
|
33977
34117
|
allowedTools: [.../* @__PURE__ */ new Set([...resolveRequiredTools(parsed.profile.features), ...["msg_husband", "media_send", "chat_history", "calendar", "goal_add", "goal_update", "goal_step", "my_eyes", "my_voice", "my_selfie", "body_move", "service", "auth", "TaskCreate", "TaskGet", "TaskList", "TaskUpdate", "AskUserQuestion", "EnterPlanMode", "ExitPlanMode", "ToolSearch"]])],
|
|
@@ -34001,9 +34141,9 @@ async function preparePairingMaterial(input) {
|
|
|
34001
34141
|
relayUser: "e7r_" + input.taskId.replaceAll("-", "").slice(0, 12),
|
|
34002
34142
|
controlUser: "e7c_" + input.taskId.replaceAll("-", "").slice(0, 12),
|
|
34003
34143
|
runtimeUser: "e7t" + input.taskId.replaceAll("-", "").slice(0, 12),
|
|
34004
|
-
build: { entry:
|
|
34005
|
-
dataBuild: { entry:
|
|
34006
|
-
fingerprints: Object.fromEntries(["local", "cloud", "manager"].map((name) => [name, new X509Certificate(readFileSync26(
|
|
34144
|
+
build: { entry: join46(setup, "dist/main.mjs"), sha256: sha6(readFileSync26(join46(engineDir, "dist/main.mjs"))), manifestId: buildManifestId },
|
|
34145
|
+
dataBuild: { entry: join46(setup, "dist/travel-node-data.mjs"), sha256: sha6(readFileSync26(join46(engineDir, "dist/travel-node-data.mjs"))) },
|
|
34146
|
+
fingerprints: Object.fromEntries(["local", "cloud", "manager"].map((name) => [name, new X509Certificate(readFileSync26(join46(tlsDirectory, name + ".pem"))).fingerprint256.replaceAll(":", "").toLowerCase()]))
|
|
34007
34147
|
};
|
|
34008
34148
|
write(receiptFile, material);
|
|
34009
34149
|
archivePairing(directory2);
|
|
@@ -34011,14 +34151,14 @@ async function preparePairingMaterial(input) {
|
|
|
34011
34151
|
}
|
|
34012
34152
|
function finalizePairingMaterial(material, binding) {
|
|
34013
34153
|
if (JSON.stringify(material.identity) !== JSON.stringify(binding.identity) || material.keySha256 !== binding.keySha256 || material.buildManifestId !== binding.buildManifestId) throw new Error("TRAVEL_PAIRING_IDENTITY");
|
|
34014
|
-
const directory2 = material.directory, remote = material.remoteRuntime, ports = material.ports, tlsDirectory =
|
|
34015
|
-
if (existsSync26(
|
|
34016
|
-
if (JSON.stringify(JSON.parse(readPrivateFile(
|
|
34017
|
-
return { cloudArchive:
|
|
34154
|
+
const directory2 = material.directory, remote = material.remoteRuntime, ports = material.ports, tlsDirectory = join46(directory2, "tls"), url = (port, path37) => `https://127.0.0.1:${port}${path37}`;
|
|
34155
|
+
if (existsSync26(join46(directory2, "cloud.tgz")) && existsSync26(join46(directory2, "host.json")) && existsSync26(join46(directory2, "local/node.json"))) {
|
|
34156
|
+
if (JSON.stringify(JSON.parse(readPrivateFile(join46(directory2, "binding.json"), 65536).toString())) !== JSON.stringify(binding)) throw new Error("TRAVEL_PAIRING_IDENTITY");
|
|
34157
|
+
return { cloudArchive: join46(directory2, "cloud.tgz"), hostConfig: join46(directory2, "host.json") };
|
|
34018
34158
|
}
|
|
34019
|
-
const raw = JSON.parse(readPrivateFile(
|
|
34159
|
+
const raw = JSON.parse(readPrivateFile(join46(directory2, "engine-config.json"), 4 * 1024 * 1024).toString());
|
|
34020
34160
|
const base = (role) => {
|
|
34021
|
-
const root = role === "local" ?
|
|
34161
|
+
const root = role === "local" ? join46(directory2, "local") : remote, clientTls = { caFile: root + "/ca.pem", certFile: root + "/client.pem", keyFile: root + "/client.key" }, peer = role === "local" ? "cloud" : "local";
|
|
34022
34162
|
const channels = Object.fromEntries(Object.entries(raw.channels ?? {}).filter(([name, v]) => name !== "emotion" && v.enabled).map(([name, v]) => [name, { enabled: true, mode: "remote-only", gatewayUrl: url(ports.gateway, "/travel/gateway/v1"), gatewayTls: clientTls, gatewayPollIntervalMs: 1e3, ...v.bubbleSplit !== void 0 ? { bubbleSplit: v.bubbleSplit, bubbleSplitGapMs: v.bubbleSplitGapMs } : {} }]));
|
|
34023
34163
|
if (raw.channels?.emotion) channels.emotion = raw.channels.emotion;
|
|
34024
34164
|
return {
|
|
@@ -34045,18 +34185,18 @@ function finalizePairingMaterial(material, binding) {
|
|
|
34045
34185
|
data: { host: "127.0.0.1", port: ports[role + "Data"], allowedPeers: { [material.fingerprints[peer]]: binding.tokens[peer] } }
|
|
34046
34186
|
};
|
|
34047
34187
|
};
|
|
34048
|
-
const local =
|
|
34188
|
+
const local = join46(directory2, "local");
|
|
34049
34189
|
preparePrivateDirectory(local);
|
|
34050
|
-
preparePrivateDirectory(
|
|
34051
|
-
for (const [source, target] of [["ca.pem", "ca.pem"], ["local-server.pem", "server.pem"], ["local-server.key", "server.key"], ["local.pem", "client.pem"], ["local.key", "client.key"]]) cpSync(
|
|
34052
|
-
write(
|
|
34053
|
-
const cloudStage =
|
|
34190
|
+
preparePrivateDirectory(join46(local, "generations"));
|
|
34191
|
+
for (const [source, target] of [["ca.pem", "ca.pem"], ["local-server.pem", "server.pem"], ["local-server.key", "server.key"], ["local.pem", "client.pem"], ["local.key", "client.key"]]) cpSync(join46(tlsDirectory, source), join46(local, target));
|
|
34192
|
+
write(join46(local, "node.json"), base("local"));
|
|
34193
|
+
const cloudStage = join46(directory2, "cloud");
|
|
34054
34194
|
preparePrivateDirectory(cloudStage);
|
|
34055
|
-
preparePrivateDirectory(
|
|
34056
|
-
for (const [source, target] of [["ca.pem", "ca.pem"], ["server.pem", "server.pem"], ["server.key", "server.key"], ["cloud.pem", "client.pem"], ["cloud.key", "client.key"]]) cpSync(
|
|
34057
|
-
write(
|
|
34058
|
-
cpSync(
|
|
34059
|
-
write(
|
|
34195
|
+
preparePrivateDirectory(join46(cloudStage, "generations"));
|
|
34196
|
+
for (const [source, target] of [["ca.pem", "ca.pem"], ["server.pem", "server.pem"], ["server.key", "server.key"], ["cloud.pem", "client.pem"], ["cloud.key", "client.key"]]) cpSync(join46(tlsDirectory, source), join46(cloudStage, target));
|
|
34197
|
+
write(join46(cloudStage, "node.json"), base("cloud"));
|
|
34198
|
+
cpSync(join46(directory2, "relay.key.pub"), join46(cloudStage, "relay.key.pub"));
|
|
34199
|
+
write(join46(directory2, "binding.json"), binding);
|
|
34060
34200
|
const controller = {
|
|
34061
34201
|
directory: material.remoteControl + "/controller",
|
|
34062
34202
|
preferredNodeId: "local",
|
|
@@ -34066,25 +34206,25 @@ function finalizePairingMaterial(material, binding) {
|
|
|
34066
34206
|
tls: { caFile: material.remoteControl + "/ca.pem", certFile: material.remoteControl + "/manager.pem", keyFile: material.remoteControl + "/manager.key" },
|
|
34067
34207
|
nodes: Object.fromEntries(["local", "cloud"].map((role) => [role, { principal: binding[role], credential: binding.tokens[role], url: url(ports[role + "Management"], "/travel/node/v1"), authorityUrl: url(ports.authority, "/travel/manage/v1") }]))
|
|
34068
34208
|
};
|
|
34069
|
-
write(
|
|
34070
|
-
if (!existsSync26(
|
|
34071
|
-
write(
|
|
34072
|
-
write(
|
|
34073
|
-
write(
|
|
34074
|
-
execFileSync2("/usr/bin/tar", ["-czf",
|
|
34075
|
-
return { cloudArchive:
|
|
34209
|
+
write(join46(directory2, "controller.json"), controller);
|
|
34210
|
+
if (!existsSync26(join46(directory2, "console-token"))) writeFileSync23(join46(directory2, "console-token"), "e7u_" + randomBytes4(32).toString("hex"), { mode: 384, flag: "wx" });
|
|
34211
|
+
write(join46(directory2, "console.json"), { retirementConfigFile: material.remoteControl + "/retirement.json", identity: material.identity, host: "127.0.0.1", port: ports.console, directory: material.remoteControl + "/console", controllerConfigFile: material.remoteControl + "/controller.json", tokenFile: material.remoteControl + "/console-token", tls: { certFile: material.remoteControl + "/server.pem", keyFile: material.remoteControl + "/server.key" } });
|
|
34212
|
+
write(join46(directory2, "retirement.json"), { identity: material.identity, jobId: "finish-" + material.taskId, directory: material.remoteControl + "/retirement", localRecoveryReceiptFile: material.remoteControl + "/local-recovery.json", resources: [{ directory: material.remoteRuntime, runAs: { user: material.runtimeUser, node: material.remoteRoot + "/node/bin/node", entry: material.remoteSetup + "/dist/travel-resource.mjs", configFile: material.remoteRoot + "/resources/runtime.json" } }, { directory: material.remoteControl + "/objects" }, { directory: material.remoteControl + "/gateway" }], keyStoreDirectory: material.remoteControl + "/keys", keyIdentity: binding.keyIdentity, stopServices: ["engine7-travel-node-" + material.taskId + ".service"], stopViaSudo: true, control: { url: url(ports.authority, "/travel/manage/v1"), nodeId: "local", credential: binding.tokens.local }, tls: { caFile: material.remoteControl + "/ca.pem", certFile: material.remoteControl + "/manager.pem", keyFile: material.remoteControl + "/manager.key" } });
|
|
34213
|
+
write(join46(directory2, "host.json"), material);
|
|
34214
|
+
execFileSync2("/usr/bin/tar", ["-czf", join46(directory2, "cloud.tgz"), "-C", directory2, "cloud", "controller.json", "console.json", "console-token", "retirement.json"], { stdio: "ignore" });
|
|
34215
|
+
return { cloudArchive: join46(directory2, "cloud.tgz"), hostConfig: join46(directory2, "host.json") };
|
|
34076
34216
|
}
|
|
34077
34217
|
|
|
34078
34218
|
// src/continuity/initial-baseline-worker.ts
|
|
34079
34219
|
import { spawn as spawn4 } from "node:child_process";
|
|
34080
|
-
import { existsSync as existsSync27, writeFileSync as
|
|
34081
|
-
import { join as
|
|
34220
|
+
import { existsSync as existsSync27, writeFileSync as writeFileSync24, unlinkSync as unlinkSync7 } from "node:fs";
|
|
34221
|
+
import { join as join47 } from "node:path";
|
|
34082
34222
|
import { fileURLToPath as fileURLToPath5 } from "node:url";
|
|
34083
34223
|
async function runInitialBaselineWorker(options, onProgress, assertCurrent) {
|
|
34084
34224
|
assertCurrent();
|
|
34085
|
-
const directory2 = String(options.directory), config =
|
|
34225
|
+
const directory2 = String(options.directory), config = join47(directory2, "..", "initial-capture.json");
|
|
34086
34226
|
const built = fileURLToPath5(new URL("./travel-initial-baseline.mjs", import.meta.url)), entry = existsSync27(built) ? built : fileURLToPath5(new URL("./initial-baseline-main.ts", import.meta.url));
|
|
34087
|
-
|
|
34227
|
+
writeFileSync24(config, JSON.stringify(options), { mode: 384, flag: "wx", flush: true });
|
|
34088
34228
|
try {
|
|
34089
34229
|
await new Promise((done, reject) => {
|
|
34090
34230
|
const child = spawn4(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--config", config], { stdio: ["ignore", "pipe", "pipe", "ipc"] });
|
|
@@ -34153,7 +34293,7 @@ import { randomUUID as randomUUID22, createHash as createHash49 } from "node:cry
|
|
|
34153
34293
|
import { DatabaseSync as DatabaseSync35 } from "node:sqlite";
|
|
34154
34294
|
|
|
34155
34295
|
// src/continuity/runtime-engine-config.ts
|
|
34156
|
-
import { join as
|
|
34296
|
+
import { join as join48, posix, win32 } from "node:path";
|
|
34157
34297
|
function runtimeEngineConfig(original, stateDir, workspace) {
|
|
34158
34298
|
const agents = original.agents;
|
|
34159
34299
|
const defaults = agents?.defaults;
|
|
@@ -34165,7 +34305,7 @@ function runtimeEngineConfig(original, stateDir, workspace) {
|
|
|
34165
34305
|
if (!paths.isAbsolute(source) || !paths.isAbsolute(value2)) continue;
|
|
34166
34306
|
const child = paths.relative(source, value2);
|
|
34167
34307
|
if (paths.isAbsolute(child) || child.split(/[\\/]/).includes("..")) continue;
|
|
34168
|
-
return
|
|
34308
|
+
return join48(target, ...child.split(/[\\/]/));
|
|
34169
34309
|
}
|
|
34170
34310
|
return value2;
|
|
34171
34311
|
}
|
|
@@ -34174,24 +34314,24 @@ function runtimeEngineConfig(original, stateDir, workspace) {
|
|
|
34174
34314
|
return value2;
|
|
34175
34315
|
};
|
|
34176
34316
|
const copy = relocate(original), copiedAgents = copy.agents;
|
|
34177
|
-
return { ...copy, stateDir, workspace, mediaDir:
|
|
34317
|
+
return { ...copy, stateDir, workspace, mediaDir: join48(stateDir, "media/inbound"), agents: { ...copiedAgents, defaults: { ...copiedAgents?.defaults, workspace } } };
|
|
34178
34318
|
}
|
|
34179
34319
|
|
|
34180
34320
|
// src/continuity/node-agent.ts
|
|
34181
|
-
import { existsSync as existsSync38, lstatSync as lstatSync28, mkdirSync as
|
|
34182
|
-
import { isAbsolute as isAbsolute11, join as
|
|
34321
|
+
import { existsSync as existsSync38, lstatSync as lstatSync28, mkdirSync as mkdirSync31, readFileSync as readFileSync31, realpathSync as realpathSync26, writeFileSync as writeFileSync40 } from "node:fs";
|
|
34322
|
+
import { isAbsolute as isAbsolute11, join as join70, resolve as resolve40 } from "node:path";
|
|
34183
34323
|
import { createHash as createHash47, randomUUID as randomUUID21 } from "node:crypto";
|
|
34184
34324
|
import { isIP as isIP2 } from "node:net";
|
|
34185
34325
|
|
|
34186
34326
|
// src/continuity/activation.ts
|
|
34187
34327
|
import { DatabaseSync as DatabaseSync22 } from "node:sqlite";
|
|
34188
|
-
import { constants as constants12, existsSync as existsSync32, mkdirSync as
|
|
34328
|
+
import { constants as constants12, existsSync as existsSync32, mkdirSync as mkdirSync25, realpathSync as realpathSync17, unlinkSync as unlinkSync12, writeFileSync as writeFileSync29 } from "node:fs";
|
|
34189
34329
|
import { lstat as lstat4, mkdir as mkdir3, readdir as readdir2 } from "node:fs/promises";
|
|
34190
34330
|
|
|
34191
34331
|
// src/continuity/activation-database-worker.ts
|
|
34192
34332
|
import { spawn as spawn5 } from "node:child_process";
|
|
34193
|
-
import { existsSync as existsSync28, writeFileSync as
|
|
34194
|
-
import { join as
|
|
34333
|
+
import { existsSync as existsSync28, writeFileSync as writeFileSync25, unlinkSync as unlinkSync8, statSync as statSync12 } from "node:fs";
|
|
34334
|
+
import { join as join49 } from "node:path";
|
|
34195
34335
|
import { fileURLToPath as fileURLToPath6 } from "node:url";
|
|
34196
34336
|
|
|
34197
34337
|
// src/continuity/activation-database.ts
|
|
@@ -34252,8 +34392,8 @@ async function runActivationDatabaseWorker(root, file2, binding, assertCurrent)
|
|
|
34252
34392
|
return;
|
|
34253
34393
|
}
|
|
34254
34394
|
const built = fileURLToPath6(new URL("./travel-activation-database.mjs", import.meta.url)), entry = existsSync28(built) ? built : fileURLToPath6(new URL("./activation-database-main.ts", import.meta.url));
|
|
34255
|
-
const config =
|
|
34256
|
-
|
|
34395
|
+
const config = join49(root, ".continuity", "activation-" + binding.databaseId + ".json");
|
|
34396
|
+
writeFileSync25(config, JSON.stringify({ root, file: file2, binding }), { mode: 384, flag: "wx", flush: true });
|
|
34257
34397
|
try {
|
|
34258
34398
|
await new Promise((done, reject) => {
|
|
34259
34399
|
const child = spawn5(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--config", config], { stdio: ["ignore", "pipe", "pipe"] });
|
|
@@ -34289,14 +34429,14 @@ async function runActivationDatabaseWorker(root, file2, binding, assertCurrent)
|
|
|
34289
34429
|
|
|
34290
34430
|
// src/continuity/activation.ts
|
|
34291
34431
|
init_runtime_authority();
|
|
34292
|
-
import { dirname as dirname21, isAbsolute as isAbsolute5, join as
|
|
34432
|
+
import { dirname as dirname21, isAbsolute as isAbsolute5, join as join54, resolve as resolve31 } from "node:path";
|
|
34293
34433
|
init_schema_migrations();
|
|
34294
34434
|
init_key_service_store();
|
|
34295
34435
|
|
|
34296
34436
|
// src/continuity/generation-integrity.ts
|
|
34297
34437
|
import { createHash as createHash36 } from "node:crypto";
|
|
34298
34438
|
import { constants as constants11, closeSync as closeSync17, fstatSync as fstatSync7, lstatSync as lstatSync19, openSync as openSync18, readSync as readSync6, readdirSync as readdirSync12, realpathSync as realpathSync14 } from "node:fs";
|
|
34299
|
-
import { join as
|
|
34439
|
+
import { join as join50, resolve as resolve28 } from "node:path";
|
|
34300
34440
|
import { open as open5 } from "node:fs/promises";
|
|
34301
34441
|
var recentSeals = /* @__PURE__ */ new Map();
|
|
34302
34442
|
function rememberSeal(root, integrity, files) {
|
|
@@ -34310,7 +34450,7 @@ function generationFiles(root) {
|
|
|
34310
34450
|
if (realpathSync14(root) !== root) throw new Error("TRAVEL_GENERATION_INTEGRITY");
|
|
34311
34451
|
const visit = (path37) => {
|
|
34312
34452
|
if (path37 === ".runtime-publication-receipt.json") return;
|
|
34313
|
-
const file2 =
|
|
34453
|
+
const file2 = join50(root, path37), stat3 = lstatSync19(file2, { bigint: true });
|
|
34314
34454
|
if (stat3.isSymbolicLink()) throw new Error("TRAVEL_GENERATION_INTEGRITY");
|
|
34315
34455
|
if (stat3.isDirectory()) {
|
|
34316
34456
|
for (const name of readdirSync12(file2).sort()) visit(path37 ? path37 + "/" + name : name);
|
|
@@ -34327,7 +34467,7 @@ function runtimeGenerationIntegrity(directory2) {
|
|
|
34327
34467
|
const root = resolve28(directory2), result = [], buffer = Buffer.allocUnsafe(1024 * 1024);
|
|
34328
34468
|
const files = generationFiles(root);
|
|
34329
34469
|
for (const { path: path37, stat: before } of files) {
|
|
34330
|
-
const file2 =
|
|
34470
|
+
const file2 = join50(root, path37);
|
|
34331
34471
|
const fd = openSync18(file2, constants11.O_RDONLY | (constants11.O_NOFOLLOW ?? 0)), hash12 = createHash36("sha256");
|
|
34332
34472
|
let bytes = 0;
|
|
34333
34473
|
try {
|
|
@@ -34351,7 +34491,7 @@ async function runtimeGenerationIntegrityAsync(directory2) {
|
|
|
34351
34491
|
const root = resolve28(directory2), result = [], buffer = Buffer.allocUnsafe(1024 * 1024);
|
|
34352
34492
|
const files = generationFiles(root);
|
|
34353
34493
|
for (const { path: path37, stat: before } of files) {
|
|
34354
|
-
const file2 =
|
|
34494
|
+
const file2 = join50(root, path37), handle = await open5(file2, constants11.O_RDONLY | (constants11.O_NOFOLLOW ?? 0)), hash12 = createHash36("sha256");
|
|
34355
34495
|
let bytes = 0;
|
|
34356
34496
|
try {
|
|
34357
34497
|
while (true) {
|
|
@@ -34389,14 +34529,14 @@ async function verifyRuntimeGenerationIntegrityAsync(directory2, expected) {
|
|
|
34389
34529
|
init_key_service_store();
|
|
34390
34530
|
import { DatabaseSync as DatabaseSync21 } from "node:sqlite";
|
|
34391
34531
|
import { createHash as createHash39, randomUUID as randomUUID17 } from "node:crypto";
|
|
34392
|
-
import { existsSync as existsSync31, realpathSync as realpathSync16, renameSync as renameSync11, unlinkSync as unlinkSync11, writeFileSync as
|
|
34393
|
-
import { join as
|
|
34532
|
+
import { existsSync as existsSync31, realpathSync as realpathSync16, renameSync as renameSync11, unlinkSync as unlinkSync11, writeFileSync as writeFileSync28 } from "node:fs";
|
|
34533
|
+
import { join as join53, resolve as resolve30 } from "node:path";
|
|
34394
34534
|
|
|
34395
34535
|
// src/continuity/recovery-deletion-overlay.ts
|
|
34396
34536
|
import { DatabaseSync as DatabaseSync20 } from "node:sqlite";
|
|
34397
34537
|
import { createHash as createHash38, randomUUID as randomUUID16 } from "node:crypto";
|
|
34398
|
-
import { existsSync as existsSync30, realpathSync as realpathSync15, renameSync as renameSync10, unlinkSync as unlinkSync10, writeFileSync as
|
|
34399
|
-
import { dirname as dirname20, join as
|
|
34538
|
+
import { existsSync as existsSync30, realpathSync as realpathSync15, renameSync as renameSync10, unlinkSync as unlinkSync10, writeFileSync as writeFileSync27 } from "node:fs";
|
|
34539
|
+
import { dirname as dirname20, join as join52, resolve as resolve29 } from "node:path";
|
|
34400
34540
|
init_key_service_store();
|
|
34401
34541
|
init_recovery_deletion_sources();
|
|
34402
34542
|
init_recovery_deletion();
|
|
@@ -34417,8 +34557,8 @@ import { DatabaseSync as DatabaseSync19 } from "node:sqlite";
|
|
|
34417
34557
|
import { createHash as createHash37 } from "node:crypto";
|
|
34418
34558
|
import { gunzipSync as gunzipSync2 } from "node:zlib";
|
|
34419
34559
|
import { isUtf8 } from "node:buffer";
|
|
34420
|
-
import { rmSync as rmSync4, writeFileSync as
|
|
34421
|
-
import { join as
|
|
34560
|
+
import { rmSync as rmSync4, writeFileSync as writeFileSync26, existsSync as existsSync29, unlinkSync as unlinkSync9 } from "node:fs";
|
|
34561
|
+
import { join as join51, dirname as dirname19 } from "node:path";
|
|
34422
34562
|
init_sqlite_replication();
|
|
34423
34563
|
init_key_service_store();
|
|
34424
34564
|
init_attachments();
|
|
@@ -34565,7 +34705,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
|
|
|
34565
34705
|
for (const tree of options.manifest.profile.trees.filter((tree2) => tree2.kind === "file")) {
|
|
34566
34706
|
for (const file2 of options.manifest.trees.find((t) => t.id === tree.id).files) {
|
|
34567
34707
|
if (currentDebugCaches.has(file2.path)) {
|
|
34568
|
-
const path38 =
|
|
34708
|
+
const path38 = join51(options.root, "trees", tree.id, file2.path);
|
|
34569
34709
|
if (existsSync29(path38)) {
|
|
34570
34710
|
check();
|
|
34571
34711
|
unlinkSync9(path38);
|
|
@@ -34576,7 +34716,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
|
|
|
34576
34716
|
continue;
|
|
34577
34717
|
}
|
|
34578
34718
|
if (!file2.path.startsWith("mem7/spool/") || !spoolNames.has(file2.path.slice("mem7/spool/".length))) continue;
|
|
34579
|
-
const path37 =
|
|
34719
|
+
const path37 = join51(options.root, "trees", tree.id, file2.path), raw = readPrivateFile(path37, 64 * 1024 * 1024);
|
|
34580
34720
|
bytes += raw.length;
|
|
34581
34721
|
if (bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
|
|
34582
34722
|
if (!isUtf8(raw)) throw new Error("RECOVERY_OVERLAY_INTAKE_ENCODING");
|
|
@@ -34592,7 +34732,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
|
|
|
34592
34732
|
}).join("");
|
|
34593
34733
|
if (!removed) continue;
|
|
34594
34734
|
check();
|
|
34595
|
-
|
|
34735
|
+
writeFileSync26(path37, retained, { flush: true });
|
|
34596
34736
|
const cursor2 = path37 + ".cursor";
|
|
34597
34737
|
if (file2.path === "mem7/spool/intake.processing.jsonl" && existsSync29(cursor2)) unlinkSync9(cursor2);
|
|
34598
34738
|
await syncDirectory(dirname19(path37));
|
|
@@ -34607,7 +34747,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
|
|
|
34607
34747
|
const metadataDb = [...options.databases].filter(([, db3]) => readSchemaVersion(db3)?.component === "session-events");
|
|
34608
34748
|
if (metadataDb.length !== 1) throw new Error("RECOVERY_OVERLAY_SESSION_PROVENANCE");
|
|
34609
34749
|
const [databaseId, db2] = metadataDb[0];
|
|
34610
|
-
const metadata4 = parse(readPrivateFile(
|
|
34750
|
+
const metadata4 = parse(readPrivateFile(join51(options.root, "trees", tree.id, "manifest.json"), 1024 * 1024).toString());
|
|
34611
34751
|
const binding = normalizeBinding({ ...options.manifest.profile.identity, baselineId: options.manifest.profile.baselineId, epoch: options.manifest.profile.epoch, databaseId });
|
|
34612
34752
|
if (metadata4.format !== "engine7-session-events-publication-v1" || metadata4.databaseId !== databaseId || JSON.stringify(metadata4.binding) !== JSON.stringify(binding) || JSON.stringify(metadata4.head) !== JSON.stringify(options.manifest.databases.find((d) => d.databaseId === databaseId)?.head)) throw new Error("RECOVERY_OVERLAY_SESSION_PROVENANCE");
|
|
34613
34753
|
if (readSchemaVersion(db2)?.version !== 1) throw new Error("RECOVERY_OVERLAY_SCHEMA");
|
|
@@ -34701,8 +34841,8 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
|
|
|
34701
34841
|
}
|
|
34702
34842
|
}
|
|
34703
34843
|
if (!updates.length) continue;
|
|
34704
|
-
const directory2 =
|
|
34705
|
-
const copy = new DatabaseSync19(
|
|
34844
|
+
const directory2 = join51(options.root, "sessions", tree.id);
|
|
34845
|
+
const copy = new DatabaseSync19(join51(directory2, ".continuity/session-events.db"), { readOnly: true });
|
|
34706
34846
|
try {
|
|
34707
34847
|
validateRecoveryDatabase(copy, options.manifest, databaseId, "replica");
|
|
34708
34848
|
} finally {
|
|
@@ -34754,8 +34894,8 @@ var evidenceRow = (row) => Object.fromEntries(Object.entries(row).map(([key2, va
|
|
|
34754
34894
|
var applyRecoveryDeletionRuntimeCopies = (options) => deletionOverlay(options, true);
|
|
34755
34895
|
async function deletionOverlay(options, runtimeCopies) {
|
|
34756
34896
|
const manifest = normalizePublication(options.manifest), root = resolve29(options.snapshot), digest7 = publicationDigest(manifest);
|
|
34757
|
-
if (root !== options.snapshot || realpathSync15(root) !== root || existsSync30(
|
|
34758
|
-
const guard = JSON.parse(readPrivateFile(
|
|
34897
|
+
if (root !== options.snapshot || realpathSync15(root) !== root || existsSync30(join52(root, ".travel-active.json"))) throw new Error("RECOVERY_OVERLAY_ISOLATION_REQUIRED");
|
|
34898
|
+
const guard = JSON.parse(readPrivateFile(join52(root, ".travel-restored.json"), 1024 * 1024).toString());
|
|
34759
34899
|
if (guard.activationAllowed !== false) throw new Error("RECOVERY_OVERLAY_ISOLATION_REQUIRED");
|
|
34760
34900
|
if (!same4(manifest.profile.identity, { tenantId: options.principal.tenantId, companionId: options.principal.companionId, seatId: options.principal.seatId })) throw new Error("RECOVERY_IDENTITY_MISMATCH");
|
|
34761
34901
|
const before = await options.authority.status(options.principal), floor = before.deletionWatermark;
|
|
@@ -34783,7 +34923,7 @@ async function deletionOverlay(options, runtimeCopies) {
|
|
|
34783
34923
|
const deletions = await options.authority.deletionsSince(options.principal, 0);
|
|
34784
34924
|
if (deletions.length !== floor || deletions.some((d, i) => d.watermark !== i + 1)) throw new Error("RECOVERY_OVERLAY_DELETION_LOG_INCOMPLETE");
|
|
34785
34925
|
await check();
|
|
34786
|
-
const logDigest = sha8(JSON.stringify(deletions)), receiptFile =
|
|
34926
|
+
const logDigest = sha8(JSON.stringify(deletions)), receiptFile = join52(root, ".runtime-publication-receipt.json");
|
|
34787
34927
|
const original = JSON.parse(readPrivateFile(receiptFile, 4 * 1024 * 1024).toString());
|
|
34788
34928
|
if (original.format !== "engine7-runtime-publication-restore-v1" || original.activationAllowed !== false || !same4(original.profile, manifest.profile) || !same4(original.databases, manifest.databases) || original.receipt?.digest !== digest7 || original.receipt.sequence !== manifest.sequence || original.receipt.state !== "PUBLISHED") throw new Error("RECOVERY_OVERLAY_ORIGINAL_PROOF");
|
|
34789
34929
|
verifyRuntimeGenerationIntegrity(root, original.integrity);
|
|
@@ -34810,7 +34950,7 @@ async function deletionOverlay(options, runtimeCopies) {
|
|
|
34810
34950
|
let memory, capture2 = false;
|
|
34811
34951
|
try {
|
|
34812
34952
|
for (const d of manifest.databases) {
|
|
34813
|
-
const db3 = new DatabaseSync20(
|
|
34953
|
+
const db3 = new DatabaseSync20(join52(root, "databases", d.databaseId + ".sqlite"), { readOnly: d.databaseId !== "memory" && (!runtimeCopies || d.databaseId !== "sessions") });
|
|
34814
34954
|
handles.push(db3);
|
|
34815
34955
|
databases.set(d.databaseId, db3);
|
|
34816
34956
|
validateRecoveryDatabase(db3, manifest, d.databaseId, "replica");
|
|
@@ -34885,7 +35025,7 @@ async function deletionOverlay(options, runtimeCopies) {
|
|
|
34885
35025
|
if (!blocked2.length) continue;
|
|
34886
35026
|
const matches = manifest.profile.trees.filter((t) => t.kind === "file" && manifest.trees.find((tree) => tree.id === t.id).files.some((file3) => file3.path === "mem7/" + path37));
|
|
34887
35027
|
if (matches.length !== 1) throw new Error("RECOVERY_OVERLAY_FILE_PROVENANCE");
|
|
34888
|
-
const file2 =
|
|
35028
|
+
const file2 = join52(root, "trees", matches[0].id, "mem7", path37);
|
|
34889
35029
|
let text2 = readPrivateFile(file2, 16 * 1024 * 1024).toString();
|
|
34890
35030
|
for (const row of blocked2) {
|
|
34891
35031
|
const body = JSON.parse(String(row.payload_json)), start = "<!-- entry:" + row.entry_id + " -->", end = "<!-- /entry:" + row.entry_id + " -->";
|
|
@@ -34902,7 +35042,7 @@ async function deletionOverlay(options, runtimeCopies) {
|
|
|
34902
35042
|
const empty = text2.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "").trim() === "";
|
|
34903
35043
|
await check();
|
|
34904
35044
|
if (empty) unlinkSync10(file2);
|
|
34905
|
-
else
|
|
35045
|
+
else writeFileSync27(file2, text2, { flush: true });
|
|
34906
35046
|
await syncDirectory(dirname20(file2));
|
|
34907
35047
|
await check();
|
|
34908
35048
|
removedFiles.push("trees/" + matches[0].id + "/mem7/" + path37);
|
|
@@ -34911,7 +35051,7 @@ async function deletionOverlay(options, runtimeCopies) {
|
|
|
34911
35051
|
await check();
|
|
34912
35052
|
if (!lance) throw new Error("RECOVERY_OVERLAY_LANCE_UNAVAILABLE");
|
|
34913
35053
|
for (const tree of manifest.profile.trees.filter((t) => t.kind === "vector")) {
|
|
34914
|
-
const connection = await lance.connect(
|
|
35054
|
+
const connection = await lance.connect(join52(root, "lance", tree.id));
|
|
34915
35055
|
await check();
|
|
34916
35056
|
try {
|
|
34917
35057
|
for (const head of db2.prepare("SELECT h.*,s.owner_id,s.app_id,s.project_id FROM memory_vector_heads h JOIN memory_scopes s USING(scope_id)").all()) {
|
|
@@ -34960,9 +35100,9 @@ async function deletionOverlay(options, runtimeCopies) {
|
|
|
34960
35100
|
remaining: ["runtime copy visibility and queue cleanup", "normal activation"]
|
|
34961
35101
|
};
|
|
34962
35102
|
const next = { ...original, originalIntegrity: original.originalIntegrity ?? original.integrity, deletionOverlay: proof, integrity: runtimeGenerationIntegrity(root) };
|
|
34963
|
-
const temporary =
|
|
35103
|
+
const temporary = join52(root, ".runtime-publication-receipt-" + randomUUID16());
|
|
34964
35104
|
try {
|
|
34965
|
-
|
|
35105
|
+
writeFileSync27(temporary, JSON.stringify(next), { mode: 384, flag: "wx", flush: true });
|
|
34966
35106
|
await check();
|
|
34967
35107
|
renameSync10(temporary, receiptFile);
|
|
34968
35108
|
await syncDirectory(root);
|
|
@@ -34983,9 +35123,9 @@ var sha9 = (value2) => createHash39("sha256").update(value2).digest("hex");
|
|
|
34983
35123
|
var format = "engine7-current-h-deletion-visibility-v1";
|
|
34984
35124
|
function receipt(options) {
|
|
34985
35125
|
const root = resolve30(options.snapshot);
|
|
34986
|
-
if (root !== options.snapshot || realpathSync16(root) !== root || existsSync31(
|
|
35126
|
+
if (root !== options.snapshot || realpathSync16(root) !== root || existsSync31(join53(root, ".travel-active.json")) || JSON.parse(readPrivateFile(join53(root, ".travel-restored.json"), 1024 * 1024).toString()).activationAllowed !== false)
|
|
34987
35127
|
throw new Error("RECOVERY_OVERLAY_ISOLATION_REQUIRED");
|
|
34988
|
-
return JSON.parse(readPrivateFile(
|
|
35128
|
+
return JSON.parse(readPrivateFile(join53(root, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
|
|
34989
35129
|
}
|
|
34990
35130
|
async function effectsCheckAsync(options, floor) {
|
|
34991
35131
|
const effects2 = await options.gateway.preparationEvidence(options.principal);
|
|
@@ -34993,7 +35133,7 @@ async function effectsCheckAsync(options, floor) {
|
|
|
34993
35133
|
}
|
|
34994
35134
|
function validateAuxiliaryState(options) {
|
|
34995
35135
|
for (const id2 of options.manifest.profile.databaseIds) {
|
|
34996
|
-
const db2 = new DatabaseSync21(
|
|
35136
|
+
const db2 = new DatabaseSync21(join53(options.snapshot, "databases", id2 + ".sqlite"), { readOnly: true });
|
|
34997
35137
|
try {
|
|
34998
35138
|
const component = readSchemaVersion(db2)?.component;
|
|
34999
35139
|
if (component === "mem7") continue;
|
|
@@ -35015,7 +35155,7 @@ function validateAuxiliaryState(options) {
|
|
|
35015
35155
|
const runnable = /^(?:tasks|todos|steer|cron|topics|topics-history|calendar|proactive|plans|runtime)(?:\/|$)|^(?:goals\.json|goal-events\.jsonl|SESSION-STATE\.md)$/;
|
|
35016
35156
|
for (const tree of options.manifest.profile.trees.filter((tree2) => tree2.kind === "file")) {
|
|
35017
35157
|
for (const file2 of options.manifest.trees.find((t) => t.id === tree.id).files) {
|
|
35018
|
-
if (runnable.test(file2.path) && existsSync31(
|
|
35158
|
+
if (runnable.test(file2.path) && existsSync31(join53(options.snapshot, "trees", tree.id, file2.path))) throw new Error("RECOVERY_VISIBILITY_AUXILIARY_PENDING");
|
|
35019
35159
|
}
|
|
35020
35160
|
}
|
|
35021
35161
|
}
|
|
@@ -35030,7 +35170,7 @@ async function completeCurrentHDeletionVisibility(options) {
|
|
|
35030
35170
|
const next = receipt(options), overlay = next.deletionOverlay;
|
|
35031
35171
|
if (overlay?.runtimeCopies?.format !== "engine7-recovery-runtime-copy-cleanup-v6" || !next.originalIntegrity)
|
|
35032
35172
|
throw new Error("RECOVERY_VISIBILITY_PROOF");
|
|
35033
|
-
const locations = validateRuntimeActivationLayout(
|
|
35173
|
+
const locations = validateRuntimeActivationLayout(join53(options.snapshot, "candidate"), options.manifest, options.layout);
|
|
35034
35174
|
validateRuntimeActivationSnapshot(options.snapshot, options.manifest, locations);
|
|
35035
35175
|
validateAuxiliaryState(options);
|
|
35036
35176
|
verifyRuntimeGenerationIntegrity(options.snapshot, next.integrity);
|
|
@@ -35044,9 +35184,9 @@ async function completeCurrentHDeletionVisibility(options) {
|
|
|
35044
35184
|
originalIntegrityDigest: sha9(JSON.stringify(next.originalIntegrity)),
|
|
35045
35185
|
activationAllowed: false
|
|
35046
35186
|
};
|
|
35047
|
-
const file2 =
|
|
35187
|
+
const file2 = join53(options.snapshot, ".runtime-publication-receipt.json"), temporary = join53(options.snapshot, ".runtime-publication-receipt-" + randomUUID17());
|
|
35048
35188
|
try {
|
|
35049
|
-
|
|
35189
|
+
writeFileSync28(temporary, JSON.stringify({ ...next, deletionVisibility: proof }), { mode: 384, flag: "wx", flush: true });
|
|
35050
35190
|
await check();
|
|
35051
35191
|
await effectsCheckAsync(options, floor);
|
|
35052
35192
|
renameSync11(temporary, file2);
|
|
@@ -35094,7 +35234,7 @@ function validateRuntimeActivationLayout(destination, raw, layout) {
|
|
|
35094
35234
|
const paths = /* @__PURE__ */ new Set();
|
|
35095
35235
|
for (const [databaseId, path37] of Object.entries(layout.databases)) {
|
|
35096
35236
|
validatePublicationPath(path37);
|
|
35097
|
-
const place = sqliteStoreLocation(
|
|
35237
|
+
const place = sqliteStoreLocation(join54(destination, path37));
|
|
35098
35238
|
if (!place || !isWithin(destination, place.stateDir) || paths.has(path37)) throw new Error("TRAVEL_ACTIVATION_LAYOUT");
|
|
35099
35239
|
locations.set(databaseId, place);
|
|
35100
35240
|
paths.add(path37);
|
|
@@ -35139,7 +35279,7 @@ function validateRuntimeActivationLayout(destination, raw, layout) {
|
|
|
35139
35279
|
function validateRuntimeActivationSnapshot(snapshot, manifest, locations) {
|
|
35140
35280
|
const sourceRoots = [];
|
|
35141
35281
|
for (const d of manifest.databases) {
|
|
35142
|
-
const db2 = new DatabaseSync22(
|
|
35282
|
+
const db2 = new DatabaseSync22(join54(snapshot, "databases", d.databaseId + ".sqlite"), { readOnly: true });
|
|
35143
35283
|
try {
|
|
35144
35284
|
validateRecoveryDatabase(db2, manifest, d.databaseId, "replica", void 0, false);
|
|
35145
35285
|
const place = locations.get(d.databaseId);
|
|
@@ -35165,7 +35305,7 @@ async function copyTree(from, to, skipControl = false) {
|
|
|
35165
35305
|
await mkdir3(to, { recursive: true, mode: 448 });
|
|
35166
35306
|
for (const name of await readdir2(from)) {
|
|
35167
35307
|
if (skipControl && (name.startsWith(".") || name === "databases" || name === "trees" || name === "lance")) continue;
|
|
35168
|
-
await copyTree(
|
|
35308
|
+
await copyTree(join54(from, name), join54(to, name));
|
|
35169
35309
|
}
|
|
35170
35310
|
}
|
|
35171
35311
|
async function activateRuntimeGeneration(options) {
|
|
@@ -35192,14 +35332,14 @@ async function activateRuntimeGeneration(options) {
|
|
|
35192
35332
|
await checkDeletion();
|
|
35193
35333
|
if (!await (options.verifyDirectory ?? verifyRuntimeDirectory)(dirname21(destination))) throw new Error("TRAVEL_ACTIVATION_DIRECTORY");
|
|
35194
35334
|
if (realpathSync17(snapshot) !== snapshot || realpathSync17(dirname21(destination)) !== dirname21(destination) || existsSync32(destination)) throw new Error("TRAVEL_ACTIVATION_NEW_DIRECTORY_REQUIRED");
|
|
35195
|
-
const proof = JSON.parse(readPrivateFile(
|
|
35335
|
+
const proof = JSON.parse(readPrivateFile(join54(snapshot, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
|
|
35196
35336
|
if (proof.format !== "engine7-runtime-publication-restore-v1" || !same6(proof.profile, manifest.profile) || proof.receipt?.digest !== digest7 || proof.receipt?.sequence !== manifest.sequence || proof.receipt?.state !== "PUBLISHED" || proof.activationAllowed !== false || !same6(proof.databases, manifest.databases)) throw new Error("TRAVEL_ACTIVATION_RECEIPT");
|
|
35197
35337
|
await verifyRuntimeGenerationIntegrityAsync(snapshot, proof.integrity);
|
|
35198
35338
|
const locations = validateRuntimeActivationLayout(destination, manifest, options.layout);
|
|
35199
35339
|
const sourceRoots = validateRuntimeActivationSnapshot(snapshot, manifest, locations);
|
|
35200
35340
|
const profile = normalizePublicationProfile({ ...manifest.profile, baselineId: options.baselineId, epoch: options.permit.epoch });
|
|
35201
|
-
|
|
35202
|
-
|
|
35341
|
+
mkdirSync25(destination, { mode: 448 });
|
|
35342
|
+
writeFileSync29(join54(destination, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
|
|
35203
35343
|
const runtime = new RuntimeAuthority({ stateDir: destination, identity: identity3, nodeId: options.permit.nodeId, bootId: options.permit.bootId, publicKey: options.authority.publicKey, allowedTools: options.allowedTools, initialize: true });
|
|
35204
35344
|
runtime.acceptPermit(options.permit, options.requestStartedAt);
|
|
35205
35345
|
runtime.advanceDeletionFloor(options.permit.deletionWatermark);
|
|
@@ -35208,16 +35348,16 @@ async function activateRuntimeGeneration(options) {
|
|
|
35208
35348
|
for (const tree of manifest.profile.trees) {
|
|
35209
35349
|
await checkDeletion();
|
|
35210
35350
|
await options.authority.assertPermit(runtime.assert("CONTROL"), "CONTROL");
|
|
35211
|
-
const source = tree.kind === "file" ?
|
|
35212
|
-
await copyTree(source,
|
|
35351
|
+
const source = tree.kind === "file" ? join54(snapshot, "trees", tree.id) : join54(snapshot, tree.kind === "vector" ? "lance" : "sessions", tree.id);
|
|
35352
|
+
await copyTree(source, join54(destination, options.layout.trees[tree.id]), tree.kind === "session");
|
|
35213
35353
|
}
|
|
35214
35354
|
for (const d of manifest.databases) {
|
|
35215
35355
|
await checkDeletion();
|
|
35216
35356
|
await options.authority.assertPermit(runtime.assert("CONTROL"), "CONTROL");
|
|
35217
|
-
const path37 =
|
|
35218
|
-
|
|
35357
|
+
const path37 = join54(destination, options.layout.databases[d.databaseId]), place = locations.get(d.databaseId);
|
|
35358
|
+
mkdirSync25(dirname21(path37), { recursive: true, mode: 448 });
|
|
35219
35359
|
try {
|
|
35220
|
-
await copyNativeFile(
|
|
35360
|
+
await copyNativeFile(join54(snapshot, "databases", d.databaseId + ".sqlite"), path37, copyFlags);
|
|
35221
35361
|
} catch (error) {
|
|
35222
35362
|
if (error.code !== "EEXIST") throw error;
|
|
35223
35363
|
}
|
|
@@ -35246,11 +35386,11 @@ async function activateRuntimeGeneration(options) {
|
|
|
35246
35386
|
await options.authority.assertPermit(runtime.assert("CONTROL"), "CONTROL");
|
|
35247
35387
|
await verifyRuntimeGenerationIntegrityAsync(snapshot, proof.integrity);
|
|
35248
35388
|
runtime.advanceDeletionFloor(options.permit.deletionWatermark);
|
|
35249
|
-
|
|
35389
|
+
writeFileSync29(join54(destination, ".travel-active.json"), JSON.stringify(receipt2), { mode: 384, flag: "wx", flush: true });
|
|
35250
35390
|
await syncDirectory(destination);
|
|
35251
35391
|
await checkDeletion();
|
|
35252
35392
|
await options.authority.assertPermit(runtime.assert("CONTROL"), "CONTROL");
|
|
35253
|
-
unlinkSync12(
|
|
35393
|
+
unlinkSync12(join54(destination, ".travel-restored.json"));
|
|
35254
35394
|
await syncDirectory(destination);
|
|
35255
35395
|
return { receipt: receipt2, profile, runtime };
|
|
35256
35396
|
} catch (error) {
|
|
@@ -35269,7 +35409,7 @@ init_key_service_store();
|
|
|
35269
35409
|
import { fork } from "node:child_process";
|
|
35270
35410
|
import { DatabaseSync as DatabaseSync23 } from "node:sqlite";
|
|
35271
35411
|
import { closeSync as closeSync18, lstatSync as lstatSync20, openSync as openSync19, readFileSync as readFileSync29, realpathSync as realpathSync18 } from "node:fs";
|
|
35272
|
-
import { isAbsolute as isAbsolute6, join as
|
|
35412
|
+
import { isAbsolute as isAbsolute6, join as join55 } from "node:path";
|
|
35273
35413
|
import { createHash as createHash40, randomUUID as randomUUID18 } from "node:crypto";
|
|
35274
35414
|
|
|
35275
35415
|
// src/continuity/engine-control.ts
|
|
@@ -35336,7 +35476,7 @@ var SupervisedRuntimeProcess = class {
|
|
|
35336
35476
|
this.timeout = options.timeoutMs ?? 6e4;
|
|
35337
35477
|
if (!Number.isSafeInteger(this.timeout) || this.timeout < 100 || this.timeout > 6e5) throw new Error("TRAVEL_PROCESS_CONFIG");
|
|
35338
35478
|
preparePrivateDirectory(options.directory);
|
|
35339
|
-
const ownerFile =
|
|
35479
|
+
const ownerFile = join55(options.directory, "process-owner.sqlite");
|
|
35340
35480
|
preparePrivateDatabase(ownerFile);
|
|
35341
35481
|
this.owner = new DatabaseSync23(ownerFile);
|
|
35342
35482
|
try {
|
|
@@ -35346,7 +35486,7 @@ var SupervisedRuntimeProcess = class {
|
|
|
35346
35486
|
throw new Error("TRAVEL_PROCESS_BUSY");
|
|
35347
35487
|
}
|
|
35348
35488
|
try {
|
|
35349
|
-
const file2 =
|
|
35489
|
+
const file2 = join55(options.directory, "process.sqlite");
|
|
35350
35490
|
preparePrivateDatabase(file2);
|
|
35351
35491
|
this.db = new DatabaseSync23(file2);
|
|
35352
35492
|
this.db.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS generations(binding TEXT PRIMARY KEY,entry_hash TEXT NOT NULL);CREATE TABLE IF NOT EXISTS recovery_continuations(binding TEXT PRIMARY KEY,entry_hash TEXT NOT NULL,authority_boot_id TEXT NOT NULL,state TEXT NOT NULL CHECK(state IN ('SUSPENDED','RESUMING','RESUMED')))");
|
|
@@ -35396,7 +35536,7 @@ var SupervisedRuntimeProcess = class {
|
|
|
35396
35536
|
this.expectedAuthorityBootId = permit.authorityBootId;
|
|
35397
35537
|
this.expected = binding;
|
|
35398
35538
|
this.plannedExit = false;
|
|
35399
|
-
const log =
|
|
35539
|
+
const log = join55(this.options.directory, "engine-" + randomUUID18() + ".log"), fd = openSync19(log, "wx", 384);
|
|
35400
35540
|
let child;
|
|
35401
35541
|
try {
|
|
35402
35542
|
child = fork(this.options.entry, [this.options.configFile], {
|
|
@@ -35568,13 +35708,13 @@ var SupervisedRuntimeProcess = class {
|
|
|
35568
35708
|
|
|
35569
35709
|
// src/continuity/runtime-publication-restore.ts
|
|
35570
35710
|
import { DatabaseSync as DatabaseSync25 } from "node:sqlite";
|
|
35571
|
-
import { mkdirSync as
|
|
35572
|
-
import { join as
|
|
35711
|
+
import { mkdirSync as mkdirSync27, writeFileSync as writeFileSync31 } from "node:fs";
|
|
35712
|
+
import { join as join57, resolve as resolve33 } from "node:path";
|
|
35573
35713
|
|
|
35574
35714
|
// src/continuity/publication-files.ts
|
|
35575
35715
|
import { DatabaseSync as DatabaseSync24 } from "node:sqlite";
|
|
35576
|
-
import { lstatSync as lstatSync21, readdirSync as readdirSync13, realpathSync as realpathSync19, mkdirSync as
|
|
35577
|
-
import { join as
|
|
35716
|
+
import { lstatSync as lstatSync21, readdirSync as readdirSync13, realpathSync as realpathSync19, mkdirSync as mkdirSync26, writeFileSync as writeFileSync30, chmodSync as chmodSync7, openSync as openSync20, closeSync as closeSync19, fsyncSync as fsyncSync11 } from "node:fs";
|
|
35717
|
+
import { join as join56, resolve as resolve32, dirname as dirname22 } from "node:path";
|
|
35578
35718
|
async function restorePublication(options) {
|
|
35579
35719
|
const { receiver } = options, status = await receiver.status(false);
|
|
35580
35720
|
if (!status.published || !status.dataReady) throw new Error("PUBLICATION_NOT_READY");
|
|
@@ -35584,13 +35724,13 @@ async function restorePublication(options) {
|
|
|
35584
35724
|
if (realpathSync19(dirname22(destination)) !== dirname22(destination)) throw new Error("SYMLINK_REFUSED");
|
|
35585
35725
|
if (isWithin(receiver.objects.directory, destination) || isWithin(destination, receiver.objects.directory)) throw new Error("PUBLICATION_OVERLAPPING_PATHS");
|
|
35586
35726
|
try {
|
|
35587
|
-
|
|
35727
|
+
mkdirSync26(destination, { mode: 448 });
|
|
35588
35728
|
} catch (error) {
|
|
35589
35729
|
if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
|
|
35590
35730
|
throw error;
|
|
35591
35731
|
}
|
|
35592
35732
|
await syncDirectory(dirname22(destination));
|
|
35593
|
-
|
|
35733
|
+
writeFileSync30(join56(destination, ".travel-restored.json"), JSON.stringify({
|
|
35594
35734
|
format: "engine7-publication-restore-v1",
|
|
35595
35735
|
activationAllowed: false,
|
|
35596
35736
|
sequence: manifest.sequence,
|
|
@@ -35602,14 +35742,14 @@ async function restorePublication(options) {
|
|
|
35602
35742
|
const missing = [];
|
|
35603
35743
|
for (let current2 = path37; isWithin(destination, current2) && !created.has(current2); current2 = dirname22(current2)) missing.push(current2);
|
|
35604
35744
|
for (const current2 of missing.reverse()) {
|
|
35605
|
-
|
|
35745
|
+
mkdirSync26(current2, { mode: 448 });
|
|
35606
35746
|
created.add(current2);
|
|
35607
35747
|
}
|
|
35608
35748
|
};
|
|
35609
|
-
directory2(
|
|
35610
|
-
directory2(
|
|
35749
|
+
directory2(join56(destination, "databases"));
|
|
35750
|
+
directory2(join56(destination, "trees"));
|
|
35611
35751
|
for (const item of manifest.databases) {
|
|
35612
|
-
const path37 =
|
|
35752
|
+
const path37 = join56(destination, "databases", item.databaseId + ".sqlite");
|
|
35613
35753
|
await snapshotNativeDatabase(options.databases[item.databaseId], path37);
|
|
35614
35754
|
chmodSync7(path37, 384);
|
|
35615
35755
|
const copy = new DatabaseSync24(path37, { readOnly: true });
|
|
@@ -35631,11 +35771,11 @@ async function restorePublication(options) {
|
|
|
35631
35771
|
}
|
|
35632
35772
|
const files = [];
|
|
35633
35773
|
for (const tree of manifest.trees) {
|
|
35634
|
-
const root =
|
|
35774
|
+
const root = join56(destination, "trees", tree.id);
|
|
35635
35775
|
directory2(root);
|
|
35636
|
-
for (const path37 of tree.directories) directory2(
|
|
35776
|
+
for (const path37 of tree.directories) directory2(join56(root, path37));
|
|
35637
35777
|
for (const file2 of tree.files) {
|
|
35638
|
-
const path37 =
|
|
35778
|
+
const path37 = join56(root, file2.path);
|
|
35639
35779
|
directory2(dirname22(path37));
|
|
35640
35780
|
files.push({ content: file2.content, destination: path37, mode: file2.mode });
|
|
35641
35781
|
}
|
|
@@ -35649,7 +35789,7 @@ async function restorePublication(options) {
|
|
|
35649
35789
|
const after = await receiver.status(false);
|
|
35650
35790
|
if (!after.dataReady || after.published?.digest !== status.published.digest) throw new Error("PUBLICATION_CONCURRENT_CHANGE");
|
|
35651
35791
|
for (const path37 of [...created].reverse()) await syncDirectory(path37);
|
|
35652
|
-
if (!options.deferReceipt)
|
|
35792
|
+
if (!options.deferReceipt) writeFileSync30(join56(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
|
|
35653
35793
|
await syncDirectory(destination);
|
|
35654
35794
|
return status.published;
|
|
35655
35795
|
}
|
|
@@ -35679,17 +35819,17 @@ async function restoreRuntimePublication(options) {
|
|
|
35679
35819
|
await restorePublication({ ...options, destination, deferReceipt: true });
|
|
35680
35820
|
const lance = [], sessionStates = [];
|
|
35681
35821
|
for (const directory2 of ["lance", "sessions"]) {
|
|
35682
|
-
|
|
35822
|
+
mkdirSync27(join57(destination, directory2), { mode: 448 });
|
|
35683
35823
|
await syncDirectory(destination);
|
|
35684
35824
|
}
|
|
35685
35825
|
for (const kind of manifest.profile.trees.filter((tree) => tree.kind === "vector")) {
|
|
35686
|
-
const tree = manifest.trees.find((tree2) => tree2.id === kind.id), directory2 =
|
|
35826
|
+
const tree = manifest.trees.find((tree2) => tree2.id === kind.id), directory2 = join57(destination, "lance", tree.id);
|
|
35687
35827
|
await restoreLancePublication({ tree, objects: receiver.objects, destination: directory2 });
|
|
35688
|
-
await syncDirectory(
|
|
35828
|
+
await syncDirectory(join57(destination, "lance"));
|
|
35689
35829
|
lance.push({ treeId: tree.id, directory: `lance/${tree.id}` });
|
|
35690
35830
|
}
|
|
35691
35831
|
for (const session of sessions) {
|
|
35692
|
-
const directory2 =
|
|
35832
|
+
const directory2 = join57(destination, "sessions", session.treeId), db2 = new DatabaseSync25(join57(destination, "databases", session.databaseId + ".sqlite"), { readOnly: true });
|
|
35693
35833
|
try {
|
|
35694
35834
|
const head = db2.prepare("SELECT head,digest FROM e7_replication_control WHERE role='replica'").get();
|
|
35695
35835
|
if (head?.head !== session.head.sequence || head.digest !== session.head.digest) throw new Error("PUBLICATION_DATABASE_SNAPSHOT_MISMATCH");
|
|
@@ -35697,13 +35837,13 @@ async function restoreRuntimePublication(options) {
|
|
|
35697
35837
|
} finally {
|
|
35698
35838
|
db2.close();
|
|
35699
35839
|
}
|
|
35700
|
-
await syncDirectory(
|
|
35840
|
+
await syncDirectory(join57(destination, "sessions"));
|
|
35701
35841
|
sessionStates.push({ treeId: session.treeId, databaseId: session.databaseId, directory: `sessions/${session.treeId}` });
|
|
35702
35842
|
}
|
|
35703
35843
|
const after = await receiver.status(false);
|
|
35704
35844
|
if (!after.dataReady || after.published?.sequence !== manifest.sequence || after.published.digest !== status.published.digest) throw new Error("PUBLICATION_CONCURRENT_CHANGE");
|
|
35705
|
-
|
|
35706
|
-
|
|
35845
|
+
writeFileSync31(join57(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
|
|
35846
|
+
writeFileSync31(join57(destination, ".runtime-publication-receipt.json"), JSON.stringify({
|
|
35707
35847
|
format: "engine7-runtime-publication-restore-v1",
|
|
35708
35848
|
profile: manifest.profile,
|
|
35709
35849
|
receipt: status.published,
|
|
@@ -35718,7 +35858,7 @@ async function restoreRuntimePublication(options) {
|
|
|
35718
35858
|
}
|
|
35719
35859
|
|
|
35720
35860
|
// src/continuity/stopped-generation-recovery.ts
|
|
35721
|
-
import { join as
|
|
35861
|
+
import { join as join59 } from "node:path";
|
|
35722
35862
|
|
|
35723
35863
|
// src/continuity/runtime-generation-source.ts
|
|
35724
35864
|
init_key_service_store();
|
|
@@ -35726,7 +35866,7 @@ init_publication_objects();
|
|
|
35726
35866
|
import { DatabaseSync as DatabaseSync26 } from "node:sqlite";
|
|
35727
35867
|
import { existsSync as existsSync33, lstatSync as lstatSync22, realpathSync as realpathSync20 } from "node:fs";
|
|
35728
35868
|
import { createHash as createHash41 } from "node:crypto";
|
|
35729
|
-
import { isAbsolute as isAbsolute7, join as
|
|
35869
|
+
import { isAbsolute as isAbsolute7, join as join58, resolve as resolve34 } from "node:path";
|
|
35730
35870
|
init_sqlite_replication();
|
|
35731
35871
|
init_schema_migrations();
|
|
35732
35872
|
init_runtime_lock();
|
|
@@ -35736,10 +35876,10 @@ async function openRuntimeGenerationSource(options) {
|
|
|
35736
35876
|
for (const path37 of [options.stateDir, options.dataDirectory]) if (!isAbsolute7(path37) || resolve34(path37) !== path37) throw new Error("TRAVEL_SOURCE_PATH");
|
|
35737
35877
|
const stateDir = options.stateDir, dataDirectory = options.dataDirectory;
|
|
35738
35878
|
assertPrivateDirectory(stateDir);
|
|
35739
|
-
if (realpathSync20(stateDir) !== stateDir || realpathSync20(
|
|
35879
|
+
if (realpathSync20(stateDir) !== stateDir || realpathSync20(join58(dataDirectory, "..")) !== resolve34(dataDirectory, "..") || isWithin(stateDir, dataDirectory) || isWithin(dataDirectory, stateDir) || isWithin(stateDir, options.objects.directory)) throw new Error("TRAVEL_SOURCE_PATH");
|
|
35740
35880
|
if (options.mode !== "LIVE" && options.mode !== "SEALED") throw new Error("TRAVEL_SOURCE_MODE");
|
|
35741
|
-
if (existsSync33(
|
|
35742
|
-
const receipt2 = JSON.parse(readPrivateFile(
|
|
35881
|
+
if (existsSync33(join58(stateDir, ".travel-restored.json"))) throw new Error("TRAVEL_ACTIVATION_REQUIRED");
|
|
35882
|
+
const receipt2 = JSON.parse(readPrivateFile(join58(stateDir, ".travel-active.json"), 4 * 1024 * 1024).toString());
|
|
35743
35883
|
const profile = normalizePublicationProfile(receipt2.profile), layout = receipt2.layout;
|
|
35744
35884
|
if (receipt2.format !== "engine7-runtime-activation-v1" || receipt2.destination !== stateDir || !same7(receipt2.identity, profile.identity) || !same7(profile.identity, options.objects.identity) || receipt2.epoch !== profile.epoch || !layout || !same7(Object.keys(layout.databases).sort(), profile.databaseIds) || !same7(Object.keys(layout.trees).sort(), profile.trees.map((tree) => tree.id).sort())) throw new Error("TRAVEL_SOURCE_PROFILE");
|
|
35745
35885
|
const runtime = runtimeAuthorityFor(stateDir);
|
|
@@ -35755,7 +35895,7 @@ async function openRuntimeGenerationSource(options) {
|
|
|
35755
35895
|
if (path37 !== ".") validatePublicationPath(path37);
|
|
35756
35896
|
else if (tree.kind === "vector") throw new Error("TRAVEL_SOURCE_LAYOUT");
|
|
35757
35897
|
}
|
|
35758
|
-
const workspace =
|
|
35898
|
+
const workspace = join58(stateDir, layout.trees[workspaceTree.id]);
|
|
35759
35899
|
assertPrivateDirectory(workspace);
|
|
35760
35900
|
if (workspace === stateDir || !isWithin(stateDir, workspace) || realpathSync20(workspace) !== workspace) throw new Error("TRAVEL_SOURCE_LAYOUT");
|
|
35761
35901
|
const handles = {}, databases = {}, writableDatabases = {};
|
|
@@ -35782,7 +35922,7 @@ async function openRuntimeGenerationSource(options) {
|
|
|
35782
35922
|
for (const id2 of profile.databaseIds) {
|
|
35783
35923
|
const path37 = layout.databases[id2];
|
|
35784
35924
|
validatePublicationPath(path37);
|
|
35785
|
-
const file2 =
|
|
35925
|
+
const file2 = join58(stateDir, path37), place = sqliteStoreLocation(file2), info = lstatSync22(file2);
|
|
35786
35926
|
if (!place || !isWithin(stateDir, place.stateDir) || !info.isFile() || info.isSymbolicLink() || realpathSync20(file2) !== file2 || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error("TRAVEL_SOURCE_LAYOUT");
|
|
35787
35927
|
const db2 = new DatabaseSync26(file2, { readOnly: options.mode === "SEALED", allowExtension: options.mode === "LIVE" && place.component === "legacy-memory" });
|
|
35788
35928
|
handles[id2] = db2;
|
|
@@ -35803,14 +35943,14 @@ async function openRuntimeGenerationSource(options) {
|
|
|
35803
35943
|
const sessionTree = profile.trees.filter((tree) => tree.kind === "session");
|
|
35804
35944
|
if (sessionTree.length !== 1 || sessionTrees.length) throw new Error("TRAVEL_SOURCE_LAYOUT");
|
|
35805
35945
|
sessionTrees.push({ treeId: sessionTree[0].id, databaseId: id2 });
|
|
35806
|
-
sessionDirectories.push(
|
|
35946
|
+
sessionDirectories.push(join58(stateDir, "agents/main/sessions"));
|
|
35807
35947
|
}
|
|
35808
35948
|
}
|
|
35809
35949
|
if (sessionTrees.length !== profile.trees.filter((tree) => tree.kind === "session").length) throw new Error("TRAVEL_SOURCE_LAYOUT");
|
|
35810
|
-
const lanceStores = profile.trees.filter((tree) => tree.kind === "vector").map((tree) => ({ treeId: tree.id, directory:
|
|
35950
|
+
const lanceStores = profile.trees.filter((tree) => tree.kind === "vector").map((tree) => ({ treeId: tree.id, directory: join58(stateDir, layout.trees[tree.id]) }));
|
|
35811
35951
|
const layoutDigest = createHash41("sha256").update(JSON.stringify([stateDir, profile, layout])).digest("hex");
|
|
35812
|
-
trees = await RuntimeTreeSource.open({ directory:
|
|
35813
|
-
source = await RuntimePublicationSource.open({ directory:
|
|
35952
|
+
trees = await RuntimeTreeSource.open({ directory: join58(dataDirectory, "runtime-trees"), profile, objects: options.objects, initialize: options.initialize });
|
|
35953
|
+
source = await RuntimePublicationSource.open({ directory: join58(dataDirectory, "runtime-publications"), profile, objects: options.objects, trees, layoutDigest, initialize: options.initialize });
|
|
35814
35954
|
const capture2 = () => {
|
|
35815
35955
|
if (closed) throw new Error("TRAVEL_SOURCE_CLOSED");
|
|
35816
35956
|
return {
|
|
@@ -35826,7 +35966,7 @@ async function openRuntimeGenerationSource(options) {
|
|
|
35826
35966
|
databaseFiles: Object.values(databases).map((db2) => db2.file),
|
|
35827
35967
|
immutableDatabaseFiles: (layout.immutableDatabases ?? []).map((path37) => {
|
|
35828
35968
|
validatePublicationPath(path37);
|
|
35829
|
-
return
|
|
35969
|
+
return join58(stateDir, path37);
|
|
35830
35970
|
}),
|
|
35831
35971
|
sessionDirectories,
|
|
35832
35972
|
vectorDirectories: lanceStores.map((store) => store.directory),
|
|
@@ -35855,7 +35995,7 @@ async function preserveStoppedGeneration(options) {
|
|
|
35855
35995
|
return floor;
|
|
35856
35996
|
};
|
|
35857
35997
|
await check();
|
|
35858
|
-
archive = await RuntimeRecoveryArchive.open({ directory:
|
|
35998
|
+
archive = await RuntimeRecoveryArchive.open({ directory: join59(options.dataDirectory, "recovery"), objects: options.objects });
|
|
35859
35999
|
await check();
|
|
35860
36000
|
return await opened.source.withStoppedPreparation(capture2, async (h) => {
|
|
35861
36001
|
await check();
|
|
@@ -35881,7 +36021,7 @@ async function readStoppedRecoveryManifests(options) {
|
|
|
35881
36021
|
const opened = await openRuntimeGenerationSource({ ...options, initialize: false, mode: "SEALED" });
|
|
35882
36022
|
let archive;
|
|
35883
36023
|
try {
|
|
35884
|
-
archive = await RuntimeRecoveryArchive.open({ directory:
|
|
36024
|
+
archive = await RuntimeRecoveryArchive.open({ directory: join59(options.dataDirectory, "recovery"), objects: options.objects });
|
|
35885
36025
|
const local = await archive.read(options.localArchiveId);
|
|
35886
36026
|
if (local.kind !== "LOCAL" || JSON.stringify(local.manifest.profile) !== JSON.stringify(opened.profile) || local.manifest.sequence < options.common.sequence || local.manifest.sequence - options.common.sequence - 1 > 4094) throw new Error("RECOVERY_LOCAL_ANCESTRY_GAP");
|
|
35887
36027
|
const check = async () => {
|
|
@@ -35919,7 +36059,7 @@ async function readStoppedRecoveryManifests(options) {
|
|
|
35919
36059
|
|
|
35920
36060
|
// src/continuity/key-service-client.ts
|
|
35921
36061
|
init_key_service_store();
|
|
35922
|
-
import { request } from "node:https";
|
|
36062
|
+
import { request as request2 } from "node:https";
|
|
35923
36063
|
async function fetchTravelKey(options) {
|
|
35924
36064
|
const url = new URL(options.url);
|
|
35925
36065
|
if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) throw new Error("KEY_SERVICE_HTTPS_REQUIRED");
|
|
@@ -35935,7 +36075,7 @@ async function fetchTravelKey(options) {
|
|
|
35935
36075
|
clearTimeout(timer);
|
|
35936
36076
|
reject(error);
|
|
35937
36077
|
};
|
|
35938
|
-
const req =
|
|
36078
|
+
const req = request2(url, {
|
|
35939
36079
|
method: "POST",
|
|
35940
36080
|
ca: options.ca,
|
|
35941
36081
|
cert: options.cert,
|
|
@@ -35995,13 +36135,13 @@ init_publication_objects();
|
|
|
35995
36135
|
// src/optional/reporting/travel.ts
|
|
35996
36136
|
init_publication_objects();
|
|
35997
36137
|
import { DatabaseSync as DatabaseSync27 } from "node:sqlite";
|
|
35998
|
-
import { join as
|
|
36138
|
+
import { join as join60 } from "node:path";
|
|
35999
36139
|
function startTravelHeartbeatReporting(options) {
|
|
36000
36140
|
const interval = options.intervalMs ?? 1e4, clock2 = options.monotonicNow ?? (() => Number(process.hrtime.bigint() / 1000000n));
|
|
36001
36141
|
const setTimer = options.setTimer ?? setTimeout, clearTimer = options.clearTimer ?? clearTimeout;
|
|
36002
36142
|
if (!Number.isSafeInteger(interval) || interval < 100 || interval > 6e4 || [options.nodeId, options.bootId].some((id2) => typeof id2 !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(id2))) throw new Error("TRAVEL_REPORTING_CONFIG");
|
|
36003
36143
|
preparePrivateDirectory(options.directory);
|
|
36004
|
-
const ownerFile =
|
|
36144
|
+
const ownerFile = join60(options.directory, "heartbeat-owner.sqlite");
|
|
36005
36145
|
preparePrivateDatabase(ownerFile);
|
|
36006
36146
|
const owner = new DatabaseSync27(ownerFile);
|
|
36007
36147
|
try {
|
|
@@ -36012,7 +36152,7 @@ function startTravelHeartbeatReporting(options) {
|
|
|
36012
36152
|
}
|
|
36013
36153
|
let db2;
|
|
36014
36154
|
try {
|
|
36015
|
-
const file2 =
|
|
36155
|
+
const file2 = join60(options.directory, "heartbeat.sqlite");
|
|
36016
36156
|
preparePrivateDatabase(file2);
|
|
36017
36157
|
db2 = new DatabaseSync27(file2);
|
|
36018
36158
|
db2.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS sequences(node TEXT NOT NULL,boot TEXT NOT NULL,sequence INTEGER NOT NULL,PRIMARY KEY(node,boot))");
|
|
@@ -36143,8 +36283,8 @@ init_key_service_store();
|
|
|
36143
36283
|
|
|
36144
36284
|
// src/continuity/recovery-archive-restore.ts
|
|
36145
36285
|
import { DatabaseSync as DatabaseSync28 } from "node:sqlite";
|
|
36146
|
-
import { mkdirSync as
|
|
36147
|
-
import { dirname as dirname23, join as
|
|
36286
|
+
import { mkdirSync as mkdirSync28, writeFileSync as writeFileSync32, realpathSync as realpathSync21 } from "node:fs";
|
|
36287
|
+
import { dirname as dirname23, join as join61, resolve as resolve35 } from "node:path";
|
|
36148
36288
|
init_sqlite_replication();
|
|
36149
36289
|
async function restoreRecoveryArchive(options) {
|
|
36150
36290
|
return restoreOriginal(options);
|
|
@@ -36164,12 +36304,12 @@ async function restoreOriginal(options, original, currentHCheck) {
|
|
|
36164
36304
|
if (realpathSync21(dirname23(destination)) !== dirname23(destination)) throw new Error("SYMLINK_REFUSED");
|
|
36165
36305
|
for (const root of [objects.directory, options.archive.directory]) if (isWithin(root, destination) || isWithin(destination, root)) throw new Error("RECOVERY_OVERLAPPING_PATHS");
|
|
36166
36306
|
try {
|
|
36167
|
-
|
|
36307
|
+
mkdirSync28(destination, { mode: 448 });
|
|
36168
36308
|
} catch (error) {
|
|
36169
36309
|
if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
|
|
36170
36310
|
throw error;
|
|
36171
36311
|
}
|
|
36172
|
-
|
|
36312
|
+
writeFileSync32(join61(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-recovery-restore-v1", id: entry.id, activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
|
|
36173
36313
|
await syncDirectory(dirname23(destination));
|
|
36174
36314
|
await syncDirectory(destination);
|
|
36175
36315
|
const created = /* @__PURE__ */ new Set([destination]);
|
|
@@ -36177,15 +36317,15 @@ async function restoreOriginal(options, original, currentHCheck) {
|
|
|
36177
36317
|
const missing = [];
|
|
36178
36318
|
for (let current2 = path37; !created.has(current2) && isWithin(destination, current2); current2 = dirname23(current2)) missing.push(current2);
|
|
36179
36319
|
for (const p of missing.reverse()) {
|
|
36180
|
-
|
|
36320
|
+
mkdirSync28(p, { mode: 448 });
|
|
36181
36321
|
created.add(p);
|
|
36182
36322
|
}
|
|
36183
36323
|
};
|
|
36184
|
-
directory2(
|
|
36185
|
-
directory2(
|
|
36186
|
-
await objects.restoreFiles(entry.databases.map((d) => ({ content: d.content, destination:
|
|
36324
|
+
directory2(join61(destination, "databases"));
|
|
36325
|
+
directory2(join61(destination, "trees"));
|
|
36326
|
+
await objects.restoreFiles(entry.databases.map((d) => ({ content: d.content, destination: join61(destination, "databases", d.databaseId + ".sqlite") })));
|
|
36187
36327
|
for (const d of entry.databases) {
|
|
36188
|
-
const path37 =
|
|
36328
|
+
const path37 = join61(destination, "databases", d.databaseId + ".sqlite");
|
|
36189
36329
|
const db2 = new DatabaseSync28(path37, { readOnly: true });
|
|
36190
36330
|
try {
|
|
36191
36331
|
validateRecoveryDatabase(db2, manifest, d.databaseId, d.role, d.schemaHash, options.verifyDatabases !== false);
|
|
@@ -36195,30 +36335,30 @@ async function restoreOriginal(options, original, currentHCheck) {
|
|
|
36195
36335
|
}
|
|
36196
36336
|
const files = [];
|
|
36197
36337
|
for (const tree of manifest.trees) {
|
|
36198
|
-
const root =
|
|
36338
|
+
const root = join61(destination, "trees", tree.id);
|
|
36199
36339
|
directory2(root);
|
|
36200
|
-
for (const path37 of tree.directories) directory2(
|
|
36340
|
+
for (const path37 of tree.directories) directory2(join61(root, path37));
|
|
36201
36341
|
for (const file2 of tree.files) {
|
|
36202
|
-
const path37 =
|
|
36342
|
+
const path37 = join61(root, file2.path);
|
|
36203
36343
|
directory2(dirname23(path37));
|
|
36204
36344
|
files.push({ content: file2.content, destination: path37, mode: file2.mode });
|
|
36205
36345
|
}
|
|
36206
36346
|
}
|
|
36207
36347
|
await objects.restoreFiles(files);
|
|
36208
|
-
directory2(
|
|
36209
|
-
directory2(
|
|
36348
|
+
directory2(join61(destination, "lance"));
|
|
36349
|
+
directory2(join61(destination, "sessions"));
|
|
36210
36350
|
for (const kind of manifest.profile.trees) {
|
|
36211
36351
|
const tree = manifest.trees.find((t) => t.id === kind.id);
|
|
36212
|
-
if (kind.kind === "vector") await restoreLancePublication({ tree, objects, destination:
|
|
36352
|
+
if (kind.kind === "vector") await restoreLancePublication({ tree, objects, destination: join61(destination, "lance", tree.id) });
|
|
36213
36353
|
if (kind.kind === "session") {
|
|
36214
36354
|
if (tree.directories.length || tree.files.length !== 1 || tree.files[0].path !== "manifest.json") throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
|
|
36215
36355
|
const metadata4 = JSON.parse((await objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
|
|
36216
36356
|
const d = entry.databases.find((d2) => d2.databaseId === metadata4.databaseId);
|
|
36217
36357
|
const binding = normalizeBinding({ ...manifest.profile.identity, databaseId: metadata4.databaseId, baselineId: manifest.profile.baselineId, epoch: manifest.profile.epoch });
|
|
36218
36358
|
if (metadata4.format !== "engine7-session-events-publication-v1" || !d || JSON.stringify(metadata4.binding) !== JSON.stringify(binding) || JSON.stringify(metadata4.head) !== JSON.stringify(manifest.databases.find((v) => v.databaseId === d.databaseId).head)) throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
|
|
36219
|
-
const db2 = new DatabaseSync28(
|
|
36359
|
+
const db2 = new DatabaseSync28(join61(destination, "databases", d.databaseId + ".sqlite"), { readOnly: true });
|
|
36220
36360
|
try {
|
|
36221
|
-
await restoreSessionEvents({ db: db2, binding, destination:
|
|
36361
|
+
await restoreSessionEvents({ db: db2, binding, destination: join61(destination, "sessions", tree.id), replicationRole: d.role });
|
|
36222
36362
|
} finally {
|
|
36223
36363
|
db2.close();
|
|
36224
36364
|
}
|
|
@@ -36226,7 +36366,7 @@ async function restoreOriginal(options, original, currentHCheck) {
|
|
|
36226
36366
|
}
|
|
36227
36367
|
for (const path37 of [...created].reverse()) await syncDirectory(path37);
|
|
36228
36368
|
await verify4();
|
|
36229
|
-
|
|
36369
|
+
writeFileSync32(join61(destination, ".recovery-archive-receipt.json"), JSON.stringify(entry.receipt), { mode: 384, flag: "wx", flush: true });
|
|
36230
36370
|
await syncDirectory(destination);
|
|
36231
36371
|
await verify4();
|
|
36232
36372
|
return entry.receipt;
|
|
@@ -36236,8 +36376,8 @@ async function restoreOriginal(options, original, currentHCheck) {
|
|
|
36236
36376
|
init_publication_objects();
|
|
36237
36377
|
init_key_service_store();
|
|
36238
36378
|
import { DatabaseSync as DatabaseSync29 } from "node:sqlite";
|
|
36239
|
-
import { existsSync as existsSync34, lstatSync as lstatSync23, writeFileSync as
|
|
36240
|
-
import { join as
|
|
36379
|
+
import { existsSync as existsSync34, lstatSync as lstatSync23, writeFileSync as writeFileSync33 } from "node:fs";
|
|
36380
|
+
import { join as join62 } from "node:path";
|
|
36241
36381
|
var zero = "0".repeat(64);
|
|
36242
36382
|
var format3 = "engine7-runtime-checkpoint-control-v1";
|
|
36243
36383
|
var hash7 = (value2) => typeof value2 === "string" && /^[a-f0-9]{64}$/.test(value2);
|
|
@@ -36253,10 +36393,10 @@ var RuntimeCheckpointControl = class {
|
|
|
36253
36393
|
if (!hash7(options.parentCheckpointDigest) || ["tenantId", "companionId", "seatId"].some((key2) => this.profile.identity[key2] !== options.principal[key2]) || ![options.bootId, options.authorityBootId, options.principal.nodeId].every((value2) => typeof value2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value2))) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
|
|
36254
36394
|
this.binding = JSON.stringify([this.profile, options.principal.nodeId, options.bootId, options.authorityBootId, options.parentCheckpointDigest]);
|
|
36255
36395
|
preparePrivateDirectory(options.directory);
|
|
36256
|
-
this.files = ["checkpoints.json", "checkpoint-owner.sqlite", "checkpoints.sqlite"].map((file2) =>
|
|
36396
|
+
this.files = ["checkpoints.json", "checkpoint-owner.sqlite", "checkpoints.sqlite"].map((file2) => join62(options.directory, file2));
|
|
36257
36397
|
const presence = this.files.map(existsSync34), fresh = presence.every((value2) => !value2);
|
|
36258
36398
|
if (fresh && options.initialize !== true || !fresh && !presence.every(Boolean)) throw new Error("TRAVEL_CHECKPOINT_RECOVERY_REQUIRED");
|
|
36259
|
-
if (fresh)
|
|
36399
|
+
if (fresh) writeFileSync33(this.files[0], JSON.stringify({ format: format3, binding: this.binding }), { mode: 384, flag: "wx", flush: true });
|
|
36260
36400
|
const marker = JSON.parse(readPrivateFile(this.files[0], 65536).toString());
|
|
36261
36401
|
if (marker.format !== format3 || marker.binding !== this.binding || Object.keys(marker).length !== 2) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
|
|
36262
36402
|
preparePrivateDatabase(this.files[1]);
|
|
@@ -36343,7 +36483,7 @@ var RuntimeCheckpointControl = class {
|
|
|
36343
36483
|
};
|
|
36344
36484
|
|
|
36345
36485
|
// src/continuity/recovery-archive-transfer.ts
|
|
36346
|
-
import { Agent, createServer as createServer2, request as
|
|
36486
|
+
import { Agent, createServer as createServer2, request as request3 } from "node:https";
|
|
36347
36487
|
import { gzipSync, gunzipSync as gunzipSync3, createGunzip, brotliCompressSync, brotliDecompressSync, createBrotliCompress, createBrotliDecompress, constants as constants13 } from "node:zlib";
|
|
36348
36488
|
import { pipeline } from "node:stream";
|
|
36349
36489
|
import { pipeline as pipelineAsync } from "node:stream/promises";
|
|
@@ -36785,7 +36925,7 @@ var RecoveryArchiveClient = class {
|
|
|
36785
36925
|
reject(error);
|
|
36786
36926
|
} else resolve47(value2);
|
|
36787
36927
|
};
|
|
36788
|
-
const req =
|
|
36928
|
+
const req = request3(this.url, { method: "POST", agent: this.agent, headers: {
|
|
36789
36929
|
"Content-Type": "application/json",
|
|
36790
36930
|
"Content-Length": body.length,
|
|
36791
36931
|
"Accept-Encoding": "br, gzip",
|
|
@@ -36954,7 +37094,7 @@ var RecoveryArchiveClient = class {
|
|
|
36954
37094
|
timer = setTimeout(() => fail2(new Error("RECOVERY_TRANSFER_UNAVAILABLE"), "IDLE_TIMEOUT"), this.timeout);
|
|
36955
37095
|
};
|
|
36956
37096
|
const abort = () => fail2(new Error("RECOVERY_TRANSFER_CANCELLED"));
|
|
36957
|
-
const req =
|
|
37097
|
+
const req = request3(this.url, { method: "POST", agent: this.agent, headers: {
|
|
36958
37098
|
"Content-Type": "application/json",
|
|
36959
37099
|
"Content-Length": body.length,
|
|
36960
37100
|
"Accept-Encoding": "br, gzip",
|
|
@@ -37138,17 +37278,17 @@ async function transferRecoveryArchive(options) {
|
|
|
37138
37278
|
let pending = [];
|
|
37139
37279
|
const concurrency = 2;
|
|
37140
37280
|
const archiveDigest = entry.receipt.digest;
|
|
37141
|
-
const readGroup = async (
|
|
37281
|
+
const readGroup = async (request9) => {
|
|
37142
37282
|
await options.beforeStep?.();
|
|
37143
37283
|
await check();
|
|
37144
37284
|
let parts;
|
|
37145
37285
|
try {
|
|
37146
|
-
parts = await options.peer.parts(options.id,
|
|
37286
|
+
parts = await options.peer.parts(options.id, request9, archiveDigest);
|
|
37147
37287
|
} catch (error) {
|
|
37148
37288
|
if (!(error instanceof Error) || error.message !== "RECOVERY_TRANSFER_UNAVAILABLE") throw error;
|
|
37149
37289
|
await options.beforeStep?.();
|
|
37150
37290
|
await check();
|
|
37151
|
-
parts = await options.peer.parts(options.id,
|
|
37291
|
+
parts = await options.peer.parts(options.id, request9, archiveDigest);
|
|
37152
37292
|
}
|
|
37153
37293
|
await options.beforeStep?.();
|
|
37154
37294
|
await check();
|
|
@@ -37163,10 +37303,10 @@ async function transferRecoveryArchive(options) {
|
|
|
37163
37303
|
if (result.status === "rejected") throw result.reason;
|
|
37164
37304
|
await options.beforeStep?.();
|
|
37165
37305
|
await check();
|
|
37166
|
-
const
|
|
37167
|
-
if (!Array.isArray(parts) || parts.length !==
|
|
37168
|
-
for (let index = 0; index <
|
|
37169
|
-
const part =
|
|
37306
|
+
const request9 = requests[requestIndex], parts = result.value;
|
|
37307
|
+
if (!Array.isArray(parts) || parts.length !== request9.length) throw new Error("RECOVERY_CONTENT_CORRUPT");
|
|
37308
|
+
for (let index = 0; index < request9.length; index++) {
|
|
37309
|
+
const part = request9[index], body = parts[index];
|
|
37170
37310
|
if (!Buffer.isBuffer(body) || body.length !== part.bytes) throw new Error("RECOVERY_CONTENT_CORRUPT");
|
|
37171
37311
|
const objectIndex = missing.findIndex((ref) => ref.sha256 === part.ref.sha256), assembled = bodies[objectIndex];
|
|
37172
37312
|
if (!assembled) throw new Error("RECOVERY_CONTENT_CORRUPT");
|
|
@@ -37232,20 +37372,20 @@ async function transferRecoveryArchive(options) {
|
|
|
37232
37372
|
init_publication_objects();
|
|
37233
37373
|
init_key_service_store();
|
|
37234
37374
|
import { DatabaseSync as DatabaseSync31 } from "node:sqlite";
|
|
37235
|
-
import { existsSync as existsSync36, lstatSync as lstatSync25, realpathSync as realpathSync23, writeFileSync as
|
|
37236
|
-
import { isAbsolute as isAbsolute9, join as
|
|
37375
|
+
import { existsSync as existsSync36, lstatSync as lstatSync25, realpathSync as realpathSync23, writeFileSync as writeFileSync35 } from "node:fs";
|
|
37376
|
+
import { isAbsolute as isAbsolute9, join as join64, resolve as resolve37 } from "node:path";
|
|
37237
37377
|
import { randomUUID as randomUUID19 } from "node:crypto";
|
|
37238
37378
|
|
|
37239
37379
|
// src/continuity/runtime-replica-seed.ts
|
|
37240
37380
|
import { DatabaseSync as DatabaseSync30 } from "node:sqlite";
|
|
37241
|
-
import { existsSync as existsSync35, writeFileSync as
|
|
37242
|
-
import { dirname as dirname24, isAbsolute as isAbsolute8, join as
|
|
37381
|
+
import { existsSync as existsSync35, writeFileSync as writeFileSync34, realpathSync as realpathSync22, lstatSync as lstatSync24 } from "node:fs";
|
|
37382
|
+
import { dirname as dirname24, isAbsolute as isAbsolute8, join as join63, resolve as resolve36 } from "node:path";
|
|
37243
37383
|
init_publication_objects();
|
|
37244
37384
|
init_sqlite_replication();
|
|
37245
37385
|
init_schema_migrations();
|
|
37246
37386
|
init_key_service_store();
|
|
37247
37387
|
function acquireReplicaOwner(directory2, initialize2 = false) {
|
|
37248
|
-
const file2 =
|
|
37388
|
+
const file2 = join63(directory2, "replica-owner.sqlite");
|
|
37249
37389
|
if (!initialize2 && !existsSync35(file2)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
|
|
37250
37390
|
preparePrivateDatabase(file2);
|
|
37251
37391
|
const owner = new DatabaseSync30(file2);
|
|
@@ -37311,7 +37451,7 @@ async function seedRuntimeReplica(options) {
|
|
|
37311
37451
|
if (failed) throw failed.reason;
|
|
37312
37452
|
}
|
|
37313
37453
|
for (const d of entry.databases) {
|
|
37314
|
-
const file2 =
|
|
37454
|
+
const file2 = join63(destination, "databases", d.databaseId + ".sqlite");
|
|
37315
37455
|
const probe = new DatabaseSync30(file2, { readOnly: true });
|
|
37316
37456
|
let component, version;
|
|
37317
37457
|
try {
|
|
@@ -37334,12 +37474,12 @@ async function seedRuntimeReplica(options) {
|
|
|
37334
37474
|
validateRecoveryDatabase(db2, manifest, d.databaseId, "replica", d.schemaHash, false);
|
|
37335
37475
|
}
|
|
37336
37476
|
await check();
|
|
37337
|
-
receiver = await PublicationReplica.open({ directory:
|
|
37477
|
+
receiver = await PublicationReplica.open({ directory: join63(dataDirectory, "publications"), profile: manifest.profile, objects: options.objects, replicas, minimumDeletionWatermark: manifest.deletionWatermark });
|
|
37338
37478
|
await receiver.receive(manifest);
|
|
37339
37479
|
const receipt2 = await receiver.publish(manifest.sequence);
|
|
37340
37480
|
if (receipt2.state !== "PUBLISHED" || receipt2.digest !== digest7) throw new Error("TRAVEL_REPLICA_CHECKPOINT");
|
|
37341
37481
|
await check();
|
|
37342
|
-
|
|
37482
|
+
writeFileSync34(join63(dataDirectory, "replica-seed.json"), JSON.stringify({ format: "engine7-runtime-replica-seed-v1", profile: manifest.profile, sourceArchiveId: entry.id, sourceArchiveDigest: entry.receipt.digest, checkpointDigest: digest7, parentCheckpointDigest: controlCheckpoint, destination }), { mode: 384, flag: "wx", flush: true });
|
|
37343
37483
|
await syncDirectory(destination);
|
|
37344
37484
|
await syncDirectory(dataDirectory);
|
|
37345
37485
|
return { receiver, databases, replicas, profile: manifest.profile, receipt: receipt2, close };
|
|
@@ -37356,8 +37496,8 @@ async function openSeededRuntimeReplica(options) {
|
|
|
37356
37496
|
}
|
|
37357
37497
|
if (isWithin(options.destination, options.dataDirectory) || isWithin(options.dataDirectory, options.destination)) throw new Error("TRAVEL_REPLICA_PATH");
|
|
37358
37498
|
for (const path37 of [options.destination, options.dataDirectory]) for (const root of [options.objects.directory, options.archive.directory, options.archive.objects.directory]) if (isWithin(root, path37) || isWithin(path37, root)) throw new Error("TRAVEL_REPLICA_PATH");
|
|
37359
|
-
const markerFile =
|
|
37360
|
-
if (!existsSync35(markerFile) || !existsSync35(publicationFile) || !existsSync35(
|
|
37499
|
+
const markerFile = join63(options.dataDirectory, "replica-seed.json"), publicationFile = join63(options.dataDirectory, "publications", "publications.sqlite");
|
|
37500
|
+
if (!existsSync35(markerFile) || !existsSync35(publicationFile) || !existsSync35(join63(options.dataDirectory, "replica-owner.sqlite"))) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
|
|
37361
37501
|
const marker = JSON.parse(readPrivateFile(markerFile, 4 * 1024 * 1024).toString()), entry = await options.archive.read(options.id), manifest = entry.manifest;
|
|
37362
37502
|
const profile = normalizePublicationProfile(marker.profile), digest7 = publicationDigest(manifest);
|
|
37363
37503
|
if (marker.format !== "engine7-runtime-replica-seed-v1" || marker.sourceArchiveId !== entry.id || marker.sourceArchiveDigest !== entry.receipt.digest || marker.checkpointDigest !== digest7 || marker.destination !== options.destination || entry.kind !== "LOCAL" || manifest.sequence !== 1 || !/^[a-f0-9]{64}$/.test(marker.parentCheckpointDigest) || JSON.stringify(profile) !== JSON.stringify(manifest.profile) || JSON.stringify(profile.identity) !== JSON.stringify(options.objects.identity)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
|
|
@@ -37390,7 +37530,7 @@ async function openSeededRuntimeReplica(options) {
|
|
|
37390
37530
|
}
|
|
37391
37531
|
for (const d of entry.databases) {
|
|
37392
37532
|
floor();
|
|
37393
|
-
const file2 =
|
|
37533
|
+
const file2 = join63(options.destination, "databases", d.databaseId + ".sqlite");
|
|
37394
37534
|
if (!existsSync35(file2)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
|
|
37395
37535
|
const stat3 = lstatSync24(file2);
|
|
37396
37536
|
if (!stat3.isFile() || stat3.isSymbolicLink() || realpathSync22(file2) !== file2 || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("TRAVEL_REPLICA_PATH");
|
|
@@ -37440,11 +37580,11 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
|
|
|
37440
37580
|
assertPrivateDirectory(options.generationsDirectory);
|
|
37441
37581
|
if (realpathSync23(options.generationsDirectory) !== options.generationsDirectory) throw new Error("TRAVEL_REPLICA_PATH");
|
|
37442
37582
|
preparePrivateDirectory(options.directory);
|
|
37443
|
-
this.files = ["replicas.json", "replicas-owner.sqlite", "replicas.sqlite"].map((name) =>
|
|
37583
|
+
this.files = ["replicas.json", "replicas-owner.sqlite", "replicas.sqlite"].map((name) => join64(options.directory, name));
|
|
37444
37584
|
const presence = this.files.map(existsSync36), fresh = presence.every((value2) => !value2);
|
|
37445
|
-
if (fresh && (options.initialize !== true || existsSync36(
|
|
37585
|
+
if (fresh && (options.initialize !== true || existsSync36(join64(options.directory, "receivers"))) || !fresh && !presence.every(Boolean)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
|
|
37446
37586
|
const binding = JSON.stringify([options.objects.identity, options.nodeId, options.generationsDirectory]);
|
|
37447
|
-
if (fresh)
|
|
37587
|
+
if (fresh) writeFileSync35(this.files[0], JSON.stringify({ format: "engine7-runtime-replica-repository-v1", binding }), { mode: 384, flag: "wx", flush: true });
|
|
37448
37588
|
const marker = JSON.parse(readPrivateFile(this.files[0], 65536).toString());
|
|
37449
37589
|
if (marker.format !== "engine7-runtime-replica-repository-v1" || marker.binding !== binding || Object.keys(marker).length !== 2) throw new Error("TRAVEL_REPLICA_IDENTITY");
|
|
37450
37590
|
preparePrivateDatabase(this.files[1]);
|
|
@@ -37518,48 +37658,48 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
|
|
|
37518
37658
|
}
|
|
37519
37659
|
async reopen(row) {
|
|
37520
37660
|
this.assertOpen();
|
|
37521
|
-
if (!validId2(row.id) || !validId2(row.attempt_id) || !isWithin(this.options.generationsDirectory, row.destination) || !isWithin(
|
|
37661
|
+
if (!validId2(row.id) || !validId2(row.attempt_id) || !isWithin(this.options.generationsDirectory, row.destination) || !isWithin(join64(this.options.directory, "receivers"), row.data_directory)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
|
|
37522
37662
|
const entry = await this.options.archive.read(row.archive_id);
|
|
37523
37663
|
if (entry.receipt.digest !== row.archive_digest || JSON.stringify(entry.manifest.profile) !== row.profile) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
|
|
37524
37664
|
return openSeededRuntimeReplica({ ...this.options, id: row.archive_id, destination: row.destination, dataDirectory: row.data_directory });
|
|
37525
37665
|
}
|
|
37526
|
-
bootstrap(
|
|
37666
|
+
bootstrap(request9) {
|
|
37527
37667
|
if (this.closed) return Promise.reject(new Error("TRAVEL_REPLICA_CLOSED"));
|
|
37528
37668
|
if (this.active) return Promise.reject(new Error("TRAVEL_REPLICA_BUSY"));
|
|
37529
|
-
this.active = this.round(
|
|
37669
|
+
this.active = this.round(request9).finally(() => {
|
|
37530
37670
|
this.active = void 0;
|
|
37531
37671
|
});
|
|
37532
37672
|
return this.active;
|
|
37533
37673
|
}
|
|
37534
|
-
async round(
|
|
37674
|
+
async round(request9) {
|
|
37535
37675
|
this.assertOpen();
|
|
37536
|
-
if (!validId2(
|
|
37537
|
-
const entry = await this.options.archive.read(
|
|
37538
|
-
if (entry.kind !== "LOCAL" || publicationDigest(entry.manifest) !==
|
|
37676
|
+
if (!validId2(request9.id) || !validId2(request9.archiveId) || !/^[a-f0-9]{64}$/.test(request9.expectedDigest)) throw new Error("TRAVEL_REPLICA_CHECKPOINT");
|
|
37677
|
+
const entry = await this.options.archive.read(request9.archiveId);
|
|
37678
|
+
if (entry.kind !== "LOCAL" || publicationDigest(entry.manifest) !== request9.expectedDigest) throw new Error("TRAVEL_REPLICA_CHECKPOINT");
|
|
37539
37679
|
const check = async () => {
|
|
37540
37680
|
this.assertOpen();
|
|
37541
|
-
const permit = await (
|
|
37542
|
-
const status =
|
|
37543
|
-
if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !==
|
|
37681
|
+
const permit = await (request9.permitSupplier?.() ?? request9.permit);
|
|
37682
|
+
const status = request9.authority.assertPermitWithStatus ? await request9.authority.assertPermitWithStatus(permit, "CONTROL") : (await request9.authority.assertPermit(permit, "CONTROL"), await request9.authority.status(request9.principal));
|
|
37683
|
+
if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !== request9.permit[key2]) || ["tenantId", "companionId", "seatId", "nodeId"].some((key2) => permit[key2] !== request9.principal[key2]) || JSON.stringify(entry.manifest.profile.identity) !== JSON.stringify(this.options.objects.identity) || entry.manifest.profile.epoch !== permit.epoch) throw new Error("TRAVEL_REPLICA_IDENTITY");
|
|
37544
37684
|
if (status.deletionWatermark !== entry.manifest.deletionWatermark || this.options.deletionWatermark() !== entry.manifest.deletionWatermark) throw new Error("TRAVEL_REPLICA_DELETION_BARRIER");
|
|
37545
37685
|
if (status.buildManifestId !== entry.manifest.profile.buildManifestId) throw new Error("TRAVEL_REPLICA_BUILD");
|
|
37546
37686
|
};
|
|
37547
37687
|
await check();
|
|
37548
37688
|
const binding = JSON.stringify([
|
|
37549
|
-
|
|
37689
|
+
request9.archiveId,
|
|
37550
37690
|
entry.receipt.digest,
|
|
37551
|
-
|
|
37552
|
-
|
|
37553
|
-
[
|
|
37554
|
-
|
|
37555
|
-
|
|
37556
|
-
|
|
37557
|
-
|
|
37691
|
+
request9.expectedDigest,
|
|
37692
|
+
request9.parentCheckpointDigest ?? request9.expectedDigest,
|
|
37693
|
+
[request9.principal.tenantId, request9.principal.companionId, request9.principal.seatId, request9.principal.nodeId, request9.principal.role, request9.principal.credentialHash],
|
|
37694
|
+
request9.permit.nodeId,
|
|
37695
|
+
request9.permit.bootId,
|
|
37696
|
+
request9.permit.authorityBootId,
|
|
37697
|
+
request9.permit.epoch
|
|
37558
37698
|
]);
|
|
37559
|
-
let row = this.db.prepare("SELECT * FROM seeds WHERE id=?").get(
|
|
37699
|
+
let row = this.db.prepare("SELECT * FROM seeds WHERE id=?").get(request9.id);
|
|
37560
37700
|
if (row && row.binding !== binding) throw new Error("TRAVEL_REPLICA_ID_COLLISION");
|
|
37561
37701
|
if (row?.state === "READY" && this.selected?.row.id === row.id) return this.selected.replica;
|
|
37562
|
-
if (row && (row.state === "READY" || existsSync36(
|
|
37702
|
+
if (row && (row.state === "READY" || existsSync36(join64(row.data_directory, "replica-seed.json")))) {
|
|
37563
37703
|
const replica = await this.reopen(row);
|
|
37564
37704
|
try {
|
|
37565
37705
|
await check();
|
|
@@ -37570,25 +37710,25 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
|
|
|
37570
37710
|
return this.select(row, replica);
|
|
37571
37711
|
}
|
|
37572
37712
|
if (row && row.state !== "PREPARING") throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
|
|
37573
|
-
preparePrivateDirectory(
|
|
37574
|
-
const attempt = randomUUID19(), destination =
|
|
37713
|
+
preparePrivateDirectory(join64(this.options.directory, "receivers"));
|
|
37714
|
+
const attempt = randomUUID19(), destination = join64(this.options.generationsDirectory, "replica-" + attempt), dataDirectory = join64(this.options.directory, "receivers", "replica-" + attempt);
|
|
37575
37715
|
this.db.exec("BEGIN IMMEDIATE");
|
|
37576
37716
|
try {
|
|
37577
37717
|
if (row) this.db.prepare("UPDATE attempts SET state='FAILED' WHERE id=? AND state='PREPARING'").run(row.attempt_id);
|
|
37578
|
-
this.db.prepare("INSERT INTO attempts VALUES(?,?,?,?,'PREPARING')").run(attempt,
|
|
37579
|
-
if (row) this.db.prepare("UPDATE seeds SET attempt_id=?,destination=?,data_directory=? WHERE id=?").run(attempt, destination, dataDirectory,
|
|
37580
|
-
else this.db.prepare("INSERT INTO seeds VALUES(?,?,?,?,?,'PREPARING',?,?,?)").run(
|
|
37718
|
+
this.db.prepare("INSERT INTO attempts VALUES(?,?,?,?,'PREPARING')").run(attempt, request9.id, destination, dataDirectory);
|
|
37719
|
+
if (row) this.db.prepare("UPDATE seeds SET attempt_id=?,destination=?,data_directory=? WHERE id=?").run(attempt, destination, dataDirectory, request9.id);
|
|
37720
|
+
else this.db.prepare("INSERT INTO seeds VALUES(?,?,?,?,?,'PREPARING',?,?,?)").run(request9.id, binding, request9.archiveId, entry.receipt.digest, JSON.stringify(entry.manifest.profile), attempt, destination, dataDirectory);
|
|
37581
37721
|
this.db.exec("COMMIT");
|
|
37582
37722
|
} catch (error) {
|
|
37583
37723
|
this.db.exec("ROLLBACK");
|
|
37584
37724
|
throw error;
|
|
37585
37725
|
}
|
|
37586
|
-
row = this.db.prepare("SELECT * FROM seeds WHERE id=?").get(
|
|
37726
|
+
row = this.db.prepare("SELECT * FROM seeds WHERE id=?").get(request9.id);
|
|
37587
37727
|
try {
|
|
37588
37728
|
const replica = await seedRuntimeReplica({
|
|
37589
|
-
...
|
|
37729
|
+
...request9,
|
|
37590
37730
|
archive: this.options.archive,
|
|
37591
|
-
id:
|
|
37731
|
+
id: request9.archiveId,
|
|
37592
37732
|
destination,
|
|
37593
37733
|
dataDirectory,
|
|
37594
37734
|
objects: this.options.objects,
|
|
@@ -37650,7 +37790,7 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
|
|
|
37650
37790
|
import { createServer as createServer4 } from "node:https";
|
|
37651
37791
|
|
|
37652
37792
|
// src/continuity/publication-transport.ts
|
|
37653
|
-
import { createServer as createServer3, request as
|
|
37793
|
+
import { createServer as createServer3, request as request4, Agent as Agent2 } from "node:https";
|
|
37654
37794
|
import { createHash as createHash42 } from "node:crypto";
|
|
37655
37795
|
init_publication_objects();
|
|
37656
37796
|
var BODY_LIMIT = PUBLICATION_MANIFEST_BYTES + 65536;
|
|
@@ -37854,19 +37994,19 @@ init_store();
|
|
|
37854
37994
|
init_schema_migrations();
|
|
37855
37995
|
import { DatabaseSync as DatabaseSync34 } from "node:sqlite";
|
|
37856
37996
|
import { lstatSync as lstatSync27, realpathSync as realpathSync25 } from "node:fs";
|
|
37857
|
-
import { isAbsolute as isAbsolute10, join as
|
|
37997
|
+
import { isAbsolute as isAbsolute10, join as join68, resolve as resolve39 } from "node:path";
|
|
37858
37998
|
|
|
37859
37999
|
// src/continuity/recovery-admission.ts
|
|
37860
38000
|
import { DatabaseSync as DatabaseSync33 } from "node:sqlite";
|
|
37861
38001
|
import { createHash as createHash44 } from "node:crypto";
|
|
37862
|
-
import { mkdtempSync as mkdtempSync3, rmSync as rmSync6, writeFileSync as
|
|
37863
|
-
import { join as
|
|
38002
|
+
import { mkdtempSync as mkdtempSync3, rmSync as rmSync6, writeFileSync as writeFileSync37 } from "node:fs";
|
|
38003
|
+
import { join as join66 } from "node:path";
|
|
37864
38004
|
|
|
37865
38005
|
// src/continuity/recovery-diff.ts
|
|
37866
38006
|
import { DatabaseSync as DatabaseSync32 } from "node:sqlite";
|
|
37867
38007
|
import { createHash as createHash43 } from "node:crypto";
|
|
37868
|
-
import { mkdtempSync as mkdtempSync2, rmSync as rmSync5, writeFileSync as
|
|
37869
|
-
import { join as
|
|
38008
|
+
import { mkdtempSync as mkdtempSync2, rmSync as rmSync5, writeFileSync as writeFileSync36 } from "node:fs";
|
|
38009
|
+
import { join as join65 } from "node:path";
|
|
37870
38010
|
init_legacy_sqlite_indexes();
|
|
37871
38011
|
init_schema_migrations();
|
|
37872
38012
|
init_recovery_deletion();
|
|
@@ -37959,10 +38099,10 @@ async function compareRecoveryArchives(options) {
|
|
|
37959
38099
|
try {
|
|
37960
38100
|
for (let index = 0; index < entries.length; index++) {
|
|
37961
38101
|
const entry = entries[index], ref = references[index], d = entry.databases.find((d2) => d2.databaseId === databaseId);
|
|
37962
|
-
const temporary = mkdtempSync2(
|
|
38102
|
+
const temporary = mkdtempSync2(join65(ref.archive.directory, ".compare-"));
|
|
37963
38103
|
temporaries.push(temporary);
|
|
37964
|
-
|
|
37965
|
-
const file2 =
|
|
38104
|
+
writeFileSync36(join65(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
|
|
38105
|
+
const file2 = join65(temporary, databaseId + ".sqlite");
|
|
37966
38106
|
await ref.archive.objects.restoreFile(d.content, file2);
|
|
37967
38107
|
const db2 = new DatabaseSync32(file2, { readOnly: true, allowExtension: true });
|
|
37968
38108
|
handles.push(db2);
|
|
@@ -38870,13 +39010,13 @@ async function admitRecoveryArchives(options) {
|
|
|
38870
39010
|
bodies.set(content.sha256, body);
|
|
38871
39011
|
}
|
|
38872
39012
|
await active();
|
|
38873
|
-
const commonDirectory = mkdtempSync3(
|
|
38874
|
-
|
|
39013
|
+
const commonDirectory = mkdtempSync3(join66(options.common.archive.directory, ".admission-common-"));
|
|
39014
|
+
writeFileSync37(join66(commonDirectory, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
|
|
38875
39015
|
const commonDatabases = /* @__PURE__ */ new Map();
|
|
38876
39016
|
try {
|
|
38877
39017
|
for (const d of common.databases) {
|
|
38878
39018
|
await active();
|
|
38879
|
-
const path37 =
|
|
39019
|
+
const path37 = join66(commonDirectory, d.databaseId + ".sqlite");
|
|
38880
39020
|
await options.common.archive.objects.restoreFile(d.content, path37);
|
|
38881
39021
|
const db2 = new DatabaseSync33(path37, { readOnly: true });
|
|
38882
39022
|
commonDatabases.set(d.databaseId, db2);
|
|
@@ -39155,8 +39295,8 @@ async function admitRecoveryArchives(options) {
|
|
|
39155
39295
|
|
|
39156
39296
|
// src/continuity/recovery-artifact-projection.ts
|
|
39157
39297
|
import { createHash as createHash45, randomUUID as randomUUID20 } from "node:crypto";
|
|
39158
|
-
import { existsSync as existsSync37, linkSync, lstatSync as lstatSync26, mkdirSync as
|
|
39159
|
-
import { dirname as dirname25, join as
|
|
39298
|
+
import { existsSync as existsSync37, linkSync, lstatSync as lstatSync26, mkdirSync as mkdirSync29, readFileSync as readFileSync30, realpathSync as realpathSync24, unlinkSync as unlinkSync13, writeFileSync as writeFileSync38 } from "node:fs";
|
|
39299
|
+
import { dirname as dirname25, join as join67, resolve as resolve38 } from "node:path";
|
|
39160
39300
|
import { createRequire as createRequire9 } from "node:module";
|
|
39161
39301
|
init_runtime_authority();
|
|
39162
39302
|
init_dependencies();
|
|
@@ -39167,7 +39307,7 @@ function privateParents(root, path37) {
|
|
|
39167
39307
|
const visit = (directory2) => {
|
|
39168
39308
|
if (!isWithin(root, directory2)) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
|
|
39169
39309
|
if (directory2 !== root) visit(dirname25(directory2));
|
|
39170
|
-
if (!existsSync37(directory2))
|
|
39310
|
+
if (!existsSync37(directory2)) mkdirSync29(directory2, { mode: 448 });
|
|
39171
39311
|
const s = lstatSync26(directory2);
|
|
39172
39312
|
if (!s.isDirectory() || s.isSymbolicLink() || process.platform !== "win32" && (s.uid !== process.getuid() || directory2 === root && s.mode & 63)) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
|
|
39173
39313
|
};
|
|
@@ -39244,7 +39384,7 @@ async function projectRecoveryArtifacts(options) {
|
|
|
39244
39384
|
};
|
|
39245
39385
|
if (kind === "file") {
|
|
39246
39386
|
if (item.common || item.remote) continue;
|
|
39247
|
-
const path37 =
|
|
39387
|
+
const path37 = join67(treeRoot, item.path);
|
|
39248
39388
|
if (local.kind === "file" && item.path.startsWith("mem7/")) {
|
|
39249
39389
|
const publications = evidence.filter((value2) => value2.table === "memory_artifact_publications" && value2.local && value2.local.medium?.[1] === "markdown" && "mem7/" + value2.local.path?.[1] === item.path);
|
|
39250
39390
|
if (!publications.length || publications.some((value2) => !["CURRENT", "DUPLICATE"].includes(value2.state))) continue;
|
|
@@ -39276,8 +39416,8 @@ async function projectRecoveryArtifacts(options) {
|
|
|
39276
39416
|
commit();
|
|
39277
39417
|
continue;
|
|
39278
39418
|
}
|
|
39279
|
-
const temporary =
|
|
39280
|
-
|
|
39419
|
+
const temporary = join67(dirname25(path37), ".recovery-" + randomUUID20()), original = Buffer.from(body);
|
|
39420
|
+
writeFileSync38(temporary, original, { mode: local.mode, flag: "wx", flush: true });
|
|
39281
39421
|
let created = false;
|
|
39282
39422
|
try {
|
|
39283
39423
|
active();
|
|
@@ -39406,7 +39546,7 @@ async function admitNormalRecoveryArchives(options) {
|
|
|
39406
39546
|
const currentPermit = runtime.assert("WRITE");
|
|
39407
39547
|
if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((field) => currentPermit[field] !== permit[field] || permit[field] !== options.permit[field])) throw new Error("RECOVERY_AUTHORITY_BARRIER");
|
|
39408
39548
|
await options.authority.assertPermit(permit, "WRITE");
|
|
39409
|
-
const activation = JSON.parse(readPrivateFile(
|
|
39549
|
+
const activation = JSON.parse(readPrivateFile(join68(stateDir, ".travel-active.json"), 4 * 1024 * 1024).toString());
|
|
39410
39550
|
const profile = normalizePublicationProfile(activation.profile), layout = activation.layout;
|
|
39411
39551
|
if (activation.format !== "engine7-runtime-activation-v1" || activation.destination !== stateDir || activation.nodeId !== permit.nodeId || activation.bootId !== permit.bootId || activation.authorityBootId !== permit.authorityBootId || profile.epoch !== permit.epoch || !same11(profile.identity, runtime.enrollment.identity) || !layout || !same11(Object.keys(layout.databases).sort(), profile.databaseIds) || !same11(Object.keys(layout.trees).sort(), profile.trees.map((tree) => tree.id).sort())) throw new Error("RECOVERY_CURRENT_LAYOUT");
|
|
39412
39552
|
return options.withSafeBoundary(async () => {
|
|
@@ -39416,7 +39556,7 @@ async function admitNormalRecoveryArchives(options) {
|
|
|
39416
39556
|
runtime.assert("WRITE");
|
|
39417
39557
|
for (const id2 of profile.databaseIds) {
|
|
39418
39558
|
validatePublicationPath(layout.databases[id2]);
|
|
39419
|
-
const file2 =
|
|
39559
|
+
const file2 = join68(stateDir, layout.databases[id2]), place = sqliteStoreLocation(file2), stat3 = lstatSync27(file2);
|
|
39420
39560
|
if (!place || !stat3.isFile() || stat3.isSymbolicLink() || realpathSync25(file2) !== file2 || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("RECOVERY_CURRENT_LAYOUT");
|
|
39421
39561
|
if (place.component === "mem7") {
|
|
39422
39562
|
if (id2 !== "memory" || memory || place.stateDir !== stateDir) throw new Error("RECOVERY_CURRENT_LAYOUT");
|
|
@@ -39495,8 +39635,8 @@ init_runtime_lock();
|
|
|
39495
39635
|
init_runtime_lock();
|
|
39496
39636
|
init_key_service_store();
|
|
39497
39637
|
import { createHash as createHash46, verify as verify2 } from "node:crypto";
|
|
39498
|
-
import { createReadStream, mkdirSync as
|
|
39499
|
-
import { join as
|
|
39638
|
+
import { createReadStream, mkdirSync as mkdirSync30, readdirSync as readdirSync14, writeFileSync as writeFileSync39 } from "node:fs";
|
|
39639
|
+
import { join as join69, relative as relative12 } from "node:path";
|
|
39500
39640
|
var hash9 = (value2) => createHash46("sha256").update(value2).digest("hex");
|
|
39501
39641
|
var equal2 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
39502
39642
|
function copyLocalExitPath(source, path37) {
|
|
@@ -39507,7 +39647,7 @@ async function localExitFilesDigest(root, ordinary = false) {
|
|
|
39507
39647
|
const files = [];
|
|
39508
39648
|
const visit = async (directory2) => {
|
|
39509
39649
|
for (const entry of readdirSync14(directory2, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
39510
|
-
const file2 =
|
|
39650
|
+
const file2 = join69(directory2, entry.name);
|
|
39511
39651
|
if (ordinary ? relative12(root, file2).replaceAll("\\", "/") === ".continuity/travel-exit-receipt.json" : !copyLocalExitPath(root, file2)) continue;
|
|
39512
39652
|
if (entry.isSymbolicLink()) throw new Error("TRAVEL_EXIT_PATH");
|
|
39513
39653
|
if (entry.isDirectory()) {
|
|
@@ -39524,7 +39664,7 @@ async function localExitFilesDigest(root, ordinary = false) {
|
|
|
39524
39664
|
return hash9(JSON.stringify(files));
|
|
39525
39665
|
}
|
|
39526
39666
|
async function currentBinding(stateDir, authority, principal) {
|
|
39527
|
-
const activation = JSON.parse(readPrivateFile(
|
|
39667
|
+
const activation = JSON.parse(readPrivateFile(join69(stateDir, ".travel-active.json"), 4 * 1024 * 1024).toString());
|
|
39528
39668
|
const permit = activation.permit, { signature: signature2, ...signed } = permit;
|
|
39529
39669
|
if (activation.format !== "engine7-runtime-activation-v1" || !verify2(null, Buffer.from(JSON.stringify(signed)), authority.publicKey, Buffer.from(signature2, "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");
|
|
39530
39670
|
const control2 = await authority.status(principal);
|
|
@@ -39544,14 +39684,14 @@ async function writeStoppedLocalExitProof(options) {
|
|
|
39544
39684
|
const filesDigest = await localExitFilesDigest(options.stateDir);
|
|
39545
39685
|
if (!equal2(binding, await currentBinding(options.stateDir, options.authority, options.principal))) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
39546
39686
|
const body = { format: "engine7-stopped-local-exit-v1", ...binding, filesDigest };
|
|
39547
|
-
|
|
39548
|
-
|
|
39687
|
+
mkdirSync30(join69(options.stateDir, ".continuity"), { recursive: true, mode: 448 });
|
|
39688
|
+
writeFileSync39(join69(options.stateDir, ".continuity/travel-exit-source.json"), JSON.stringify({ ...body, digest: hash9(JSON.stringify(body)) }), { mode: 384, flush: true });
|
|
39549
39689
|
});
|
|
39550
39690
|
}
|
|
39551
39691
|
async function verifyStoppedLocalExitProof(options) {
|
|
39552
39692
|
let proof;
|
|
39553
39693
|
try {
|
|
39554
|
-
proof = JSON.parse(readPrivateFile(
|
|
39694
|
+
proof = JSON.parse(readPrivateFile(join69(options.stateDir, ".continuity/travel-exit-source.json"), 65536).toString());
|
|
39555
39695
|
} catch {
|
|
39556
39696
|
throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
39557
39697
|
}
|
|
@@ -39588,9 +39728,9 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
39588
39728
|
this.refreshInterval = options.keyRefreshIntervalMs ?? 1e4;
|
|
39589
39729
|
if (!Number.isSafeInteger(this.maxKeyAge) || this.maxKeyAge < 200 || this.maxKeyAge > 3e4 || !Number.isSafeInteger(this.refreshInterval) || this.refreshInterval < 100 || this.refreshInterval > 1e4 || this.maxKeyAge < 2 * this.refreshInterval) throw new Error("TRAVEL_NODE_KEY_TIMING");
|
|
39590
39730
|
preparePrivateDirectory(options.directory);
|
|
39591
|
-
const ownerFile =
|
|
39731
|
+
const ownerFile = join70(options.directory, "agent-owner.sqlite"), file2 = join70(options.directory, "agent.sqlite");
|
|
39592
39732
|
const present = [existsSync38(ownerFile), existsSync38(file2)], fresh = present.every((value2) => !value2);
|
|
39593
|
-
if (!fresh && !present.every(Boolean) || fresh && existsSync38(
|
|
39733
|
+
if (!fresh && !present.every(Boolean) || fresh && existsSync38(join70(options.directory, "recovery"))) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
39594
39734
|
preparePrivateDatabase(ownerFile);
|
|
39595
39735
|
this.owner = new DatabaseSync35(ownerFile);
|
|
39596
39736
|
try {
|
|
@@ -39672,7 +39812,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
39672
39812
|
const node = new _TravelNodeAgent(options);
|
|
39673
39813
|
try {
|
|
39674
39814
|
await node.refreshKey();
|
|
39675
|
-
const path37 =
|
|
39815
|
+
const path37 = join70(options.directory, "recovery"), lifecycle = node.db.prepare("SELECT archive_ready FROM lifecycle WHERE id=1").get();
|
|
39676
39816
|
if (!lifecycle || ![0, 1].includes(Number(lifecycle.archive_ready))) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
39677
39817
|
const initialize2 = lifecycle.archive_ready === 0;
|
|
39678
39818
|
if (initialize2 && (node.db.prepare("SELECT 1 FROM preparations LIMIT 1").get() || node.db.prepare("SELECT 1 FROM generations LIMIT 1").get())) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
@@ -39685,7 +39825,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
39685
39825
|
if (selected) node.replica = selected;
|
|
39686
39826
|
} else if (replicasReady !== 0) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
39687
39827
|
node.reporter = startTravelHeartbeatReporting({
|
|
39688
|
-
directory:
|
|
39828
|
+
directory: join70(options.directory, "reporting"),
|
|
39689
39829
|
nodeId: options.principal.nodeId,
|
|
39690
39830
|
bootId: options.bootId,
|
|
39691
39831
|
runtime: () => node.stopping ? null : node.runtime ?? node.activatingRuntime ?? null,
|
|
@@ -39737,7 +39877,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
39737
39877
|
assertLocalDataAvailable() {
|
|
39738
39878
|
this.assertKey();
|
|
39739
39879
|
if (this.sourceObjects) {
|
|
39740
|
-
const stat3 = lstatSync28(
|
|
39880
|
+
const stat3 = lstatSync28(join70(this.sourceObjects.directory, "catalog.sqlite"), { bigint: true });
|
|
39741
39881
|
if (stat3.isSymbolicLink() || !stat3.isFile() || `${stat3.dev}:${stat3.ino}` !== this.sourceCatalogIdentity) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
39742
39882
|
}
|
|
39743
39883
|
}
|
|
@@ -39893,7 +40033,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
39893
40033
|
const objects = await this.sourceObjectStore(profile);
|
|
39894
40034
|
let archive = this.sourceArchives.get(String(row.binding));
|
|
39895
40035
|
if (!archive) {
|
|
39896
|
-
archive = await RuntimeRecoveryArchive.open({ directory:
|
|
40036
|
+
archive = await RuntimeRecoveryArchive.open({ directory: join70(this.options.directory, "data", "source-" + hash10(String(row.binding)), "recovery"), objects });
|
|
39897
40037
|
this.sourceArchives.set(String(row.binding), archive);
|
|
39898
40038
|
}
|
|
39899
40039
|
const entry = await archive.read(id2);
|
|
@@ -39906,9 +40046,9 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
39906
40046
|
}
|
|
39907
40047
|
async sourceObjectStore(profile) {
|
|
39908
40048
|
if (!this.sourceObjects) {
|
|
39909
|
-
const directory2 =
|
|
40049
|
+
const directory2 = join70(this.options.directory, "data", "objects"), file2 = join70(directory2, "catalog.sqlite");
|
|
39910
40050
|
assertPrivateDirectory(directory2);
|
|
39911
|
-
assertPrivateDirectory(
|
|
40051
|
+
assertPrivateDirectory(join70(directory2, "chunks"));
|
|
39912
40052
|
if (realpathSync26(directory2) !== directory2 || !existsSync38(file2)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
39913
40053
|
const stat3 = lstatSync28(file2, { bigint: true });
|
|
39914
40054
|
if (!stat3.isFile() || stat3.isSymbolicLink()) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
@@ -40021,7 +40161,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40021
40161
|
const objects = await this.sourceObjectStore(profile);
|
|
40022
40162
|
return readStoppedRecoveryManifests({
|
|
40023
40163
|
stateDir,
|
|
40024
|
-
dataDirectory:
|
|
40164
|
+
dataDirectory: join70(this.options.directory, "data", "source-" + hash10(String(row.binding))),
|
|
40025
40165
|
objects,
|
|
40026
40166
|
common,
|
|
40027
40167
|
localArchiveId,
|
|
@@ -40042,7 +40182,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40042
40182
|
const binding = JSON.parse(String(row.binding)), profile = normalizePublicationProfile(JSON.parse(String(row.profile)));
|
|
40043
40183
|
const stateDir = String(row.state_dir);
|
|
40044
40184
|
if (!Array.isArray(binding) || binding.length !== 4 || binding[0] !== this.principal.nodeId || binding[3] !== profile.epoch || !isWithin(this.options.generationsDirectory, stateDir) || ["tenantId", "companionId", "seatId"].some((field) => profile.identity[field] !== this.principal[field])) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
40045
|
-
const objects = await this.sourceObjectStore(profile), dataDirectory =
|
|
40185
|
+
const objects = await this.sourceObjectStore(profile), dataDirectory = join70(this.options.directory, "data", "source-" + hash10(String(row.binding)));
|
|
40046
40186
|
const prior = this.db.prepare("SELECT archive_id,receipt FROM stopped_branches WHERE binding=?").get(String(row.binding));
|
|
40047
40187
|
const receipt2 = prior ? JSON.parse(String(prior.receipt)) : await preserveStoppedGeneration({
|
|
40048
40188
|
stateDir,
|
|
@@ -40055,7 +40195,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40055
40195
|
}
|
|
40056
40196
|
});
|
|
40057
40197
|
const cached = this.sourceArchives.get(String(row.binding));
|
|
40058
|
-
const archive = cached ?? await RuntimeRecoveryArchive.open({ directory:
|
|
40198
|
+
const archive = cached ?? await RuntimeRecoveryArchive.open({ directory: join70(dataDirectory, "recovery"), objects });
|
|
40059
40199
|
try {
|
|
40060
40200
|
const entry = await archive.read(prior ? String(prior.archive_id) : receipt2.id);
|
|
40061
40201
|
if (entry.kind !== "LOCAL" || !same12(entry.manifest.profile, profile) || !same12(entry.receipt, receipt2)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
@@ -40115,7 +40255,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40115
40255
|
const manifest = await receiver.manifest(status.published.sequence);
|
|
40116
40256
|
if (publicationDigest(manifest) !== digest7 || ["tenantId", "companionId", "seatId"].some((field) => manifest.profile.identity[field] !== this.principal[field])) throw new Error("TRAVEL_NODE_CHECKPOINT");
|
|
40117
40257
|
if (manifest.profile.buildManifestId !== this.options.build.manifestId) throw new Error("TRAVEL_NODE_BUILD");
|
|
40118
|
-
const locations = validateRuntimeActivationLayout(
|
|
40258
|
+
const locations = validateRuntimeActivationLayout(join70(this.options.generationsDirectory, "candidate"), manifest, this.options.layout);
|
|
40119
40259
|
if (manifest.deletionWatermark < this.keyWatermark) return this.preparedDeletion(manifest, replica);
|
|
40120
40260
|
if (manifest.deletionWatermark !== this.keyWatermark) throw new Error("TRAVEL_NODE_DELETION_BARRIER");
|
|
40121
40261
|
if (!status.dataReady) throw new Error("TRAVEL_NODE_CHECKPOINT");
|
|
@@ -40123,13 +40263,13 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40123
40263
|
if (prior) {
|
|
40124
40264
|
const snapshot2 = String(prior.snapshot);
|
|
40125
40265
|
if (!isWithin(this.options.generationsDirectory, snapshot2) || realpathSync26(snapshot2) !== snapshot2) throw new Error("TRAVEL_NODE_PATH");
|
|
40126
|
-
const receipt2 = JSON.parse(readPrivateFile(
|
|
40266
|
+
const receipt2 = JSON.parse(readPrivateFile(join70(snapshot2, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
|
|
40127
40267
|
if (receipt2.receipt?.digest !== digest7) throw new Error("TRAVEL_NODE_CHECKPOINT");
|
|
40128
40268
|
await verifyRuntimeGenerationIntegrityAsync(snapshot2, receipt2.integrity);
|
|
40129
40269
|
validateRuntimeActivationSnapshot(snapshot2, manifest, locations);
|
|
40130
40270
|
return { snapshot: snapshot2, manifest };
|
|
40131
40271
|
}
|
|
40132
|
-
const snapshot =
|
|
40272
|
+
const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID21());
|
|
40133
40273
|
await restoreRuntimePublication({ receiver, databases, destination: snapshot, sequence: manifest.sequence });
|
|
40134
40274
|
validateRuntimeActivationSnapshot(snapshot, manifest, locations);
|
|
40135
40275
|
this.db.prepare("INSERT INTO preparations VALUES(?,?)").run(digest7, snapshot);
|
|
@@ -40150,23 +40290,23 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40150
40290
|
if (entry.kind !== "COMMON" || entry.publication?.state !== "PUBLISHED" || entry.publication.digest !== digest7 || publicationDigest(manifest) !== digest7 || manifest.profile.buildManifestId !== this.options.build.manifestId) throw new Error("TRAVEL_NODE_COMMON_CHECKPOINT");
|
|
40151
40291
|
if (manifest.deletionWatermark < this.keyWatermark) return this.preparedDeletion(manifest);
|
|
40152
40292
|
await checkRecoveryDeletionAsync(manifest, check);
|
|
40153
|
-
const locations = validateRuntimeActivationLayout(
|
|
40293
|
+
const locations = validateRuntimeActivationLayout(join70(this.options.generationsDirectory, "candidate"), manifest, this.options.layout);
|
|
40154
40294
|
const prior = this.db.prepare("SELECT * FROM common_preparations WHERE digest=?").get(digest7);
|
|
40155
40295
|
if (prior) {
|
|
40156
40296
|
const snapshot2 = String(prior.snapshot);
|
|
40157
40297
|
if (prior.archive_digest !== entry.receipt.digest || !isWithin(this.options.generationsDirectory, snapshot2) || realpathSync26(snapshot2) !== snapshot2) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
40158
|
-
const proof = JSON.parse(readPrivateFile(
|
|
40298
|
+
const proof = JSON.parse(readPrivateFile(join70(snapshot2, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
|
|
40159
40299
|
if (proof.recoveryArchive?.id !== entry.id || proof.recoveryArchive?.digest !== entry.receipt.digest || !same12(proof.receipt, entry.publication) || !same12(proof.profile, manifest.profile)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
40160
40300
|
await verifyRuntimeGenerationIntegrityAsync(snapshot2, proof.integrity);
|
|
40161
40301
|
validateRuntimeActivationSnapshot(snapshot2, manifest, locations);
|
|
40162
40302
|
await check();
|
|
40163
40303
|
return { snapshot: snapshot2, manifest };
|
|
40164
40304
|
}
|
|
40165
|
-
const snapshot =
|
|
40305
|
+
const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID21());
|
|
40166
40306
|
await restoreRecoveryArchive({ archive: this.archive, id: entry.id, destination: snapshot, deletionWatermark: check, verifyDatabases: false });
|
|
40167
40307
|
validateRuntimeActivationSnapshot(snapshot, manifest, locations);
|
|
40168
40308
|
await check();
|
|
40169
|
-
|
|
40309
|
+
writeFileSync40(join70(snapshot, ".runtime-publication-receipt.json"), JSON.stringify({
|
|
40170
40310
|
format: "engine7-runtime-publication-restore-v1",
|
|
40171
40311
|
profile: manifest.profile,
|
|
40172
40312
|
receipt: entry.publication,
|
|
@@ -40194,15 +40334,15 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40194
40334
|
if (prior) {
|
|
40195
40335
|
const snapshot2 = String(prior.snapshot);
|
|
40196
40336
|
if (!isWithin(this.options.generationsDirectory, snapshot2) || realpathSync26(snapshot2) !== snapshot2 || prior.archive_digest !== entry.receipt.digest) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
40197
|
-
const proof2 = JSON.parse(readPrivateFile(
|
|
40337
|
+
const proof2 = JSON.parse(readPrivateFile(join70(snapshot2, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
|
|
40198
40338
|
if (proof2.deletionVisibility?.deletionWatermark === this.keyWatermark) {
|
|
40199
40339
|
const deletionWatermark = await (await verifyCurrentHDeletionVisibilityAsync({ snapshot: snapshot2, manifest, layout: this.options.layout, gateway: this.options.gateway, ...control2 }))();
|
|
40200
40340
|
return { snapshot: snapshot2, manifest, deletionWatermark };
|
|
40201
40341
|
}
|
|
40202
40342
|
}
|
|
40203
|
-
const snapshot =
|
|
40343
|
+
const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID21());
|
|
40204
40344
|
await restoreCurrentHForDeletion({ archive: this.archive, id: id2, destination: snapshot, ...control2 });
|
|
40205
|
-
|
|
40345
|
+
writeFileSync40(join70(snapshot, ".runtime-publication-receipt.json"), JSON.stringify({
|
|
40206
40346
|
format: "engine7-runtime-publication-restore-v1",
|
|
40207
40347
|
profile: manifest.profile,
|
|
40208
40348
|
receipt: entry.publication,
|
|
@@ -40251,7 +40391,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40251
40391
|
}
|
|
40252
40392
|
openReplicaRepository(initialize2) {
|
|
40253
40393
|
return RuntimeReplicaRepository.open({
|
|
40254
|
-
directory:
|
|
40394
|
+
directory: join70(this.options.directory, "replicas"),
|
|
40255
40395
|
generationsDirectory: this.options.generationsDirectory,
|
|
40256
40396
|
nodeId: this.principal.nodeId,
|
|
40257
40397
|
objects: this.archive.objects,
|
|
@@ -40292,7 +40432,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40292
40432
|
const id2 = "baseline-" + hash10(JSON.stringify(profile)), objects = await this.sourceObjectStore(profile);
|
|
40293
40433
|
let archive = this.sourceArchives.get(binding);
|
|
40294
40434
|
if (!archive) {
|
|
40295
|
-
archive = await RuntimeRecoveryArchive.open({ directory:
|
|
40435
|
+
archive = await RuntimeRecoveryArchive.open({ directory: join70(this.options.directory, "data", "source-" + hash10(binding), "recovery"), objects });
|
|
40296
40436
|
this.sourceArchives.set(binding, archive);
|
|
40297
40437
|
}
|
|
40298
40438
|
const entry = await archive.read(id2);
|
|
@@ -40325,12 +40465,12 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40325
40465
|
if (!this.options.replicationPeer) return Promise.reject(new Error("TRAVEL_NODE_REPLICATION_PEER"));
|
|
40326
40466
|
return this.connectPeer({ ...this.options.replicationPeer, profile });
|
|
40327
40467
|
}
|
|
40328
|
-
bootstrapReplica(
|
|
40468
|
+
bootstrapReplica(request9) {
|
|
40329
40469
|
return this.exclusive(async () => {
|
|
40330
40470
|
const trace = this.operationTrace("bootstrap-replica");
|
|
40331
40471
|
trace("source-check");
|
|
40332
40472
|
const token = this.generationToken;
|
|
40333
|
-
let currentPermit =
|
|
40473
|
+
let currentPermit = request9.permit;
|
|
40334
40474
|
const localCheck = () => {
|
|
40335
40475
|
if (this.closed || token !== this.generationToken) throw new Error("TRAVEL_NODE_CANCELLED");
|
|
40336
40476
|
if (this.runtime || this.process || this.dataProcess) throw new Error("TRAVEL_NODE_GENERATION_COLLISION");
|
|
@@ -40339,7 +40479,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40339
40479
|
const boundedCheck = async () => {
|
|
40340
40480
|
localCheck();
|
|
40341
40481
|
const permit = currentPermit;
|
|
40342
|
-
if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !==
|
|
40482
|
+
if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !== request9.permit[key2]) || ["tenantId", "companionId", "seatId", "nodeId"].some((key2) => permit[key2] !== request9.principal[key2]) || request9.principal.nodeId === this.principal.nodeId || ["tenantId", "companionId", "seatId"].some((key2) => request9.principal[key2] !== this.principal[key2])) throw new Error("TRAVEL_NODE_IDENTITY");
|
|
40343
40483
|
const authority = this.options.authority, status = authority.assertPermitWithStatus ? await authority.assertPermitWithStatus(permit, "CONTROL") : (await authority.assertPermit(permit, "CONTROL"), await authority.status(this.principal));
|
|
40344
40484
|
localCheck();
|
|
40345
40485
|
if (status.expired || status.authorityBootId !== permit.authorityBootId || status.epoch !== permit.epoch || status.activeNodeId !== permit.nodeId || status.activeBootId !== permit.bootId) throw new Error("TRAVEL_NODE_CHECKPOINT");
|
|
@@ -40347,7 +40487,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40347
40487
|
return status.deletionWatermark;
|
|
40348
40488
|
};
|
|
40349
40489
|
const check = async () => {
|
|
40350
|
-
currentPermit = await (
|
|
40490
|
+
currentPermit = await (request9.permitSupplier?.() ?? request9.permit);
|
|
40351
40491
|
return boundedCheck();
|
|
40352
40492
|
};
|
|
40353
40493
|
await this.refreshKey();
|
|
@@ -40359,7 +40499,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40359
40499
|
await check();
|
|
40360
40500
|
const peer = new RecoveryArchiveClient(this.options.bootstrapPeer);
|
|
40361
40501
|
let renewing;
|
|
40362
|
-
const timer =
|
|
40502
|
+
const timer = request9.permitSupplier ? setInterval(() => {
|
|
40363
40503
|
if (!renewing) renewing = check().then(() => {
|
|
40364
40504
|
}, () => {
|
|
40365
40505
|
}).finally(() => {
|
|
@@ -40369,11 +40509,11 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40369
40509
|
timer?.unref();
|
|
40370
40510
|
try {
|
|
40371
40511
|
trace("read-source-archive");
|
|
40372
|
-
const entry = await peer.read(
|
|
40512
|
+
const entry = await peer.read(request9.archiveId);
|
|
40373
40513
|
await check();
|
|
40374
|
-
if (entry.kind !== "LOCAL" || entry.receipt.digest !==
|
|
40514
|
+
if (entry.kind !== "LOCAL" || entry.receipt.digest !== request9.archiveDigest || publicationDigest(entry.manifest) !== request9.expectedDigest || entry.manifest.profile.epoch !== request9.permit.epoch || entry.manifest.profile.buildManifestId !== this.options.build.manifestId) throw new Error("TRAVEL_NODE_CHECKPOINT");
|
|
40375
40515
|
trace("copy-source-archive");
|
|
40376
|
-
await transferRecoveryArchive({ peer, archive: this.archive, id:
|
|
40516
|
+
await transferRecoveryArchive({ peer, archive: this.archive, id: request9.archiveId, expectedDigest: request9.archiveDigest, entry, deletionWatermark: boundedCheck, beforeStep: async () => localCheck() });
|
|
40377
40517
|
await check();
|
|
40378
40518
|
if (!this.replicaRepository) {
|
|
40379
40519
|
const initialize2 = this.db.prepare("SELECT replicas_ready FROM lifecycle WHERE id=1").get()?.replicas_ready === 0;
|
|
@@ -40382,7 +40522,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40382
40522
|
}
|
|
40383
40523
|
await check();
|
|
40384
40524
|
trace("seed-receiver");
|
|
40385
|
-
const replica = await this.replicaRepository.bootstrap({ ...
|
|
40525
|
+
const replica = await this.replicaRepository.bootstrap({ ...request9, authority: this.options.authority, permitSupplier: async () => {
|
|
40386
40526
|
await this.freshKeyWatermark();
|
|
40387
40527
|
await check();
|
|
40388
40528
|
return currentPermit;
|
|
@@ -40436,7 +40576,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40436
40576
|
unresolvedRecovery(prepared) {
|
|
40437
40577
|
let pending = 0;
|
|
40438
40578
|
for (const id2 of prepared.manifest.profile.databaseIds) {
|
|
40439
|
-
const file2 = this.runtime ?
|
|
40579
|
+
const file2 = this.runtime ? join70(this.runtime.stateDir, this.options.layout.databases[id2]) : join70(prepared.snapshot, "databases", id2 + ".sqlite");
|
|
40440
40580
|
const db2 = new DatabaseSync35(file2, { readOnly: true });
|
|
40441
40581
|
try {
|
|
40442
40582
|
if (!db2.prepare("SELECT 1 FROM sqlite_master WHERE name='e7_recovery_items'").get()) continue;
|
|
@@ -40510,7 +40650,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40510
40650
|
}
|
|
40511
40651
|
}
|
|
40512
40652
|
if (!this.runtime || !this.options.commonPeer || (await this.options.authority.status(this.principal)).checkpointDigest !== digest7) throw new Error("TRAVEL_NODE_CHECKPOINT");
|
|
40513
|
-
const permit = this.runtime.assert("CONTROL"), profile = normalizePublicationProfile(JSON.parse(readPrivateFile(
|
|
40653
|
+
const permit = this.runtime.assert("CONTROL"), profile = normalizePublicationProfile(JSON.parse(readPrivateFile(join70(this.runtime.stateDir, ".travel-active.json"), 4 * 1024 * 1024).toString()).profile);
|
|
40514
40654
|
const peer = new RecoveryArchiveClient(this.options.commonPeer);
|
|
40515
40655
|
try {
|
|
40516
40656
|
trace("read-common");
|
|
@@ -40592,7 +40732,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40592
40732
|
});
|
|
40593
40733
|
}
|
|
40594
40734
|
assertActive();
|
|
40595
|
-
const destination =
|
|
40735
|
+
const destination = join70(this.options.generationsDirectory, "runtime-" + randomUUID21()), baselineId = "node-" + randomUUID21();
|
|
40596
40736
|
this.db.prepare("INSERT INTO generations VALUES(?,?,?,?,?)").run(binding, destination, digest7, "{}", "ACTIVATING");
|
|
40597
40737
|
try {
|
|
40598
40738
|
const activation = await activateRuntimeGeneration({
|
|
@@ -40625,27 +40765,27 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40625
40765
|
this.activatingRuntime = void 0;
|
|
40626
40766
|
assertActive();
|
|
40627
40767
|
await assertGatewayResolved();
|
|
40628
|
-
const configFile =
|
|
40768
|
+
const configFile = join70(destination, ".continuity", "engine-config.json"), config = runtimeEngineConfig(this.options.engineConfig, destination, join70(destination, this.options.layout.trees.workspace));
|
|
40629
40769
|
validateTravelChannelConfiguration(config.channels);
|
|
40630
|
-
|
|
40631
|
-
const processDirectory =
|
|
40632
|
-
|
|
40633
|
-
const dataRoot =
|
|
40770
|
+
writeFileSync40(configFile, JSON.stringify(config), { mode: 384, flush: true });
|
|
40771
|
+
const processDirectory = join70(this.options.directory, "processes");
|
|
40772
|
+
mkdirSync31(processDirectory, { recursive: true, mode: 448 });
|
|
40773
|
+
const dataRoot = join70(this.options.directory, "data");
|
|
40634
40774
|
preparePrivateDirectory(dataRoot);
|
|
40635
|
-
this.dataDirectory =
|
|
40775
|
+
this.dataDirectory = join70(dataRoot, "source-" + hash10(binding));
|
|
40636
40776
|
const encode2 = (value2) => value2.toString("base64"), keyService = this.options.keyService;
|
|
40637
|
-
const dataConfigFile =
|
|
40638
|
-
|
|
40777
|
+
const dataConfigFile = join70(destination, ".continuity", "data-config.json");
|
|
40778
|
+
writeFileSync40(dataConfigFile, JSON.stringify({
|
|
40639
40779
|
stateDir: destination,
|
|
40640
40780
|
dataDirectory: this.dataDirectory,
|
|
40641
|
-
objectsDirectory:
|
|
40781
|
+
objectsDirectory: join70(dataRoot, "objects"),
|
|
40642
40782
|
initialize: true,
|
|
40643
40783
|
keySha256: this.options.keySha256,
|
|
40644
40784
|
intervalMs: this.options.dataIntervalMs,
|
|
40645
40785
|
keyService: { ...keyService, ca: encode2(keyService.ca), cert: encode2(keyService.cert), key: encode2(keyService.key) }
|
|
40646
40786
|
}), { mode: 384, flush: true });
|
|
40647
40787
|
this.dataProcess = new SupervisedRuntimeProcess({
|
|
40648
|
-
directory:
|
|
40788
|
+
directory: join70(processDirectory, hash10(binding) + "-data"),
|
|
40649
40789
|
runtime: this.runtime,
|
|
40650
40790
|
entry: this.options.dataBuild.entry,
|
|
40651
40791
|
entrySha256: this.options.dataBuild.sha256,
|
|
@@ -40658,7 +40798,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40658
40798
|
await this.assertDataAvailable();
|
|
40659
40799
|
this.runtime.assert("CONTROL");
|
|
40660
40800
|
this.process = new SupervisedRuntimeProcess({
|
|
40661
|
-
directory:
|
|
40801
|
+
directory: join70(processDirectory, hash10(binding)),
|
|
40662
40802
|
runtime: this.runtime,
|
|
40663
40803
|
entry: this.options.build.entry,
|
|
40664
40804
|
entrySha256: this.options.build.sha256,
|
|
@@ -40669,10 +40809,10 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40669
40809
|
await this.process.start();
|
|
40670
40810
|
assertActive();
|
|
40671
40811
|
await assertGatewayResolved();
|
|
40672
|
-
const checkpointRoot =
|
|
40812
|
+
const checkpointRoot = join70(this.options.directory, "checkpoints");
|
|
40673
40813
|
preparePrivateDirectory(checkpointRoot);
|
|
40674
40814
|
this.checkpointControl = new RuntimeCheckpointControl({
|
|
40675
|
-
directory:
|
|
40815
|
+
directory: join70(checkpointRoot, hash10(binding)),
|
|
40676
40816
|
profile: activation.profile,
|
|
40677
40817
|
principal: this.principal,
|
|
40678
40818
|
bootId: permit.bootId,
|
|
@@ -40731,7 +40871,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40731
40871
|
if (this.runtime) {
|
|
40732
40872
|
const roots = /* @__PURE__ */ new Set([this.runtime.stateDir]);
|
|
40733
40873
|
for (const file2 of Object.values(this.options.layout.databases)) {
|
|
40734
|
-
const place = sqliteStoreLocation(
|
|
40874
|
+
const place = sqliteStoreLocation(join70(this.runtime.stateDir, file2));
|
|
40735
40875
|
if (!place) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
40736
40876
|
roots.add(place.stateDir);
|
|
40737
40877
|
}
|
|
@@ -40886,7 +41026,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40886
41026
|
await check();
|
|
40887
41027
|
this.db.prepare("UPDATE recovery_jobs SET state='DONE' WHERE binding=? AND state='ADMITTED'").run(binding);
|
|
40888
41028
|
}
|
|
40889
|
-
const profile = normalizePublicationProfile(JSON.parse(readPrivateFile(
|
|
41029
|
+
const profile = normalizePublicationProfile(JSON.parse(readPrivateFile(join70(runtime.stateDir, ".travel-active.json"), 4 * 1024 * 1024).toString()).profile);
|
|
40890
41030
|
const unresolvedCritical = this.unresolvedRecovery({ snapshot: runtime.stateDir, manifest: { profile } });
|
|
40891
41031
|
await check();
|
|
40892
41032
|
trace("complete");
|
|
@@ -40919,12 +41059,12 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
40919
41059
|
await check();
|
|
40920
41060
|
await data.pauseForRecovery();
|
|
40921
41061
|
await check();
|
|
40922
|
-
const activation = JSON.parse(readPrivateFile(
|
|
41062
|
+
const activation = JSON.parse(readPrivateFile(join70(runtime.stateDir, ".travel-active.json"), 4 * 1024 * 1024).toString());
|
|
40923
41063
|
const roots = [runtime.stateDir, ...Object.values(activation.layout.databases).map((path37) => {
|
|
40924
|
-
const place = sqliteStoreLocation(
|
|
41064
|
+
const place = sqliteStoreLocation(join70(runtime.stateDir, path37));
|
|
40925
41065
|
if (!place) throw new Error("RECOVERY_CURRENT_LAYOUT");
|
|
40926
41066
|
return place.stateDir;
|
|
40927
|
-
}), ...normalizePublicationProfile(activation.profile).trees.filter((tree) => tree.kind === "file").map((tree) =>
|
|
41067
|
+
}), ...normalizePublicationProfile(activation.profile).trees.filter((tree) => tree.kind === "file").map((tree) => join70(runtime.stateDir, activation.layout.trees[tree.id]))];
|
|
40928
41068
|
const result = await withRecoveryWriterLocks(roots, async () => {
|
|
40929
41069
|
await check();
|
|
40930
41070
|
const result2 = await operation();
|
|
@@ -41047,14 +41187,14 @@ var TravelNodeAgent = class _TravelNodeAgent {
|
|
|
41047
41187
|
if (!/^[a-f0-9]{64}$/.test(String(prior.digest)) || (await this.options.authority.status(this.principal)).checkpointDigest !== prior.digest) throw new Error("TRAVEL_NODE_CHECKPOINT");
|
|
41048
41188
|
const effects3 = await this.options.gateway.preparationEvidence(this.principal);
|
|
41049
41189
|
if (!Number.isSafeInteger(prior.deletion_watermark) || prior.deletion_watermark !== runtime.deletionFloor() || !effects3.loaded || !effects3.effectsSettled || effects3.unresolvedInputs !== 0 || effects3.deletionWatermark !== runtime.deletionFloor()) return null;
|
|
41050
|
-
const profile2 = normalizePublicationProfile(JSON.parse(readPrivateFile(
|
|
41190
|
+
const profile2 = normalizePublicationProfile(JSON.parse(readPrivateFile(join70(runtime.stateDir, ".travel-active.json"), 4 * 1024 * 1024).toString()).profile);
|
|
41051
41191
|
if (this.unresolvedRecovery({ snapshot: runtime.stateDir, manifest: { profile: profile2 } }) > 0) return null;
|
|
41052
41192
|
trace("complete");
|
|
41053
41193
|
return { checkpointDigest: String(prior.digest), safeBoundary: true, effectsSettled: true };
|
|
41054
41194
|
}
|
|
41055
41195
|
if (handoff.state !== "PREPARING") throw new Error("TRAVEL_HANDOFF_STATE");
|
|
41056
41196
|
const effects2 = await this.options.gateway.preparationEvidence(this.principal);
|
|
41057
|
-
const profile = normalizePublicationProfile(JSON.parse(readPrivateFile(
|
|
41197
|
+
const profile = normalizePublicationProfile(JSON.parse(readPrivateFile(join70(runtime.stateDir, ".travel-active.json"), 4 * 1024 * 1024).toString()).profile);
|
|
41058
41198
|
if (!effects2.loaded || !effects2.effectsSettled || effects2.unresolvedInputs !== 0 || effects2.deletionWatermark !== runtime.deletionFloor() || this.unresolvedRecovery({ snapshot: runtime.stateDir, manifest: { profile } }) > 0 || control2.status().sequence === 0) return null;
|
|
41059
41199
|
runtime.pauseInput(true);
|
|
41060
41200
|
if ((await this.process.observe()).busy) return null;
|
|
@@ -41360,7 +41500,7 @@ var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteT
|
|
|
41360
41500
|
};
|
|
41361
41501
|
|
|
41362
41502
|
// src/continuity/authority-client.ts
|
|
41363
|
-
import { Agent as Agent3, request as
|
|
41503
|
+
import { Agent as Agent3, request as request5 } from "node:https";
|
|
41364
41504
|
var publicErrors = /* @__PURE__ */ new Set([
|
|
41365
41505
|
"TRAVEL_HEARTBEAT_REPLAY",
|
|
41366
41506
|
"TRAVEL_BOOT_MISMATCH",
|
|
@@ -41428,7 +41568,7 @@ var TravelReportClient = class {
|
|
|
41428
41568
|
if (error) reject(error);
|
|
41429
41569
|
else resolve47(value2);
|
|
41430
41570
|
};
|
|
41431
|
-
const req =
|
|
41571
|
+
const req = request5(this.url, { method: "POST", agent: readActions.has(input?.action) ? this.agent : this.mutationAgent, headers: {
|
|
41432
41572
|
Authorization: "Bearer " + this.options.credential,
|
|
41433
41573
|
"X-Engine7-Travel-Node": this.options.nodeId,
|
|
41434
41574
|
"Content-Type": "application/json",
|
|
@@ -41587,7 +41727,7 @@ var TravelManagementClient = class extends TravelReportClient {
|
|
|
41587
41727
|
};
|
|
41588
41728
|
|
|
41589
41729
|
// src/continuity/gateway-server.ts
|
|
41590
|
-
import { Agent as Agent4, createServer as createServer5, request as
|
|
41730
|
+
import { Agent as Agent4, createServer as createServer5, request as request6 } from "node:https";
|
|
41591
41731
|
var prefix = "/travel/gateway/v1/";
|
|
41592
41732
|
var requestLimit2 = 24 * 1024 * 1024;
|
|
41593
41733
|
var responseLimit = 48 * 1024 * 1024;
|
|
@@ -41650,7 +41790,7 @@ var TravelGatewayClient = class {
|
|
|
41650
41790
|
};
|
|
41651
41791
|
const url = new URL(this.url);
|
|
41652
41792
|
url.pathname = action === "recovery-deletions" ? "/travel/gateway-recovery/v1" : url.pathname + "/" + action;
|
|
41653
|
-
const req =
|
|
41793
|
+
const req = request6(url, { method: "POST", agent: this.agent, headers: { "Content-Type": "application/json", "Content-Length": body.length } }, (res) => {
|
|
41654
41794
|
responseStarted = true;
|
|
41655
41795
|
const chunks = [];
|
|
41656
41796
|
let bytes = 0;
|
|
@@ -41755,7 +41895,7 @@ var TravelGatewayClient = class {
|
|
|
41755
41895
|
};
|
|
41756
41896
|
|
|
41757
41897
|
// src/continuity/node-supervisor-client.ts
|
|
41758
|
-
import { Agent as Agent5, request as
|
|
41898
|
+
import { Agent as Agent5, request as request7 } from "node:https";
|
|
41759
41899
|
|
|
41760
41900
|
// src/continuity/node-supervisor-protocol.ts
|
|
41761
41901
|
var nodeSupervisorPath = "/travel/node/v1";
|
|
@@ -41885,7 +42025,7 @@ var RemoteTravelNodeSupervisor = class {
|
|
|
41885
42025
|
reported = true;
|
|
41886
42026
|
reject(unavailable());
|
|
41887
42027
|
};
|
|
41888
|
-
const req =
|
|
42028
|
+
const req = request7(this.url, { method: "POST", agent: this.agents[slot], headers: {
|
|
41889
42029
|
Authorization: "Bearer " + this.options.credential,
|
|
41890
42030
|
"X-Engine7-Travel-Node": this.principal.nodeId,
|
|
41891
42031
|
"Content-Type": "application/json",
|
|
@@ -41996,15 +42136,15 @@ var RemoteTravelNodeSupervisor = class {
|
|
|
41996
42136
|
replicaProfile() {
|
|
41997
42137
|
return this.invoke("replicaProfile");
|
|
41998
42138
|
}
|
|
41999
|
-
async bootstrapReplica(
|
|
42139
|
+
async bootstrapReplica(request9) {
|
|
42000
42140
|
const wire = {
|
|
42001
|
-
id:
|
|
42002
|
-
archiveId:
|
|
42003
|
-
archiveDigest:
|
|
42004
|
-
expectedDigest:
|
|
42005
|
-
parentCheckpointDigest:
|
|
42006
|
-
principal:
|
|
42007
|
-
permit:
|
|
42141
|
+
id: request9.id,
|
|
42142
|
+
archiveId: request9.archiveId,
|
|
42143
|
+
archiveDigest: request9.archiveDigest,
|
|
42144
|
+
expectedDigest: request9.expectedDigest,
|
|
42145
|
+
parentCheckpointDigest: request9.parentCheckpointDigest,
|
|
42146
|
+
principal: request9.principal,
|
|
42147
|
+
permit: request9.permit
|
|
42008
42148
|
};
|
|
42009
42149
|
await this.invoke("bootstrapReplica", { request: wire });
|
|
42010
42150
|
}
|
|
@@ -42128,9 +42268,9 @@ function createTravelNodeSupervisorServer(options) {
|
|
|
42128
42268
|
result = await node.replicaProfile?.() ?? null;
|
|
42129
42269
|
break;
|
|
42130
42270
|
case "bootstrapReplica": {
|
|
42131
|
-
const
|
|
42132
|
-
if (!peer || !node.bootstrapReplica || ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].some((key2) =>
|
|
42133
|
-
await node.bootstrapReplica({ ...
|
|
42271
|
+
const request9 = input.request;
|
|
42272
|
+
if (!peer || !node.bootstrapReplica || ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].some((key2) => request9.principal[key2] !== peer.principal[key2])) throw new Error("TRAVEL_NODE_IDENTITY");
|
|
42273
|
+
await node.bootstrapReplica({ ...request9, permitSupplier: () => peer.permit() });
|
|
42134
42274
|
break;
|
|
42135
42275
|
}
|
|
42136
42276
|
case "connectReplica":
|
|
@@ -42646,7 +42786,7 @@ import { DatabaseSync as DatabaseSync38 } from "node:sqlite";
|
|
|
42646
42786
|
import { createHash as createHash51 } from "node:crypto";
|
|
42647
42787
|
import { existsSync as existsSync39 } from "node:fs";
|
|
42648
42788
|
import { accessSync, constants as constants14, lstatSync as lstatSync30, readdirSync as readdirSync15, readFileSync as readFileSync33, readlinkSync, realpathSync as realpathSync28, rmSync as rmSync7 } from "node:fs";
|
|
42649
|
-
import { dirname as dirname26, isAbsolute as isAbsolute14, join as
|
|
42789
|
+
import { dirname as dirname26, isAbsolute as isAbsolute14, join as join71, resolve as resolve43, relative as relative13 } from "node:path";
|
|
42650
42790
|
var identity = (value2) => JSON.stringify([value2.tenantId, value2.companionId, value2.seatId]);
|
|
42651
42791
|
var sha11 = (value2) => createHash51("sha256").update(value2).digest("hex");
|
|
42652
42792
|
var LocalSeatResource = class {
|
|
@@ -42661,7 +42801,7 @@ var LocalSeatResource = class {
|
|
|
42661
42801
|
if (!existsSync39(this.path)) return false;
|
|
42662
42802
|
const stat3 = lstatSync30(this.path);
|
|
42663
42803
|
if (!stat3.isDirectory() || stat3.isSymbolicLink() || realpathSync28(this.path) !== this.path || process.platform !== "win32" && stat3.uid !== process.getuid()) throw new Error("TRAVEL_RETIREMENT_PATH");
|
|
42664
|
-
if (identity(JSON.parse(readPrivateFile(
|
|
42804
|
+
if (identity(JSON.parse(readPrivateFile(join71(this.path, ".travel-seat-resource.json"), 65536).toString())) !== identity(this.identity)) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
|
|
42665
42805
|
return true;
|
|
42666
42806
|
}
|
|
42667
42807
|
async inventory() {
|
|
@@ -42672,7 +42812,7 @@ var LocalSeatResource = class {
|
|
|
42672
42812
|
const result = [];
|
|
42673
42813
|
const visit = (directory2) => {
|
|
42674
42814
|
for (const item of readdirSync15(directory2, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
42675
|
-
const path37 =
|
|
42815
|
+
const path37 = join71(directory2, item.name), version = relative13(this.path, path37);
|
|
42676
42816
|
if (item.isSymbolicLink()) result.push({ version, digest: sha11(readlinkSync(path37)) });
|
|
42677
42817
|
else if (item.isDirectory()) visit(path37);
|
|
42678
42818
|
else if (item.isFile()) {
|
|
@@ -42697,7 +42837,7 @@ var LocalSeatResource = class {
|
|
|
42697
42837
|
removeRoot = false;
|
|
42698
42838
|
}
|
|
42699
42839
|
if (removeRoot) rmSync7(this.path, { recursive: true });
|
|
42700
|
-
else for (const name of readdirSync15(this.path)) if (name !== ".travel-seat-resource.json") rmSync7(
|
|
42840
|
+
else for (const name of readdirSync15(this.path)) if (name !== ".travel-seat-resource.json") rmSync7(join71(this.path, name), { recursive: true });
|
|
42701
42841
|
}
|
|
42702
42842
|
if (this.inventoryNow().length) throw new Error("TRAVEL_RETIREMENT_PENDING");
|
|
42703
42843
|
}
|
|
@@ -42707,7 +42847,7 @@ var TravelRetirement = class {
|
|
|
42707
42847
|
this.options = options;
|
|
42708
42848
|
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");
|
|
42709
42849
|
preparePrivateDirectory(options.directory);
|
|
42710
|
-
const ownerFile =
|
|
42850
|
+
const ownerFile = join71(options.directory, "owner.sqlite");
|
|
42711
42851
|
preparePrivateDatabase(ownerFile);
|
|
42712
42852
|
this.owner = new DatabaseSync38(ownerFile);
|
|
42713
42853
|
try {
|
|
@@ -42716,7 +42856,7 @@ var TravelRetirement = class {
|
|
|
42716
42856
|
this.owner.close();
|
|
42717
42857
|
throw new Error("TRAVEL_RETIREMENT_BUSY", { cause: error });
|
|
42718
42858
|
}
|
|
42719
|
-
const file2 =
|
|
42859
|
+
const file2 = join71(options.directory, "retirement.sqlite");
|
|
42720
42860
|
preparePrivateDatabase(file2);
|
|
42721
42861
|
this.db = new DatabaseSync38(file2);
|
|
42722
42862
|
try {
|
|
@@ -42813,9 +42953,9 @@ var TravelRetirement = class {
|
|
|
42813
42953
|
|
|
42814
42954
|
// src/continuity/local-exit.ts
|
|
42815
42955
|
init_runtime_lock();
|
|
42816
|
-
import { cpSync as cpSync2, existsSync as existsSync40, mkdirSync as
|
|
42956
|
+
import { cpSync as cpSync2, existsSync as existsSync40, mkdirSync as mkdirSync32, readFileSync as readFileSync34, readdirSync as readdirSync16, realpathSync as realpathSync29, rmSync as rmSync8, writeFileSync as writeFileSync41 } from "node:fs";
|
|
42817
42957
|
import { DatabaseSync as DatabaseSync40 } from "node:sqlite";
|
|
42818
|
-
import { isAbsolute as isAbsolute15, join as
|
|
42958
|
+
import { isAbsolute as isAbsolute15, join as join72, dirname as dirname28, resolve as resolve44 } from "node:path";
|
|
42819
42959
|
import { createHash as createHash53, verify as verify3 } from "node:crypto";
|
|
42820
42960
|
|
|
42821
42961
|
// src/continuity/local-dedupe.ts
|
|
@@ -42894,7 +43034,7 @@ var identity2 = (value2) => JSON.stringify([value2.tenantId, value2.companionId,
|
|
|
42894
43034
|
var sha13 = (value2) => createHash53("sha256").update(value2).digest("hex");
|
|
42895
43035
|
function detachReplication(directory2) {
|
|
42896
43036
|
for (const entry of readdirSync16(directory2, { withFileTypes: true })) {
|
|
42897
|
-
const file2 =
|
|
43037
|
+
const file2 = join72(directory2, entry.name);
|
|
42898
43038
|
if (entry.isSymbolicLink()) throw new Error("TRAVEL_EXIT_PATH");
|
|
42899
43039
|
if (entry.isDirectory()) {
|
|
42900
43040
|
detachReplication(file2);
|
|
@@ -42921,7 +43061,7 @@ function detachReplication(directory2) {
|
|
|
42921
43061
|
async function createOrdinaryLocalRecovery(options) {
|
|
42922
43062
|
const source = resolve44(options.stateDir), destination = resolve44(options.destination);
|
|
42923
43063
|
if (!isAbsolute15(options.destination) || source !== options.stateDir || destination !== options.destination || realpathSync29(source) !== source || destination === source || destination.startsWith(source + "/") || source.startsWith(destination + "/") || realpathSync29(dirname28(destination)) !== dirname28(destination)) throw new Error("TRAVEL_EXIT_PATH");
|
|
42924
|
-
const activation = JSON.parse(readFileSync34(
|
|
43064
|
+
const activation = JSON.parse(readFileSync34(join72(source, ".travel-active.json"), "utf8")), permit = activation.permit, { signature: signature2, ...signed } = permit;
|
|
42925
43065
|
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 || !verify3(null, Buffer.from(JSON.stringify(signed)), options.publicKey, Buffer.from(signature2, "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");
|
|
42926
43066
|
return withCheckpointLock(source, async () => {
|
|
42927
43067
|
if (!options.authority || !options.principal || options.authority.publicKey !== options.publicKey) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
@@ -42930,7 +43070,7 @@ async function createOrdinaryLocalRecovery(options) {
|
|
|
42930
43070
|
if (realpathSync29(destination) !== destination) throw new Error("TRAVEL_EXIT_PATH");
|
|
42931
43071
|
let receipt2;
|
|
42932
43072
|
try {
|
|
42933
|
-
receipt2 = JSON.parse(readPrivateFile(
|
|
43073
|
+
receipt2 = JSON.parse(readPrivateFile(join72(destination, ".continuity/travel-exit-receipt.json"), 65536).toString());
|
|
42934
43074
|
} catch {
|
|
42935
43075
|
throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
|
|
42936
43076
|
}
|
|
@@ -42940,10 +43080,10 @@ async function createOrdinaryLocalRecovery(options) {
|
|
|
42940
43080
|
return receipt2;
|
|
42941
43081
|
}
|
|
42942
43082
|
try {
|
|
42943
|
-
|
|
43083
|
+
mkdirSync32(destination, { mode: 448 });
|
|
42944
43084
|
cpSync2(source, destination, { recursive: true, force: false, errorOnExist: true, filter: (path37) => copyLocalExitPath(source, path37) });
|
|
42945
43085
|
detachReplication(destination);
|
|
42946
|
-
const store = new PlatformReceiptStore(
|
|
43086
|
+
const store = new PlatformReceiptStore(join72(destination, ".continuity/feishu-receipts.sqlite"), options.platformNamespace);
|
|
42947
43087
|
try {
|
|
42948
43088
|
store.importTravelReceipt(options.dedupeReceipt);
|
|
42949
43089
|
} finally {
|
|
@@ -42963,7 +43103,7 @@ async function createOrdinaryLocalRecovery(options) {
|
|
|
42963
43103
|
await proof.check();
|
|
42964
43104
|
const body = { ...receipt2, ordinaryFilesDigest: await localExitFilesDigest(destination, true) };
|
|
42965
43105
|
const result = { ...body, digest: sha13(JSON.stringify(body)) };
|
|
42966
|
-
|
|
43106
|
+
writeFileSync41(join72(destination, ".continuity/travel-exit-receipt.json"), JSON.stringify(result), { mode: 384, flag: "wx", flush: true });
|
|
42967
43107
|
return result;
|
|
42968
43108
|
} catch (error) {
|
|
42969
43109
|
if (existsSync40(destination)) rmSync8(destination, { recursive: true });
|
|
@@ -43109,11 +43249,11 @@ function initialPairingSnapshot(options) {
|
|
|
43109
43249
|
...pending ? { transfer: { id: state2.requestId, target, state: error ? "ABORTED" : ["STARTING", "CAPTURING", "LOCAL_ACTIVE"].includes(state2.state) ? state2.state : target === "local" ? "SYNCHRONIZING" : "PREPARING", ...error && /^[A-Z_]{1,95}$/.test(error) ? { error } : {}, ...state2.startedAt ? { startedAt: state2.startedAt } : {}, ...state2.updatedAt ? { updatedAt: state2.updatedAt } : {}, ...state2.progress ? { progress: Object.fromEntries(["phase", "completedFiles", "totalFiles", "completedBytes", "totalBytes"].filter((k) => state2.progress[k] !== void 0).map((k) => [k, state2.progress[k]])) } : {} } } : {}
|
|
43110
43250
|
};
|
|
43111
43251
|
}
|
|
43112
|
-
var write2 = (file2, value2) =>
|
|
43252
|
+
var write2 = (file2, value2) => writeFileSync42(file2, JSON.stringify(value2), { mode: 384, flush: true });
|
|
43113
43253
|
var delay = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
43114
43254
|
function rpc(url, tls2, token, body, timeout = 6e5) {
|
|
43115
43255
|
return new Promise((done, reject) => {
|
|
43116
|
-
const req =
|
|
43256
|
+
const req = request8(url, { method: "POST", ...tls2, minVersion: "TLSv1.3", headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" } }, (res) => {
|
|
43117
43257
|
const chunks = [];
|
|
43118
43258
|
let bytes = 0;
|
|
43119
43259
|
res.on("data", (chunk) => {
|
|
@@ -43145,7 +43285,7 @@ function startPairingRelays(material, spawnRelay = spawn7) {
|
|
|
43145
43285
|
if (stopped) return;
|
|
43146
43286
|
const forwards = state2.lane.forward.flatMap((name) => ["-L", `127.0.0.1:${ports[name]}:127.0.0.1:${ports[name]}`]);
|
|
43147
43287
|
const reverse = state2.lane.reverse.flatMap((name) => ["-R", `127.0.0.1:${ports[name]}:127.0.0.1:${ports[name]}`]);
|
|
43148
|
-
const child = spawnRelay("/usr/bin/ssh", ["-F", "/dev/null", "-N", "-T", "-p", String(material.sshPort), "-i",
|
|
43288
|
+
const child = spawnRelay("/usr/bin/ssh", ["-F", "/dev/null", "-N", "-T", "-p", String(material.sshPort), "-i", join73(directory2, "relay.key"), "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "IdentityAgent=none", "-o", "StrictHostKeyChecking=yes", "-o", "UserKnownHostsFile=" + join73(directory2, "known_hosts"), "-o", "GlobalKnownHostsFile=/dev/null", "-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ExitOnForwardFailure=yes", "-o", "ServerAliveInterval=5", "-o", "ServerAliveCountMax=3", ...forwards, ...reverse, material.relayUser + "@" + material.host], { stdio: "ignore" });
|
|
43149
43289
|
state2.child = child;
|
|
43150
43290
|
child.once("error", () => {
|
|
43151
43291
|
});
|
|
@@ -43172,9 +43312,9 @@ function startPairingRelays(material, spawnRelay = spawn7) {
|
|
|
43172
43312
|
} };
|
|
43173
43313
|
}
|
|
43174
43314
|
async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
43175
|
-
const directory2 = material.directory, ports = material.ports, binding = JSON.parse(readPrivateFile(
|
|
43315
|
+
const directory2 = material.directory, ports = material.ports, binding = JSON.parse(readPrivateFile(join73(directory2, "binding.json"), 65536).toString());
|
|
43176
43316
|
if (JSON.stringify(binding.identity) !== JSON.stringify(material.identity)) throw new Error("TRAVEL_PAIRING_IDENTITY");
|
|
43177
|
-
const ownerFile =
|
|
43317
|
+
const ownerFile = join73(directory2, "host-owner.sqlite");
|
|
43178
43318
|
preparePrivateDatabase(ownerFile);
|
|
43179
43319
|
const owner = new DatabaseSync41(ownerFile);
|
|
43180
43320
|
try {
|
|
@@ -43183,15 +43323,15 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
|
43183
43323
|
owner.close();
|
|
43184
43324
|
throw new Error("TRAVEL_PAIRING_BUSY");
|
|
43185
43325
|
}
|
|
43186
|
-
const lifecycleFile =
|
|
43326
|
+
const lifecycleFile = join73(directory2, "lifecycle.json");
|
|
43187
43327
|
let lifecycle = existsSync42(lifecycleFile) ? JSON.parse(readPrivateFile(lifecycleFile, 65536).toString()) : { state: "PAIRED", automatic: true };
|
|
43188
43328
|
const save = () => {
|
|
43189
43329
|
lifecycle.updatedAt = Date.now();
|
|
43190
43330
|
write2(lifecycleFile, lifecycle);
|
|
43191
43331
|
};
|
|
43192
43332
|
const tls2 = { ca: readFileSync36(material.tls.caFile), cert: readFileSync36(material.tls.certFile), key: readPrivateFile(material.tls.keyFile, 65536) };
|
|
43193
|
-
const consoleToken = readPrivateFile(
|
|
43194
|
-
const pairToken = readPrivateFile(
|
|
43333
|
+
const consoleToken = readPrivateFile(join73(directory2, "console-token"), 1024).toString().trim();
|
|
43334
|
+
const pairToken = readPrivateFile(join73(directory2, "stage/control/pair-token"), 1024).toString().trim();
|
|
43195
43335
|
const url = (port, path37) => `https://127.0.0.1:${port}${path37}`;
|
|
43196
43336
|
const remote = (action, payload) => rpc(url(ports.console, "/travel/console/v1"), { ca: tls2.ca }, consoleToken, { version: 1, identity: material.identity, action, ...payload ? { payload } : {} });
|
|
43197
43337
|
let gatewayIngress;
|
|
@@ -43209,7 +43349,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
|
43209
43349
|
};
|
|
43210
43350
|
let stopped = false, pendingInitial = false, localService, initial;
|
|
43211
43351
|
const relays = startRelays(material);
|
|
43212
|
-
const localConfigFile =
|
|
43352
|
+
const localConfigFile = join73(directory2, "local/node.json");
|
|
43213
43353
|
const localConfig = () => JSON.parse(readPrivateFile(localConfigFile, 4 * 1024 * 1024).toString());
|
|
43214
43354
|
const localClient = new RemoteTravelNodeSupervisor({ ...tls2, url: url(ports.localManagement, "/travel/node/v1"), principal: binding.local, credential: binding.tokens.local });
|
|
43215
43355
|
const cloudClient = new RemoteTravelNodeSupervisor({ ...tls2, url: url(ports.cloudManagement, "/travel/node/v1"), principal: binding.cloud, credential: binding.tokens.cloud });
|
|
@@ -43218,7 +43358,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
|
43218
43358
|
let stoppedOrdinary = false, leaseAttempted = false;
|
|
43219
43359
|
let web, hostServer, webStarting;
|
|
43220
43360
|
const bindWeb = () => webStarting ??= (async () => {
|
|
43221
|
-
const module = await import(pathToFileURL2(
|
|
43361
|
+
const module = await import(pathToFileURL2(join73(material.engineDir, "dist/web-console.mjs")).href);
|
|
43222
43362
|
web = module.createConsoleServer({ configs: [material.configPath], engineDir: material.engineDir, travelTest: { storage: material.hostStorage ?? resolve46(directory2, "../../hosts") } });
|
|
43223
43363
|
await new Promise((done, reject) => {
|
|
43224
43364
|
web.server.once("error", reject);
|
|
@@ -43241,9 +43381,9 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
|
43241
43381
|
};
|
|
43242
43382
|
const resumeOrdinary = async () => {
|
|
43243
43383
|
if (!stoppedOrdinary || stopped || sourcePid() !== null) return;
|
|
43244
|
-
const log = openSync21(
|
|
43384
|
+
const log = openSync21(join73(directory2, "ordinary-resumed.log"), "a", 384);
|
|
43245
43385
|
try {
|
|
43246
|
-
const child = spawn7(process.execPath, [
|
|
43386
|
+
const child = spawn7(process.execPath, [join73(material.engineDir, "dist/main.mjs"), "--engine-config", material.configPath], { cwd: material.stateDir, detached: true, stdio: ["ignore", log, log] });
|
|
43247
43387
|
await new Promise((done, reject) => {
|
|
43248
43388
|
child.once("spawn", done);
|
|
43249
43389
|
child.once("error", reject);
|
|
@@ -43287,7 +43427,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
|
43287
43427
|
if (preflight.activeNodeId !== null && !preflight.expired) throw new Error("TRAVEL_INITIAL_SOURCE_RUNNING");
|
|
43288
43428
|
lifecycle.previousInitialDigest = preflight.checkpointDigest;
|
|
43289
43429
|
const pid = sourcePid();
|
|
43290
|
-
if (pid !== null && existsSync42(
|
|
43430
|
+
if (pid !== null && existsSync42(join73(directory2, "first-baseline/ready.json"))) {
|
|
43291
43431
|
lifecycle.recapture = true;
|
|
43292
43432
|
save();
|
|
43293
43433
|
}
|
|
@@ -43303,19 +43443,19 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
|
43303
43443
|
lifecycle.state = "CAPTURING";
|
|
43304
43444
|
delete lifecycle.progress;
|
|
43305
43445
|
save();
|
|
43306
|
-
const baselineDir =
|
|
43307
|
-
if (lifecycle.recapture && existsSync42(
|
|
43308
|
-
renameSync12(baselineDir,
|
|
43446
|
+
const baselineDir = join73(directory2, "first-baseline");
|
|
43447
|
+
if (lifecycle.recapture && existsSync42(join73(baselineDir, "ready.json"))) {
|
|
43448
|
+
renameSync12(baselineDir, join73(directory2, "unused-baseline-" + randomUUID23()));
|
|
43309
43449
|
delete lifecycle.recapture;
|
|
43310
43450
|
save();
|
|
43311
43451
|
}
|
|
43312
43452
|
let baseline;
|
|
43313
|
-
if (!existsSync42(
|
|
43314
|
-
if (existsSync42(baselineDir)) renameSync12(baselineDir,
|
|
43315
|
-
const key2 = readPrivateFile(
|
|
43453
|
+
if (!existsSync42(join73(baselineDir, "ready.json"))) {
|
|
43454
|
+
if (existsSync42(baselineDir)) renameSync12(baselineDir, join73(directory2, "failed-baseline-" + randomUUID23()));
|
|
43455
|
+
const key2 = readPrivateFile(join73(directory2, "data.key"), 32);
|
|
43316
43456
|
let lastProgressSave = 0, lastPhase = "";
|
|
43317
43457
|
try {
|
|
43318
|
-
await runInitialBaselineWorker({ stateDir: material.stateDir, workspace: material.workspace, selection: material.layout.inventorySelection, directory: baselineDir, objectsDirectory:
|
|
43458
|
+
await runInitialBaselineWorker({ stateDir: material.stateDir, workspace: material.workspace, selection: material.layout.inventorySelection, directory: baselineDir, objectsDirectory: join73(localConfig().directory, "data", "objects"), keyFile: join73(directory2, "data.key"), identity: material.identity, engineVersion: JSON.parse(readFileSync36(join73(material.engineDir, "package.json"), "utf8")).version, buildManifestId: material.buildManifestId }, (progress) => {
|
|
43319
43459
|
if (stopped) throw new Error("TRAVEL_INITIAL_CANCELLED");
|
|
43320
43460
|
const now2 = Date.now(), changed = progress.phase !== lastPhase;
|
|
43321
43461
|
lifecycle.progress = progress;
|
|
@@ -43336,12 +43476,12 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
|
43336
43476
|
}
|
|
43337
43477
|
await baseline?.close();
|
|
43338
43478
|
if (stopped) throw new Error("TRAVEL_INITIAL_CANCELLED");
|
|
43339
|
-
const receipt2 = JSON.parse(readPrivateFile(
|
|
43479
|
+
const receipt2 = JSON.parse(readPrivateFile(join73(baselineDir, "ready.json"), 65536).toString());
|
|
43340
43480
|
if (JSON.stringify(receipt2.layout) !== JSON.stringify(material.layout)) throw new Error("TRAVEL_INITIAL_LAYOUT_CHANGED");
|
|
43341
43481
|
const config = localConfig();
|
|
43342
43482
|
config.layout = receipt2.layout;
|
|
43343
|
-
config.objectsDirectory = receipt2.objectsDirectory ??
|
|
43344
|
-
config.initialReplica = { directory:
|
|
43483
|
+
config.objectsDirectory = receipt2.objectsDirectory ?? join73(baselineDir, "data/objects");
|
|
43484
|
+
config.initialReplica = { directory: join73(baselineDir, "replica-publications"), profile: receipt2.profile, databases: Object.fromEntries(receipt2.profile.databaseIds.map((id2) => [id2, join73(baselineDir, "replica", id2 + ".sqlite")])) };
|
|
43345
43485
|
if (stopped) throw new Error("TRAVEL_INITIAL_CANCELLED");
|
|
43346
43486
|
write2(localConfigFile, config);
|
|
43347
43487
|
const current2 = await authority.status();
|
|
@@ -43363,7 +43503,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
|
43363
43503
|
} }, receipt2.digest, () => {
|
|
43364
43504
|
if (stopped) throw new Error("TRAVEL_INITIAL_CANCELLED");
|
|
43365
43505
|
});
|
|
43366
|
-
write2(
|
|
43506
|
+
write2(join73(material.stateDir, ".continuity/travel-managed.json"), { version: 1, identity: material.identity, hostConfig: join73(directory2, "host.json") });
|
|
43367
43507
|
lifecycle.state = "LOCAL_ACTIVE";
|
|
43368
43508
|
delete lifecycle.progress;
|
|
43369
43509
|
save();
|
|
@@ -43399,8 +43539,8 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
|
43399
43539
|
if (!resolve46(stateDir).startsWith(resolve46(directory2, "local/generations") + "/")) throw new Error("recovery_unavailable");
|
|
43400
43540
|
lifecycle.recoveryRuntime = stateDir;
|
|
43401
43541
|
save();
|
|
43402
|
-
const configFile =
|
|
43403
|
-
const raw = JSON.parse(readPrivateFile(
|
|
43542
|
+
const configFile = join73(directory2, "ordinary-recovery.json"), dedupeFile = join73(directory2, "exit-dedupe.json");
|
|
43543
|
+
const raw = JSON.parse(readPrivateFile(join73(directory2, "engine-config.json"), 4 * 1024 * 1024).toString()), feishu = raw.channels?.feishu;
|
|
43404
43544
|
const platformNamespace = material.platformNamespace ?? (feishu?.enabled ? "feishu:" + (feishu.appId ?? feishu.accounts?.default?.appId) : "travel-gateway");
|
|
43405
43545
|
await remote("recover", payload);
|
|
43406
43546
|
const source = await authority.retirementStatus();
|
|
@@ -43408,7 +43548,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
|
43408
43548
|
write2(dedupeFile, dedupe);
|
|
43409
43549
|
write2(configFile, {
|
|
43410
43550
|
stateDir,
|
|
43411
|
-
destination:
|
|
43551
|
+
destination: join73(material.stateDir, "travel-recovered-" + material.taskId),
|
|
43412
43552
|
identity: material.identity,
|
|
43413
43553
|
checkpointDigest: dedupe.checkpointDigest,
|
|
43414
43554
|
publicKey: binding.publicKey,
|
|
@@ -43461,7 +43601,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
|
43461
43601
|
if (attempt >= 30) throw new Error("TRAVEL_PAIRING_HEALTH");
|
|
43462
43602
|
await delay(500);
|
|
43463
43603
|
}
|
|
43464
|
-
hostServer = createTravelConsoleServer({ manager: { execute }, identity: material.identity, token: consoleToken, startInitial, cert: readFileSync36(
|
|
43604
|
+
hostServer = createTravelConsoleServer({ manager: { execute }, identity: material.identity, token: consoleToken, startInitial, cert: readFileSync36(join73(directory2, "tls/local-server.pem")), key: readPrivateFile(join73(directory2, "tls/local-server.key"), 65536) });
|
|
43465
43605
|
await new Promise((done, reject) => {
|
|
43466
43606
|
hostServer.once("error", reject);
|
|
43467
43607
|
hostServer.listen(ports.hostControl, "127.0.0.1", done);
|
|
@@ -43472,7 +43612,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
|
43472
43612
|
});
|
|
43473
43613
|
}
|
|
43474
43614
|
if (!sourcePid() && !lifecycle.error) await bindWeb();
|
|
43475
|
-
write2(
|
|
43615
|
+
write2(join73(directory2, "host-ready.json"), { identity: material.identity, paired: true, pid: process.pid });
|
|
43476
43616
|
const close = async () => {
|
|
43477
43617
|
if (stopped) return;
|
|
43478
43618
|
stopped = true;
|
|
@@ -43483,7 +43623,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
|
|
|
43483
43623
|
await pauseInitialPairingIngress(lifecycle.state, gatewayIngress, pair);
|
|
43484
43624
|
await initial;
|
|
43485
43625
|
await pauseInitialPairingIngress(lifecycle.state, gatewayIngress, pair);
|
|
43486
|
-
if (initialOnly && !existsSync42(
|
|
43626
|
+
if (initialOnly && !existsSync42(join73(material.stateDir, ".continuity/travel-managed.json"))) {
|
|
43487
43627
|
lifecycle = { state: "PAIRED", automatic: false };
|
|
43488
43628
|
save();
|
|
43489
43629
|
}
|