engine7 7.1.148 → 7.1.150

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.
@@ -289,14 +289,14 @@ var init_capture_cache = __esm({
289
289
  });
290
290
 
291
291
  // src/travel/apply-transaction.ts
292
- import { closeSync as closeSync2, existsSync as existsSync4, fsyncSync as fsyncSync2, lstatSync as lstatSync4, mkdirSync as mkdirSync3, openSync as openSync2, readFileSync as readFileSync3, readSync as readSync2, renameSync as renameSync3, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
293
- import { dirname as dirname2, join as join4, resolve } from "node:path";
292
+ import { closeSync as closeSync2, existsSync as existsSync4, fsyncSync as fsyncSync2, linkSync, lstatSync as lstatSync4, mkdirSync as mkdirSync3, openSync as openSync2, readFileSync as readFileSync4, readSync as readSync2, renameSync as renameSync3, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
293
+ import { dirname as dirname2, join as join5, resolve as resolve2 } from "node:path";
294
294
  import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
295
295
  function assertPath(root, rel) {
296
296
  if (!safeRel(rel)) throw Error("TRAVEL_UNSAFE_PATH");
297
297
  let path5 = root;
298
298
  for (const part of rel.split("/")) {
299
- path5 = join4(path5, part);
299
+ path5 = join5(path5, part);
300
300
  try {
301
301
  if (lstatSync4(path5).isSymbolicLink()) throw Error("TRAVEL_UNSAFE_PATH");
302
302
  } catch (e) {
@@ -305,7 +305,7 @@ function assertPath(root, rel) {
305
305
  }
306
306
  return path5;
307
307
  }
308
- function atomic(path5, body) {
308
+ function atomic(path5, body, exclusive = false) {
309
309
  const temp = path5 + "." + randomUUID3() + ".tmp";
310
310
  let fd;
311
311
  try {
@@ -314,20 +314,21 @@ function atomic(path5, body) {
314
314
  fsyncSync2(fd);
315
315
  closeSync2(fd);
316
316
  fd = void 0;
317
- renameSync3(temp, path5);
317
+ if (exclusive) linkSync(temp, path5);
318
+ else renameSync3(temp, path5);
318
319
  } finally {
319
320
  if (fd !== void 0) closeSync2(fd);
320
321
  rmSync(temp, { force: true });
321
322
  }
322
323
  }
323
- function save(root, journal) {
324
+ function save(root, journal, exclusive = false) {
324
325
  const { digest: _, ...body } = journal;
325
- atomic(journalFile(root), JSON.stringify({ ...body, digest: hash(JSON.stringify(body)) }));
326
+ atomic(journalFile(root), JSON.stringify({ ...body, digest: hash(JSON.stringify(body)) }), exclusive);
326
327
  }
327
328
  function read(root) {
328
329
  if (!existsSync4(journalFile(root))) return;
329
- const value = JSON.parse(readFileSync3(journalFile(root), "utf8")), { digest: digest2, ...body } = value;
330
- if (value.version !== 1 || value.root !== resolve(root) || !Number.isSafeInteger(value.pid) || value.pid < 1 || !/^[a-f0-9-]{36}$/.test(value.token) || typeof value.committed !== "boolean" || digest2 !== hash(JSON.stringify(body)) || !Array.isArray(value.entries) || value.entries.some((e) => !safeRel(e.rel) || e.oldSha !== void 0 && !/^[a-f0-9]{64}$/.test(e.oldSha) || e.newSha !== void 0 && !/^[a-f0-9]{64}$/.test(e.newSha))) throw Error("TRAVEL_APPLY_RECOVERY_INVALID");
330
+ const value = JSON.parse(readFileSync4(journalFile(root), "utf8")), { digest: digest2, ...body } = value;
331
+ if (value.version !== 1 || value.root !== resolve2(root) || !Number.isSafeInteger(value.pid) || value.pid < 1 || !/^[a-f0-9-]{36}$/.test(value.token) || typeof value.committed !== "boolean" || digest2 !== hash(JSON.stringify(body)) || !Array.isArray(value.entries) || value.entries.some((e) => !safeRel(e.rel) || e.oldSha !== void 0 && !/^[a-f0-9]{64}$/.test(e.oldSha) || e.newSha !== void 0 && !/^[a-f0-9]{64}$/.test(e.newSha))) throw Error("TRAVEL_APPLY_RECOVERY_INVALID");
331
332
  return value;
332
333
  }
333
334
  function matches(path5, sha) {
@@ -360,14 +361,14 @@ function rollback(root, journal) {
360
361
  renameSync3(old, dest);
361
362
  } else if (!entry.oldSha) rmSync(dest, { force: true });
362
363
  }
363
- const state = join4(root, ".travel/sync-state.json");
364
+ const state = join5(root, ".travel/sync-state.json");
364
365
  if (journal.previousState !== null) atomic(state, journal.previousState);
365
366
  else rmSync(state, { force: true });
366
367
  rmSync(journalFile(root), { force: true });
367
368
  rmSync(stage, { recursive: true, force: true });
368
369
  }
369
370
  function recoverPendingApply(root) {
370
- root = resolve(root);
371
+ root = resolve2(root);
371
372
  const journal = read(root);
372
373
  if (!journal) return;
373
374
  if (!journal.committed) {
@@ -385,24 +386,27 @@ function recoverPendingApply(root) {
385
386
  }
386
387
  function newApplyStage(root) {
387
388
  const token = randomUUID3(), path5 = assertPath(root, ".travel-sync-staging/" + token);
388
- mkdirSync3(join4(path5, "new"), { recursive: true, mode: 448 });
389
+ mkdirSync3(join5(path5, "new"), { recursive: true, mode: 448 });
389
390
  return { token, path: path5 };
390
391
  }
391
392
  function promoteFiles(root, stage, entries, commit) {
392
393
  let previousState = null;
393
394
  try {
394
- previousState = readFileSync3(join4(root, ".travel/sync-state.json"), "utf8");
395
+ previousState = readFileSync4(join5(root, ".travel/sync-state.json"), "utf8");
395
396
  } catch {
396
397
  }
397
- const journal = { version: 1, pid: process.pid, token: stage.token, root: resolve(root), committed: false, entries, previousState };
398
+ const journal = { version: 1, pid: process.pid, token: stage.token, root: resolve2(root), committed: false, entries, previousState };
398
399
  for (const entry of entries) {
399
400
  const dest = assertPath(root, entry.rel);
400
401
  if (entry.before ? fileFingerprint(dest) !== entry.before : existsSync4(dest)) throw Error("TRAVEL_DESTINATION_CHANGED");
401
402
  }
402
- mkdirSync3(join4(root, ".travel"), { recursive: true, mode: 448 });
403
- const fd = openSync2(journalFile(root), "wx", 384);
404
- closeSync2(fd);
405
- save(root, journal);
403
+ mkdirSync3(join5(root, ".travel"), { recursive: true, mode: 448 });
404
+ try {
405
+ save(root, journal, true);
406
+ } catch (error) {
407
+ if (error.code === "EEXIST") throw Error("TRAVEL_APPLY_BUSY");
408
+ throw error;
409
+ }
406
410
  try {
407
411
  for (const entry of entries) {
408
412
  const dest = assertPath(root, entry.rel), old = assertPath(stage.path, "old/" + entry.rel);
@@ -430,7 +434,7 @@ var init_apply_transaction = __esm({
430
434
  "src/travel/apply-transaction.ts"() {
431
435
  "use strict";
432
436
  init_capture_cache();
433
- journalFile = (root) => join4(root, ".travel/apply-transaction.json");
437
+ journalFile = (root) => join5(root, ".travel/apply-transaction.json");
434
438
  safeRel = (rel) => !!rel && !/[\\:\x00-\x1f]/.test(rel) && rel.split("/").every((p) => p && p !== "." && p !== "..");
435
439
  hash = (body) => createHash2("sha256").update(body).digest("hex");
436
440
  }
@@ -2094,6 +2098,18 @@ var init_registry = __esm({
2094
2098
  effect: "hot",
2095
2099
  internal: true
2096
2100
  },
2101
+ // 1130 Gmail 冷启动:连接即触发 + 每日巡查,新装机默认开。model 为空走 topics.clean.model → extract → mem7 链(免费档自动退回主力模型)
2102
+ { path: "gmailColdstart.enabled", type: "boolean", group: "feature", label: "Gmail \u51B7\u542F\u52A8\uFF08\u8FDE\u63A5\u540E\u81EA\u52A8\u8BFB\u5386\u53F2\u8BA4\u4EBA\uFF09", effect: "hot", internal: true },
2103
+ { path: "gmailColdstart.model", type: "string", group: "model", label: "Gmail \u51B7\u542F\u52A8\u63D0\u70BC\u6A21\u578B\uFF08\u7A7A=\u6CBF\u7528\u8BB0\u5FC6\u63D0\u53D6\u6A21\u578B\uFF0C\u514D\u8D39\u6863\u81EA\u52A8\u9000\u56DE\u4E3B\u529B\uFF09", effect: "hot", internal: true },
2104
+ {
2105
+ path: "gmailColdstart.patrolHour",
2106
+ type: "number",
2107
+ group: "feature",
2108
+ label: "Gmail \u6BCF\u65E5\u5DE1\u67E5\u6574\u70B9\uFF080-23\uFF09",
2109
+ effect: "hot",
2110
+ internal: true,
2111
+ validate: (value) => Number.isInteger(value) && Number(value) >= 0 && Number(value) <= 23 ? null : "\u5DE1\u67E5\u6574\u70B9\u987B\u4E3A 0-23"
2112
+ },
2097
2113
  {
2098
2114
  path: "mem7.turnReadBudgetMs",
2099
2115
  type: "number",
@@ -3229,8 +3245,8 @@ __export(secrets_env_exports, {
3229
3245
  writeSecretsValue: () => writeSecretsValue
3230
3246
  });
3231
3247
  import { createHash as createHash4 } from "node:crypto";
3232
- import { chmodSync, existsSync as existsSync9, mkdirSync as mkdirSync6, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "node:fs";
3233
- import { basename, dirname as dirname3, join as join10, normalize, resolve as resolve4 } from "node:path";
3248
+ import { chmodSync, existsSync as existsSync9, mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync6 } from "node:fs";
3249
+ import { basename, dirname as dirname3, join as join11, normalize, resolve as resolve5 } from "node:path";
3234
3250
  function secretsHome() {
3235
3251
  return process.env.HOME || process.env.USERPROFILE || ".";
3236
3252
  }
@@ -3241,17 +3257,17 @@ function stateKey(stateDir) {
3241
3257
  return createHash4("sha256").update(normalizeStateDir(stateDir)).digest("hex").slice(0, 8);
3242
3258
  }
3243
3259
  function isDefaultStateDir(stateDir) {
3244
- return normalizeStateDir(stateDir) === normalizeStateDir(join10(secretsHome(), ".engine7"));
3260
+ return normalizeStateDir(stateDir) === normalizeStateDir(join11(secretsHome(), ".engine7"));
3245
3261
  }
3246
3262
  function secretsCandidates(stateDir, configName) {
3247
- const shared = join10(secretsHome(), ".engine7-secrets", `${configName}.env`);
3263
+ const shared = join11(secretsHome(), ".engine7-secrets", `${configName}.env`);
3248
3264
  const inState = [
3249
- join10(stateDir, "configs", `.env.${configName}`),
3250
- join10(stateDir, "configs", ".env")
3265
+ join11(stateDir, "configs", `.env.${configName}`),
3266
+ join11(stateDir, "configs", ".env")
3251
3267
  ];
3252
3268
  if (isDefaultStateDir(stateDir)) return [shared, ...inState];
3253
3269
  return [
3254
- join10(secretsHome(), ".engine7-secrets", `${configName}-${stateKey(stateDir)}.env`),
3270
+ join11(secretsHome(), ".engine7-secrets", `${configName}-${stateKey(stateDir)}.env`),
3255
3271
  shared,
3256
3272
  ...inState
3257
3273
  ];
@@ -3260,7 +3276,7 @@ function readSecretsEntries(stateDir, configName) {
3260
3276
  for (const p of secretsCandidates(stateDir, configName)) {
3261
3277
  if (!existsSync9(p)) continue;
3262
3278
  const entries = [];
3263
- for (const line of readFileSync6(p, "utf-8").split("\n")) {
3279
+ for (const line of readFileSync7(p, "utf-8").split("\n")) {
3264
3280
  const t = line.trim();
3265
3281
  if (!t || t.startsWith("#")) continue;
3266
3282
  const eq = t.indexOf("=");
@@ -3287,7 +3303,7 @@ function loadSecretsEnv(stateDir, configName, options = {}) {
3287
3303
  return selected.path;
3288
3304
  }
3289
3305
  function resolveConfigIdentity(configPath) {
3290
- const abs = resolve4(configPath);
3306
+ const abs = resolve5(configPath);
3291
3307
  const cfgName = basename(abs, ".json");
3292
3308
  const cfgDir = dirname3(abs);
3293
3309
  const stateDir = basename(cfgDir) === "configs" ? dirname3(cfgDir) : cfgDir;
@@ -3296,7 +3312,7 @@ function resolveConfigIdentity(configPath) {
3296
3312
  function engineStateDirOfConfig(configPath, env = process.env) {
3297
3313
  let raw;
3298
3314
  try {
3299
- raw = JSON.parse(readFileSync6(configPath, "utf-8"));
3315
+ raw = JSON.parse(readFileSync7(configPath, "utf-8"));
3300
3316
  } catch {
3301
3317
  return null;
3302
3318
  }
@@ -3312,13 +3328,13 @@ function loadSecretsEnvForConfig(configPath, options = {}) {
3312
3328
  }
3313
3329
  function writeSecretsValue(configPath, envKey, value) {
3314
3330
  const { stateDir, configName } = resolveConfigIdentity(configPath);
3315
- const dir = join10(secretsHome(), ".engine7-secrets");
3331
+ const dir = join11(secretsHome(), ".engine7-secrets");
3316
3332
  mkdirSync6(dir, { recursive: true });
3317
3333
  const file = secretsCandidates(stateDir, configName)[0];
3318
3334
  const seedFrom = existsSync9(file) ? file : secretsCandidates(stateDir, configName).find((p) => existsSync9(p)) ?? null;
3319
3335
  const lines = [];
3320
3336
  if (seedFrom) {
3321
- for (const line of readFileSync6(seedFrom, "utf8").split(/\r?\n/)) {
3337
+ for (const line of readFileSync7(seedFrom, "utf8").split(/\r?\n/)) {
3322
3338
  if (new RegExp(`^\\s*${envKey}\\s*=`).test(line)) continue;
3323
3339
  lines.push(line);
3324
3340
  }
@@ -3349,7 +3365,7 @@ __export(oss_broker_exports, {
3349
3365
  withOssBatches: () => withOssBatches
3350
3366
  });
3351
3367
  import { randomBytes } from "node:crypto";
3352
- import { readFileSync as readFileSync7 } from "node:fs";
3368
+ import { readFileSync as readFileSync8 } from "node:fs";
3353
3369
  function clearOssRequests(config) {
3354
3370
  cache.delete(config);
3355
3371
  }
@@ -3409,8 +3425,8 @@ async function authorize(config, operations, background = false) {
3409
3425
  const result = current.tail.catch(() => {
3410
3426
  }).then(async () => {
3411
3427
  const wait = 1e3 - (Date.now() - current.last);
3412
- if (wait > 0) await new Promise((resolve5) => {
3413
- const timer = setTimeout(resolve5, wait);
3428
+ if (wait > 0) await new Promise((resolve6) => {
3429
+ const timer = setTimeout(resolve6, wait);
3414
3430
  if (background) timer.unref();
3415
3431
  });
3416
3432
  try {
@@ -3463,7 +3479,7 @@ async function brokerOssConfig(configPath, options = {}) {
3463
3479
  let providers;
3464
3480
  try {
3465
3481
  loadSecretsEnvForConfig2(configPath);
3466
- const raw = makeEnvResolver2()(JSON.parse(readFileSync7(configPath, "utf8")));
3482
+ const raw = makeEnvResolver2()(JSON.parse(readFileSync8(configPath, "utf8")));
3467
3483
  providers = { ...raw.models?.providers, ...raw.providers };
3468
3484
  } catch {
3469
3485
  return null;
@@ -3537,8 +3553,8 @@ __export(oss_transport_exports, {
3537
3553
  withOssBatches: () => withOssBatches
3538
3554
  });
3539
3555
  import { createHmac, createHash as createHash5 } from "node:crypto";
3540
- import { readFileSync as readFileSync8, statSync as statSync2 } from "node:fs";
3541
- import { join as join11 } from "node:path";
3556
+ import { readFileSync as readFileSync9, statSync as statSync2 } from "node:fs";
3557
+ import { join as join12 } from "node:path";
3542
3558
  function ossFailureCode(error) {
3543
3559
  const message = error instanceof Error ? error.message : "";
3544
3560
  const code = /^TRAVEL_[A-Z_0-9]+/.exec(message)?.[0];
@@ -3563,12 +3579,12 @@ function loadOssConfig(stateDir) {
3563
3579
  if (ak && sk && bucket && endpoint) return { accessKeyId: ak, accessKeySecret: sk, bucket, endpoint };
3564
3580
  if (!stateDir) return null;
3565
3581
  try {
3566
- const ossJsonPath = join11(stateDir, ".travel", "oss.json");
3582
+ const ossJsonPath = join12(stateDir, ".travel", "oss.json");
3567
3583
  try {
3568
3584
  if (statSync2(ossJsonPath).mode & 63) console.warn(`[travel] ${ossJsonPath} \u6743\u9650\u8FC7\u5BBD\uFF08\u5E94 600\uFF09\u2014\u2014OSS \u51ED\u636E\u53EF\u88AB\u540C\u673A\u5176\u4ED6\u7528\u6237\u8BFB\u53D6`);
3569
3585
  } catch {
3570
3586
  }
3571
- const file = JSON.parse(readFileSync8(ossJsonPath, "utf8"));
3587
+ const file = JSON.parse(readFileSync9(ossJsonPath, "utf8"));
3572
3588
  if (file.accessKeyId && file.accessKeySecret && file.bucket && file.endpoint)
3573
3589
  return { accessKeyId: file.accessKeyId, accessKeySecret: file.accessKeySecret, bucket: file.bucket, endpoint: file.endpoint };
3574
3590
  } catch {
@@ -3737,7 +3753,7 @@ import { createHash as createHash6 } from "node:crypto";
3737
3753
  import { gzip as gzip2, gunzip } from "node:zlib";
3738
3754
  import { promisify as promisify2 } from "node:util";
3739
3755
  import { statSync as statSync3 } from "node:fs";
3740
- import { join as join12 } from "node:path";
3756
+ import { join as join13 } from "node:path";
3741
3757
  function validateBundleRef(value) {
3742
3758
  if (!value || !/^[a-f0-9]{64}$/.test(value.sha256) || !Number.isSafeInteger(value.plainBytes) || value.plainBytes < 12 || value.plainBytes > BUNDLE_RAW_MAX + BUNDLE_HEADER_MAX + 12 || !Array.isArray(value.refs) || !value.refs.length || value.refs.length > BUNDLE_REFS_MAX) throw Error("TRAVEL_INVALID_BUNDLE");
3743
3759
  const seen = /* @__PURE__ */ new Set();
@@ -3755,7 +3771,7 @@ function bundleGroups(store, refs) {
3755
3771
  let group = [], raw = 0, hint = 0;
3756
3772
  for (const ref of refs) {
3757
3773
  validateChunkRef(ref);
3758
- const size = statSync3(join12(store.dir, ref.sha256 + ".gz")).size;
3774
+ const size = statSync3(join13(store.dir, ref.sha256 + ".gz")).size;
3759
3775
  if (group.length && (raw + ref.bytes > BUNDLE_RAW_MAX || hint + size > 7.5 * 1048576 || group.length >= BUNDLE_REFS_MAX)) {
3760
3776
  groups.push(group);
3761
3777
  group = [];
@@ -3803,17 +3819,17 @@ var init_oss_bundle = __esm({
3803
3819
  });
3804
3820
 
3805
3821
  // src/travel/oss-resume.ts
3806
- import { appendFileSync, existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync9, renameSync as renameSync5, statSync as statSync4, writeFileSync as writeFileSync7 } from "node:fs";
3807
- import { join as join13 } from "node:path";
3822
+ import { appendFileSync, existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync10, renameSync as renameSync5, statSync as statSync4, writeFileSync as writeFileSync7 } from "node:fs";
3823
+ import { join as join14 } from "node:path";
3808
3824
  import { createHash as createHash7, randomUUID as randomUUID4 } from "node:crypto";
3809
3825
  async function openOssResume(stateDir, config, first) {
3810
3826
  if (config.broker && !config.broker.tokenId) await ossHeadChunk(config, first.sha256);
3811
3827
  const scope = createHash7("sha256").update(JSON.stringify([config.bucket, config.endpoint, config.broker?.url ?? "", config.broker?.tokenId ?? createHash7("sha256").update(config.accessKeyId ?? "").digest("hex")])).digest("hex");
3812
- mkdirSync7(join13(stateDir, ".travel"), { recursive: true, mode: 448 });
3828
+ mkdirSync7(join14(stateDir, ".travel"), { recursive: true, mode: 448 });
3813
3829
  const metadata = assertPath(stateDir, ".travel/oss-resume.json"), receipts = assertPath(stateDir, ".travel/oss-upload-receipts.jsonl");
3814
3830
  let session;
3815
3831
  try {
3816
- const saved = JSON.parse(readFileSync9(metadata, "utf8"));
3832
+ const saved = JSON.parse(readFileSync10(metadata, "utf8"));
3817
3833
  if (saved.version === 2 && saved.scope === scope && /^(?:[a-f0-9]{64}|legacy)$/.test(saved.transferId) && Number.isSafeInteger(saved.createdAt) && saved.createdAt > Date.now() - KEEP_MS && saved.createdAt <= Date.now()) session = saved;
3818
3834
  } catch {
3819
3835
  }
@@ -3829,7 +3845,7 @@ async function openOssResume(stateDir, config, first) {
3829
3845
  }
3830
3846
  const packages = /* @__PURE__ */ new Map();
3831
3847
  if (existsSync10(receipts) && statSync4(receipts).size <= 64 * 1048576) {
3832
- for (const line of readFileSync9(receipts, "utf8").split("\n")) try {
3848
+ for (const line of readFileSync10(receipts, "utf8").split("\n")) try {
3833
3849
  const value = JSON.parse(line);
3834
3850
  if (value.scope !== scope || value.transferId !== session.transferId || !Number.isSafeInteger(value.at) || value.at < Date.now() - KEEP_MS || value.at > Date.now()) continue;
3835
3851
  for (const ref of value.bundles ?? []) {
@@ -3863,21 +3879,21 @@ var init_oss_resume = __esm({
3863
3879
  });
3864
3880
 
3865
3881
  // src/travel/oss-bundle-stream.ts
3866
- import { readFileSync as readFileSync10, existsSync as existsSync11 } from "node:fs";
3882
+ import { readFileSync as readFileSync11, existsSync as existsSync11 } from "node:fs";
3867
3883
  import { fileURLToPath } from "node:url";
3868
3884
  function openBundleStream(options) {
3869
3885
  let source = options.source;
3870
3886
  if (!source) {
3871
3887
  for (const url of [new URL("./travel-oss-bundle-stream.mjs", import.meta.url), new URL("../../dist/travel-oss-bundle-stream.mjs", import.meta.url)]) if (existsSync11(fileURLToPath(url))) {
3872
- source = readFileSync10(url, "utf8");
3888
+ source = readFileSync11(url, "utf8");
3873
3889
  break;
3874
3890
  }
3875
3891
  }
3876
3892
  if (!source) throw Error("TRAVEL_OSS_HELPER_MISSING");
3877
3893
  const child = options.spawn("node --input-type=module -e " + quote(bootstrap)), pending = /* @__PURE__ */ new Map();
3878
3894
  let sequence = 0, text = "", settled = false, closed = false, resolveReady, rejectReady;
3879
- const ready = new Promise((resolve5, reject) => {
3880
- resolveReady = resolve5;
3895
+ const ready = new Promise((resolve6, reject) => {
3896
+ resolveReady = resolve6;
3881
3897
  rejectReady = reject;
3882
3898
  });
3883
3899
  const fail = () => {
@@ -3928,8 +3944,8 @@ function openBundleStream(options) {
3928
3944
  await ready;
3929
3945
  if (closed) throw Error("TRAVEL_OSS_BUNDLE_CONNECTION_CLOSED");
3930
3946
  const id = ++sequence;
3931
- return new Promise((resolve5, reject) => {
3932
- pending.set(id, { resolve: resolve5, reject });
3947
+ return new Promise((resolve6, reject) => {
3948
+ pending.set(id, { resolve: resolve6, reject });
3933
3949
  child.stdin.write(JSON.stringify({ id, bundles }) + "\n", (error) => {
3934
3950
  if (error) {
3935
3951
  pending.delete(id);
@@ -4060,18 +4076,51 @@ var init_oss_bundle_lane = __esm({
4060
4076
  // src/travel/sync-worker.ts
4061
4077
  init_chunk_store();
4062
4078
  init_capture_cache();
4063
- import { join as join14 } from "node:path";
4079
+ import { join as join15 } from "node:path";
4080
+ import { readFileSync as readFileSync12 } from "node:fs";
4064
4081
  import { createHash as createHash8 } from "node:crypto";
4065
4082
 
4083
+ // src/travel/ssh.ts
4084
+ function isConnectionError(error) {
4085
+ if (!(error instanceof Error)) return false;
4086
+ if (error.message === "TRAVEL_CONNECTION_CLOSED") return true;
4087
+ const { code, stderr } = error;
4088
+ if (["ECONNRESET", "EHOSTUNREACH", "ENETUNREACH", "ETIMEDOUT"].includes(String(code))) return true;
4089
+ if (code !== 255 && code !== "255" && stderr !== void 0) return false;
4090
+ const diagnostic = stderr ?? error.message;
4091
+ if (/Permission denied|Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED|Connection refused/i.test(diagnostic)) return false;
4092
+ return /^(?:(?:ssh: connect to host .+ port \d+: |client_loop: send disconnect: |kex_exchange_identification: |banner exchange: .+: )(?:No route to host|Network is unreachable|Connection timed out|Connection reset by peer|Broken pipe|Operation timed out)|Connection (?:reset|closed) by |Timeout, server .* not responding)/im.test(diagnostic);
4093
+ }
4094
+
4066
4095
  // src/travel/tree-manifest.ts
4067
4096
  init_chunk_store();
4068
4097
  import { lstatSync as lstatSync3, readdirSync, existsSync as existsSync3 } from "node:fs";
4069
- import { join as join3 } from "node:path";
4098
+ import { join as join4 } from "node:path";
4070
4099
 
4071
4100
  // src/memory/topics-history/import-backups.ts
4072
4101
  import { DatabaseSync, backup as backupSqlite } from "node:sqlite";
4073
4102
  var TOPICS_BACKUP_RETENTION_MS = 7 * 864e5;
4074
4103
 
4104
+ // src/travel/exclusions.ts
4105
+ import { readFileSync as readFileSync3 } from "node:fs";
4106
+ import { isAbsolute, join as join3, posix, resolve } from "node:path";
4107
+
4108
+ // src/tools/selfie-references.ts
4109
+ var DEFAULT_REFERENCES = [
4110
+ { name: "default", p: "images/xiaomei_clean_v2.png" },
4111
+ { name: "v3", p: "images/xiaomei_clean_v3.png" },
4112
+ { name: "base", p: "images/xiaomei_base_v3.jpg" },
4113
+ { name: "blue", p: "images/xiaomei_blue_shirt_base.jpg" },
4114
+ { name: "office", p: "images/xiaomei_office_final.jpg" }
4115
+ ];
4116
+ function selfieReferences(config) {
4117
+ const cfg = config;
4118
+ const refs = cfg?.my_selfie?.references || cfg?.tools?.my_selfie?.references;
4119
+ if (!Array.isArray(refs) || refs.length === 0) return DEFAULT_REFERENCES;
4120
+ const valid = refs.filter((ref) => typeof ref?.name === "string" && typeof ref?.path === "string").map((ref) => ({ name: ref.name, p: ref.path }));
4121
+ return valid.length ? valid : DEFAULT_REFERENCES;
4122
+ }
4123
+
4075
4124
  // src/travel/exclusions.ts
4076
4125
  var EXCLUDED_NAMES = /* @__PURE__ */ new Set(["node_modules", ".venv", ".venvs", "venv", ".git", "__pycache__", ".cache", "cache", "caches", "tmp", "temp", ".playwright-mcp", ".DS_Store"]);
4077
4126
  var EXCLUDED_TOP = /* @__PURE__ */ new Set(["logs", "diagnostics", "node_modules", "CogniFold", "everos-venv", "ollama-models", ".log-baseline.txt"]);
@@ -4097,17 +4146,46 @@ function excludeReason(relPath, isDir) {
4097
4146
  }
4098
4147
  var WORKSPACE_MEMORY_DIRS = /* @__PURE__ */ new Set(["topics", "memory", "inner-voice", ".calendar", ".proactive", ".system", "docs", "skills"]);
4099
4148
  function workspaceTopFileReason(name, size) {
4100
- if (!(/\.md$/i.test(name) || name === ".gitignore")) return `workspace \u9876\u5C42\u975E md \u6587\u4EF6\u4E0D\u968F\u884C\uFF08${name}\uFF09`;
4101
- if (typeof size === "number" && size > WORKSPACE_BIG_FILE_BYTES) return `workspace \u9876\u5C42 md \u8D85 32MB \u4E0D\u968F\u884C\uFF08${name}\uFF09`;
4149
+ if (!(/\.md$/i.test(name) || name === ".gitignore" || name === ".skill-gate.json")) return `workspace \u9876\u5C42\u975E md \u6587\u4EF6\u4E0D\u968F\u884C\uFF08${name}\uFF09`;
4150
+ if (typeof size === "number" && size > WORKSPACE_BIG_FILE_BYTES) return `workspace \u9876\u5C42\u6587\u4EF6\u8D85 32MB \u4E0D\u968F\u884C\uFF08${name}\uFF09`;
4102
4151
  return void 0;
4103
4152
  }
4104
4153
  var WORKSPACE_MEDIA_EXT = /\.(mp4|mov|mkv|webm|avi|m4v|flv|wmv|mpg|mpeg|mp3|wav|flac|aac|ogg|opus|m4a|zip|rar|7z|dmg|iso)$/i;
4105
4154
  var WORKSPACE_BIG_FILE_BYTES = 32 * 1024 * 1024;
4106
4155
  var RETURN_MEDIA_KEEP_MS = 14 * 24 * 3600 * 1e3;
4156
+ function isTopicsCleaningWorkPath(relPath) {
4157
+ return /^topics-history\/[a-f0-9]{64}\/(?:page-cache|batches\/[a-f0-9]{64}\/(?:snapshot|cleaned|work))(?:\/|$)/.test(relPath);
4158
+ }
4159
+ function isWorkspacePortraitPath(rel) {
4160
+ return rel.startsWith("workspace/") && /\.(?:png|jpe?g|webp)$/i.test(rel);
4161
+ }
4162
+ function withSelfieReferences(stateDir, configPath, exclude) {
4163
+ let config = {};
4164
+ try {
4165
+ config = JSON.parse(readFileSync3(configPath, "utf8")) ?? {};
4166
+ } catch {
4167
+ }
4168
+ const workspace = resolve(stateDir, "workspace");
4169
+ if (config.agents?.defaults?.workspace && resolve(config.agents.defaults.workspace) !== workspace) return exclude;
4170
+ const photos = /* @__PURE__ */ new Set();
4171
+ const parents = /* @__PURE__ */ new Set();
4172
+ for (const { p } of selfieReferences(config)) {
4173
+ if (!p || isAbsolute(p) || p.includes("..") || /[\\:\x00-\x1f]/.test(p)) continue;
4174
+ const rel = posix.join("workspace", p);
4175
+ if (!isWorkspacePortraitPath(rel)) continue;
4176
+ photos.add(rel);
4177
+ for (let dir = posix.dirname(rel); dir !== "workspace"; dir = posix.dirname(dir)) parents.add(dir);
4178
+ }
4179
+ return (rel, isDir, size, mtimeMs) => {
4180
+ if (!excludeReason(rel, isDir) && (isDir ? parents.has(rel) : photos.has(rel) && (size === void 0 || size <= WORKSPACE_BIG_FILE_BYTES))) return;
4181
+ return exclude(rel, isDir, size, mtimeMs);
4182
+ };
4183
+ }
4107
4184
  function syncExcludeWith(mediaPolicy) {
4108
4185
  return (relPath, isDir, size, mtimeMs) => {
4109
4186
  const parts = relPath.split("/");
4110
4187
  const name = parts[parts.length - 1];
4188
+ if (isTopicsCleaningWorkPath(relPath)) return "\u8BDD\u9898\u6E05\u6D17\u4E2D\u95F4\u6587\u4EF6\u7559\u5728\u539F\u673A";
4111
4189
  if (parts[0] === "runtime") return "\u5F15\u64CE\u5B89\u88C5\u526F\u672C\u4E0D\u968F\u884C\uFF08\u4E91\u7AEF\u72EC\u7ACB\u5B89\u88C5\u5F53\u524D\u5F15\u64CE\uFF09";
4112
4190
  if (!relPath.includes("/") && (relPath === "config.json" || relPath === "secrets.env")) {
4113
4191
  return "\u5BF9\u7AEF\u5B89\u88C5\u4EA7\u7269\u4FDD\u62A4\uFF08config \u8D70 config-remap\uFF0Csecrets \u8D70 travel-setup\uFF09";
@@ -4141,8 +4219,9 @@ function syncExcludeWith(mediaPolicy) {
4141
4219
  var syncExcludeReason = syncExcludeWith("none");
4142
4220
  var syncExcludeToCloud = syncExcludeWith("none");
4143
4221
  var syncExcludeToLocal = syncExcludeWith({ windowMs: RETURN_MEDIA_KEEP_MS });
4144
- function syncExcludeWithDays(days) {
4145
- return days > 0 ? syncExcludeWith({ windowMs: days * 864e5 }) : syncExcludeWith("none");
4222
+ function syncExcludeWithDays(days, stateDir) {
4223
+ const exclude = days > 0 ? syncExcludeWith({ windowMs: days * 864e5 }) : syncExcludeWith("none");
4224
+ return stateDir ? withSelfieReferences(stateDir, join3(stateDir, "config.json"), exclude) : exclude;
4146
4225
  }
4147
4226
 
4148
4227
  // src/travel/tree-manifest.ts
@@ -4186,7 +4265,7 @@ async function buildTreeManifest(root, store, opts = {}) {
4186
4265
  const walk = async (dir, rel) => {
4187
4266
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
4188
4267
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
4189
- const childPath = join3(dir, entry.name);
4268
+ const childPath = join4(dir, entry.name);
4190
4269
  if (entry.isSymbolicLink()) {
4191
4270
  excluded.push(`${childRel} \u2014 symlink refused`);
4192
4271
  continue;
@@ -4243,7 +4322,7 @@ async function buildTreeManifest(root, store, opts = {}) {
4243
4322
  if (opts.requireStableDatabases) {
4244
4323
  for (const [rel, before] of dbBefore) {
4245
4324
  try {
4246
- if (fileFingerprint(join3(root, rel)) !== before) throw Error();
4325
+ if (fileFingerprint(join4(root, rel)) !== before) throw Error();
4247
4326
  } catch {
4248
4327
  throw Error("TRAVEL_DATABASE_SOURCE_CHANGED");
4249
4328
  }
@@ -4262,21 +4341,21 @@ import {
4262
4341
  existsSync as existsSync6,
4263
4342
  mkdirSync as mkdirSync4,
4264
4343
  openSync as openSync5,
4265
- readFileSync as readFileSync4,
4344
+ readFileSync as readFileSync5,
4266
4345
  readSync as readSync5,
4267
4346
  renameSync as renameSync4,
4268
4347
  rmSync as rmSync2,
4269
4348
  writeFileSync as writeFileSync4
4270
4349
  } from "node:fs";
4271
4350
  import { createHash as createHash3 } from "node:crypto";
4272
- import { join as join6, resolve as resolve2 } from "node:path";
4351
+ import { join as join7, resolve as resolve3 } from "node:path";
4273
4352
  init_capture_cache();
4274
4353
  init_apply_transaction();
4275
4354
 
4276
4355
  // src/travel/sqlite-snapshot.ts
4277
4356
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
4278
4357
  import { closeSync as closeSync4, fstatSync as fstatSync3, openSync as openSync4, readSync as readSync4, readdirSync as readdirSync2, statSync } from "node:fs";
4279
- import { join as join5 } from "node:path";
4358
+ import { join as join6 } from "node:path";
4280
4359
 
4281
4360
  // src/travel/sqlite-wal.ts
4282
4361
  import { closeSync as closeSync3, existsSync as existsSync5, fstatSync as fstatSync2, openSync as openSync3, readSync as readSync3 } from "node:fs";
@@ -4325,7 +4404,7 @@ function validateSqliteWal(path5) {
4325
4404
  // src/travel/sqlite-snapshot.ts
4326
4405
  function validateDatabaseSnapshots(root, files) {
4327
4406
  for (const file of files) {
4328
- const path5 = join5(root, file), fd = openSync4(path5, "r"), header = Buffer.alloc(100);
4407
+ const path5 = join6(root, file), fd = openSync4(path5, "r"), header = Buffer.alloc(100);
4329
4408
  try {
4330
4409
  const size = fstatSync3(fd).size, n = readSync4(fd, header, 0, header.length, 0);
4331
4410
  const encoded = header.readUInt16BE(16), pageSize = encoded === 1 ? 65536 : encoded;
@@ -4436,7 +4515,7 @@ var SYNC_STATE_FILE = ".travel/sync-state.json";
4436
4515
  var DB_RE = /\.(db|sqlite)$/;
4437
4516
  function readSyncState(root) {
4438
4517
  try {
4439
- const value = JSON.parse(readFileSync4(join6(root, SYNC_STATE_FILE), "utf8"));
4518
+ const value = JSON.parse(readFileSync5(join7(root, SYNC_STATE_FILE), "utf8"));
4440
4519
  if (value?.version !== 1 || !value.files || typeof value.files !== "object") throw new Error("bad");
4441
4520
  const files = {};
4442
4521
  for (const [rel, sha] of Object.entries(value.files)) {
@@ -4450,10 +4529,10 @@ function readSyncState(root) {
4450
4529
  }
4451
4530
  }
4452
4531
  function writeSyncState(root, files) {
4453
- mkdirSync4(join6(root, ".travel"), { recursive: true, mode: 448 });
4454
- const temp = join6(root, ".travel", "sync-state.json.tmp");
4532
+ mkdirSync4(join7(root, ".travel"), { recursive: true, mode: 448 });
4533
+ const temp = join7(root, ".travel", "sync-state.json.tmp");
4455
4534
  writeFileSync4(temp, JSON.stringify({ version: 1, syncedAt: Date.now(), files }));
4456
- renameSync4(temp, join6(root, SYNC_STATE_FILE));
4535
+ renameSync4(temp, join7(root, SYNC_STATE_FILE));
4457
4536
  }
4458
4537
  function fileSha(path5) {
4459
4538
  try {
@@ -4476,10 +4555,11 @@ function fileSha(path5) {
4476
4555
  }
4477
4556
  async function applyTree(root, manifestValue, store, lastState, onProgress) {
4478
4557
  const manifest = parseTreeManifest(manifestValue);
4479
- root = resolve2(root);
4558
+ root = resolve3(root);
4480
4559
  if (ownEnginePid(root, 0) !== null) throw Error("TRAVEL_DESTINATION_RUNNING");
4481
4560
  mkdirSync4(root, { recursive: true, mode: 448 });
4482
4561
  recoverPendingApply(root);
4562
+ if (lastState === void 0) lastState = readSyncState(root);
4483
4563
  const newRels = new Set(manifest.files.map((file) => file.rel));
4484
4564
  const byRel = new Map(manifest.files.map((file) => [file.rel, file]));
4485
4565
  for (const file of manifest.files) if (/\.(db|sqlite)-(wal|shm)$/.test(file.rel) && !byRel.has(file.rel.replace(/-(wal|shm)$/, ""))) throw Error("TRAVEL_DATABASE_FAMILY_INCOMPLETE");
@@ -4537,6 +4617,8 @@ async function applyTree(root, manifestValue, store, lastState, onProgress) {
4537
4617
  if (lastState) {
4538
4618
  for (const [rel, sha] of Object.entries(lastState.files)) {
4539
4619
  if (newRels.has(rel)) continue;
4620
+ if (isTopicsCleaningWorkPath(rel)) continue;
4621
+ if (isWorkspacePortraitPath(rel) && syncExcludeReason(rel, false)) continue;
4540
4622
  const dest = assertPath(root, rel);
4541
4623
  if (!existsSync6(dest)) continue;
4542
4624
  const before = fileFingerprint(dest);
@@ -4562,12 +4644,12 @@ async function applyTree(root, manifestValue, store, lastState, onProgress) {
4562
4644
  const stage = newApplyStage(root);
4563
4645
  try {
4564
4646
  for (const file of changed.values()) {
4565
- await store.restoreFile(file.content, assertPath(join6(stage.path, "new"), file.rel), file.mode);
4647
+ await store.restoreFile(file.content, assertPath(join7(stage.path, "new"), file.rel), file.mode);
4566
4648
  applied++;
4567
4649
  appliedBytes += file.content.bytes;
4568
4650
  onProgress?.({ files: applied, bytes: appliedBytes });
4569
4651
  }
4570
- validateDatabaseSnapshots(join6(stage.path, "new"), dbs);
4652
+ validateDatabaseSnapshots(join7(stage.path, "new"), dbs);
4571
4653
  validateDatabaseSnapshots(root, unchangedDbs);
4572
4654
  if (ownEnginePid(root, 0) !== null) throw Error("TRAVEL_DESTINATION_RUNNING");
4573
4655
  promoteFiles(root, stage, [...promotions.values()], () => {
@@ -4578,7 +4660,7 @@ async function applyTree(root, manifestValue, store, lastState, onProgress) {
4578
4660
  rmSync2(assertPath(root, ".travel/pre-copy-only.json"), { force: true });
4579
4661
  seedCaptureCache(root, manifest.files);
4580
4662
  } catch (error) {
4581
- if (!existsSync6(join6(root, ".travel/apply-transaction.json"))) rmSync2(stage.path, { recursive: true, force: true });
4663
+ if (!existsSync6(join7(root, ".travel/apply-transaction.json"))) rmSync2(stage.path, { recursive: true, force: true });
4582
4664
  throw error;
4583
4665
  }
4584
4666
  return { applied, deleted, skipped };
@@ -4588,14 +4670,14 @@ function sidecarsOf(dbRel) {
4588
4670
  }
4589
4671
 
4590
4672
  // src/travel/checked-apply.ts
4591
- import { isAbsolute, join as join7 } from "node:path";
4673
+ import { isAbsolute as isAbsolute2, join as join8 } from "node:path";
4592
4674
  init_chunk_store();
4593
4675
  init_apply_transaction();
4594
4676
  import { existsSync as existsSync7, mkdirSync as mkdirSync5, writeFileSync as writeFileSync5 } from "node:fs";
4595
4677
  function markPreCopyOnly(root) {
4596
- if (!isAbsolute(root)) throw Error("TRAVEL_UNSAFE_PATH");
4678
+ if (!isAbsolute2(root)) throw Error("TRAVEL_UNSAFE_PATH");
4597
4679
  if (ownEnginePid(root, 0) !== null) throw Error("TRAVEL_DESTINATION_RUNNING");
4598
- mkdirSync5(join7(root, ".travel"), { recursive: true, mode: 448 });
4680
+ mkdirSync5(join8(root, ".travel"), { recursive: true, mode: 448 });
4599
4681
  writeFileSync5(assertPath(root, ".travel/pre-copy-only.json"), JSON.stringify({ version: 1, databasesVerified: false }), { mode: 384 });
4600
4682
  return { marked: true };
4601
4683
  }
@@ -4605,15 +4687,15 @@ function assertReturnSourceInactive(root) {
4605
4687
  }
4606
4688
  async function runCheckedCapture(root, days = 14) {
4607
4689
  assertReturnSourceInactive(root);
4608
- return buildTreeManifest(root, openChunkStore(join7(root, ".travel/chunks")), { exclude: syncExcludeWithDays(days), requireStableDatabases: true });
4690
+ return buildTreeManifest(root, openChunkStore(join8(root, ".travel/chunks")), { exclude: syncExcludeWithDays(days, root), requireStableDatabases: true });
4609
4691
  }
4610
4692
  async function runCheckedApply(root, manifest, pre = false) {
4611
- if (!isAbsolute(root)) throw Error("TRAVEL_UNSAFE_PATH");
4693
+ if (!isAbsolute2(root)) throw Error("TRAVEL_UNSAFE_PATH");
4612
4694
  if (pre) {
4613
4695
  markPreCopyOnly(root);
4614
4696
  return { applied: 0, deleted: [], skipped: [] };
4615
4697
  }
4616
- return applyTree(root, manifest, openChunkStore(join7(root, ".travel/chunks")), readSyncState(root));
4698
+ return applyTree(root, manifest, openChunkStore(join8(root, ".travel/chunks")));
4617
4699
  }
4618
4700
 
4619
4701
  // src/travel/sync-worker.ts
@@ -4662,15 +4744,15 @@ var ProtocolReader = class {
4662
4744
  }
4663
4745
  readLine() {
4664
4746
  if (this.waiter) throw new Error("TRAVEL_PROTOCOL_BUSY");
4665
- return new Promise((resolve5) => {
4666
- this.waiter = { kind: "line", resolve: resolve5 };
4747
+ return new Promise((resolve6) => {
4748
+ this.waiter = { kind: "line", resolve: resolve6 };
4667
4749
  this.drain();
4668
4750
  });
4669
4751
  }
4670
4752
  readBytes(count) {
4671
4753
  if (this.waiter) throw new Error("TRAVEL_PROTOCOL_BUSY");
4672
- return new Promise((resolve5, reject) => {
4673
- this.waiter = { kind: "bytes", count, resolve: resolve5, reject };
4754
+ return new Promise((resolve6, reject) => {
4755
+ this.waiter = { kind: "bytes", count, resolve: resolve6, reject };
4674
4756
  this.drain();
4675
4757
  });
4676
4758
  }
@@ -4684,9 +4766,9 @@ var ProtocolReader = class {
4684
4766
  const rest = total.subarray(newline + 1);
4685
4767
  this.buffer = rest.length ? [rest] : [];
4686
4768
  this.buffered = rest.length;
4687
- const resolve5 = this.waiter.resolve;
4769
+ const resolve6 = this.waiter.resolve;
4688
4770
  this.waiter = null;
4689
- resolve5(line);
4771
+ resolve6(line);
4690
4772
  continue;
4691
4773
  }
4692
4774
  break;
@@ -4697,9 +4779,9 @@ var ProtocolReader = class {
4697
4779
  const rest = total.subarray(this.waiter.count);
4698
4780
  this.buffer = rest.length ? [rest] : [];
4699
4781
  this.buffered = rest.length;
4700
- const resolve5 = this.waiter.resolve;
4782
+ const resolve6 = this.waiter.resolve;
4701
4783
  this.waiter = null;
4702
- resolve5(body);
4784
+ resolve6(body);
4703
4785
  continue;
4704
4786
  }
4705
4787
  break;
@@ -4714,8 +4796,13 @@ var ProtocolReader = class {
4714
4796
  }
4715
4797
  };
4716
4798
  var WorkerConnection = class _WorkerConnection {
4717
- constructor(child) {
4799
+ constructor(child, classifyExit = false) {
4718
4800
  this.child = child;
4801
+ this.classifyExit = classifyExit;
4802
+ this.closed = new Promise((resolve6) => child.once("close", (code, signal) => resolve6({ code, signal })));
4803
+ child.stderr?.on("data", (chunk) => {
4804
+ this.stderr = (this.stderr + String(chunk)).slice(-4096);
4805
+ });
4719
4806
  child.stdout.on("data", (chunk) => this.reader.push(chunk));
4720
4807
  child.stdout.on("end", () => this.reader.end());
4721
4808
  const die = () => {
@@ -4726,25 +4813,51 @@ var WorkerConnection = class _WorkerConnection {
4726
4813
  child.stdout.on("error", die);
4727
4814
  child.stdin.on("error", die);
4728
4815
  child.on("error", die);
4729
- child.on("exit", die);
4816
+ child.on("exit", () => {
4817
+ this.broken = true;
4818
+ this.onDied?.();
4819
+ });
4820
+ child.on("close", die);
4730
4821
  }
4731
4822
  reader = new ProtocolReader();
4732
4823
  chain = Promise.resolve();
4733
4824
  broken = false;
4825
+ stderr = "";
4826
+ closed;
4734
4827
  // 1123 妹妹 review P0:字段按声明序初始化——died 的 executor 先跑,若
4735
4828
  // onDied 声明在其后带默认值会把 resolve 覆盖成 noop,died 永远 pending,
4736
4829
  // race 防挂整个落空。onDied 必须先声明且默认 null。
4737
4830
  onDied = null;
4738
- died = new Promise((resolve5) => {
4739
- this.onDied = resolve5;
4831
+ died = new Promise((resolve6) => {
4832
+ this.onDied = resolve6;
4740
4833
  });
4741
4834
  static from(child) {
4742
4835
  return new _WorkerConnection(child);
4743
4836
  }
4744
4837
  static async fromSource(child, source, root) {
4745
- const worker = new _WorkerConnection(child);
4746
- if ((await worker.request({ module: source, root })).bootstrap !== true) throw Error("TRAVEL_PROTOCOL_MISMATCH");
4747
- return worker;
4838
+ const worker = new _WorkerConnection(child, true);
4839
+ try {
4840
+ if ((await worker.request({ module: source, root })).bootstrap !== true) throw Error("TRAVEL_PROTOCOL_MISMATCH");
4841
+ return worker;
4842
+ } catch (error) {
4843
+ await worker.close();
4844
+ throw error;
4845
+ }
4846
+ }
4847
+ async disconnected() {
4848
+ if (!this.classifyExit) throw Error("TRAVEL_CONNECTION_CLOSED");
4849
+ let timer;
4850
+ try {
4851
+ const exit = await Promise.race([this.closed, new Promise((resolve6) => {
4852
+ timer = setTimeout(() => resolve6(null), 500);
4853
+ })]);
4854
+ if (!exit || isConnectionError(Object.assign(new Error("ssh"), { code: exit.code, stderr: this.stderr }))) {
4855
+ throw Error("TRAVEL_CONNECTION_CLOSED");
4856
+ }
4857
+ throw Error(`TRAVEL_WORKER_EXIT (${exit.code ?? exit.signal}): ${this.stderr.trim()}`);
4858
+ } finally {
4859
+ if (timer) clearTimeout(timer);
4860
+ }
4748
4861
  }
4749
4862
  enqueue(operation) {
4750
4863
  const next = this.chain.then(operation, operation);
@@ -4754,24 +4867,24 @@ var WorkerConnection = class _WorkerConnection {
4754
4867
  }
4755
4868
  request(header, payload) {
4756
4869
  return this.enqueue(async () => {
4757
- if (this.broken) throw new Error("TRAVEL_CONNECTION_CLOSED");
4758
- const written = new Promise((resolve5) => this.child.stdin.write(JSON.stringify(header) + "\n", () => resolve5()));
4870
+ if (this.broken) return this.disconnected();
4871
+ const written = new Promise((resolve6) => this.child.stdin.write(JSON.stringify(header) + "\n", () => resolve6()));
4759
4872
  await Promise.race([written, this.died]);
4760
- if (this.broken) throw new Error("TRAVEL_CONNECTION_CLOSED");
4873
+ if (this.broken) return this.disconnected();
4761
4874
  if (payload) {
4762
- const payloadWritten = new Promise((resolve5) => this.child.stdin.write(payload, () => resolve5()));
4875
+ const payloadWritten = new Promise((resolve6) => this.child.stdin.write(payload, () => resolve6()));
4763
4876
  await Promise.race([payloadWritten, this.died]);
4764
- if (this.broken) throw new Error("TRAVEL_CONNECTION_CLOSED");
4877
+ if (this.broken) return this.disconnected();
4765
4878
  }
4766
4879
  const line = await this.reader.readLine();
4767
- if (line === null) throw new Error("TRAVEL_CONNECTION_CLOSED");
4880
+ if (line === null) return this.disconnected();
4768
4881
  const reply = JSON.parse(line);
4769
4882
  if (reply?.error) throw new Error(reply.detail ? `${reply.error}: ${reply.detail}` : reply.error);
4770
4883
  return reply;
4771
4884
  });
4772
4885
  }
4773
- hello(pre = false) {
4774
- return this.request({ op: "hello", pre });
4886
+ hello(pre = false, owner) {
4887
+ return this.request({ op: "hello", pre, owner });
4775
4888
  }
4776
4889
  async has(refs) {
4777
4890
  return (await this.request({ op: "has", refs })).missing;
@@ -4782,15 +4895,15 @@ var WorkerConnection = class _WorkerConnection {
4782
4895
  /** 拉块:应答行后跟原始明文字节(to-local 方向)。 */
4783
4896
  async get(sha2563, bytes) {
4784
4897
  return this.enqueue(async () => {
4785
- if (this.broken) throw new Error("TRAVEL_CONNECTION_CLOSED");
4786
- const written = new Promise((resolve5) => this.child.stdin.write(JSON.stringify({ op: "get", sha256: sha2563, bytes }) + "\n", () => resolve5()));
4898
+ if (this.broken) return this.disconnected();
4899
+ const written = new Promise((resolve6) => this.child.stdin.write(JSON.stringify({ op: "get", sha256: sha2563, bytes }) + "\n", () => resolve6()));
4787
4900
  await Promise.race([written, this.died]);
4788
- if (this.broken) throw new Error("TRAVEL_CONNECTION_CLOSED");
4901
+ if (this.broken) return this.disconnected();
4789
4902
  const line = await this.reader.readLine();
4790
- if (line === null) throw new Error("TRAVEL_CONNECTION_CLOSED");
4903
+ if (line === null) return this.disconnected();
4791
4904
  const reply = JSON.parse(line);
4792
4905
  if (reply?.error) throw new Error(reply.detail ? `${reply.error}: ${reply.detail}` : reply.error);
4793
- return await this.reader.readBytes(reply.bytes);
4906
+ return this.reader.readBytes(reply.bytes).catch(() => this.disconnected());
4794
4907
  });
4795
4908
  }
4796
4909
  async manifest(manifest) {
@@ -4810,11 +4923,11 @@ var WorkerConnection = class _WorkerConnection {
4810
4923
  /** A single reader serializes descriptors and acknowledgements; payloads use OSS. */
4811
4924
  pushViaOss(refs, config, receive, progress) {
4812
4925
  return this.enqueue(async () => {
4813
- if (this.broken) throw Error("TRAVEL_CONNECTION_CLOSED");
4926
+ if (this.broken) return this.disconnected();
4814
4927
  this.child.stdin.write(JSON.stringify({ op: "oss-push", refs, config }) + "\n");
4815
4928
  for (; ; ) {
4816
4929
  const line = await this.reader.readLine();
4817
- if (line === null) throw Error("TRAVEL_CONNECTION_CLOSED");
4930
+ if (line === null) return this.disconnected();
4818
4931
  const value = JSON.parse(line);
4819
4932
  if (value.error) throw Error(value.detail ? `${value.error}: ${value.detail}` : value.error);
4820
4933
  if (value.progress) {
@@ -4848,20 +4961,20 @@ var WorkerConnection = class _WorkerConnection {
4848
4961
  } catch {
4849
4962
  }
4850
4963
  await Promise.race([
4851
- new Promise((resolve5) => this.child.once("exit", () => resolve5())),
4964
+ new Promise((resolve6) => this.child.once("exit", () => resolve6())),
4852
4965
  this.died,
4853
- new Promise((resolve5) => {
4854
- setTimeout(resolve5, 1e4).unref?.();
4966
+ new Promise((resolve6) => {
4967
+ setTimeout(resolve6, 1e4).unref?.();
4855
4968
  })
4856
4969
  ]);
4857
4970
  }
4858
4971
  };
4859
4972
  async function runWorker(stateDir) {
4860
- const store = openChunkStore(join14(stateDir, ".travel/chunks"));
4973
+ const store = openChunkStore(join15(stateDir, ".travel/chunks"));
4861
4974
  const reader = new ProtocolReader();
4862
4975
  process.stdin.on("data", (chunk) => reader.push(chunk));
4863
4976
  process.stdin.on("end", () => reader.end());
4864
- const ended = new Promise((resolve5) => process.stdin.on("end", resolve5));
4977
+ const ended = new Promise((resolve6) => process.stdin.on("end", resolve6));
4865
4978
  let pendingManifest = null;
4866
4979
  let capturedForReturn = false;
4867
4980
  let databasePiecesSeeded = false;
@@ -4873,6 +4986,14 @@ async function runWorker(stateDir) {
4873
4986
  const op = JSON.parse(line);
4874
4987
  switch (op.op) {
4875
4988
  case "hello": {
4989
+ if (op.owner !== void 0) {
4990
+ try {
4991
+ const owner = JSON.parse(readFileSync12(join15(stateDir, ".travel/owner.json"), "utf8"));
4992
+ if (owner.instanceId !== op.owner) throw Error("TRAVEL_WRONG_REMOTE_OWNER");
4993
+ } catch {
4994
+ throw Error("TRAVEL_WRONG_REMOTE_OWNER");
4995
+ }
4996
+ }
4876
4997
  if (op.pre === true) markPreCopyOnly(stateDir);
4877
4998
  reply = { ok: true, version: 3, stateDir, region: await cloudRegion() };
4878
4999
  break;
@@ -4914,7 +5035,7 @@ async function runWorker(stateDir) {
4914
5035
  if (typeof sha !== "string" || !/^[a-f0-9]{64}$/.test(sha) || !Number.isSafeInteger(bytes) || bytes < 1 || bytes > CHUNK_BYTES) throw new Error("TRAVEL_INVALID_CHUNK");
4915
5036
  const body = await store.read(sha, bytes);
4916
5037
  process.stdout.write(JSON.stringify({ ok: true, bytes: body.length }) + "\n");
4917
- await new Promise((resolve5) => process.stdout.write(body, () => resolve5()));
5038
+ await new Promise((resolve6) => process.stdout.write(body, () => resolve6()));
4918
5039
  reply = null;
4919
5040
  break;
4920
5041
  }