engine7 7.1.141 → 7.1.142

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/cli.mjs CHANGED
@@ -140,7 +140,7 @@ async function registerFeishuApp(options = {}) {
140
140
  return result;
141
141
  }
142
142
  function sleep(ms) {
143
- return new Promise((resolve40) => setTimeout(resolve40, ms));
143
+ return new Promise((resolve45) => setTimeout(resolve45, ms));
144
144
  }
145
145
  var ACCOUNTS_URL, REGISTRATION_PATH, REQUEST_TIMEOUT_MS, DEFAULT_POLL_INTERVAL;
146
146
  var init_feishu_quick_register = __esm({
@@ -8898,7 +8898,7 @@ function captureSocialInterpretation(store, scope, sources, providedContext = []
8898
8898
  }
8899
8899
  function socialComparisonRequests(store, scope, sources, result) {
8900
8900
  const mentions = new Map(result.mentions.map((mention) => [mention.key, mention]));
8901
- const resolve40 = (key4, sourceId, seen = /* @__PURE__ */ new Set()) => {
8901
+ const resolve45 = (key4, sourceId, seen = /* @__PURE__ */ new Set()) => {
8902
8902
  if (key4 === "speaker") return store.entities.speaker(scope, sourceId)?.entityId;
8903
8903
  if (seen.has(key4)) return void 0;
8904
8904
  const mention = mentions.get(key4);
@@ -8906,15 +8906,15 @@ function socialComparisonRequests(store, scope, sources, result) {
8906
8906
  if (!mention.actual || mention.disposition !== "existing" || mention.identity?.relation === "different_person" || mention.identity?.relation === "uncertain") return void 0;
8907
8907
  if (mention.entityId) return store.entities.get(scope, mention.entityId)?.entityId;
8908
8908
  const anchor = mention.identity?.anchor;
8909
- if (typeof anchor === "string") return resolve40(anchor, mention.sourceId, new Set(seen).add(key4));
8909
+ if (typeof anchor === "string") return resolve45(anchor, mention.sourceId, new Set(seen).add(key4));
8910
8910
  if (anchor) return "author" in anchor ? store.entities.speaker(scope, anchor.sourceId)?.entityId : store.entities.sourceMentions(scope, anchor.sourceId).find((item) => item.start === anchor.start && item.end === anchor.end && item.quote === anchor.quote)?.entityId;
8911
8911
  return void 0;
8912
8912
  };
8913
8913
  return result.relationships.flatMap((relation) => {
8914
8914
  if (!relation.actual || !sources.some((source) => source.sourceId === relation.sourceId)) return [];
8915
- const perspectiveEntityId = resolve40(relation.perspective, relation.sourceId);
8916
- const subjectId = resolve40(relation.subject, relation.sourceId);
8917
- const objectId = resolve40(relation.object, relation.sourceId);
8915
+ const perspectiveEntityId = resolve45(relation.perspective, relation.sourceId);
8916
+ const subjectId = resolve45(relation.subject, relation.sourceId);
8917
+ const objectId = resolve45(relation.object, relation.sourceId);
8918
8918
  return perspectiveEntityId && subjectId && objectId ? [{
8919
8919
  perspectiveEntityId,
8920
8920
  subjectId,
@@ -9289,16 +9289,16 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
9289
9289
  }
9290
9290
  }
9291
9291
  const speaker = store.entities.speaker(scope, source.sourceId);
9292
- const resolve40 = (ref) => ref === "speaker" ? speaker?.entityId : ids.has(ref) ? ids.get(ref) : !captured.providedSourceIds && captured.entityIds.includes(ref) ? ref : void 0;
9293
- const perspectiveEntityId = resolve40(relation.perspective);
9294
- const subjectId = resolve40(relation.subject);
9295
- const objectId = resolve40(relation.object);
9292
+ const resolve45 = (ref) => ref === "speaker" ? speaker?.entityId : ids.has(ref) ? ids.get(ref) : !captured.providedSourceIds && captured.entityIds.includes(ref) ? ref : void 0;
9293
+ const perspectiveEntityId = resolve45(relation.perspective);
9294
+ const subjectId = resolve45(relation.subject);
9295
+ const objectId = resolve45(relation.object);
9296
9296
  if ([perspectiveEntityId, subjectId, objectId].some((id2) => id2 === null)) {
9297
9297
  applied.relationships.push({
9298
9298
  index: ordinal,
9299
9299
  label: relation.label,
9300
9300
  state: "skipped",
9301
- unresolvedKeys: [...new Set([relation.perspective, relation.subject, relation.object].filter((ref) => resolve40(ref) === null))]
9301
+ unresolvedKeys: [...new Set([relation.perspective, relation.subject, relation.object].filter((ref) => resolve45(ref) === null))]
9302
9302
  });
9303
9303
  continue;
9304
9304
  }
@@ -9332,7 +9332,7 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
9332
9332
  ...metadata2?.basisRefs || [],
9333
9333
  ...store.socialSources.identityRefs(scope, source.sourceId),
9334
9334
  ...references(relation.basisSourceIds, source.sourceId, `${path72}.basisSourceIds`),
9335
- ...[relation.perspective, relation.subject, relation.object].flatMap((ref) => [...mentionBasis.get(ref) || [], ...entityBasis.get(resolve40(ref)) || []])
9335
+ ...[relation.perspective, relation.subject, relation.object].flatMap((ref) => [...mentionBasis.get(ref) || [], ...entityBasis.get(resolve45(ref)) || []])
9336
9336
  ])
9337
9337
  };
9338
9338
  const existing = reuseSameSource && proposal.operation === "create" ? store.relationships.matchingMeaning(scope, proposal).find((record) => record.current && record.groundingState === "current" && !["retracted", "deleted"].includes(record.state) && record.subjectId === subjectId && record.objectId === objectId && record.direction === proposal.direction && (record.realm ?? "real") === (proposal.realm ?? "real") && (record.sensitivity ?? "normal") === (proposal.sensitivity ?? "normal") && record.contentKind === proposal.contentKind && record.temporalScope === proposal.temporalScope && record.claimKind === claimKind && record.label === proposal.label && record.body.trim() === proposal.body.trim() && record.certainty === proposal.certainty && record.validFrom === proposal.validFrom && record.validTo === proposal.validTo && record.observedAsCurrentAt === proposal.observedAsCurrentAt && canonicalJson(record.attribution ?? null) === canonicalJson(proposal.attribution ?? null) && canonicalJson(record.attributionQuote ?? null) === canonicalJson(proposal.attributionQuote ?? null) && canonicalJson(record.basisRefs) === canonicalJson(proposal.basisRefs) && record.evidence.some((evidence) => evidence.sourceId === source.sourceId && evidence.quote === source.text)) : void 0;
@@ -11571,20 +11571,20 @@ function readRelationshipContext(store, scope, request, clock = () => (/* @__PUR
11571
11571
  const known = cutoff ? store.knowledgeSnapshot(scope, cutoff) : void 0;
11572
11572
  const recall = store.socialSources.recall(scope, cutoff);
11573
11573
  const resolved = /* @__PURE__ */ new Map();
11574
- const resolve40 = (id2) => {
11574
+ const resolve45 = (id2) => {
11575
11575
  if (!resolved.has(id2)) resolved.set(id2, store.entities.resolve(scope, id2, known?.entityRevision, cutoff));
11576
11576
  return resolved.get(id2);
11577
11577
  };
11578
11578
  const matching = request.entityIds ? request.entityIds.map((id2) => {
11579
- const entity = resolve40(id2);
11579
+ const entity = resolve45(id2);
11580
11580
  if (!entity) throw new Error("ENTITY_SCOPE_MISMATCH");
11581
11581
  return entity;
11582
- }) : store.entities.matchQuery(scope, request.query, cutoff, recall).map((entity) => resolve40(entity.entityId)).filter(Boolean);
11582
+ }) : store.entities.matchQuery(scope, request.query, cutoff, recall).map((entity) => resolve45(entity.entityId)).filter(Boolean);
11583
11583
  const queried = [...new Map(matching.filter((entity) => ["person", "agent", "organization"].includes(entity.kind)).map((entity) => [entity.entityId, entity])).values()];
11584
11584
  const selected = new Set(queried.map((entity) => entity.entityId));
11585
11585
  const self = request.perspectiveEntityId ? store.entities.get(scope, request.perspectiveEntityId, cutoff) : store.entities.self(scope, cutoff);
11586
11586
  if (request.perspectiveEntityId && !self) throw new Error("ENTITY_SCOPE_MISMATCH");
11587
- const name = (id2) => resolve40(id2)?.canonicalName || "[\u8EAB\u4EFD\u5F85\u89E3]";
11587
+ const name = (id2) => resolve45(id2)?.canonicalName || "[\u8EAB\u4EFD\u5F85\u89E3]";
11588
11588
  const context2 = {
11589
11589
  scopeId: scopeId(scope),
11590
11590
  ...cutoff ? { knowledgeCoverage: store.relationships.knowledgeComplete(scope, cutoff) ? "complete" : "partial" } : {},
@@ -11674,11 +11674,11 @@ function readRelationshipContext(store, scope, request, clock = () => (/* @__PUR
11674
11674
  } : {}
11675
11675
  };
11676
11676
  };
11677
- const endpointScore = (record) => Number(selected.has(resolve40(record.subjectId)?.entityId || record.subjectId)) + Number(selected.has(resolve40(record.objectId)?.entityId || record.objectId));
11677
+ const endpointScore = (record) => Number(selected.has(resolve45(record.subjectId)?.entityId || record.subjectId)) + Number(selected.has(resolve45(record.objectId)?.entityId || record.objectId));
11678
11678
  const ongoingFirst = /关系|relationship/i.test(request.query);
11679
11679
  const firstName = Math.min(...queried.map((entity) => request.query.indexOf(entity.canonicalName)).filter((index) => index >= 0));
11680
11680
  const focus = new Set(queried.filter((entity) => request.query.indexOf(entity.canonicalName) === firstName).map((entity) => entity.entityId));
11681
- const focusScore = (record) => Number(ongoingFirst && [record.subjectId, record.objectId].some((id2) => focus.has(resolve40(id2)?.entityId || id2)));
11681
+ const focusScore = (record) => Number(ongoingFirst && [record.subjectId, record.objectId].some((id2) => focus.has(resolve45(id2)?.entityId || id2)));
11682
11682
  const select = (record) => endpointScore(record) > 0 || selected.has(record.perspectiveEntityId) || Boolean(request.retrievedRelationshipIds?.includes(record.relationshipId));
11683
11683
  const available = (record) => (!request.knownAt || record.knownAt <= instant(request.knownAt)) && (request.history || !["retracted", "deleted"].includes(record.state)) && (record.validFrom ? record.validFrom <= validAt : record.observedAsCurrentAt ? record.observedAsCurrentAt <= validAt : request.validAt === void 0) && (request.history || !record.validTo || validAt < record.validTo);
11684
11684
  for (const entity of queried) add("people", entity);
@@ -11735,11 +11735,11 @@ function readRelationshipContext(store, scope, request, clock = () => (/* @__PUR
11735
11735
  }, [fact.assertionId]);
11736
11736
  }
11737
11737
  }
11738
- for (const entity of (request.graphEntityIds ?? []).flatMap((id2) => resolve40(id2) || []).filter((entity2) => !selected.has(entity2.entityId)).slice(0, 4)) {
11738
+ for (const entity of (request.graphEntityIds ?? []).flatMap((id2) => resolve45(id2) || []).filter((entity2) => !selected.has(entity2.entityId)).slice(0, 4)) {
11739
11739
  if (!context2.people.some((person) => person.entityId === entity.entityId)) add("people", entity);
11740
11740
  }
11741
11741
  for (const path72 of (request.graphPaths ?? []).slice(0, 40)) add("paths", path72, [path72.source, path72.target]);
11742
- const linkedIds = store.entities.list(scope, cutoff).filter((entity) => selected.has(resolve40(entity.entityId)?.entityId || entity.entityId)).map((entity) => entity.entityId);
11742
+ const linkedIds = store.entities.list(scope, cutoff).filter((entity) => selected.has(resolve45(entity.entityId)?.entityId || entity.entityId)).map((entity) => entity.entityId);
11743
11743
  const views = recall.entitySources(linkedIds, maxRecords);
11744
11744
  const sourceIds = [.../* @__PURE__ */ new Set([
11745
11745
  ...(request.continuationIds ?? []).filter((id2) => !id2.startsWith("rel_")),
@@ -15564,8 +15564,8 @@ function isSqliteBusy(error) {
15564
15564
  async function withMem7BusyRetry(operation, options = {}) {
15565
15565
  const attempts = options.attempts ?? 6;
15566
15566
  const baseDelayMs = options.baseDelayMs ?? 300;
15567
- const sleep8 = options.sleep ?? ((ms) => new Promise((resolve40) => {
15568
- setTimeout(resolve40, ms);
15567
+ const sleep8 = options.sleep ?? ((ms) => new Promise((resolve45) => {
15568
+ setTimeout(resolve45, ms);
15569
15569
  }));
15570
15570
  for (let attempt = 1; attempt <= attempts; attempt++) {
15571
15571
  try {
@@ -16260,11 +16260,11 @@ __export(qr_render_exports, {
16260
16260
  });
16261
16261
  import { createRequire as createRequire4 } from "node:module";
16262
16262
  async function renderQrTerminal(url, options) {
16263
- return new Promise((resolve40, reject) => {
16263
+ return new Promise((resolve45, reject) => {
16264
16264
  try {
16265
16265
  const qt = require2("qrcode-terminal");
16266
16266
  qt.generate(url, { small: options?.small ?? true }, (output) => {
16267
- resolve40(output);
16267
+ resolve45(output);
16268
16268
  });
16269
16269
  } catch (err) {
16270
16270
  reject(err);
@@ -16437,8 +16437,8 @@ var init_wechat = __esm({
16437
16437
 
16438
16438
  // src/cli-stdout.ts
16439
16439
  function writeTo(stream, text4) {
16440
- const p = new Promise((resolve40) => {
16441
- stream.write(text4, () => resolve40());
16440
+ const p = new Promise((resolve45) => {
16441
+ stream.write(text4, () => resolve45());
16442
16442
  });
16443
16443
  if (stream === process.stdout) tail = p;
16444
16444
  return p;
@@ -17720,6 +17720,9 @@ var init_registry = __esm({
17720
17720
  }
17721
17721
  }
17722
17722
  },
17723
+ // 1119:引擎侧 Gmail 读信的 scoped 代理出口(只作用于 GmailClient→gmail.googleapis.com,
17724
+ // broker 不走它)。Mac 直连被墙的机器配本机代理即可;不配=维持直连行为。
17725
+ { path: "auth.gmailProxy", type: "string", group: "api", label: "Gmail \u51FA\u53E3\u4EE3\u7406", effect: "hot" },
17723
17726
  {
17724
17727
  path: "tools.email",
17725
17728
  type: "json",
@@ -18759,13 +18762,13 @@ var init_overwrite_backup = __esm({
18759
18762
  const backupPath = `files/${this.files.size}-${path7.basename(originalPath)}`;
18760
18763
  const dest = path7.join(this.directory, backupPath);
18761
18764
  durableWrite(dest, bytes);
18762
- const sha256 = createHash22("sha256").update(bytes).digest("hex");
18763
- if (createHash22("sha256").update(fs8.readFileSync(dest)).digest("hex") !== sha256) throw new Error("\u526F\u672C\u6821\u9A8C\u5931\u8D25");
18765
+ const sha2563 = createHash22("sha256").update(bytes).digest("hex");
18766
+ if (createHash22("sha256").update(fs8.readFileSync(dest)).digest("hex") !== sha2563) throw new Error("\u526F\u672C\u6821\u9A8C\u5931\u8D25");
18764
18767
  this.files.set(originalPath, {
18765
18768
  originalPath,
18766
18769
  existed: true,
18767
18770
  backupPath,
18768
- sha256,
18771
+ sha256: sha2563,
18769
18772
  mode: fs8.statSync(originalPath).mode & 511,
18770
18773
  ...info.isSymbolicLink() ? { symlinkTarget: fs8.readlinkSync(originalPath) } : {}
18771
18774
  });
@@ -20203,14 +20206,14 @@ var init_provider = __esm({
20203
20206
  // src/services/withRetry.ts
20204
20207
  import { ProxyAgent } from "undici";
20205
20208
  function sleep3(ms, signal) {
20206
- return new Promise((resolve40, reject) => {
20209
+ return new Promise((resolve45, reject) => {
20207
20210
  if (signal?.aborted) {
20208
20211
  reject(new DOMException("Aborted", "AbortError"));
20209
20212
  return;
20210
20213
  }
20211
20214
  const timer = setTimeout(() => {
20212
20215
  signal?.removeEventListener("abort", onAbort);
20213
- resolve40();
20216
+ resolve45();
20214
20217
  }, ms);
20215
20218
  const onAbort = () => {
20216
20219
  clearTimeout(timer);
@@ -22885,13 +22888,13 @@ var init_cpu_router = __esm({
22885
22888
  }
22886
22889
  const id2 = ++this.nextId;
22887
22890
  const worker = this.worker;
22888
- return await new Promise((resolve40) => {
22891
+ return await new Promise((resolve45) => {
22889
22892
  const finish = (result) => {
22890
22893
  clearTimeout(timer);
22891
22894
  signal?.removeEventListener("abort", onAbort);
22892
22895
  this.pending.delete(id2);
22893
22896
  if (this.pending.size === 0) worker.unref();
22894
- resolve40(signal?.aborted ? null : result);
22897
+ resolve45(signal?.aborted ? null : result);
22895
22898
  };
22896
22899
  const onAbort = () => {
22897
22900
  finish(null);
@@ -23155,9 +23158,9 @@ async function execCommandHook(hook, hookEvent, hookName, jsonInput, signal, hoo
23155
23158
  child.stderr.on("data", (chunk) => {
23156
23159
  stderr += chunk;
23157
23160
  });
23158
- const exitCode = await new Promise((resolve40) => {
23159
- child.on("close", (code) => resolve40(code ?? 0));
23160
- child.on("error", () => resolve40(1));
23161
+ const exitCode = await new Promise((resolve45) => {
23162
+ child.on("close", (code) => resolve45(code ?? 0));
23163
+ child.on("error", () => resolve45(1));
23161
23164
  });
23162
23165
  if (timeoutHandle) clearTimeout(timeoutHandle);
23163
23166
  if (killHandle) clearTimeout(killHandle);
@@ -23974,8 +23977,8 @@ var init_on_demand_recall = __esm({
23974
23977
  const result = (async () => {
23975
23978
  let onAbort;
23976
23979
  try {
23977
- const stopped = new Promise((resolve40) => {
23978
- onAbort = () => resolve40(status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002"));
23980
+ const stopped = new Promise((resolve45) => {
23981
+ onAbort = () => resolve45(status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002"));
23979
23982
  combined.addEventListener("abort", onAbort, { once: true });
23980
23983
  });
23981
23984
  const answer = await Promise.race([run(bounded, combined), stopped]);
@@ -24060,7 +24063,7 @@ async function assertFormat(bytes, mediaType) {
24060
24063
  const actual = "image/" + (metadata2.format === "jpg" ? "jpeg" : metadata2.format);
24061
24064
  if (actual !== mediaType || !extensions[actual]) throw new Error("Image asset MIME does not match its bytes");
24062
24065
  }
24063
- async function materializeImageMessages(messages, store, signal, maxBase64Bytes = REQUEST_IMAGE_MAX_BASE64_SIZE) {
24066
+ async function materializeImageMessages(messages, store, signal, maxBase64Bytes = REQUEST_IMAGE_MAX_BASE64_SIZE, opts = {}) {
24064
24067
  signal?.throwIfAborted();
24065
24068
  let total = 0;
24066
24069
  for (const message of messages) if (Array.isArray(message.content)) for (const block of message.content) {
@@ -24085,6 +24088,7 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
24085
24088
  return { ...message, content: content.length ? content : "[previous image omitted]" };
24086
24089
  });
24087
24090
  if (total > maxBase64Bytes) throw new Error(`Request image base64 exceeds ${maxBase64Bytes} byte limit`);
24091
+ const { strict = false } = opts;
24088
24092
  const cache2 = /* @__PURE__ */ new Map();
24089
24093
  const output = [];
24090
24094
  for (const message of requestView) {
@@ -24101,8 +24105,12 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
24101
24105
  }
24102
24106
  if (!store) throw new Error("Image asset store is required to materialize image refs");
24103
24107
  const key4 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
24104
- if (!cache2.has(key4)) cache2.set(key4, store.materialize(block.image));
24105
- content.push(await cache2.get(key4));
24108
+ if (!cache2.has(key4)) cache2.set(key4, store.materialize(block.image).catch((error) => {
24109
+ if (strict) throw error;
24110
+ console.warn(`[image-assets] \u5386\u53F2\u56FE\u7247\u4E0D\u53EF\u7528\uFF0C\u964D\u7EA7\u4E3A\u5360\u4F4D\uFF08sha256=${block.image.sha256.slice(0, 12)}\uFF09\uFF1A${error instanceof Error ? error.message : String(error)}`);
24111
+ return null;
24112
+ }));
24113
+ content.push(await cache2.get(key4) ?? { type: "text", text: "[\u56FE\u7247\u6587\u4EF6\u5DF2\u4E0D\u5728\u672C\u673A\uFF0C\u5185\u5BB9\u4E0D\u53EF\u89C1]" });
24106
24114
  signal?.throwIfAborted();
24107
24115
  }
24108
24116
  output.push({ ...message, content });
@@ -25716,11 +25724,11 @@ var init_background = __esm({
25716
25724
  signal?.throwIfAborted();
25717
25725
  const task = this.tasks.get(sessionId);
25718
25726
  if (!task) return;
25719
- await new Promise((resolve40, reject) => {
25727
+ await new Promise((resolve45, reject) => {
25720
25728
  const stop = () => reject(signal?.aborted ? signal.reason : task.abort.signal.reason);
25721
25729
  signal?.addEventListener("abort", stop, { once: true });
25722
25730
  task.abort.signal.addEventListener("abort", stop, { once: true });
25723
- task.promise.then(resolve40, reject).finally(() => {
25731
+ task.promise.then(resolve45, reject).finally(() => {
25724
25732
  signal?.removeEventListener("abort", stop);
25725
25733
  task.abort.signal.removeEventListener("abort", stop);
25726
25734
  });
@@ -26282,7 +26290,7 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
26282
26290
  await fs18.promises.unlink(outputFile);
26283
26291
  return { content: "[not executed: new user input or stop received before command start]" };
26284
26292
  }
26285
- return new Promise((resolve40) => {
26293
+ return new Promise((resolve45) => {
26286
26294
  const { shell, args: shellArgs } = findShell();
26287
26295
  const child = spawn2(shell, [...shellArgs, command], {
26288
26296
  cwd,
@@ -26329,7 +26337,7 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
26329
26337
  aborted ? "<error>Command was aborted before completion</error>" : "",
26330
26338
  truncated ? "...[output truncated]" : ""
26331
26339
  ].filter(Boolean);
26332
- resolve40({ content: parts.join("\n") || "(no output)", isError: aborted || !!error });
26340
+ resolve45({ content: parts.join("\n") || "(no output)", isError: aborted || !!error });
26333
26341
  };
26334
26342
  const onExit = (code) => {
26335
26343
  void done2(code);
@@ -26362,7 +26370,7 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
26362
26370
  });
26363
26371
  settled = true;
26364
26372
  cleanup2();
26365
- resolve40({ content: `Waiting yielded for new user input. Command running in background with ID: ${task.id}. Output is being written to: ${task.outputFile}. Use TaskOutput or Read to observe it; do not restart the command.` });
26373
+ resolve45({ content: `Waiting yielded for new user input. Command running in background with ID: ${task.id}. Output is being written to: ${task.outputFile}. Use TaskOutput or Read to observe it; do not restart the command.` });
26366
26374
  };
26367
26375
  const timer = setTimeout(() => {
26368
26376
  if (!settled) {
@@ -27720,7 +27728,7 @@ var init_query = __esm({
27720
27728
  const postData = JSON.stringify({ text: line, isPlaceholder: true });
27721
27729
  assertExternalEffectCurrent();
27722
27730
  beginHostTurnEffect();
27723
- await new Promise((resolve40, reject) => {
27731
+ await new Promise((resolve45, reject) => {
27724
27732
  const req = https.request(url, {
27725
27733
  method: "POST",
27726
27734
  headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(postData) },
@@ -27728,7 +27736,7 @@ var init_query = __esm({
27728
27736
  }, (res) => {
27729
27737
  res.resume();
27730
27738
  if ((res.statusCode ?? 500) >= 400) reject(new Error(`VOICE_PLACEHOLDER_HTTP_${res.statusCode}`));
27731
- else resolve40();
27739
+ else resolve45();
27732
27740
  });
27733
27741
  req.on("error", reject);
27734
27742
  req.write(postData);
@@ -29180,18 +29188,22 @@ function frameBytes(row) {
29180
29188
  if (createHash28("sha256").update(bytes).digest("hex") !== row.digest) throw new Error("SESSION_EVENT_CORRUPT");
29181
29189
  return bytes;
29182
29190
  }
29183
- function mapSessionIndex(bytes, db2, path72, stateDir, sourceRoot, targetRoot) {
29191
+ function mapSessionIndex(bytes, _db, path72, stateDir, sourceRoot, targetRoot) {
29184
29192
  if (basename9(path72) !== "session-index.json") return bytes;
29185
- const index = JSON.parse(bytes.toString("utf8"));
29193
+ let index;
29194
+ try {
29195
+ index = JSON.parse(bytes.toString("utf8"));
29196
+ } catch {
29197
+ return bytes;
29198
+ }
29199
+ if (!index || typeof index !== "object" || Array.isArray(index)) return bytes;
29186
29200
  const prefixes = [sourceRoot, stateDir].map((root) => root.replace(/\\/g, "/").replace(/\/$/, "") + "/");
29187
- if (!index || typeof index !== "object" || Array.isArray(index)) throw new Error("SESSION_INDEX_INVALID");
29188
29201
  for (const entry of Object.values(index)) {
29189
- if (!entry || typeof entry.file !== "string") throw new Error("SESSION_INDEX_INVALID");
29202
+ if (!entry || typeof entry.file !== "string") continue;
29190
29203
  const old = entry.file.replace(/\\/g, "/"), prefix2 = prefixes.find((value) => old.startsWith(value));
29191
- if (!prefix2) throw new Error("SESSION_INDEX_PATH_UNSUPPORTED");
29204
+ if (!prefix2) continue;
29192
29205
  const local = old.slice(prefix2.length);
29193
29206
  sessionFilePath(stateDir, join34(stateDir, local));
29194
- if (!db2.prepare("SELECT 1 FROM session_files WHERE path=? AND state='active'").get(local)) throw new Error("SESSION_INDEX_TARGET_MISSING");
29195
29207
  entry.file = join34(targetRoot, local);
29196
29208
  }
29197
29209
  return Buffer.from(JSON.stringify(index, null, 2));
@@ -29962,8 +29974,8 @@ var init_writer2 = __esm({
29962
29974
  if (!stream) return;
29963
29975
  if (stream.errored) throw stream.errored;
29964
29976
  if (stream.destroyed) throw new Error("SessionWriter stream is closed");
29965
- await new Promise((resolve40, reject) => {
29966
- stream.write("", (error) => error ? reject(error) : resolve40());
29977
+ await new Promise((resolve45, reject) => {
29978
+ stream.write("", (error) => error ? reject(error) : resolve45());
29967
29979
  });
29968
29980
  }
29969
29981
  /** A boundary becomes recoverable only together with the complete replacement. */
@@ -30017,9 +30029,9 @@ var init_writer2 = __esm({
30017
30029
  committed = true;
30018
30030
  } else {
30019
30031
  const stream = this.stream;
30020
- await new Promise((resolve40, reject) => {
30032
+ await new Promise((resolve45, reject) => {
30021
30033
  stream.once("error", reject);
30022
- stream.end(resolve40);
30034
+ stream.end(resolve45);
30023
30035
  });
30024
30036
  this.stream = null;
30025
30037
  temporary = this.filePath + ".compact-" + crypto2.randomUUID();
@@ -30318,7 +30330,7 @@ import * as readline from "node:readline";
30318
30330
  async function readSessionHeader(filePath) {
30319
30331
  const stream = fs22.createReadStream(filePath, { encoding: "utf-8" });
30320
30332
  const rl = readline.createInterface({ input: stream });
30321
- return new Promise((resolve40) => {
30333
+ return new Promise((resolve45) => {
30322
30334
  let resolved = false;
30323
30335
  rl.on("line", (line) => {
30324
30336
  try {
@@ -30327,7 +30339,7 @@ async function readSessionHeader(filePath) {
30327
30339
  resolved = true;
30328
30340
  rl.close();
30329
30341
  stream.destroy();
30330
- resolve40({
30342
+ resolve45({
30331
30343
  id: obj.id,
30332
30344
  timestamp: obj.timestamp,
30333
30345
  cwd: obj.cwd,
@@ -30339,10 +30351,10 @@ async function readSessionHeader(filePath) {
30339
30351
  }
30340
30352
  });
30341
30353
  rl.on("close", () => {
30342
- if (!resolved) resolve40(null);
30354
+ if (!resolved) resolve45(null);
30343
30355
  });
30344
30356
  rl.on("error", () => {
30345
- if (!resolved) resolve40(null);
30357
+ if (!resolved) resolve45(null);
30346
30358
  });
30347
30359
  });
30348
30360
  }
@@ -30596,9 +30608,9 @@ async function readAllLines(filePath) {
30596
30608
  const stream = fs22.createReadStream(filePath, { encoding: "utf-8" });
30597
30609
  const rl = readline.createInterface({ input: stream });
30598
30610
  const lines = [];
30599
- return new Promise((resolve40, reject) => {
30611
+ return new Promise((resolve45, reject) => {
30600
30612
  rl.on("line", (line) => lines.push(line));
30601
- rl.on("close", () => resolve40(lines));
30613
+ rl.on("close", () => resolve45(lines));
30602
30614
  rl.on("error", (err) => reject(err));
30603
30615
  });
30604
30616
  }
@@ -32116,8 +32128,8 @@ ${terminalText(job.prompt)}`;
32116
32128
  throw failure("prompt and source required", 400);
32117
32129
  }
32118
32130
  if (queue.length >= 32) throw failure("Desktop queue full", 429);
32119
- const result = new Promise((resolve40, reject) => {
32120
- job = { id: randomUUID22(), prompt: input.prompt, source: input.source, sessionId: input.sessionId, submitted: false, resolve: resolve40, reject };
32131
+ const result = new Promise((resolve45, reject) => {
32132
+ job = { id: randomUUID22(), prompt: input.prompt, source: input.source, sessionId: input.sessionId, submitted: false, resolve: resolve45, reject };
32121
32133
  queue.push(job);
32122
32134
  });
32123
32135
  if (res.destroyed) disconnect();
@@ -32129,9 +32141,9 @@ ${terminalText(job.prompt)}`;
32129
32141
  res.off("close", disconnect);
32130
32142
  }
32131
32143
  });
32132
- await new Promise((resolve40, reject) => {
32144
+ await new Promise((resolve45, reject) => {
32133
32145
  server.once("error", reject);
32134
- server.listen(0, "127.0.0.1", resolve40);
32146
+ server.listen(0, "127.0.0.1", resolve45);
32135
32147
  });
32136
32148
  endpoint.port = server.address().port;
32137
32149
  save2();
@@ -32143,8 +32155,8 @@ ${terminalText(job.prompt)}`;
32143
32155
  fs26.unlinkSync(file2);
32144
32156
  } catch {
32145
32157
  }
32146
- await new Promise((resolve40) => {
32147
- server.close(() => resolve40());
32158
+ await new Promise((resolve45) => {
32159
+ server.close(() => resolve45());
32148
32160
  server.closeAllConnections();
32149
32161
  });
32150
32162
  } };
@@ -32596,6 +32608,10 @@ function rowElements(state2, rowCap) {
32596
32608
  }
32597
32609
  }
32598
32610
  flush();
32611
+ if (state2.steerNotes?.length) {
32612
+ for (const s of state2.steerNotes) lines.push(`\u21AA \u63D2\u8BDD\uFF1A${s.length > ARGS_MAX ? s.slice(0, ARGS_MAX - 1) + "\u2026" : s}`);
32613
+ flush();
32614
+ }
32599
32615
  const lt = state2.liveThink;
32600
32616
  if (lt) {
32601
32617
  const sec = Math.max(1, Math.round((Date.now() - lt.start) / 1e3));
@@ -32606,6 +32622,9 @@ function rowElements(state2, rowCap) {
32606
32622
  } else if (state2.status === "run") {
32607
32623
  els.push({ tag: "div", text: { tag: "lark_md", content: `*${spinnerFrame()} ${state2.verb}\u2026\uFF08${fmtDur(Math.max(1, Math.round((Date.now() - state2.startedAt) / 1e3)))}\uFF09*` } });
32608
32624
  }
32625
+ if (state2.stopAction && (state2.status === "run" || state2.status === "wait")) {
32626
+ els.push({ tag: "action", actions: [{ tag: "button", type: "default", text: { tag: "plain_text", content: "\u505C\u6B62" }, value: state2.stopAction }] });
32627
+ }
32609
32628
  return { els, dropped };
32610
32629
  }
32611
32630
  function buildProcessCard(state2, level = 2) {
@@ -32798,6 +32817,10 @@ function buildProcessCardV2At(state2, level, panelCap) {
32798
32817
  }
32799
32818
  }
32800
32819
  flushPlain();
32820
+ if (state2.steerNotes?.length) {
32821
+ for (const s of state2.steerNotes) plain.push(`\u21AA \u63D2\u8BDD\uFF1A${capStr(s, ARGS_MAX)}`);
32822
+ flushPlain();
32823
+ }
32801
32824
  const lt = state2.liveThink;
32802
32825
  if (lt) {
32803
32826
  const sec = Math.max(1, Math.round((Date.now() - lt.start) / 1e3));
@@ -32808,6 +32831,9 @@ function buildProcessCardV2At(state2, level, panelCap) {
32808
32831
  } else if (state2.status === "run") {
32809
32832
  els.push({ tag: "markdown", content: `*${spinnerFrame()} ${state2.verb}\u2026\uFF08${fmtDur(Math.max(1, Math.round((Date.now() - state2.startedAt) / 1e3)))}\uFF09*` });
32810
32833
  }
32834
+ if (state2.stopAction && (state2.status === "run" || state2.status === "wait")) {
32835
+ els.push(buttonRow([{ tag: "button", type: "default", text: { tag: "plain_text", content: "\u505C\u6B62" }, value: state2.stopAction }]));
32836
+ }
32811
32837
  const notes = [];
32812
32838
  if (state2.usage) notes.push(state2.usage);
32813
32839
  if (state2.status === "wait") notes.push("\u70B9\u6309\u94AE\u5BA1\u6279\uFF0C\u4E5F\u53EF\u76F4\u63A5\u6253\u5B57");
@@ -32919,7 +32945,7 @@ var init_process_card = __esm({
32919
32945
  this.summarySent = false;
32920
32946
  this.terminal = null;
32921
32947
  this.patchFailures = 0;
32922
- this.state = { repoName: this.repoName, prompt, status: "run", rows: [], finalText: "", usage: "", liveThink: null, startedAt: Date.now(), verb: VERBS[Math.floor(Math.random() * VERBS.length)], presentation: this.options.presentation };
32948
+ this.state = { repoName: this.repoName, prompt, status: "run", rows: [], finalText: "", usage: "", liveThink: null, startedAt: Date.now(), verb: VERBS[Math.floor(Math.random() * VERBS.length)], presentation: this.options.presentation, requestId: this.options.requestId };
32923
32949
  this.lastPushKey = this.pushKey();
32924
32950
  this.messageId = null;
32925
32951
  this.channelV = null;
@@ -32940,7 +32966,10 @@ var init_process_card = __esm({
32940
32966
  }
32941
32967
  /** Mode decisions can start native progress without awaiting any channel I/O. */
32942
32968
  start() {
32943
- if (!this.ended && !this.started && (this.nativeCapable() || this.legacyCapable())) this.beginInBackground();
32969
+ if (!this.ended && !this.started && (this.nativeCapable() || this.legacyCapable() || this.progressCapable())) this.beginInBackground();
32970
+ }
32971
+ progressCapable() {
32972
+ return !!this.adapter.sendProgress && !!this.adapter.updateProgress && !!this.adapter.removeProgress;
32944
32973
  }
32945
32974
  nativeCapable() {
32946
32975
  const ad = this.adapter;
@@ -32954,10 +32983,16 @@ var init_process_card = __esm({
32954
32983
  }
32955
32984
  ensureStarted() {
32956
32985
  const ad = this.adapter;
32957
- if (this.options.autoStart && !this.started && (this.nativeCapable() || this.legacyCapable() || ad.sendPreview && ad.editPreview)) this.beginInBackground();
32986
+ if (this.options.autoStart && !this.started && (this.nativeCapable() || this.legacyCapable() || this.progressCapable() || ad.sendPreview && ad.editPreview)) this.beginInBackground();
32958
32987
  }
32959
32988
  async createCard() {
32960
32989
  const ad = this.adapter;
32990
+ if (this.progressCapable()) {
32991
+ this.messageId = await ad.sendProgress(this.target, structuredClone(this.state));
32992
+ this.channelV = "progress";
32993
+ this.lastPatchAt = Date.now();
32994
+ return;
32995
+ }
32961
32996
  if (!this.nativeCapable() && this.legacyCapable()) return this.createLegacyCard();
32962
32997
  if (!this.nativeCapable() && this.options.allowLegacyCard === false) {
32963
32998
  if (!ad.sendPreview || !ad.editPreview) throw new Error("\u65E0\u8FC7\u7A0B\u5361\u6216\u53EF\u7F16\u8F91\u6D88\u606F\u80FD\u529B");
@@ -33004,8 +33039,10 @@ var init_process_card = __esm({
33004
33039
  }
33005
33040
  async removeCard() {
33006
33041
  if (this.messageId) {
33007
- if (!this.adapter.deletePreview) throw new Error("\u65E0\u8FC7\u7A0B\u5361\u6E05\u7406\u80FD\u529B");
33008
- await this.adapter.deletePreview({ channelId: this.target, messageId: this.messageId });
33042
+ if (this.channelV === "progress" && this.adapter.removeProgress) {
33043
+ await this.adapter.removeProgress(this.messageId);
33044
+ } else if (!this.adapter.deletePreview) throw new Error("\u65E0\u8FC7\u7A0B\u5361\u6E05\u7406\u80FD\u529B");
33045
+ else await this.adapter.deletePreview({ channelId: this.target, messageId: this.messageId });
33009
33046
  }
33010
33047
  this.messageId = null;
33011
33048
  this.cardKitId = null;
@@ -33016,7 +33053,7 @@ var init_process_card = __esm({
33016
33053
  /** Shared heartbeat samples state; the push key suppresses unchanged cards. */
33017
33054
  startHeartbeat() {
33018
33055
  this.stopHeartbeat();
33019
- const interval = this.channelV === "cardkit" ? 800 : 2500;
33056
+ const interval = this.channelV === "cardkit" || this.channelV === "progress" ? 800 : 2500;
33020
33057
  this.heartbeat = setInterval(() => {
33021
33058
  if (this.state.status !== "run" && this.state.status !== "wait") {
33022
33059
  this.stopHeartbeat();
@@ -33030,10 +33067,10 @@ var init_process_card = __esm({
33030
33067
  if (this.heartbeat) clearInterval(this.heartbeat);
33031
33068
  this.heartbeat = null;
33032
33069
  }
33033
- onToolUse(name, input, id2) {
33070
+ onToolUse(name, input, id2, inputFull) {
33034
33071
  if (this.ended || this.disposed) return;
33035
33072
  this.ensureStarted();
33036
- this.state.rows.push({ kind: "tool", id: id2, name, args: stripCardUnsafe(typeof input === "string" ? input : toolArgsSummary(name, input)), state: "run", out: "", more: 0 });
33073
+ this.state.rows.push({ kind: "tool", id: id2, name, args: stripCardUnsafe(typeof input === "string" ? input : toolArgsSummary(name, input)), state: "run", out: "", more: 0, ...inputFull ? { inputFull: stripCardUnsafe(inputFull.slice(0, OUTFULL_MAX)) } : {} });
33037
33074
  if (this.state.status === "wait") this.state.status = "run";
33038
33075
  this.schedulePatch();
33039
33076
  }
@@ -33046,7 +33083,7 @@ var init_process_card = __esm({
33046
33083
  row = this.state.rows.at(-1);
33047
33084
  }
33048
33085
  if (!row) return;
33049
- const retain = match?.visible !== false || this.nativeCapable();
33086
+ const retain = match?.visible !== false || this.nativeCapable() || this.progressCapable();
33050
33087
  const lines = (out || "").split("\n").filter((line) => line.trim());
33051
33088
  row.state = retain && isError ? "err" : "ok";
33052
33089
  row.resultVisible = match?.visible;
@@ -33102,7 +33139,7 @@ var init_process_card = __esm({
33102
33139
  askPermission(toolName, input, signal, suggestions) {
33103
33140
  const rid = this.nextRid("p");
33104
33141
  const preview = stripCardUnsafe(toolArgsSummary(toolName, input) || oneLine(JSON.stringify(input).slice(0, 200)));
33105
- return new Promise((resolve40) => {
33142
+ return new Promise((resolve45) => {
33106
33143
  let settled = false;
33107
33144
  const settle = (v, message) => {
33108
33145
  if (settled) return;
@@ -33114,7 +33151,7 @@ var init_process_card = __esm({
33114
33151
  if (row) row.settled = v;
33115
33152
  if (pendingPerms.size === 0 && pendingAsks.size === 0 && this.state.status === "wait") this.state.status = "run";
33116
33153
  this.schedulePatch(true);
33117
- resolve40({ verdict: v, message });
33154
+ resolve45({ verdict: v, message });
33118
33155
  };
33119
33156
  const timer = setTimeout(() => settle("deny"), PERM_TIMEOUT_MS);
33120
33157
  const onAbort = () => settle("deny");
@@ -33133,7 +33170,7 @@ var init_process_card = __esm({
33133
33170
  askUser(questions, signal) {
33134
33171
  const rid = this.nextRid("q");
33135
33172
  const safeQ = questions.map((q) => ({ ...q, question: stripCardUnsafe(q.question), header: stripCardUnsafe(q.header), options: q.options.map((o) => ({ ...o, label: stripCardUnsafe(o.label) })) }));
33136
- return new Promise((resolve40) => {
33173
+ return new Promise((resolve45) => {
33137
33174
  let settled = false;
33138
33175
  const settle = (answers, message) => {
33139
33176
  if (settled) return;
@@ -33147,7 +33184,7 @@ var init_process_card = __esm({
33147
33184
  }
33148
33185
  if (pendingPerms.size === 0 && pendingAsks.size === 0 && this.state.status === "wait") this.state.status = "run";
33149
33186
  this.schedulePatch(true);
33150
- resolve40({ answers, message });
33187
+ resolve45({ answers, message });
33151
33188
  };
33152
33189
  const timer = setTimeout(() => settle(null), PERM_TIMEOUT_MS);
33153
33190
  const onAbort = () => settle(null);
@@ -33180,6 +33217,19 @@ var init_process_card = __esm({
33180
33217
  }
33181
33218
  return false;
33182
33219
  }
33220
+ /** 1119 cc-desk steer:忙时插话在卡片上留 ↪ 行(过程可见) */
33221
+ onSteer(text4) {
33222
+ if (this.ended || this.disposed) return;
33223
+ this.ensureStarted();
33224
+ this.state.steerNotes = [...this.state.steerNotes ?? [], stripCardUnsafe(oneLine(text4))].slice(-3);
33225
+ this.schedulePatch();
33226
+ }
33227
+ /** 1119 卡片停止钮:设置/清除停止按钮的 action value(run/wait 态渲染) */
33228
+ setStopAction(value) {
33229
+ if (this.ended || this.disposed) return;
33230
+ this.state.stopAction = value ?? void 0;
33231
+ this.schedulePatch();
33232
+ }
33183
33233
  turnEnd(finalText, usage, outcome) {
33184
33234
  return this.finish(outcome, finalText, usage);
33185
33235
  }
@@ -33215,7 +33265,7 @@ var init_process_card = __esm({
33215
33265
  return;
33216
33266
  }
33217
33267
  if (this.patchTimer) return;
33218
- const min = this.channelV === "cardkit" ? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
33268
+ const min = this.channelV === "cardkit" || this.channelV === "progress" ? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
33219
33269
  const wait = Math.max(0, min - (Date.now() - this.lastPatchAt));
33220
33270
  this.patchTimer = setTimeout(() => {
33221
33271
  this.patchTimer = null;
@@ -33230,7 +33280,7 @@ var init_process_card = __esm({
33230
33280
  await this.creation?.catch(() => {
33231
33281
  });
33232
33282
  if (this.disposed || this.ended && !final) return;
33233
- if (final && this.options.discardEmptyOnDone && this.state.status === "done" && !this.state.earlierSteps && !this.state.rows.some((row) => row.kind !== "think") && (!this.messageId || this.adapter.deletePreview)) {
33283
+ if (final && this.options.discardEmptyOnDone && this.state.status === "done" && !this.state.earlierSteps && !this.state.rows.some((row) => row.kind !== "think") && (!this.messageId || this.adapter.deletePreview || this.adapter.removeProgress)) {
33234
33284
  await this.removeCard().catch((error) => console.warn("[process-card] \u7A7A\u56DE\u5408\u6E05\u7406\u5931\u8D25:", error instanceof Error ? error.message : String(error)));
33235
33285
  return;
33236
33286
  }
@@ -33253,17 +33303,19 @@ var init_process_card = __esm({
33253
33303
  return `q${r.rid}:${r.settled}:${JSON.stringify(r.answers)}`;
33254
33304
  }).join("|");
33255
33305
  const bucket = Math.floor((Date.now() - s.startedAt) / LIVE_BUCKET_MS);
33256
- return JSON.stringify([s.prompt, s.status, rows, s.earlierSteps || 0, s.finalText.length, s.usage, s.liveThink ? `${s.liveThink.text.length}:${s.liveThink.text.slice(-24)}` : "", bucket]);
33306
+ return JSON.stringify([s.prompt, s.status, rows, s.earlierSteps || 0, s.finalText.length, s.usage, s.liveThink ? `${s.liveThink.text.length}:${s.liveThink.text.slice(-24)}` : "", bucket, s.steerNotes?.join("\n").length ?? 0, s.stopAction ? 1 : 0]);
33257
33307
  }
33258
33308
  async doPatch(final = false) {
33259
33309
  if (this.degraded || !this.messageId && this.channelV !== "cardkit") return false;
33260
33310
  const key4 = this.pushKey();
33261
33311
  if (key4 === this.lastPushKey) return true;
33262
33312
  this.lastPatchAt = Date.now();
33263
- const card = this.channelV === "patch-v1" ? buildProcessCard(this.state) : buildProcessCardV2(this.state) ?? (this.options.allowLegacyCard !== false ? buildProcessCard(this.state) : null);
33264
- if (this.channelV !== "preview" && !card) return false;
33313
+ const card = this.channelV === "progress" ? null : this.channelV === "patch-v1" ? buildProcessCard(this.state) : buildProcessCardV2(this.state) ?? (this.options.allowLegacyCard !== false ? buildProcessCard(this.state) : null);
33314
+ if (this.channelV !== "preview" && this.channelV !== "progress" && !card) return false;
33265
33315
  try {
33266
- if (this.channelV === "preview" && this.previewHandle && this.adapter.editPreview) {
33316
+ if (this.channelV === "progress" && this.messageId && this.adapter.updateProgress) {
33317
+ await this.adapter.updateProgress(this.messageId, structuredClone(this.state));
33318
+ } else if (this.channelV === "preview" && this.previewHandle && this.adapter.editPreview) {
33267
33319
  await this.adapter.editPreview(this.previewHandle, buildProcessText(this.state), this.repoName, final);
33268
33320
  } else if (this.channelV === "cardkit" && this.cardKitId && card) {
33269
33321
  this.seq++;
@@ -33322,6 +33374,12 @@ async function handleCcCardAction(data) {
33322
33374
  const fv = action?.form_value ?? {};
33323
33375
  const v = action?.value;
33324
33376
  if (!v || v.cc !== 1) return { toast: { type: "info", content: "\u672A\u77E5\u64CD\u4F5C" } };
33377
+ if (v.kind === "stop" && typeof v.key === "string") {
33378
+ const { ccDriverRouter: ccDriverRouter2 } = await Promise.resolve().then(() => (init_router(), router_exports));
33379
+ const session = ccDriverRouter2.hub?.forChatKey(v.key);
33380
+ const stopped = session ? session.stopAll() : false;
33381
+ return { toast: { type: stopped ? "success" : "info", content: stopped ? "\u5DF2\u505C\u6B62\u5F53\u524D\u4EFB\u52A1" : "\u5F53\u524D\u6CA1\u6709\u5728\u8DD1\u7684\u4EFB\u52A1" } };
33382
+ }
33325
33383
  if (v.kind === "perm" && v.rid) {
33326
33384
  const p = pendingPerms.get(v.rid);
33327
33385
  if (!p) return { toast: { type: "info", content: "\u8BE5\u5BA1\u6279\u5DF2\u5904\u7406\u6216\u5DF2\u5931\u6548" } };
@@ -33753,6 +33811,9 @@ var init_dep_downloader = __esm({
33753
33811
  function requestError(message, status = 409) {
33754
33812
  return Object.assign(new Error(message), { status });
33755
33813
  }
33814
+ function ccUserMsg(text4) {
33815
+ return { type: "user", message: { role: "user", content: text4 }, parent_tool_use_id: null };
33816
+ }
33756
33817
  function resultToText(content) {
33757
33818
  if (typeof content === "string") return content;
33758
33819
  if (Array.isArray(content)) {
@@ -33777,7 +33838,7 @@ function chunkText(text4, maxChars) {
33777
33838
  if (rest.trim()) chunks.push(rest);
33778
33839
  return chunks;
33779
33840
  }
33780
- var MAX_QUEUE, INTERIM_MIN_INTERVAL_MS, INTERIM_MIN_CHARS, MAX_INTERIM_PER_TURN, INTERIM_SNIPPET_CHARS, FINAL_CHUNK_CHARS, CcDriverSession, CcDriverHub;
33841
+ var MAX_QUEUE, INTERIM_MIN_INTERVAL_MS, INTERIM_MIN_CHARS, MAX_INTERIM_PER_TURN, INTERIM_SNIPPET_CHARS, FINAL_CHUNK_CHARS, SteerFeeder, defaultCcRuntimeLoader, ccRuntimeLoader, CcDriverSession, CcDriverHub;
33781
33842
  var init_driver = __esm({
33782
33843
  "src/cc-driver/driver.ts"() {
33783
33844
  "use strict";
@@ -33792,6 +33853,53 @@ var init_driver = __esm({
33792
33853
  MAX_INTERIM_PER_TURN = 4;
33793
33854
  INTERIM_SNIPPET_CHARS = 600;
33794
33855
  FINAL_CHUNK_CHARS = 1500;
33856
+ SteerFeeder = class {
33857
+ pending = [];
33858
+ waiters = [];
33859
+ ended = false;
33860
+ /** 已 yield 给 CLI 的消息数(含首条) */
33861
+ yieldCount = 0;
33862
+ /** 最近一次 yield 的文本(续 turn 卡片的 prompt 用) */
33863
+ lastYield = "";
33864
+ /** 注入一条;返回 false = 已收口,进不了这个流了 */
33865
+ push(text4) {
33866
+ if (this.ended && this.pending.length === 0) return false;
33867
+ this.pending.push(text4);
33868
+ for (const w of this.waiters.splice(0)) w();
33869
+ return true;
33870
+ }
33871
+ /** 收口:吐完 pending 后生成器结束 */
33872
+ close() {
33873
+ this.ended = true;
33874
+ for (const w of this.waiters.splice(0)) w();
33875
+ }
33876
+ /** 还有没被 turn 消化的输入吗(未 shift 的 pending + 已 yield 未出 result 的) */
33877
+ expectsMoreTurns(turnsSeen) {
33878
+ return this.pending.length > 0 || this.yieldCount > turnsSeen;
33879
+ }
33880
+ /** 即将注入的下一条(1121:续 turn 卡片显示用——显示"接下来要处理的",不是刚答完的旧消息);无 pending 时 undefined */
33881
+ upcoming() {
33882
+ return this.pending[0];
33883
+ }
33884
+ async *stream(first) {
33885
+ this.yieldCount++;
33886
+ this.lastYield = first;
33887
+ yield ccUserMsg(first);
33888
+ while (true) {
33889
+ if (this.pending.length > 0) {
33890
+ const text4 = this.pending.shift();
33891
+ this.yieldCount++;
33892
+ this.lastYield = text4;
33893
+ yield ccUserMsg(text4);
33894
+ continue;
33895
+ }
33896
+ if (this.ended) return;
33897
+ await new Promise((resolve45) => this.waiters.push(resolve45));
33898
+ }
33899
+ }
33900
+ };
33901
+ defaultCcRuntimeLoader = (onProgress) => loadOptionalModule("cc-runtime", onProgress);
33902
+ ccRuntimeLoader = defaultCcRuntimeLoader;
33795
33903
  CcDriverSession = class {
33796
33904
  constructor(binding, cm, map, predecessor) {
33797
33905
  this.predecessor = predecessor;
@@ -33813,6 +33921,8 @@ var init_driver = __esm({
33813
33921
  revision = 0;
33814
33922
  idleWaiters = [];
33815
33923
  abort = null;
33924
+ /** 当前流式 chunk 的 steer 口(仅用户消息路径开;外部 ask/桌面路径为 null) */
33925
+ feeder = null;
33816
33926
  sessionId = null;
33817
33927
  sendChain = Promise.resolve();
33818
33928
  ui = null;
@@ -33837,11 +33947,16 @@ var init_driver = __esm({
33837
33947
  this.sessionId = null;
33838
33948
  return this.map.clear(this.key) || had;
33839
33949
  }
33840
- /** 入站一条消息:排队(busy 时 FIFO),队列满则提示。 */
33950
+ /** 入站一条消息:流式 chunk 开着 → steer 注入(1119);否则排队(busy 时 FIFO),队列满则提示。 */
33841
33951
  enqueue(text4) {
33842
33952
  const trimmed = text4.trim();
33843
33953
  if (!trimmed || this.closed) return;
33844
33954
  if (this.ui?.routeTyped(trimmed)) return;
33955
+ const feeder = this.feeder;
33956
+ if (feeder && feeder.push(trimmed)) {
33957
+ this.ui?.onSteer(trimmed);
33958
+ return;
33959
+ }
33845
33960
  if (this.queue.length >= MAX_QUEUE) {
33846
33961
  void this.sendText(`[cc-driver] \u961F\u5217\u5DF2\u6EE1\uFF08${MAX_QUEUE} \u6761\uFF09\uFF0C\u8FD9\u6761\u6CA1\u6392\u4E0A\u2014\u2014\u7B49\u5F53\u524D\u4EFB\u52A1\u5B8C\u4E8B\u518D\u53D1\u3002`);
33847
33962
  return;
@@ -33864,8 +33979,8 @@ var init_driver = __esm({
33864
33979
  job.reject?.(requestError("CC request cancelled before execution", 499));
33865
33980
  }
33866
33981
  };
33867
- const pending2 = new Promise((resolve40, reject) => {
33868
- job.resolve = resolve40;
33982
+ const pending2 = new Promise((resolve45, reject) => {
33983
+ job.resolve = resolve45;
33869
33984
  job.reject = reject;
33870
33985
  this.queue.push(job);
33871
33986
  signal?.addEventListener("abort", cancel, { once: true });
@@ -33878,9 +33993,22 @@ var init_driver = __esm({
33878
33993
  this.closed = true;
33879
33994
  this.revision++;
33880
33995
  for (const job of this.queue.splice(0)) job.reject?.(requestError("CC binding stopped before execution", 503));
33996
+ this.feeder?.close();
33881
33997
  this.stop();
33882
33998
  }
33883
- /** 中断当前 turn(队列里后续消息继续) */
33999
+ /**
34000
+ * 全停(1119 翀哥拍板):中断当前 turn + 清 FIFO(外部 ask 按取消拒)+ 关 steer 口。
34001
+ * abort 杀进程 → CLI 里已排队未消费的插话一并死——所见即所得的「全停」。
34002
+ */
34003
+ stopAll() {
34004
+ const hadQueued = this.queue.length > 0;
34005
+ for (const job of this.queue.splice(0)) job.reject?.(requestError("CC request cancelled (stop)", 499));
34006
+ this.feeder?.close();
34007
+ const active = this.busy;
34008
+ if (active) this.stop();
34009
+ return active || hadQueued;
34010
+ }
34011
+ /** 中断当前 turn(不清队列)——外部取消场景用;用户面全停走 stopAll() */
33884
34012
  stop() {
33885
34013
  this.abort?.abort();
33886
34014
  }
@@ -33888,7 +34016,7 @@ var init_driver = __esm({
33888
34016
  return this.draining;
33889
34017
  }
33890
34018
  whenIdle() {
33891
- return this.draining ? new Promise((resolve40) => this.idleWaiters.push(resolve40)) : Promise.resolve();
34019
+ return this.draining ? new Promise((resolve45) => this.idleWaiters.push(resolve45)) : Promise.resolve();
33892
34020
  }
33893
34021
  async drain() {
33894
34022
  if (this.draining) return;
@@ -33902,10 +34030,14 @@ var init_driver = __esm({
33902
34030
  if (job.expectedSessionId !== void 0 && job.expectedSessionId !== this.sessionId) {
33903
34031
  throw requestError("CC session changed while this request was queued");
33904
34032
  }
33905
- const prompt = job.source ? `[cc_ask from ${job.source.replace(/[\r\n]/g, " ").slice(0, 160)}]
33906
- ${job.prompt}` : job.prompt;
33907
- const result = await this.runTurn(prompt, job.signal, !!job.source);
33908
- job.resolve?.(result);
34033
+ if (job.source) {
34034
+ const prompt = `[cc_ask from ${job.source.replace(/[\r\n]/g, " ").slice(0, 160)}]
34035
+ ${job.prompt}`;
34036
+ const result = await this.runTurn(prompt, job.signal, true);
34037
+ job.resolve?.(result);
34038
+ } else {
34039
+ await this.runStreaming(job);
34040
+ }
33909
34041
  } catch (err) {
33910
34042
  job.reject?.(err);
33911
34043
  console.error(`[cc-driver] turn \u5931\u8D25 key=${this.key}: ${err?.stack || err}`);
@@ -33914,7 +34046,7 @@ ${job.prompt}` : job.prompt;
33914
34046
  }
33915
34047
  } finally {
33916
34048
  this.draining = false;
33917
- for (const resolve40 of this.idleWaiters.splice(0)) resolve40();
34049
+ for (const resolve45 of this.idleWaiters.splice(0)) resolve45();
33918
34050
  }
33919
34051
  }
33920
34052
  async runTurn(prompt, signal, external = false) {
@@ -33939,15 +34071,11 @@ ${job.prompt}` : job.prompt;
33939
34071
  this.ui = null;
33940
34072
  }
33941
34073
  }
33942
- let textSoFar = "";
33943
- let gotPartial = false;
33944
- let lastInterimAt = Date.now();
33945
- let interimCount = 0;
33946
- let lastSentLen = 0;
33947
34074
  let finalText = "";
33948
34075
  let isError = false;
33949
34076
  let gotResult = false;
33950
34077
  let usage = "";
34078
+ const acc = this.makeStreamAccumulator();
33951
34079
  try {
33952
34080
  const desktops = resumedFrom ? await findDesktopTargets(this.workDir, resumedFrom) : [];
33953
34081
  if (desktops.length > 1) throw new Error("Multiple desktop writers claim this CC session; close the duplicate");
@@ -33963,7 +34091,7 @@ ${job.prompt}` : job.prompt;
33963
34091
  throw new Error("This CC session is open in another process; use cc-desktop to receive messages there");
33964
34092
  }
33965
34093
  let ccRuntimeNoticeSent = false;
33966
- const { query } = await loadOptionalModule("cc-runtime", (label, got, total) => {
34094
+ const { query } = await ccRuntimeLoader((label, got, total) => {
33967
34095
  if (ccRuntimeNoticeSent) return;
33968
34096
  ccRuntimeNoticeSent = true;
33969
34097
  const mb = total ? `\u7EA6 ${Math.round(total / 1024 / 1024)}M` : "\u7EA6 350M";
@@ -34007,43 +34135,7 @@ ${job.prompt}` : job.prompt;
34007
34135
  if (process.env.CC_DRIVER_DEBUG) console.log(`[cc-driver:dbg] type=${msg2.type} subtype=${msg2.subtype ?? "-"} sid=${msg2.session_id?.slice(0, 8) ?? "-"}`);
34008
34136
  const parentToolUseId = msg2.parent_tool_use_id;
34009
34137
  if (parentToolUseId) continue;
34010
- if (msg2.type === "stream_event") {
34011
- const ev = msg2.event;
34012
- if (ev.type === "content_block_start" && ev.content_block?.type === "thinking") this.ui?.onThinkingDelta("");
34013
- else if (ev.type === "content_block_delta" && ev.delta?.type === "thinking_delta" && typeof ev.delta.thinking === "string") this.ui?.onThinkingDelta(ev.delta.thinking);
34014
- else if (ev.type === "content_block_stop" && this.ui) this.ui.onThinkingEnd();
34015
- if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && typeof ev.delta.text === "string") {
34016
- gotPartial = true;
34017
- textSoFar += ev.delta.text;
34018
- const now2 = Date.now();
34019
- const newChars = textSoFar.length - lastSentLen;
34020
- if (!this.ui && now2 - lastInterimAt >= INTERIM_MIN_INTERVAL_MS && newChars >= INTERIM_MIN_CHARS && interimCount < MAX_INTERIM_PER_TURN) {
34021
- lastInterimAt = now2;
34022
- lastSentLen = textSoFar.length;
34023
- interimCount++;
34024
- const snippet2 = textSoFar.slice(-INTERIM_SNIPPET_CHARS);
34025
- void this.sendText(`\u2026${snippet2}`);
34026
- }
34027
- }
34028
- } else if (msg2.type === "assistant") {
34029
- const content = msg2.message.content ?? [];
34030
- for (const block of content) {
34031
- if (block.type === "thinking" && block.thinking) this.ui?.onThinking(String(block.thinking));
34032
- else if (block.type === "tool_use" && block.id) this.ui?.onToolUse(String(block.name), block.input ?? {});
34033
- }
34034
- if (!gotPartial) {
34035
- for (const block of content) {
34036
- if (block.type === "text" && typeof block.text === "string") textSoFar += block.text;
34037
- }
34038
- }
34039
- } else if (msg2.type === "user") {
34040
- const content = msg2.message.content;
34041
- if (Array.isArray(content) && this.ui) {
34042
- for (const block of content) {
34043
- if (block.type === "tool_result") this.ui.onToolResult(resultToText(block.content), block.is_error === true);
34044
- }
34045
- }
34046
- } else if (msg2.type === "result") {
34138
+ if (msg2.type === "result") {
34047
34139
  const r = msg2;
34048
34140
  if (r.session_id) {
34049
34141
  turnSessionId = r.session_id;
@@ -34059,6 +34151,8 @@ ${job.prompt}` : job.prompt;
34059
34151
  turnSessionId = sid;
34060
34152
  if (this.revision === revision) this.sessionId = sid;
34061
34153
  }
34154
+ } else {
34155
+ await acc.handle(msg2);
34062
34156
  }
34063
34157
  }
34064
34158
  }
@@ -34067,22 +34161,22 @@ ${job.prompt}` : job.prompt;
34067
34161
  this.abort = null;
34068
34162
  signal?.removeEventListener("abort", cancel);
34069
34163
  }
34070
- const result = { sessionId: turnSessionId, text: finalText || textSoFar, isError: isError || ac.signal.aborted };
34164
+ const result = { sessionId: turnSessionId, text: finalText || acc.textSoFar, isError: isError || ac.signal.aborted };
34071
34165
  if (ac.signal.aborted) {
34072
34166
  if (this.ui && this.ui.alive) {
34073
34167
  await this.ui.turnEnd("", "", "aborted");
34074
- await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (textSoFar ? `
34168
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
34075
34169
  \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
34076
- ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
34170
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
34077
34171
  return { ...result, text: "[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" };
34078
34172
  }
34079
- await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (textSoFar ? `
34173
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
34080
34174
 
34081
34175
  \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
34082
- ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
34176
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
34083
34177
  return { ...result, text: "[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" };
34084
34178
  }
34085
- const answer = finalText || textSoFar;
34179
+ const answer = finalText || acc.textSoFar;
34086
34180
  if (this.ui && this.ui.alive) {
34087
34181
  await this.ui.turnEnd("", usage, isError ? "err" : "done");
34088
34182
  if (!answer.trim()) {
@@ -34101,6 +34195,215 @@ ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
34101
34195
  }
34102
34196
  return result;
34103
34197
  }
34198
+ /**
34199
+ * stream_event / assistant / user 三类消息的共用处理(runTurn 与 runStreaming 共享;
34200
+ * result / system 两个分支各自的循环里处理——流式 chunk 是多 result 语义)。
34201
+ * 返回 per-turn 累积态访问器(reset 在每个 result 后调)。
34202
+ */
34203
+ makeStreamAccumulator() {
34204
+ let textSoFar = "";
34205
+ let gotPartial = false;
34206
+ let lastInterimAt = Date.now();
34207
+ let interimCount = 0;
34208
+ let lastSentLen = 0;
34209
+ return {
34210
+ reset: () => {
34211
+ textSoFar = "";
34212
+ gotPartial = false;
34213
+ lastInterimAt = Date.now();
34214
+ interimCount = 0;
34215
+ lastSentLen = 0;
34216
+ },
34217
+ handle: async (msg2) => {
34218
+ if (msg2.type === "stream_event") {
34219
+ const ev = msg2.event;
34220
+ if (ev.type === "content_block_start" && ev.content_block?.type === "thinking") this.ui?.onThinkingDelta("");
34221
+ else if (ev.type === "content_block_delta" && ev.delta?.type === "thinking_delta" && typeof ev.delta.thinking === "string") this.ui?.onThinkingDelta(ev.delta.thinking);
34222
+ else if (ev.type === "content_block_stop" && this.ui) this.ui.onThinkingEnd();
34223
+ if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && typeof ev.delta.text === "string") {
34224
+ gotPartial = true;
34225
+ textSoFar += ev.delta.text;
34226
+ const now2 = Date.now();
34227
+ const newChars = textSoFar.length - lastSentLen;
34228
+ if (!this.ui && now2 - lastInterimAt >= INTERIM_MIN_INTERVAL_MS && newChars >= INTERIM_MIN_CHARS && interimCount < MAX_INTERIM_PER_TURN) {
34229
+ lastInterimAt = now2;
34230
+ lastSentLen = textSoFar.length;
34231
+ interimCount++;
34232
+ const snippet2 = textSoFar.slice(-INTERIM_SNIPPET_CHARS);
34233
+ void this.sendText(`\u2026${snippet2}`);
34234
+ }
34235
+ }
34236
+ } else if (msg2.type === "assistant") {
34237
+ const content = msg2.message.content ?? [];
34238
+ for (const block of content) {
34239
+ if (block.type === "thinking" && block.thinking) this.ui?.onThinking(String(block.thinking));
34240
+ else if (block.type === "tool_use" && block.id) this.ui?.onToolUse(String(block.name), block.input ?? {});
34241
+ }
34242
+ if (!gotPartial) {
34243
+ for (const block of content) {
34244
+ if (block.type === "text" && typeof block.text === "string") textSoFar += block.text;
34245
+ }
34246
+ }
34247
+ } else if (msg2.type === "user") {
34248
+ const content = msg2.message.content;
34249
+ if (Array.isArray(content) && this.ui) {
34250
+ for (const block of content) {
34251
+ if (block.type === "tool_result") this.ui.onToolResult(resultToText(block.content), block.is_error === true);
34252
+ }
34253
+ }
34254
+ }
34255
+ },
34256
+ get textSoFar() {
34257
+ return textSoFar;
34258
+ }
34259
+ };
34260
+ }
34261
+ /**
34262
+ * 用户消息的流式 chunk(1119 cc-desk steer):一次 query() 的 prompt 是 feeder 生成器,
34263
+ * busy 时 enqueue → feeder.push 注入(模型下一次 API 调用看到),同一进程可出多个
34264
+ * result(每 result 交付一轮答案);全部消化完 → close → 进程退出,空闲零进程不变。
34265
+ * 桌面托管 / 他进程占用 → 退回 runTurn 封闭路径(桌面桥无 steer)。
34266
+ */
34267
+ async runStreaming(job) {
34268
+ const resumedFrom = this.sessionId;
34269
+ const desktops = resumedFrom ? await findDesktopTargets(this.workDir, resumedFrom) : [];
34270
+ if (desktops.length > 0 || resumedFrom && nativeSessionOwners(resumedFrom).length) {
34271
+ await this.runTurn(job.prompt, job.signal, false);
34272
+ return;
34273
+ }
34274
+ const ac = new AbortController();
34275
+ this.abort = ac;
34276
+ const revision = this.revision;
34277
+ let turnSessionId = resumedFrom;
34278
+ const cancel = () => ac.abort();
34279
+ job.signal?.addEventListener("abort", cancel, { once: true });
34280
+ if (job.signal?.aborted) ac.abort();
34281
+ console.log(`[cc-driver] streaming turn start key=${this.key} resume=${resumedFrom ? resumedFrom.slice(0, 8) : "new"} cwd=${this.workDir}`);
34282
+ if (this.binding.channel === "feishu" && !this.uiTried) {
34283
+ this.uiTried = true;
34284
+ this.ui = await makeFeishuCardUi(this.cm, this.binding);
34285
+ }
34286
+ if (this.ui) {
34287
+ try {
34288
+ await this.ui.turnStart(job.prompt);
34289
+ this.ui.setStopAction({ cc: 1, kind: "stop", key: this.key });
34290
+ } catch (err) {
34291
+ console.warn(`[cc-driver:card] \u5F00\u5361\u5931\u8D25\uFF0C\u672C binding \u56DE\u9000\u7EAF\u6587\u672C\uFF1A${err?.message ?? err}`);
34292
+ this.ui = null;
34293
+ }
34294
+ }
34295
+ const feeder = new SteerFeeder();
34296
+ this.feeder = feeder;
34297
+ const acc = this.makeStreamAccumulator();
34298
+ let turnsSeen = 0;
34299
+ let deliveredAfterAbort = false;
34300
+ try {
34301
+ const { query } = await ccRuntimeLoader();
34302
+ const stream = query({
34303
+ prompt: feeder.stream(job.prompt),
34304
+ options: {
34305
+ abortController: ac,
34306
+ cwd: this.workDir,
34307
+ ...this.binding.permissionMode && this.binding.permissionMode !== "auto" ? { permissionMode: this.binding.permissionMode } : {},
34308
+ model: this.binding.model,
34309
+ resume: resumedFrom ?? void 0,
34310
+ includePartialMessages: true,
34311
+ ...this.ui ? {
34312
+ canUseTool: async (toolName, input, opts) => {
34313
+ if (!this.ui) return { behavior: "deny", message: "\u5361\u7247\u901A\u9053\u5DF2\u65AD\u5F00\uFF0C\u64CD\u4F5C\u88AB\u62D2\u7EDD\u3002" };
34314
+ if (toolName === "AskUserQuestion") {
34315
+ const questions = normalizeQuestions(input.questions);
34316
+ if (questions.length === 0) return { behavior: "deny", message: "\u95EE\u9898\u683C\u5F0F\u65E0\u6CD5\u6E32\u67D3\uFF0C\u8BF7\u76F4\u63A5\u8BF4\u660E\u65B9\u6848\u7EE7\u7EED\u3002" };
34317
+ const r2 = await this.ui.askUser(questions, opts.signal);
34318
+ if (r2.answers) return { behavior: "allow", updatedInput: { ...input, answers: r2.answers } };
34319
+ return { behavior: "deny", message: r2.message ?? "\u7528\u6237\u6CA1\u6709\u56DE\u7B54\u8FD9\u4E9B\u95EE\u9898\uFF08\u98DE\u4E66\u5361\u7247\u672A\u7B54/\u8D85\u65F6\uFF09\uFF0C\u8BF7\u76F4\u63A5\u8BF4\u660E\u4F60\u7684\u65B9\u6848\u7EE7\u7EED\u3002" };
34320
+ }
34321
+ const r = await this.ui.askPermission(toolName, input, opts.signal, opts.suggestions);
34322
+ if (r.verdict === "deny") return { behavior: "deny", message: r.message ?? "\u7528\u6237\u5728\u98DE\u4E66\u5361\u7247\u4E0A\u62D2\u7EDD\u4E86\u8FD9\u6B21\u64CD\u4F5C\u3002" };
34323
+ return {
34324
+ behavior: "allow",
34325
+ updatedInput: input,
34326
+ ...r.verdict === "always" && Array.isArray(opts.suggestions) && opts.suggestions.length > 0 ? { updatedPermissions: opts.suggestions } : {}
34327
+ };
34328
+ }
34329
+ } : {}
34330
+ }
34331
+ });
34332
+ try {
34333
+ for await (const msg2 of stream) {
34334
+ if (process.env.CC_DRIVER_DEBUG) console.log(`[cc-driver:dbg] type=${msg2.type} subtype=${msg2.subtype ?? "-"} sid=${msg2.session_id?.slice(0, 8) ?? "-"}`);
34335
+ const parentToolUseId = msg2.parent_tool_use_id;
34336
+ if (parentToolUseId) continue;
34337
+ if (msg2.type === "result") {
34338
+ const r = msg2;
34339
+ turnsSeen++;
34340
+ if (r.session_id) {
34341
+ turnSessionId = r.session_id;
34342
+ if (this.revision === revision) this.sessionId = r.session_id;
34343
+ }
34344
+ const isError = r.is_error === true;
34345
+ const finalText = typeof r.result === "string" ? r.result : "";
34346
+ const usage = r.usage ? `\u2193 ${fmtTok(r.usage.input_tokens)} \xB7 \u2191 ${fmtTok(r.usage.output_tokens)}` : "";
34347
+ if (turnSessionId && this.revision === revision) this.map.switchTo(this.key, turnSessionId, this.workDir);
34348
+ const more = feeder.expectsMoreTurns(turnsSeen);
34349
+ const answer = finalText || acc.textSoFar;
34350
+ if (ac.signal.aborted) deliveredAfterAbort = true;
34351
+ if (this.ui && this.ui.alive) {
34352
+ await this.ui.turnEnd("", usage, isError ? "err" : "done");
34353
+ }
34354
+ if (!answer.trim()) {
34355
+ await this.sendText(isError ? "[cc-driver] \u4EFB\u52A1\u51FA\u9519\u4E14\u6CA1\u6709\u4EA7\u51FA\u6587\u672C" : "[cc-driver] \u4EFB\u52A1\u7ED3\u675F\uFF08\u65E0\u6587\u672C\u4EA7\u51FA\uFF09");
34356
+ } else {
34357
+ for (const chunk of chunkText(answer, FINAL_CHUNK_CHARS)) await this.sendText(chunk);
34358
+ }
34359
+ acc.reset();
34360
+ if (ac.signal.aborted) break;
34361
+ if (!more) {
34362
+ feeder.close();
34363
+ break;
34364
+ }
34365
+ if (this.ui) {
34366
+ try {
34367
+ await this.ui.turnStart(`\u21AA ${feeder.upcoming() ?? feeder.lastYield}`);
34368
+ this.ui.setStopAction({ cc: 1, kind: "stop", key: this.key });
34369
+ } catch (err) {
34370
+ console.warn(`[cc-driver:card] \u7EED turn \u5F00\u5361\u5931\u8D25\uFF0C\u56DE\u9000\u7EAF\u6587\u672C\uFF1A${err?.message ?? err}`);
34371
+ this.ui = null;
34372
+ }
34373
+ }
34374
+ } else if (msg2.type === "system" && msg2.subtype === "init") {
34375
+ const sid = msg2.session_id;
34376
+ if (sid) {
34377
+ turnSessionId = sid;
34378
+ if (this.revision === revision) this.sessionId = sid;
34379
+ }
34380
+ } else {
34381
+ await acc.handle(msg2);
34382
+ }
34383
+ }
34384
+ } catch (err) {
34385
+ if (!(ac.signal.aborted || !feeder.expectsMoreTurns(turnsSeen))) throw err;
34386
+ }
34387
+ } finally {
34388
+ feeder.close();
34389
+ this.feeder = null;
34390
+ this.abort = null;
34391
+ job.signal?.removeEventListener("abort", cancel);
34392
+ }
34393
+ if (ac.signal.aborted && !deliveredAfterAbort) {
34394
+ if (this.ui && this.ui.alive) {
34395
+ await this.ui.turnEnd("", "", "aborted");
34396
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
34397
+ \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
34398
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
34399
+ } else {
34400
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
34401
+
34402
+ \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
34403
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
34404
+ }
34405
+ }
34406
+ }
34104
34407
  /** 串行发送器:wechat 3s 节流在适配器层,这里保证不并发、失败不炸链 */
34105
34408
  sendText(text4) {
34106
34409
  const task = this.sendChain.then(async () => {
@@ -34148,6 +34451,12 @@ ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
34148
34451
  forChat(channel, chatId) {
34149
34452
  return this.sessions.get(`${channel}:${chatId}`);
34150
34453
  }
34454
+ /** 按 bindingKey(channel:chatId)找 session——卡片停止钮回调用(1119) */
34455
+ forChatKey(key4) {
34456
+ const idx = key4.indexOf(":");
34457
+ if (idx <= 0) return void 0;
34458
+ return this.sessions.get(key4);
34459
+ }
34151
34460
  /** 全部绑定的工作目录(去重;cc-progress 工具省参推断用) */
34152
34461
  get bindingWorkDirs() {
34153
34462
  return [...new Set([...this.sessions.values()].map((s) => s.workDir))];
@@ -35360,7 +35669,7 @@ ${filenames.join("\n")}${truncatedNote}`
35360
35669
  import { execFile as execFile2 } from "node:child_process";
35361
35670
  import * as path36 from "node:path";
35362
35671
  function ripGrep(args, searchPath, signal) {
35363
- return new Promise((resolve40) => {
35672
+ return new Promise((resolve45) => {
35364
35673
  const fullArgs = [...args, searchPath];
35365
35674
  const child = execFile2("rg", fullArgs, {
35366
35675
  maxBuffer: 50 * 1024 * 1024,
@@ -35371,15 +35680,15 @@ function ripGrep(args, searchPath, signal) {
35371
35680
  // 1011:GUI 宿主(Electron 装机版)下 rg 别闪黑窗
35372
35681
  }, (error, stdout, stderr) => {
35373
35682
  if (error && error.code === "ENOENT") {
35374
- resolve40({ lines: [], exitCode: -1, timedOut: false, rgMissing: true });
35683
+ resolve45({ lines: [], exitCode: -1, timedOut: false, rgMissing: true });
35375
35684
  return;
35376
35685
  }
35377
35686
  if (error && error.killed) {
35378
- resolve40({ lines: [], exitCode: -1, timedOut: true });
35687
+ resolve45({ lines: [], exitCode: -1, timedOut: true });
35379
35688
  return;
35380
35689
  }
35381
35690
  const lines = stdout ? stdout.split("\n").filter(Boolean) : [];
35382
- resolve40({ lines, exitCode: error ? error.code || 1 : 0, timedOut: false });
35691
+ resolve45({ lines, exitCode: error ? error.code || 1 : 0, timedOut: false });
35383
35692
  });
35384
35693
  });
35385
35694
  }
@@ -36371,16 +36680,16 @@ async function writeTeamFileAsync(teamName, teamFile) {
36371
36680
  }
36372
36681
  async function withTeamFileLock(teamName, fn) {
36373
36682
  const prev = teamFileMutex.get(teamName) || Promise.resolve();
36374
- let resolve40;
36683
+ let resolve45;
36375
36684
  const next = new Promise((r) => {
36376
- resolve40 = r;
36685
+ resolve45 = r;
36377
36686
  });
36378
36687
  teamFileMutex.set(teamName, next);
36379
36688
  await prev;
36380
36689
  try {
36381
36690
  return await fn();
36382
36691
  } finally {
36383
- resolve40();
36692
+ resolve45();
36384
36693
  if (teamFileMutex.get(teamName) === next) teamFileMutex.delete(teamName);
36385
36694
  }
36386
36695
  }
@@ -36619,7 +36928,7 @@ async function ensureInboxDir(teamName) {
36619
36928
  await mkdir3(inboxDir, { recursive: true });
36620
36929
  }
36621
36930
  async function sleep4(ms) {
36622
- return new Promise((resolve40) => setTimeout(resolve40, ms));
36931
+ return new Promise((resolve45) => setTimeout(resolve45, ms));
36623
36932
  }
36624
36933
  function parseLockContent(raw) {
36625
36934
  const [pidStr, tsStr] = raw.split("-");
@@ -38757,7 +39066,7 @@ function buildPersonCards(store, scope, context2, cutoff) {
38757
39066
  const owner = store.entities.ownerPerson(scope, cutoff);
38758
39067
  const ambiguous = new Set(context2.ambiguity.flatMap((group) => group.entityIds));
38759
39068
  const facts = [...context2.currentFacts, ...context2.futureChanges, ...context2.hypotheses, ...context2.historicalFacts];
38760
- const resolve40 = (id2) => store.entities.resolve(scope, id2, context2.snapshot.entityRevision, cutoff);
39069
+ const resolve45 = (id2) => store.entities.resolve(scope, id2, context2.snapshot.entityRevision, cutoff);
38761
39070
  const inverse = { father: "child", mother: "child", child: "parent", sibling: "sibling", spouse: "spouse", ex_spouse: "ex_spouse" };
38762
39071
  return context2.people.filter((person) => !ambiguous.has(person.entityId) && person.canonicalName !== "[deleted memory]").map((person) => {
38763
39072
  const details = store.entities.details(scope, person.entityId, cutoff);
@@ -38768,7 +39077,7 @@ function buildPersonCards(store, scope, context2, cutoff) {
38768
39077
  const objectId = fact.resolvedObjectId ?? fact.value.entityId;
38769
39078
  if (subjectId !== person.entityId && objectId !== person.entityId) continue;
38770
39079
  const direction = subjectId === person.entityId ? "outgoing" : "incoming";
38771
- const other = resolve40(direction === "outgoing" ? objectId : subjectId);
39080
+ const other = resolve45(direction === "outgoing" ? objectId : subjectId);
38772
39081
  if (!other || other.canonicalName === "[deleted memory]" || other.entityId === person.entityId) continue;
38773
39082
  const open7 = fact.predicate === "relation.open" ? fact.value : void 0;
38774
39083
  const role = open7 ? open7.label : fact.predicate === "relation.colleague" ? fact.contextKey : direction === "outgoing" ? fact.contextKey : inverse[fact.contextKey];
@@ -38877,13 +39186,13 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
38877
39186
  const resolved = /* @__PURE__ */ new Map();
38878
39187
  const redirects = store.entities.redirectedIds(scope, snapshot.entityRevision);
38879
39188
  for (const entity of entities) if (!redirects.has(entity.entityId)) resolved.set(entity.entityId, entity);
38880
- const resolve40 = (id2) => {
39189
+ const resolve45 = (id2) => {
38881
39190
  checkMemoryReadBudget();
38882
39191
  if (!resolved.has(id2)) resolved.set(id2, store.entities.resolve(scope, id2, snapshot.entityRevision, cutoff ?? void 0));
38883
39192
  return resolved.get(id2);
38884
39193
  };
38885
- const resolvedSelection = new Set((request.entityRef || matching.length ? matching : entities).map((entity) => resolve40(entity.entityId)?.entityId));
38886
- const selected = new Set(entities.filter((entity) => resolvedSelection.has(resolve40(entity.entityId)?.entityId)).map((entity) => entity.entityId));
39194
+ const resolvedSelection = new Set((request.entityRef || matching.length ? matching : entities).map((entity) => resolve45(entity.entityId)?.entityId));
39195
+ const selected = new Set(entities.filter((entity) => resolvedSelection.has(resolve45(entity.entityId)?.entityId)).map((entity) => entity.entityId));
38887
39196
  const context2 = {
38888
39197
  validAt,
38889
39198
  ...cutoff ? { knowledgeCoverage: cutoff.complete ? "complete" : "partial" } : {},
@@ -38898,7 +39207,7 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
38898
39207
  } },
38899
39208
  futureChanges: [],
38900
39209
  people: [...new Map(matching.filter((entity) => entity.kind === "person").flatMap((entity) => {
38901
- const target = resolve40(entity.entityId);
39210
+ const target = resolve45(entity.entityId);
38902
39211
  return target ? [[target.entityId, target]] : [];
38903
39212
  })).values()],
38904
39213
  hypotheses: [],
@@ -38911,7 +39220,7 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
38911
39220
  freshness: snapshot.interpretedSeq < snapshot.sourceSeq || receipt?.state === "received" ? "pending" : "current",
38912
39221
  knownRevision
38913
39222
  };
38914
- if (!request.entityRef) context2.ambiguity = store.entities.queryAmbiguities(scope, request.query, cutoff).map((group) => ({ ...group, entityIds: [...new Set(group.entityIds.map((id2) => resolve40(id2)?.entityId).filter((id2) => Boolean(id2)))] })).filter((group) => group.entityIds.length > 1);
39223
+ if (!request.entityRef) context2.ambiguity = store.entities.queryAmbiguities(scope, request.query, cutoff).map((group) => ({ ...group, entityIds: [...new Set(group.entityIds.map((id2) => resolve45(id2)?.entityId).filter((id2) => Boolean(id2)))] })).filter((group) => group.entityIds.length > 1);
38915
39224
  const citationKeys = /* @__PURE__ */ new Set();
38916
39225
  let used = 0;
38917
39226
  for (const slot of store.facts.snapshot(scope, knownRevision, [...selected], true)) {
@@ -38922,7 +39231,7 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
38922
39231
  slotRevision: slot.revision
38923
39232
  };
38924
39233
  context2.knownRevision = read2.factRevision;
38925
- if (read2.hasConflict) context2.conflicts.push({ subjectId: resolve40(slot.subjectId)?.entityId ?? slot.subjectId, predicate: slot.predicate, contextKey: slot.contextKey });
39234
+ if (read2.hasConflict) context2.conflicts.push({ subjectId: resolve45(slot.subjectId)?.entityId ?? slot.subjectId, predicate: slot.predicate, contextKey: slot.contextKey });
38926
39235
  const future = slot.assertions.filter((fact) => fact.state === "supported" && fact.validFrom !== null && fact.validFrom > validAt && fact.systemFromRevision <= knownRevision);
38927
39236
  for (const fact of [...read2.facts, ...read2.hypotheses, ...future]) {
38928
39237
  if (!selected.has(slot.subjectId) && !selected.has(fact.value?.entityId ?? "")) continue;
@@ -38931,8 +39240,8 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
38931
39240
  if (fact.evidence.some((evidence) => !store.sources.exists(scope, evidence.sourceId, cutoff))) continue;
38932
39241
  const objectId = fact.value?.entityId;
38933
39242
  if (objectId && (!store.entities.get(scope, objectId, cutoff) || store.entities.get(scope, objectId, cutoff)?.canonicalName === "[deleted memory]")) continue;
38934
- const resolvedSubject = resolve40(slot.subjectId);
38935
- const resolvedObject = objectId ? resolve40(objectId) : void 0;
39243
+ const resolvedSubject = resolve45(slot.subjectId);
39244
+ const resolvedObject = objectId ? resolve45(objectId) : void 0;
38936
39245
  const item = {
38937
39246
  ...fact,
38938
39247
  validationState: "hypothesis",
@@ -39016,8 +39325,8 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
39016
39325
  if (!subject || subject.canonicalName === "[deleted memory]" || sources.some((source) => !source)) continue;
39017
39326
  const objectId = fact.value?.entityId;
39018
39327
  if (objectId && (!store.entities.get(scope, objectId, cutoff) || store.entities.get(scope, objectId, cutoff)?.canonicalName === "[deleted memory]")) continue;
39019
- const resolvedSubject = resolve40(slot.subjectId);
39020
- const resolvedObject = objectId ? resolve40(objectId) : void 0;
39328
+ const resolvedSubject = resolve45(slot.subjectId);
39329
+ const resolvedObject = objectId ? resolve45(objectId) : void 0;
39021
39330
  const item = {
39022
39331
  ...fact,
39023
39332
  validationState: "historical",
@@ -39750,7 +40059,7 @@ async function deliverMemoryChanges(store, consumer, options = {}) {
39750
40059
  publishReadyCells(store);
39751
40060
  if (!consumer.available()) return 0;
39752
40061
  return store.changes.deliver("proactive", async (event2) => {
39753
- await new Promise((resolve40) => setImmediate(resolve40));
40062
+ await new Promise((resolve45) => setImmediate(resolve45));
39754
40063
  return consumer.receive(loadProjectionInput(store, event2));
39755
40064
  }, {
39756
40065
  limit: options.limit,
@@ -41493,15 +41802,15 @@ function blockTask(stateDir, listId, fromTaskId, toTaskId) {
41493
41802
  }
41494
41803
  function withTaskLock(listId, fn) {
41495
41804
  const prev = taskMutex.get(listId) || Promise.resolve();
41496
- let resolve40;
41805
+ let resolve45;
41497
41806
  const next = new Promise((r) => {
41498
- resolve40 = r;
41807
+ resolve45 = r;
41499
41808
  });
41500
41809
  taskMutex.set(listId, next);
41501
41810
  try {
41502
41811
  return fn();
41503
41812
  } finally {
41504
- resolve40();
41813
+ resolve45();
41505
41814
  if (taskMutex.get(listId) === next) taskMutex.delete(listId);
41506
41815
  }
41507
41816
  }
@@ -42503,9 +42812,9 @@ print('EOS')
42503
42812
  } catch {
42504
42813
  }
42505
42814
  });
42506
- const exitCode = await new Promise((resolve40) => {
42507
- child.on("close", (c) => resolve40(c));
42508
- child.on("error", () => resolve40(-1));
42815
+ const exitCode = await new Promise((resolve45) => {
42816
+ child.on("close", (c) => resolve45(c));
42817
+ child.on("error", () => resolve45(-1));
42509
42818
  });
42510
42819
  if (exitCode !== 0 || !eos || pcmAll.length === 0) {
42511
42820
  throw new Error(`CosyVoice produced empty output | python stderr: ${pyErr.slice(-500)}`);
@@ -43069,9 +43378,9 @@ async function sendVoiceToMulticaIssue(text4, issueId, opts) {
43069
43378
  }
43070
43379
  const content = opts.caption || `\u{1F399}\uFE0F \u8BED\u97F3\u6D88\u606F\uFF08${text4.length} \u5B57\uFF09`;
43071
43380
  try {
43072
- const { execFile: execFile6 } = await import("node:child_process");
43073
- const { promisify: promisify7 } = await import("node:util");
43074
- const execFileA = promisify7(execFile6);
43381
+ const { execFile: execFile7 } = await import("node:child_process");
43382
+ const { promisify: promisify8 } = await import("node:util");
43383
+ const execFileA = promisify8(execFile7);
43075
43384
  const { stdout } = await execFileA("multica", [
43076
43385
  "issue",
43077
43386
  "comment",
@@ -44865,7 +45174,7 @@ var init_service = __esm({
44865
45174
  lines.push(`start: spawned PID ${pid} (background${svcArgs ? ", args=" + svcArgs : ""})`);
44866
45175
  if (svc.healthCheck) {
44867
45176
  for (let i = 0; i < 12; i++) {
44868
- await new Promise((resolve40) => setTimeout(resolve40, 5e3));
45177
+ await new Promise((resolve45) => setTimeout(resolve45, 5e3));
44869
45178
  const after2 = await checkStatus();
44870
45179
  if (after2.running) {
44871
45180
  lines.push(`health: \u2705 running (after ${(i + 1) * 5}s)`);
@@ -44875,7 +45184,7 @@ var init_service = __esm({
44875
45184
  const after = await checkStatus();
44876
45185
  lines.push(`health: \u274C not responding after 60s \u2014 ${after.detail}`);
44877
45186
  } else {
44878
- await new Promise((resolve40) => setTimeout(resolve40, 3e3));
45187
+ await new Promise((resolve45) => setTimeout(resolve45, 3e3));
44879
45188
  lines.push(`start: PID ${pid} spawned (no healthCheck, waited 3s)`);
44880
45189
  }
44881
45190
  } else {
@@ -44900,7 +45209,7 @@ var init_service = __esm({
44900
45209
  const before = await checkStatus();
44901
45210
  if (before.running) {
44902
45211
  results.push(await doStop());
44903
- await new Promise((resolve40) => setTimeout(resolve40, 2e3));
45212
+ await new Promise((resolve45) => setTimeout(resolve45, 2e3));
44904
45213
  } else {
44905
45214
  results.push("stop: already stopped");
44906
45215
  }
@@ -46656,7 +46965,7 @@ var init_TeamDeleteTool = __esm({
46656
46965
 
46657
46966
  // src/tools/task-output.ts
46658
46967
  async function sleep5(ms) {
46659
- return new Promise((resolve40) => setTimeout(resolve40, ms));
46968
+ return new Promise((resolve45) => setTimeout(resolve45, ms));
46660
46969
  }
46661
46970
  async function waitForTaskCompletion(taskId, timeoutMs, signal, yieldSignal) {
46662
46971
  const startTime = Date.now();
@@ -47033,12 +47342,12 @@ var init_wx_query = __esm({
47033
47342
  handler: async (args, _context) => {
47034
47343
  const { findShell: findShell2 } = await Promise.resolve().then(() => (init_BashTool(), BashTool_exports));
47035
47344
  const shell = findShell2();
47036
- const { spawn: spawn5 } = await import("node:child_process");
47345
+ const { spawn: spawn8 } = await import("node:child_process");
47037
47346
  const cmd = args.command.trim();
47038
47347
  const timeout = args.timeout || 12e4;
47039
47348
  const fullCmd = `${PYTHON} "${SCRIPT}" ${cmd.replace(/^python3\s+.*wx_query\.py\s*/, "")}`;
47040
- return new Promise((resolve40) => {
47041
- const child = spawn5(shell.shell, [...shell.args, fullCmd], {
47349
+ return new Promise((resolve45) => {
47350
+ const child = spawn8(shell.shell, [...shell.args, fullCmd], {
47042
47351
  timeout,
47043
47352
  env: { ...process.env },
47044
47353
  windowsHide: true
@@ -47054,16 +47363,16 @@ var init_wx_query = __esm({
47054
47363
  });
47055
47364
  child.on("close", (code) => {
47056
47365
  if (code === 0) {
47057
- resolve40({ content: stdout });
47366
+ resolve45({ content: stdout });
47058
47367
  } else {
47059
- resolve40({
47368
+ resolve45({
47060
47369
  content: stderr || stdout || "(no output)",
47061
47370
  isError: true
47062
47371
  });
47063
47372
  }
47064
47373
  });
47065
47374
  child.on("error", (err) => {
47066
- resolve40({
47375
+ resolve45({
47067
47376
  content: `wx_query error: ${err.message}`,
47068
47377
  isError: true
47069
47378
  });
@@ -47132,7 +47441,7 @@ async function restoreSteerInputs(sessions, sessionId, stateDir, route, activeQu
47132
47441
  return;
47133
47442
  }
47134
47443
  if (!pending2.length) return;
47135
- await materializeImageMessages(pending2.map(buildSteerMessage), imageAssets);
47444
+ await materializeImageMessages(pending2.map(buildSteerMessage), imageAssets, void 0, void 0, { strict: true });
47136
47445
  const history = await sessions.inspectHistory(sessionId);
47137
47446
  const seen = new Set(history.flatMap((m) => "steerInput" in m && m.steerInput ? [m.steerInput.id] : []));
47138
47447
  const writer = sessions.getWriter(sessionId);
@@ -47298,15 +47607,15 @@ var init_owner_rpc = __esm({
47298
47607
  readyWaiters = [];
47299
47608
  awaitReady(timeoutMs) {
47300
47609
  if (this.ready || !this.child) return Promise.resolve();
47301
- return new Promise((resolve40) => {
47610
+ return new Promise((resolve45) => {
47302
47611
  const timer = setTimeout(() => {
47303
47612
  this.readyWaiters = this.readyWaiters.filter((wake) => wake !== wake0);
47304
- resolve40();
47613
+ resolve45();
47305
47614
  }, timeoutMs);
47306
47615
  timer.unref?.();
47307
47616
  const wake0 = () => {
47308
47617
  clearTimeout(timer);
47309
- resolve40();
47618
+ resolve45();
47310
47619
  };
47311
47620
  this.readyWaiters.push(wake0);
47312
47621
  });
@@ -47318,13 +47627,13 @@ var init_owner_rpc = __esm({
47318
47627
  if (!this.available() || !child?.send) throw new Mem7OwnerUnavailableError(this.child ? `owner not ready after ${timeoutMs}ms` : "no live owner child");
47319
47628
  const remaining = Math.max(1, deadline - Date.now());
47320
47629
  const id2 = ++this.seq;
47321
- return new Promise((resolve40, reject) => {
47630
+ return new Promise((resolve45, reject) => {
47322
47631
  const timer = setTimeout(() => {
47323
47632
  this.pending.delete(id2);
47324
47633
  reject(new Mem7OwnerUnavailableError(`timeout after ${remaining}ms (type=${message.type}, request=${id2}, child=${child.pid ?? "unknown"}, pending=${this.pending.size})`));
47325
47634
  }, remaining);
47326
47635
  timer.unref?.();
47327
- this.pending.set(id2, { resolve: (response) => response.ok ? resolve40(response.result) : reject(new Mem7OwnerUnavailableError(response.error)), timer });
47636
+ this.pending.set(id2, { resolve: (response) => response.ok ? resolve45(response.result) : reject(new Mem7OwnerUnavailableError(response.error)), timer });
47328
47637
  try {
47329
47638
  child.send({ ...message, id: id2 }, (error) => {
47330
47639
  if (error) {
@@ -47577,8 +47886,8 @@ function cosineSim(a, b) {
47577
47886
  return dot / (Math.sqrt(normA) * Math.sqrt(normB));
47578
47887
  }
47579
47888
  function readDbEmbeddings(dbPath) {
47580
- const { DatabaseSync: DatabaseSync18 } = require4("node:sqlite");
47581
- const db2 = new DatabaseSync18(dbPath, { readOnly: true });
47889
+ const { DatabaseSync: DatabaseSync19 } = require4("node:sqlite");
47890
+ const db2 = new DatabaseSync19(dbPath, { readOnly: true });
47582
47891
  try {
47583
47892
  const stmt = db2.prepare(`
47584
47893
  SELECT file_path, name, description, mtime, embedding
@@ -50234,7 +50543,7 @@ var init_cross_encoder = __esm({
50234
50543
  this.active++;
50235
50544
  return;
50236
50545
  }
50237
- await new Promise((resolve40) => this.queue.push(resolve40));
50546
+ await new Promise((resolve45) => this.queue.push(resolve45));
50238
50547
  }
50239
50548
  release() {
50240
50549
  const next = this.queue.shift();
@@ -52079,10 +52388,22 @@ var init_import_backups = __esm({
52079
52388
 
52080
52389
  // src/memory/topics-history/import-mem7.ts
52081
52390
  import { DatabaseSync as DatabaseSync16 } from "node:sqlite";
52082
- import { existsSync as existsSync44, writeFileSync as writeFileSync34 } from "node:fs";
52391
+ import { existsSync as existsSync44, renameSync as renameSync19, writeFileSync as writeFileSync34 } from "node:fs";
52083
52392
  import { join as join74 } from "node:path";
52084
52393
  function topicsImported(binding) {
52085
- return !!binding.stateDir && existsSync44(join74(topicsHistoryRoot(binding), "topics-import.json"));
52394
+ if (!binding.stateDir) return false;
52395
+ const marker = join74(topicsHistoryRoot(binding), "topics-import.json");
52396
+ if (!existsSync44(marker)) return false;
52397
+ try {
52398
+ const done2 = readJson(marker);
52399
+ if ((done2.report?.total ?? 0) > 0) return true;
52400
+ const retired = join74(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
52401
+ renameSync19(marker, retired);
52402
+ console.warn(`[topics-import] total=0 \u5B8C\u6210\u6E05\u5355\u4F5C\u5E9F\uFF08\u6E05\u6D17\u9000\u5316\u5047\u5B8C\u6210\uFF0C\u95F8\u95E8\u91CD\u5F00\uFF09\u2192 ${retired}`);
52403
+ } catch {
52404
+ return false;
52405
+ }
52406
+ return false;
52086
52407
  }
52087
52408
  var init_import_mem7 = __esm({
52088
52409
  "src/memory/topics-history/import-mem7.ts"() {
@@ -52455,8 +52776,8 @@ async function findRelevantMemoriesMem7(query, alreadySurfaced = /* @__PURE__ */
52455
52776
  if (!active || signal.aborted) throw new MemoryReadSupersededError();
52456
52777
  };
52457
52778
  let onAbort;
52458
- const cancelled = new Promise((resolve40) => {
52459
- onAbort = () => resolve40([]);
52779
+ const cancelled = new Promise((resolve45) => {
52780
+ onAbort = () => resolve45([]);
52460
52781
  signal.addEventListener("abort", onAbort, { once: true });
52461
52782
  if (signal.aborted) onAbort();
52462
52783
  });
@@ -56942,13 +57263,13 @@ function installStdoutGuard() {
56942
57263
  console.debug = toStderr;
56943
57264
  }
56944
57265
  function startStdinHandler() {
56945
- return new Promise((resolve40) => {
57266
+ return new Promise((resolve45) => {
56946
57267
  const userTexts = [];
56947
57268
  let resolved = false;
56948
57269
  const settle = () => {
56949
57270
  if (!resolved) {
56950
57271
  resolved = true;
56951
- resolve40(userTexts.join("\n"));
57272
+ resolve45(userTexts.join("\n"));
56952
57273
  }
56953
57274
  };
56954
57275
  const rl = readline2.createInterface({ input: process.stdin, terminal: false });
@@ -57689,16 +58010,16 @@ function channelHasCredentials(name, conf) {
57689
58010
  return true;
57690
58011
  }
57691
58012
  function probePort(port, timeoutMs) {
57692
- return new Promise((resolve40) => {
58013
+ return new Promise((resolve45) => {
57693
58014
  const sock = net.connect({ port, host: "127.0.0.1", timeout: timeoutMs });
57694
58015
  sock.once("connect", () => {
57695
58016
  sock.destroy();
57696
- resolve40(true);
58017
+ resolve45(true);
57697
58018
  });
57698
- sock.once("error", () => resolve40(false));
58019
+ sock.once("error", () => resolve45(false));
57699
58020
  sock.once("timeout", () => {
57700
58021
  sock.destroy();
57701
- resolve40(false);
58022
+ resolve45(false);
57702
58023
  });
57703
58024
  });
57704
58025
  }
@@ -57874,14 +58195,18 @@ async function runSetup(opts, deps) {
57874
58195
  return fail2(`\u9886\u53F7\u5931\u8D25\uFF1A${e?.message || e}\u3002\u7F51\u7EDC\u4E0D\u901A\u65F6\u53EF\u91CD\u8BD5\uFF1B\u4E2D\u8F6C\u7AD9\u5730\u5740\u53EF\u7528 --relay \u6307\u5B9A`);
57875
58196
  }
57876
58197
  }
57877
- try {
57878
- deps.writeAnswers(answersPath);
57879
- } catch (e) {
57880
- return fail2(`\u5199 answers \u5931\u8D25\uFF1A${e?.message || e}\uFF08${answersPath}\uFF09`);
58198
+ if (deps.configExists?.()) {
58199
+ say("\u5DF2\u521D\u59CB\u5316\u2014\u2014\u8DF3\u8FC7 init\uFF08\u4E0D\u78B0\u73B0\u6709\u914D\u7F6E\u4E0E\u901A\u9053\uFF09");
58200
+ } else {
58201
+ try {
58202
+ deps.writeAnswers(answersPath);
58203
+ } catch (e) {
58204
+ return fail2(`\u5199 answers \u5931\u8D25\uFF1A${e?.message || e}\uFF08${answersPath}\uFF09`);
58205
+ }
58206
+ say("\u521D\u59CB\u5316\uFF08init --answers\uFF0C\u7EAF\u79BB\u7EBF\uFF09\u2026");
58207
+ const initCode = await deps.runInit(answersPath);
58208
+ if (initCode !== 0) return fail2(`init \u5931\u8D25\uFF08\u9000\u51FA\u7801 ${initCode}\uFF09\u2014\u2014\u4E0A\u9762 init \u7684\u8F93\u51FA\u91CC\u6709\u5177\u4F53\u539F\u56E0\uFF0C\u522B\u8DF3\u8FC7\u5B83`);
57881
58209
  }
57882
- say("\u521D\u59CB\u5316\uFF08init --answers\uFF0C\u7EAF\u79BB\u7EBF\uFF09\u2026");
57883
- const initCode = await deps.runInit(answersPath);
57884
- if (initCode !== 0) return fail2(`init \u5931\u8D25\uFF08\u9000\u51FA\u7801 ${initCode}\uFF09\u2014\u2014\u4E0A\u9762 init \u7684\u8F93\u51FA\u91CC\u6709\u5177\u4F53\u539F\u56E0\uFF0C\u522B\u8DF3\u8FC7\u5B83`);
57885
58210
  const port = opts.apiPort ?? await deps.apiPort();
57886
58211
  say("\u62C9\u8D77\u5F15\u64CE\u2026");
57887
58212
  try {
@@ -57891,7 +58216,10 @@ async function runSetup(opts, deps) {
57891
58216
  }
57892
58217
  say(`\u63A2\u6D3B http://127.0.0.1:${port}/api/status \u2026`);
57893
58218
  if (!await deps.probe(`http://127.0.0.1:${port}/api/status`)) {
57894
- return fail2(`\u63A2\u6D3B\u672A\u901A\u8FC7\uFF08/api/status \u4E0D\u7EFF\uFF09\u2014\u2014\u5F15\u64CE\u53EF\u80FD\u6CA1\u8D77\u6765\uFF1B\u770B ${path55.join(opts.stateDir, "logs")} \u4E0B\u7684\u65E5\u5FD7`);
58219
+ return fail2(`\u63A2\u6D3B\u672A\u901A\u8FC7\uFF08/api/status 90s \u5185\u4E0D\u7EFF\uFF09\u2014\u2014\u5F15\u64CE\u53EF\u80FD\u6CA1\u8D77\u6765\uFF1B\u770B ${path55.join(opts.stateDir, "logs")} \u4E0B\u7684\u65E5\u5FD7\u3002\u82E5\u662F\u51B7\u542F\u52A8\u6162\uFF1A\u7A0D\u5019\u81EA\u6D4B curl http://127.0.0.1:${port}/api/status\uFF0C\u7EFF\u4E86\u63A7\u5236\u53F0\u5373\u7528 http://127.0.0.1:${port}/console`);
58220
+ }
58221
+ if (process.platform === "win32" && deps.installService) {
58222
+ if (await deps.installService() !== 0) say("\u26A0 \u5F00\u673A\u81EA\u542F\u6CE8\u518C\u5931\u8D25\u2014\u2014\u5F15\u64CE\u5DF2\u5728\u8DD1\uFF0C\u672C\u6B21\u53EF\u7528\uFF1B\u7A0D\u540E\u53EF\u624B\u52A8: engine7 service install");
57895
58223
  }
57896
58224
  say("\u2705 \u88C5\u597D\u4E86\uFF0C\u5F00\u7BB1\u5373\u804A\uFF08\u514D\u8D39\u6863\u5DF2\u914D\u597D\uFF09");
57897
58225
  say(` \u63A7\u5236\u53F0: http://127.0.0.1:${port}/console`);
@@ -57907,6 +58235,7 @@ function wireSetupDeps(opts) {
57907
58235
  const configPath = path55.join(stateDir, "configs", "main7.json");
57908
58236
  return {
57909
58237
  hasToken: () => freeTokenPresent(stateDir),
58238
+ configExists: () => fs52.existsSync(configPath),
57910
58239
  provision: async () => {
57911
58240
  const { provisionFreeToken: provisionFreeToken2 } = await Promise.resolve().then(() => (init_provision_free(), provision_free_exports));
57912
58241
  const { resolveRelayUrl: resolveRelayUrl2 } = await Promise.resolve().then(() => (init_cli_init_config(), cli_init_config_exports));
@@ -57917,19 +58246,19 @@ function wireSetupDeps(opts) {
57917
58246
  fs52.writeFileSync(p, JSON.stringify(buildFreeTierAnswers({ agentName: opts.agentName, apiPort: opts.apiPort })), "utf8");
57918
58247
  },
57919
58248
  runInit: async (answersPath) => {
57920
- const { spawn: spawn5 } = await import("node:child_process");
58249
+ const { spawn: spawn8 } = await import("node:child_process");
57921
58250
  const pointerPath = path55.join(process.env.HOME || process.env.USERPROFILE || ".", ".engine7.json");
57922
58251
  let prevPointer = null;
57923
58252
  try {
57924
58253
  prevPointer = fs52.readFileSync(pointerPath, "utf8");
57925
58254
  } catch {
57926
58255
  }
57927
- const code = await new Promise((resolve40) => {
57928
- const child = spawn5(process.execPath, [resolveCliEntry(), "init", "--state-dir", stateDir, "--answers", answersPath], { stdio: "inherit" });
57929
- child.on("exit", (c) => resolve40(c ?? 1));
58256
+ const code = await new Promise((resolve45) => {
58257
+ const child = spawn8(process.execPath, [resolveCliEntry(), "init", "--state-dir", stateDir, "--answers", answersPath], { stdio: "inherit" });
58258
+ child.on("exit", (c) => resolve45(c ?? 1));
57930
58259
  child.on("error", (e) => {
57931
58260
  console.error(`[setup] \u274C \u62C9\u8D77 init \u5931\u8D25\uFF1A${e.message}`);
57932
- resolve40(1);
58261
+ resolve45(1);
57933
58262
  });
57934
58263
  });
57935
58264
  if (prevPointer !== null) {
@@ -57946,13 +58275,28 @@ function wireSetupDeps(opts) {
57946
58275
  return computeApiPort2(cfg);
57947
58276
  },
57948
58277
  startEngine: async () => {
57949
- const { spawn: spawn5 } = await import("node:child_process");
58278
+ ensureWin32Runtime();
58279
+ const { spawn: spawn8 } = await import("node:child_process");
57950
58280
  const enginePath = resolveEngineEntry();
57951
- const child = spawn5(process.execPath, [enginePath, "--engine-config", configPath], { detached: true, stdio: "ignore" });
58281
+ const child = spawn8(process.execPath, [enginePath, "--engine-config", configPath], { detached: true, stdio: "ignore" });
57952
58282
  child.unref();
57953
58283
  },
58284
+ installService: process.platform !== "win32" ? void 0 : async () => {
58285
+ const { spawn: spawn8 } = await import("node:child_process");
58286
+ return await new Promise((resolve45) => {
58287
+ const child = spawn8(process.execPath, [resolveCliEntry(), "service", "install", "--config", configPath], { stdio: "inherit" });
58288
+ child.on("exit", (c) => resolve45(c ?? 1));
58289
+ child.on("error", (e) => {
58290
+ console.error(`[setup] \u26A0 service install \u62C9\u8D77\u5931\u8D25\uFF1A${e.message}`);
58291
+ resolve45(1);
58292
+ });
58293
+ });
58294
+ },
58295
+ // 1119 第二台 Win 新机实弹:20s 窗口对冷启动假阴性(磁盘缓存全冷 + Defender
58296
+ // 逐个扫 native DLL,http-api 又在组装链尾部才 listen;47.93 第九跑是热缓存
58297
+ // 才勉强赶上)。放宽到 90s,每 15s 报一次仍在等;热启动依旧几秒内通过。
57954
58298
  probe: async (url) => {
57955
- for (let i = 0; i < 20; i++) {
58299
+ for (let i = 0; i < 90; i++) {
57956
58300
  try {
57957
58301
  const res = await fetch(url);
57958
58302
  if (res.ok) {
@@ -57961,12 +58305,35 @@ function wireSetupDeps(opts) {
57961
58305
  }
57962
58306
  } catch {
57963
58307
  }
58308
+ if (i > 0 && i % 15 === 0) say(`\u2026\u5F15\u64CE\u542F\u52A8\u4E2D\uFF08\u51B7\u542F\u52A8\u53EF\u80FD\u6162\uFF0C\u6700\u591A\u518D\u7B49 ${90 - i}s\uFF09`);
57964
58309
  await new Promise((r) => setTimeout(r, 1e3));
57965
58310
  }
57966
58311
  return false;
57967
58312
  }
57968
58313
  };
57969
58314
  }
58315
+ function ensureWin32Runtime() {
58316
+ if (process.platform !== "win32") return;
58317
+ const sys = path55.join(process.env.SystemRoot || "C:\\Windows", "System32", "vcruntime140.dll");
58318
+ if (fs52.existsSync(sys)) return;
58319
+ const nodeDir = path55.dirname(process.execPath);
58320
+ const names = ["vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll"];
58321
+ const srcDir = path55.join(path55.dirname(__filename2), "..", "dlls", "win32");
58322
+ let placed = 0;
58323
+ for (const n of names) {
58324
+ const dst = path55.join(nodeDir, n);
58325
+ if (fs52.existsSync(dst)) continue;
58326
+ const src = path55.join(srcDir, n);
58327
+ if (!fs52.existsSync(src)) throw new Error(`\u5305\u5185\u7F3A ${n}\uFF08${srcDir}\uFF09\u2014\u2014\u539F\u751F\u6A21\u5757\u4F1A\u52A0\u8F7D\u5931\u8D25`);
58328
+ try {
58329
+ fs52.copyFileSync(src, dst);
58330
+ placed++;
58331
+ } catch (e) {
58332
+ throw new Error(`\u65E0\u6CD5\u628A ${n} \u590D\u5236\u5230 ${nodeDir}\uFF1A${e?.message || e}\u2014\u2014node \u76EE\u5F55\u4E0D\u53EF\u5199\uFF1B\u6362\u53EF\u5199\u7684 node \u76EE\u5F55\u91CD\u8BD5\uFF0C\u6216\u5148\u88C5 VC++ \u8FD0\u884C\u5E93`);
58333
+ }
58334
+ }
58335
+ if (placed > 0) console.log(`[setup] VC++ \u8FD0\u884C\u5E93\u5DF2 app-local \u653E\u7F6E ${placed} \u4E2A DLL \u2192 ${nodeDir}`);
58336
+ }
57970
58337
  function resolveCliEntry() {
57971
58338
  const candidates2 = [
57972
58339
  path55.join(path55.dirname(path55.resolve(process.argv[1])), "cli.mjs"),
@@ -59088,7 +59455,7 @@ async function runDesktopCli(args) {
59088
59455
  process.stdout.on("resize", resize);
59089
59456
  process.on("SIGTERM", terminate);
59090
59457
  process.on("SIGHUP", terminate);
59091
- return await new Promise((resolve40) => terminal.onExit(({ exitCode }) => resolve40(exitCode)));
59458
+ return await new Promise((resolve45) => terminal.onExit(({ exitCode }) => resolve45(exitCode)));
59092
59459
  } finally {
59093
59460
  process.stdin.off("data", data);
59094
59461
  process.stdout.off("resize", resize);
@@ -61420,7 +61787,7 @@ async function runMemServe(args) {
61420
61787
  process.on("unhandledRejection", (reason) => {
61421
61788
  console.error(`[mem-serve] Unhandled rejection: ${reason?.stack ?? reason}`);
61422
61789
  });
61423
- await new Promise((resolve40) => {
61790
+ await new Promise((resolve45) => {
61424
61791
  server.listen(cfg.port, "127.0.0.1", () => {
61425
61792
  console.log("=== engine7 mem-serve\uFF08\u8BB0\u5FC6\u7F51\u5173\uFF09===");
61426
61793
  console.log(`config: ${configPath}`);
@@ -61441,7 +61808,7 @@ async function runMemServe(args) {
61441
61808
  } catch (err) {
61442
61809
  console.log(` \u26A0\uFE0F \u6574\u7406\u7BA1\u9053\u672A\u542F\u52A8\uFF08\u4E0D\u5F71\u54CD\u7F51\u5173\uFF09\uFF1A${err?.message ?? err}`);
61443
61810
  }
61444
- resolve40();
61811
+ resolve45();
61445
61812
  });
61446
61813
  });
61447
61814
  const shutdown = () => {
@@ -62293,6 +62660,7 @@ import { lstat as lstat2, open as open4, readdir as readdir2, realpath } from "n
62293
62660
  import { isAbsolute as isAbsolute8, join as join97, relative as relative9, resolve as resolve36, sep as sep13 } from "node:path";
62294
62661
  function coreReason(path72) {
62295
62662
  const name = path72.split("/").at(-1);
62663
+ if (path72 === "chan7-files" || path72.startsWith("chan7-files/")) return void 0;
62296
62664
  if (CORE_OMITTED.has(name) || /(?:\.lance$|(?:^|[-.])bak(?:[-.]|$))/i.test(name)) return "optional attachments, historical copies or rebuildable indexes; outside core travel";
62297
62665
  if (/\.(?:mp4|mov|mkv|webm|avi|m4v|mp3|wav|ogg|opus|m4a|aac|flac|png|jpe?g|gif|webp|heic|bmp|tiff?|ico|pdf|docx?|pptx?|xlsx?|zip|gz|tgz|tar|7z|rar|dmg|exe|dll|so|dylib|bin|onnx|safetensors|gguf|vrm|glb|gltf|fbx|ttf|otf|woff2?|pyc|log|out)$/i.test(name) || name === ".DS_Store" || name === "package-lock.json" || name === ".context-debug.txt" || path72 === "mem7/spool/intake.failed.jsonl") return "attachments, installed binaries or diagnostics; outside core travel";
62298
62666
  }
@@ -62483,7 +62851,7 @@ var init_inventory = __esm({
62483
62851
  NESTED_EXCLUDED = { ".git": "source control metadata", node_modules: "installed dependencies", __pycache__: "Python bytecode cache" };
62484
62852
  WORKSPACE_DIAGNOSTICS = /* @__PURE__ */ new Set([".system-prompt.txt", ".context-debug.txt"]);
62485
62853
  RUNTIME_CONTROL = /* @__PURE__ */ new Set([".continuity", ".engine.pid", ".bg-worker.pid", ".travel-restored.json", ".travel-enrolled.json", ".travel-active.json"]);
62486
- CORE_DIRECTORIES = new Set(`agents auth configs cron mem7 memory runtime session-memory steer tasks teams todos tools .everos .calendar calendar .proactive proactive skills prompts .nudge hooks inner-voice goals plans private scripts state .voice-chat .desktopBuddy body`.split(" "));
62854
+ CORE_DIRECTORIES = new Set(`agents auth configs cron mem7 memory runtime session-memory steer tasks teams todos tools .everos .calendar calendar .proactive proactive skills prompts topics .nudge hooks inner-voice goals plans private scripts state .voice-chat .desktopBuddy body`.split(" "));
62487
62855
  CORE_OMITTED = new Set(`media images videos audio content content-library docs output outputs dogfood-output backup backups topics-history node_modules .venvs venv .venv asr .cache cache caches tmp temp .playwright-mcp lancedb`.split(" "));
62488
62856
  }
62489
62857
  });
@@ -63106,6 +63474,2027 @@ var init_cli2 = __esm({
63106
63474
  }
63107
63475
  });
63108
63476
 
63477
+ // src/travel/config-remap.ts
63478
+ function remapConfigForRemote(config, remoteRoot) {
63479
+ const clone = structuredClone(config);
63480
+ const originalStateDir = typeof clone.stateDir === "string" ? clone.stateDir : void 0;
63481
+ const roots = [];
63482
+ const agents = clone.agents;
63483
+ const defaults = agents?.defaults;
63484
+ if (typeof defaults?.workspace === "string") roots.push([defaults.workspace, remoteRoot + "/workspace"]);
63485
+ if (typeof clone.workspace === "string") roots.push([clone.workspace, remoteRoot + "/workspace"]);
63486
+ if (originalStateDir) roots.push([originalStateDir, remoteRoot]);
63487
+ const relocate = (value) => {
63488
+ if (typeof value === "string") {
63489
+ for (const [source, target] of roots) {
63490
+ if (source && value === source) return target;
63491
+ if (source && value.startsWith(source + "/")) return target + value.slice(source.length);
63492
+ }
63493
+ return value;
63494
+ }
63495
+ if (Array.isArray(value)) return value.map(relocate);
63496
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key4, item]) => [key4, relocate(item)]));
63497
+ return value;
63498
+ };
63499
+ const remapped = relocate(clone);
63500
+ remapped.stateDir = remoteRoot;
63501
+ if (remapped.agents && typeof remapped.agents === "object") {
63502
+ const a = remapped.agents;
63503
+ if (a.defaults && typeof a.defaults === "object") a.defaults.workspace = remoteRoot + "/workspace";
63504
+ }
63505
+ return remapped;
63506
+ }
63507
+ function unitIdFor(companion) {
63508
+ const slug = companion.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
63509
+ return slug || "companion";
63510
+ }
63511
+ function buildSystemdUnit(options) {
63512
+ return `[Unit]
63513
+ Description=engine7 ${options.companion}
63514
+ After=network-online.target
63515
+
63516
+ [Service]
63517
+ Type=simple
63518
+ EnvironmentFile=${options.remoteRoot}/secrets.env
63519
+ ExecStart=${options.nodeBin} ${options.engineBin} start --config ${options.remoteRoot}/config.json
63520
+ WorkingDirectory=${options.remoteRoot}
63521
+ Restart=on-failure
63522
+ RestartSec=5
63523
+
63524
+ [Install]
63525
+ WantedBy=multi-user.target
63526
+ `;
63527
+ }
63528
+ var init_config_remap = __esm({
63529
+ "src/travel/config-remap.ts"() {
63530
+ "use strict";
63531
+ }
63532
+ });
63533
+
63534
+ // src/travel/gate.ts
63535
+ var gate_exports2 = {};
63536
+ __export(gate_exports2, {
63537
+ ensureGate: () => ensureGate,
63538
+ ensureTunnelDown: () => ensureTunnelDown,
63539
+ gatePidFile: () => gatePidFile,
63540
+ gateSocketPath: () => gateSocketPath,
63541
+ readResidency: () => readResidency,
63542
+ residencyPath: () => residencyPath,
63543
+ runGateFromArgv: () => runGateFromArgv,
63544
+ startGate: () => startGate,
63545
+ writeResidency: () => writeResidency
63546
+ });
63547
+ import { createServer as createServer3, connect as socketConnect } from "node:net";
63548
+ import { readFileSync as readFileSync74, writeFileSync as writeFileSync44, mkdirSync as mkdirSync40, unlinkSync as unlinkSync15, existsSync as existsSync60, realpathSync as realpathSync10 } from "node:fs";
63549
+ import { join as join103, resolve as resolve39, dirname as dirname39 } from "node:path";
63550
+ import { spawn as spawn5 } from "node:child_process";
63551
+ function writeResidency(stateDir, where, cloud) {
63552
+ try {
63553
+ mkdirSync40(join103(stateDir, ".travel"), { recursive: true });
63554
+ writeFileSync44(residencyPath(stateDir), JSON.stringify({ where, ...where === "cloud" && cloud ? cloud : {} }));
63555
+ } catch {
63556
+ }
63557
+ }
63558
+ function readResidency(stateDir) {
63559
+ try {
63560
+ return JSON.parse(readFileSync74(residencyPath(stateDir), "utf8"));
63561
+ } catch {
63562
+ return null;
63563
+ }
63564
+ }
63565
+ async function ensureTunnelDown(stateDir) {
63566
+ const pidFile = join103(stateDir, ".travel", "tunnel.pid");
63567
+ let pid = 0;
63568
+ try {
63569
+ pid = Number(readFileSync74(pidFile, "utf8").trim());
63570
+ } catch {
63571
+ return;
63572
+ }
63573
+ if (Number.isSafeInteger(pid) && pid > 0) {
63574
+ try {
63575
+ process.kill(pid, "SIGTERM");
63576
+ } catch {
63577
+ }
63578
+ const deadline = Date.now() + 3e3;
63579
+ while (Date.now() < deadline) {
63580
+ let alive4 = false;
63581
+ try {
63582
+ process.kill(pid, 0);
63583
+ alive4 = true;
63584
+ } catch {
63585
+ }
63586
+ if (!alive4) break;
63587
+ await new Promise((r) => setTimeout(r, 100));
63588
+ }
63589
+ }
63590
+ try {
63591
+ unlinkSync15(pidFile);
63592
+ } catch {
63593
+ }
63594
+ }
63595
+ function startGate(options) {
63596
+ const travelDir = join103(options.stateDir, ".travel");
63597
+ const stateDirReal = (() => {
63598
+ try {
63599
+ return realpathSync10(options.stateDir);
63600
+ } catch {
63601
+ return resolve39(options.stateDir);
63602
+ }
63603
+ })();
63604
+ const lockPath2 = join103(travelDir, "gate.lock");
63605
+ mkdirSync40(travelDir, { recursive: true });
63606
+ for (let attempt = 0; ; attempt++) {
63607
+ try {
63608
+ writeFileSync44(lockPath2, `${process.pid}
63609
+ `, { flag: "wx" });
63610
+ break;
63611
+ } catch (error) {
63612
+ if (error?.code !== "EEXIST" || attempt >= 1) throw error;
63613
+ let holderAlive = false;
63614
+ try {
63615
+ const holder = Number(readFileSync74(lockPath2, "utf8").trim());
63616
+ if (Number.isSafeInteger(holder) && holder > 0) {
63617
+ if (holder === process.pid) holderAlive = true;
63618
+ else {
63619
+ try {
63620
+ process.kill(holder, 0);
63621
+ holderAlive = true;
63622
+ } catch {
63623
+ holderAlive = false;
63624
+ }
63625
+ }
63626
+ }
63627
+ } catch {
63628
+ }
63629
+ if (holderAlive) throw new Error(`TRAVEL_GATE_ALREADY_RUNNING\uFF08pid \u89C1 ${lockPath2}\uFF09`);
63630
+ try {
63631
+ unlinkSync15(lockPath2);
63632
+ } catch {
63633
+ }
63634
+ }
63635
+ }
63636
+ const socketPath = gateSocketPath(options.stateDir);
63637
+ try {
63638
+ unlinkSync15(socketPath);
63639
+ } catch {
63640
+ }
63641
+ let mode = "idle";
63642
+ let cloudTarget = null;
63643
+ let listener = null;
63644
+ let holdOffUntil = 0;
63645
+ const sockets = /* @__PURE__ */ new Set();
63646
+ const connectRemote = options.connector ?? ((host, port) => spawn5("ssh", ["-o", "ConnectTimeout=5", "-W", `127.0.0.1:${port}`, host]));
63647
+ const readTravelFile = (file2, maxBytes = 16 * 1024) => {
63648
+ try {
63649
+ const raw = readFileSync74(join103(travelDir, file2));
63650
+ return raw.length > maxBytes ? raw.subarray(raw.length - maxBytes).toString("utf8") : raw.toString("utf8");
63651
+ } catch {
63652
+ return "";
63653
+ }
63654
+ };
63655
+ const progressResponse = () => {
63656
+ const step = readTravelFile("status.json", 512);
63657
+ const log = readTravelFile("last-op.log");
63658
+ const body = `<!doctype html><html lang="zh"><head><meta charset="utf-8"><meta http-equiv="refresh" content="2"><title>\u968F\u884C\u5207\u6362\u4E2D</title>
63659
+ <style>body{font-family:system-ui,sans-serif;background:#14121f;color:#efeaf8;margin:0;padding:28px}h1{font-size:20px}pre{background:#1e1a2e;border-radius:10px;padding:14px;font-size:12px;line-height:1.6;white-space:pre-wrap;word-break:break-all}code{color:#c9b8ff}</style>
63660
+ </head><body><h1>\u{1F9F3} \u968F\u884C\u5207\u6362\u8FDB\u884C\u4E2D</h1><p>\u5F53\u524D\u6B65\u9AA4\uFF08\u6BCF 2 \u79D2\u81EA\u52A8\u5237\u65B0\uFF09\uFF1A</p><p><code>${escapeHtml(step)}</code></p><pre>${escapeHtml(log)}</pre>
63661
+ <p style="color:#9d93b8">\u5207\u6362\u5B8C\u6210\u540E\u672C\u9875\u81EA\u52A8\u53D8\u56DE\u5979\u7684\u63A7\u5236\u53F0\u2014\u2014\u5730\u5740\u59CB\u7EC8\u662F 127.0.0.1:16992\uFF0C\u4E0D\u7528\u6539\u4E66\u7B7E\u3002</p></body></html>`;
63662
+ return `HTTP/1.1 200 OK\r
63663
+ Content-Type: text/html; charset=utf-8\r
63664
+ Cache-Control: no-store\r
63665
+ Content-Length: ${Buffer.byteLength(body, "utf8")}\r
63666
+ Connection: close\r
63667
+ \r
63668
+ ${body}`;
63669
+ };
63670
+ const respondProgress = (socket) => {
63671
+ try {
63672
+ socket.end(progressResponse());
63673
+ } catch {
63674
+ }
63675
+ };
63676
+ const bindPort = () => {
63677
+ if (listener) {
63678
+ const server2 = listener;
63679
+ if (server2.listening !== false) return;
63680
+ listener = null;
63681
+ }
63682
+ const server = createServer3((socket) => {
63683
+ sockets.add(socket);
63684
+ socket.on("close", () => sockets.delete(socket));
63685
+ if (mode === "cloud" && cloudTarget) {
63686
+ const upstream = connectRemote(cloudTarget.host, cloudTarget.port);
63687
+ let dataFlowed = false;
63688
+ if (upstream.stdout && upstream.stdin) {
63689
+ socket.pipe(upstream.stdin);
63690
+ upstream.stdout.on("data", () => {
63691
+ dataFlowed = true;
63692
+ });
63693
+ upstream.stdout.pipe(socket, { end: false });
63694
+ }
63695
+ const finish = () => {
63696
+ if (socket.destroyed) return;
63697
+ if (dataFlowed) {
63698
+ try {
63699
+ socket.end();
63700
+ } catch {
63701
+ }
63702
+ } else respondProgress(socket);
63703
+ };
63704
+ upstream.on("error", finish);
63705
+ upstream.on("close", finish);
63706
+ socket.on("error", () => {
63707
+ try {
63708
+ upstream.kill();
63709
+ } catch {
63710
+ }
63711
+ });
63712
+ socket.on("close", () => {
63713
+ try {
63714
+ upstream.kill();
63715
+ } catch {
63716
+ }
63717
+ });
63718
+ } else {
63719
+ respondProgress(socket);
63720
+ }
63721
+ });
63722
+ server.on("error", () => {
63723
+ listener = null;
63724
+ });
63725
+ server.listen(options.port, "127.0.0.1");
63726
+ listener = server;
63727
+ };
63728
+ const releasePort = () => {
63729
+ const server = listener;
63730
+ listener = null;
63731
+ if (!server) return;
63732
+ for (const socket of sockets) {
63733
+ try {
63734
+ socket.destroy();
63735
+ } catch {
63736
+ }
63737
+ }
63738
+ server.close(() => {
63739
+ });
63740
+ };
63741
+ const watcher = setInterval(() => {
63742
+ if (mode !== "idle" || Date.now() < holdOffUntil) return;
63743
+ const probe = socketConnect(options.port, "127.0.0.1");
63744
+ probe.on("connect", () => {
63745
+ try {
63746
+ probe.destroy();
63747
+ } catch {
63748
+ }
63749
+ });
63750
+ probe.on("error", () => {
63751
+ try {
63752
+ probe.destroy();
63753
+ } catch {
63754
+ }
63755
+ const residency = readResidency(options.stateDir);
63756
+ if (residency?.where === "cloud" && residency.host && residency.port) {
63757
+ mode = "cloud";
63758
+ cloudTarget = { host: residency.host, port: residency.port };
63759
+ } else {
63760
+ mode = "progress";
63761
+ cloudTarget = null;
63762
+ }
63763
+ bindPort();
63764
+ });
63765
+ }, 2e3);
63766
+ watcher.unref?.();
63767
+ const control2 = createServer3((client) => {
63768
+ let buffer = "";
63769
+ client.on("error", () => {
63770
+ });
63771
+ client.on("data", (chunk) => {
63772
+ try {
63773
+ buffer += chunk.toString("utf8");
63774
+ for (; ; ) {
63775
+ const newline = buffer.indexOf("\n");
63776
+ if (newline < 0) return;
63777
+ const line = buffer.slice(0, newline);
63778
+ buffer = buffer.slice(newline + 1);
63779
+ let command;
63780
+ try {
63781
+ command = JSON.parse(line);
63782
+ } catch {
63783
+ client.end(JSON.stringify({ ok: false, error: "bad_json" }) + "\n");
63784
+ return;
63785
+ }
63786
+ if (command.cmd === "status") {
63787
+ client.end(JSON.stringify({ ok: true, mode }) + "\n");
63788
+ return;
63789
+ }
63790
+ if (command.cmd === "hold-progress") {
63791
+ mode = "progress";
63792
+ cloudTarget = null;
63793
+ holdOffUntil = 0;
63794
+ bindPort();
63795
+ } else if (command.cmd === "hold-cloud") {
63796
+ mode = "cloud";
63797
+ cloudTarget = { host: command.host, port: command.port };
63798
+ holdOffUntil = 0;
63799
+ bindPort();
63800
+ } else if (command.cmd === "release") {
63801
+ mode = "idle";
63802
+ cloudTarget = null;
63803
+ holdOffUntil = Date.now() + 1e4;
63804
+ releasePort();
63805
+ } else if (command.cmd === "die") {
63806
+ client.end(JSON.stringify({ ok: true, mode }) + "\n");
63807
+ setTimeout(() => process.exit(0), 50);
63808
+ return;
63809
+ }
63810
+ client.end(JSON.stringify({ ok: true, mode }) + "\n");
63811
+ return;
63812
+ }
63813
+ } catch {
63814
+ try {
63815
+ client.end(JSON.stringify({ ok: false, error: "handler_error" }) + "\n");
63816
+ } catch {
63817
+ }
63818
+ }
63819
+ });
63820
+ });
63821
+ control2.listen(socketPath);
63822
+ try {
63823
+ writeFileSync44(gatePidFile(options.stateDir), String(process.pid) + "\n");
63824
+ } catch {
63825
+ }
63826
+ return {
63827
+ socketPath,
63828
+ stop: () => {
63829
+ clearInterval(watcher);
63830
+ try {
63831
+ unlinkSync15(socketPath);
63832
+ } catch {
63833
+ }
63834
+ try {
63835
+ unlinkSync15(lockPath2);
63836
+ } catch {
63837
+ }
63838
+ releasePort();
63839
+ control2.close();
63840
+ }
63841
+ };
63842
+ }
63843
+ async function ensureGate(options) {
63844
+ const socketPath = gateSocketPath(options.stateDir);
63845
+ const trySend = async (command) => {
63846
+ try {
63847
+ return await new Promise((resolvePromise, rejectPromise) => {
63848
+ const client = socketConnect(socketPath);
63849
+ const finish = (value) => {
63850
+ client.destroy();
63851
+ resolvePromise(value);
63852
+ };
63853
+ client.on("error", () => rejectPromise(new Error("gate unreachable")));
63854
+ client.on("connect", () => {
63855
+ client.write(JSON.stringify(command) + "\n");
63856
+ });
63857
+ let data = "";
63858
+ client.on("data", (chunk) => {
63859
+ data += chunk.toString("utf8");
63860
+ if (data.includes("\n")) {
63861
+ try {
63862
+ finish(JSON.parse(data.trim()));
63863
+ } catch {
63864
+ finish(null);
63865
+ }
63866
+ }
63867
+ });
63868
+ setTimeout(() => finish(null), 3e3);
63869
+ });
63870
+ } catch {
63871
+ return null;
63872
+ }
63873
+ };
63874
+ if (await trySend({ cmd: "status" })) {
63875
+ return { socketPath, send: async (command) => await trySend(command) ?? { ok: false, error: "gate_gone" } };
63876
+ }
63877
+ const selfEntry = new URL("./gate.js", import.meta.url).pathname.endsWith("/gate.js") && existsSync60(new URL("./gate.js", import.meta.url).pathname) ? new URL("./gate.js", import.meta.url).pathname : null;
63878
+ if (selfEntry) {
63879
+ const child = spawn5(process.execPath, [selfEntry, "--state-dir", options.stateDir, "--port", String(options.port)], { detached: true, stdio: "ignore" });
63880
+ child.unref();
63881
+ } else {
63882
+ const argv1 = process.argv[1] ? resolve39(process.argv[1]) : null;
63883
+ const siblingCli = argv1 ? join103(dirname39(argv1), "cli.mjs") : null;
63884
+ const cliSelf = [siblingCli, argv1].find((candidate) => candidate && existsSync60(candidate)) ?? null;
63885
+ if (!cliSelf) throw new Error(`gate \u65E0\u6CD5\u81EA\u4E3E\uFF1A\u627E\u4E0D\u5230\u5165\u53E3\uFF08argv1=${process.argv[1]}\uFF09`);
63886
+ const child = spawn5(process.execPath, [cliSelf, "travel-gate", "--state-dir", options.stateDir, "--port", String(options.port)], { detached: true, stdio: "ignore" });
63887
+ child.unref();
63888
+ }
63889
+ for (let i = 0; i < 20; i++) {
63890
+ await new Promise((r) => setTimeout(r, 150));
63891
+ if (await trySend({ cmd: "status" })) break;
63892
+ }
63893
+ return { socketPath, send: async (command) => await trySend(command) ?? { ok: false, error: "gate_gone" } };
63894
+ }
63895
+ function runGateFromArgv(argv) {
63896
+ let stateDir = "", port = 16992;
63897
+ for (let i = 0; i < argv.length; i++) {
63898
+ if (argv[i] === "--state-dir" && argv[i + 1]) stateDir = argv[++i];
63899
+ else if (argv[i] === "--port" && argv[i + 1]) port = Number(argv[++i]);
63900
+ }
63901
+ if (!stateDir) {
63902
+ console.error("\u7528\u6CD5: engine7 travel-gate --state-dir <dir> [--port 16992]");
63903
+ process.exit(1);
63904
+ }
63905
+ try {
63906
+ startGate({ stateDir, port });
63907
+ } catch (error) {
63908
+ if (error instanceof Error && error.message.startsWith("TRAVEL_GATE_ALREADY_RUNNING")) return;
63909
+ throw error;
63910
+ }
63911
+ }
63912
+ var gateSocketPath, gatePidFile, residencyPath, escapeHtml;
63913
+ var init_gate2 = __esm({
63914
+ "src/travel/gate.ts"() {
63915
+ "use strict";
63916
+ gateSocketPath = (stateDir) => join103(stateDir, ".travel", "gate.sock");
63917
+ gatePidFile = (stateDir) => join103(stateDir, ".travel", "gate.pid");
63918
+ residencyPath = (stateDir) => join103(stateDir, ".travel", "gate-residency.json");
63919
+ escapeHtml = (text4) => text4.replace(/[&<>"']/g, (ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[ch] ?? ch);
63920
+ }
63921
+ });
63922
+
63923
+ // src/travel/chunk-store.ts
63924
+ import { createHash as createHash46, randomUUID as randomUUID38 } from "node:crypto";
63925
+ import {
63926
+ closeSync as closeSync20,
63927
+ existsSync as existsSync61,
63928
+ fstatSync as fstatSync9,
63929
+ fsyncSync as fsyncSync10,
63930
+ lstatSync as lstatSync14,
63931
+ mkdirSync as mkdirSync41,
63932
+ openSync as openSync21,
63933
+ readFileSync as readFileSync75,
63934
+ readSync as readSync10,
63935
+ renameSync as renameSync21,
63936
+ unlinkSync as unlinkSync16,
63937
+ writeFileSync as writeFileSync45,
63938
+ writeSync as writeSync4,
63939
+ constants as constants15
63940
+ } from "node:fs";
63941
+ import { gunzipSync as gunzipSync2, gzipSync } from "node:zlib";
63942
+ import { dirname as dirname40, join as join104 } from "node:path";
63943
+ function validateChunkRef(ref) {
63944
+ if (!ref || !SHA.test(ref.sha256) || !Number.isSafeInteger(ref.bytes) || ref.bytes < 1 || ref.bytes > CHUNK_BYTES2)
63945
+ throw new Error("TRAVEL_INVALID_CHUNK");
63946
+ }
63947
+ function validateFileManifest(file2) {
63948
+ if (!file2 || !SHA.test(file2.sha256) || !Number.isSafeInteger(file2.bytes) || file2.bytes < 0 || !Array.isArray(file2.chunks))
63949
+ throw new Error("TRAVEL_INVALID_FILE");
63950
+ let total = 0;
63951
+ for (const ref of file2.chunks) {
63952
+ validateChunkRef(ref);
63953
+ total += ref.bytes;
63954
+ }
63955
+ if (total !== file2.bytes) throw new Error("TRAVEL_INVALID_FILE");
63956
+ }
63957
+ function openChunkStore(dir) {
63958
+ return new ChunkStore(dir);
63959
+ }
63960
+ var CHUNK_BYTES2, SHA, sha256, ChunkStore;
63961
+ var init_chunk_store = __esm({
63962
+ "src/travel/chunk-store.ts"() {
63963
+ "use strict";
63964
+ CHUNK_BYTES2 = 1024 * 1024;
63965
+ SHA = /^[a-f0-9]{64}$/;
63966
+ sha256 = (body) => createHash46("sha256").update(body).digest("hex");
63967
+ ChunkStore = class {
63968
+ dir;
63969
+ constructor(dir) {
63970
+ this.dir = dir;
63971
+ mkdirSync41(dir, { recursive: true, mode: 448 });
63972
+ }
63973
+ chunkPath(sha2) {
63974
+ return join104(this.dir, sha2 + ".gz");
63975
+ }
63976
+ /** 幂等:同 sha 已存在直接返回;写盘走 tmp+rename,读者永远看不到半个块。 */
63977
+ async put(body) {
63978
+ if (!(body instanceof Buffer) || body.length < 1 || body.length > CHUNK_BYTES2) throw new Error("TRAVEL_INVALID_CHUNK");
63979
+ const ref = { sha256: sha256(body), bytes: body.length };
63980
+ const path72 = this.chunkPath(ref.sha256);
63981
+ if (!existsSync61(path72)) {
63982
+ const temp = path72 + "." + randomUUID38() + ".tmp";
63983
+ try {
63984
+ writeFileSync45(temp, gzipSync(body), { flag: "wx", mode: 384 });
63985
+ renameSync21(temp, path72);
63986
+ } finally {
63987
+ try {
63988
+ if (existsSync61(temp)) unlinkSync16(temp);
63989
+ } catch {
63990
+ }
63991
+ }
63992
+ }
63993
+ return ref;
63994
+ }
63995
+ async has(sha2) {
63996
+ if (!SHA.test(sha2)) throw new Error("TRAVEL_INVALID_CHUNK");
63997
+ if (!existsSync61(this.chunkPath(sha2))) return false;
63998
+ try {
63999
+ await this.read(sha2);
64000
+ return true;
64001
+ } catch {
64002
+ return false;
64003
+ }
64004
+ }
64005
+ async read(sha2, bytes = -1) {
64006
+ if (!SHA.test(sha2) || !Number.isSafeInteger(bytes) || bytes < -1 || bytes > CHUNK_BYTES2) throw new Error("TRAVEL_INVALID_CHUNK");
64007
+ let plain;
64008
+ try {
64009
+ plain = gunzipSync2(readFileSync75(this.chunkPath(sha2)));
64010
+ } catch {
64011
+ throw new Error("TRAVEL_CHUNK_CORRUPT");
64012
+ }
64013
+ if (sha256(plain) !== sha2 || bytes >= 0 && plain.length !== bytes) throw new Error("TRAVEL_CHUNK_CORRUPT");
64014
+ return plain;
64015
+ }
64016
+ /** 捕获 = 边读边入仓。终态 fstat 复核(抄 codex captureFileWith):中途被写一律拒绝。 */
64017
+ async captureFile(source) {
64018
+ const fd = openSync21(source, constants15.O_RDONLY);
64019
+ try {
64020
+ const before = fstatSync9(fd, { bigint: true });
64021
+ if (!before.isFile()) throw new Error("TRAVEL_NOT_REGULAR_FILE");
64022
+ const digest6 = createHash46("sha256");
64023
+ const buffer = Buffer.alloc(Math.min(CHUNK_BYTES2, Number(before.size) || 1));
64024
+ const chunks = [];
64025
+ let bytes = 0;
64026
+ for (; ; ) {
64027
+ const count = readSync10(fd, buffer, 0, buffer.length, null);
64028
+ if (!count) break;
64029
+ const piece = Buffer.from(buffer.subarray(0, count));
64030
+ digest6.update(piece);
64031
+ bytes += count;
64032
+ chunks.push(await this.put(piece));
64033
+ }
64034
+ const after = fstatSync9(fd, { bigint: true });
64035
+ const pathInfo = lstatSync14(source, { bigint: true });
64036
+ if (["dev", "ino", "size", "mtimeNs", "ctimeNs"].some((key4) => after[key4] !== before[key4] || pathInfo[key4] !== before[key4]) || BigInt(bytes) !== before.size) throw new Error("TRAVEL_SOURCE_CHANGED");
64037
+ return { sha256: digest6.digest("hex"), bytes, chunks };
64038
+ } finally {
64039
+ closeSync20(fd);
64040
+ }
64041
+ }
64042
+ async restoreFile(file2, destination, mode = 384) {
64043
+ validateFileManifest(file2);
64044
+ if (existsSync61(destination)) throw new Error("TRAVEL_DESTINATION_EXISTS");
64045
+ mkdirSync41(dirname40(destination), { recursive: true });
64046
+ const temp = destination + "." + randomUUID38() + ".incoming";
64047
+ const digest6 = createHash46("sha256");
64048
+ const fd = openSync21(temp, "wx", mode);
64049
+ try {
64050
+ for (const ref of file2.chunks) {
64051
+ const body = await this.read(ref.sha256, ref.bytes);
64052
+ digest6.update(body);
64053
+ let offset = 0;
64054
+ while (offset < body.length) offset += writeSync4(fd, body, offset, body.length - offset);
64055
+ }
64056
+ if (digest6.digest("hex") !== file2.sha256) throw new Error("TRAVEL_FILE_CORRUPT");
64057
+ fsyncSync10(fd);
64058
+ renameSync21(temp, destination);
64059
+ } finally {
64060
+ closeSync20(fd);
64061
+ try {
64062
+ if (existsSync61(temp)) unlinkSync16(temp);
64063
+ } catch {
64064
+ }
64065
+ }
64066
+ }
64067
+ /** 盘上文件是否与 manifest 一致(apply 的跳过判断)。 */
64068
+ static fileMatches(destination, manifest) {
64069
+ try {
64070
+ const info = lstatSync14(destination);
64071
+ if (!info.isFile() || info.size !== manifest.bytes) return false;
64072
+ const digest6 = createHash46("sha256");
64073
+ const fd = openSync21(destination, constants15.O_RDONLY);
64074
+ try {
64075
+ const buffer = Buffer.alloc(Math.min(CHUNK_BYTES2, manifest.bytes || 1));
64076
+ for (; ; ) {
64077
+ const count = readSync10(fd, buffer, 0, buffer.length, null);
64078
+ if (!count) break;
64079
+ digest6.update(buffer.subarray(0, count));
64080
+ }
64081
+ } finally {
64082
+ closeSync20(fd);
64083
+ }
64084
+ return digest6.digest("hex") === manifest.sha256;
64085
+ } catch {
64086
+ return false;
64087
+ }
64088
+ }
64089
+ };
64090
+ }
64091
+ });
64092
+
64093
+ // src/travel/exclusions.ts
64094
+ function excludeReason(relPath, isDir) {
64095
+ const parts = relPath.split("/");
64096
+ for (let i = 0; i < parts.length - 1; i++) {
64097
+ const part = parts[i];
64098
+ if (part === "media" && parts[i + 1] === "inbound") {
64099
+ i++;
64100
+ continue;
64101
+ }
64102
+ if (EXCLUDED_NAMES.has(part)) return `installed dependency, cache or temporary directory: ${part}`;
64103
+ }
64104
+ const name = parts[parts.length - 1];
64105
+ if (isDir && EXCLUDED_NAMES.has(name)) return `installed dependency, cache or temporary directory: ${name}`;
64106
+ if (parts.length === 1 && EXCLUDED_TOP.has(name)) return `diagnostics, installed or rebuildable material: ${name}`;
64107
+ if (/\.lock$/.test(name) || /\.pid$/.test(name) || name === "package-lock.json" || name === "nohup.out") return "lock/pid/junk file";
64108
+ if (parts.length === 1 && EXCLUDED_NAMES.has(name)) return `installed dependency, cache or temporary file: ${name}`;
64109
+ if (/\.log$/.test(name) && parts[0] !== "workspace") return "diagnostics log";
64110
+ const mediaIndex = parts.indexOf("media");
64111
+ if (mediaIndex >= 0 && parts[mediaIndex + 1] === "generated") return "self-generated media";
64112
+ return void 0;
64113
+ }
64114
+ function syncExcludeWith(mediaPolicy) {
64115
+ return (relPath, isDir, size, mtimeMs) => {
64116
+ const parts = relPath.split("/");
64117
+ const name = parts[parts.length - 1];
64118
+ if (!relPath.includes("/") && (relPath === "config.json" || relPath === "secrets.env")) {
64119
+ return "\u5BF9\u7AEF\u5B89\u88C5\u4EA7\u7269\u4FDD\u62A4\uFF08config \u8D70 config-remap\uFF0Csecrets \u8D70 travel-setup\uFF09";
64120
+ }
64121
+ const isUserMedia = parts[0] === "media" && parts[1] === "inbound" || parts[0] === "chan7-files";
64122
+ if (isUserMedia) {
64123
+ if (mediaPolicy === "none") return "\u7528\u6237\u5A92\u4F53\u6863\u6848\u4E0D\u968F\u884C\uFF081122\uFF1A\u4E91\u7AEF\u7FFB\u65E7\u56FE\u8D70\u964D\u7EA7\u5360\u4F4D\uFF09";
64124
+ if (typeof size === "number" && size > WORKSPACE_BIG_FILE_BYTES) return `\u7528\u6237\u5A92\u4F53\u5927\u6587\u4EF6\u4E0D\u968F\u884C\uFF08${(size / 1048576).toFixed(0)}MB > 32MB\uFF09`;
64125
+ if (typeof mtimeMs === "number" && Date.now() - mtimeMs > mediaPolicy.windowMs) return `\u7528\u6237\u5A92\u4F53\u4EC5\u8FD1 ${Math.round(mediaPolicy.windowMs / 864e5)} \u5929\u968F\u884C\uFF08\u56DE\u7A0B\u7A97\u53E3\uFF09`;
64126
+ return void 0;
64127
+ }
64128
+ if (parts[0] === "workspace") {
64129
+ if (parts.length === 1) return isDir ? void 0 : WORKSPACE_MEMORY_FILES.test(name) ? void 0 : `workspace \u9876\u5C42\u6587\u4EF6\u4EC5\u8EAB\u4EFD\u6587\u6863\u968F\u884C\uFF08${name}\uFF09`;
64130
+ const second = parts[1];
64131
+ if (!WORKSPACE_MEMORY_DIRS.has(second)) {
64132
+ if (parts.length === 2 && !isDir) return WORKSPACE_MEMORY_FILES.test(second) ? void 0 : `workspace \u9876\u5C42\u6587\u4EF6\u4EC5\u8EAB\u4EFD\u6587\u6863\u968F\u884C\uFF08${second}\uFF09`;
64133
+ return `workspace \u5DE5\u4F5C\u4EA7\u7269\u4E0D\u968F\u884C\uFF08${second}/\uFF09\u2014\u2014\u53EA\u5E26\u6838\u5FC3\u8BB0\u5FC6\uFF081122 \u7ACB\u6CD5\uFF09`;
64134
+ }
64135
+ if (!isDir) {
64136
+ if (WORKSPACE_MEDIA_EXT.test(name)) return `workspace \u5185\u97F3\u89C6\u9891/\u538B\u7F29\u5305\u4E0D\u968F\u884C\uFF08${name}\uFF09`;
64137
+ if (typeof size === "number" && size > WORKSPACE_BIG_FILE_BYTES) return `workspace \u5927\u6587\u4EF6\u4E0D\u968F\u884C\uFF08${(size / 1048576).toFixed(0)}MB > 32MB\uFF09`;
64138
+ }
64139
+ return void 0;
64140
+ }
64141
+ if (parts[0] === "media" && parts.length >= 2) return `media \u4EC5 inbound\uFF08\u56DE\u7A0B\u8FD1\u7A97\uFF09\u968F\u884C\uFF1A${parts[1]}`;
64142
+ if (parts[0] === "content") return "\u5185\u5BB9\u4EA7\u7269\u76EE\u5F55\u4E0D\u968F\u884C";
64143
+ return excludeReason(relPath, isDir);
64144
+ };
64145
+ }
64146
+ function syncExcludeWithDays(days) {
64147
+ return days > 0 ? syncExcludeWith({ windowMs: days * 864e5 }) : syncExcludeWith("none");
64148
+ }
64149
+ var EXCLUDED_NAMES, EXCLUDED_TOP, WORKSPACE_MEMORY_DIRS, WORKSPACE_MEMORY_FILES, WORKSPACE_MEDIA_EXT, WORKSPACE_BIG_FILE_BYTES, RETURN_MEDIA_KEEP_MS, syncExcludeReason, syncExcludeToCloud, syncExcludeToLocal;
64150
+ var init_exclusions = __esm({
64151
+ "src/travel/exclusions.ts"() {
64152
+ "use strict";
64153
+ EXCLUDED_NAMES = /* @__PURE__ */ new Set(["node_modules", ".venv", ".venvs", "venv", ".git", "__pycache__", ".cache", "cache", "caches", "tmp", "temp", ".playwright-mcp", ".DS_Store"]);
64154
+ EXCLUDED_TOP = /* @__PURE__ */ new Set(["logs", "diagnostics", "node_modules", "CogniFold", "everos-venv", "ollama-models", ".log-baseline.txt"]);
64155
+ WORKSPACE_MEMORY_DIRS = /* @__PURE__ */ new Set(["topics", "memory", "inner-voice", ".calendar", ".proactive", ".system", "docs", "skills"]);
64156
+ WORKSPACE_MEMORY_FILES = /^((SOUL|AGENTS|SESSION-STATE|HEARTBEAT|MEMORY|README)\.md|\.?gitignore)$/;
64157
+ 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;
64158
+ WORKSPACE_BIG_FILE_BYTES = 32 * 1024 * 1024;
64159
+ RETURN_MEDIA_KEEP_MS = 14 * 24 * 3600 * 1e3;
64160
+ syncExcludeReason = syncExcludeWith("none");
64161
+ syncExcludeToCloud = syncExcludeWith("none");
64162
+ syncExcludeToLocal = syncExcludeWith({ windowMs: RETURN_MEDIA_KEEP_MS });
64163
+ }
64164
+ });
64165
+
64166
+ // src/travel/tree-manifest.ts
64167
+ import { lstatSync as lstatSync15, readdirSync as readdirSync21 } from "node:fs";
64168
+ import { join as join105 } from "node:path";
64169
+ function parseTreeManifest(value) {
64170
+ const manifest = value;
64171
+ if (!manifest || manifest.version !== TREE_MANIFEST_VERSION || !Array.isArray(manifest.files) || !Array.isArray(manifest.excluded))
64172
+ throw new Error("TRAVEL_INVALID_MANIFEST");
64173
+ for (const file2 of manifest.files) {
64174
+ if (typeof file2.rel !== "string" || !file2.rel || file2.rel.includes("..") || file2.rel.startsWith("/") || typeof file2.mode !== "number" || !file2.content?.sha256) throw new Error("TRAVEL_INVALID_MANIFEST");
64175
+ }
64176
+ return manifest;
64177
+ }
64178
+ async function buildTreeManifest(root, store, opts = {}) {
64179
+ const exclude = opts.exclude ?? syncExcludeReason;
64180
+ const files = [];
64181
+ const excluded = [];
64182
+ const walk = async (dir, rel) => {
64183
+ for (const entry of readdirSync21(dir, { withFileTypes: true })) {
64184
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
64185
+ const childPath = join105(dir, entry.name);
64186
+ if (entry.isSymbolicLink()) {
64187
+ excluded.push(`${childRel} \u2014 symlink refused`);
64188
+ continue;
64189
+ }
64190
+ if (rel === "" && SELF_EXCLUDED_TOP.has(entry.name)) {
64191
+ excluded.push(`${childRel} \u2014 travel internal state`);
64192
+ continue;
64193
+ }
64194
+ let size, mtimeMs;
64195
+ if (entry.isFile()) {
64196
+ try {
64197
+ const info2 = lstatSync15(childPath);
64198
+ size = info2.size;
64199
+ mtimeMs = info2.mtimeMs;
64200
+ } catch {
64201
+ }
64202
+ }
64203
+ const reason = exclude(childRel, entry.isDirectory(), size, mtimeMs);
64204
+ if (reason) {
64205
+ excluded.push(`${childRel} \u2014 ${reason}`);
64206
+ continue;
64207
+ }
64208
+ if (entry.isDirectory()) {
64209
+ await walk(childPath, childRel);
64210
+ continue;
64211
+ }
64212
+ if (!entry.isFile()) {
64213
+ excluded.push(`${childRel} \u2014 not a regular file`);
64214
+ continue;
64215
+ }
64216
+ const info = lstatSync15(childPath);
64217
+ files.push({ rel: childRel, mode: info.mode & 511, content: await store.captureFile(childPath) });
64218
+ }
64219
+ };
64220
+ await walk(root, "");
64221
+ files.sort((a, b) => a.rel < b.rel ? -1 : 1);
64222
+ return { version: TREE_MANIFEST_VERSION, generatedAt: Date.now(), files, excluded };
64223
+ }
64224
+ var TREE_MANIFEST_VERSION, SELF_EXCLUDED_TOP;
64225
+ var init_tree_manifest = __esm({
64226
+ "src/travel/tree-manifest.ts"() {
64227
+ "use strict";
64228
+ init_exclusions();
64229
+ TREE_MANIFEST_VERSION = 2;
64230
+ SELF_EXCLUDED_TOP = /* @__PURE__ */ new Set([".travel", ".travel-sync-staging"]);
64231
+ }
64232
+ });
64233
+
64234
+ // src/travel/apply-tree.ts
64235
+ import {
64236
+ closeSync as closeSync21,
64237
+ constants as constants16,
64238
+ existsSync as existsSync62,
64239
+ mkdirSync as mkdirSync42,
64240
+ openSync as openSync22,
64241
+ readFileSync as readFileSync76,
64242
+ readSync as readSync11,
64243
+ renameSync as renameSync22,
64244
+ rmSync as rmSync6,
64245
+ unlinkSync as unlinkSync17,
64246
+ writeFileSync as writeFileSync46
64247
+ } from "node:fs";
64248
+ import { createHash as createHash47 } from "node:crypto";
64249
+ import { join as join106 } from "node:path";
64250
+ function readSyncState(root) {
64251
+ try {
64252
+ const value = JSON.parse(readFileSync76(join106(root, SYNC_STATE_FILE), "utf8"));
64253
+ if (value?.version !== 1 || !value.files || typeof value.files !== "object") throw new Error("bad");
64254
+ const files = {};
64255
+ for (const [rel, sha2] of Object.entries(value.files)) {
64256
+ if (typeof rel !== "string" || typeof sha2 !== "string") throw new Error("bad");
64257
+ files[rel] = sha2;
64258
+ }
64259
+ return { version: 1, syncedAt: Number(value.syncedAt) || 0, files };
64260
+ } catch {
64261
+ console.warn("[travel] sync-state \u7F3A\u5931\u6216\u635F\u574F\uFF0C\u6309\u9996\u6B21\u540C\u6B65\u5904\u7406\uFF08\u4E0D\u5220\u4EFB\u4F55\u6587\u4EF6\uFF09");
64262
+ return null;
64263
+ }
64264
+ }
64265
+ function writeSyncState(root, files) {
64266
+ mkdirSync42(join106(root, ".travel"), { recursive: true });
64267
+ const temp = join106(root, ".travel", "sync-state.json.tmp");
64268
+ writeFileSync46(temp, JSON.stringify({ version: 1, syncedAt: Date.now(), files }));
64269
+ renameSync22(temp, join106(root, SYNC_STATE_FILE));
64270
+ }
64271
+ function fileSha(path72) {
64272
+ try {
64273
+ const fd = openSync22(path72, constants16.O_RDONLY);
64274
+ const digest6 = createHash47("sha256");
64275
+ const buffer = Buffer.alloc(1024 * 1024);
64276
+ try {
64277
+ for (; ; ) {
64278
+ const count = readSync11(fd, buffer, 0, buffer.length, null);
64279
+ if (!count) break;
64280
+ digest6.update(buffer.subarray(0, count));
64281
+ }
64282
+ } finally {
64283
+ closeSync21(fd);
64284
+ }
64285
+ return digest6.digest("hex");
64286
+ } catch {
64287
+ return null;
64288
+ }
64289
+ }
64290
+ async function applyTree(root, manifestValue, store, lastState, onProgress) {
64291
+ const manifest = parseTreeManifest(manifestValue);
64292
+ const newRels = new Set(manifest.files.map((file2) => file2.rel));
64293
+ const deleted = [];
64294
+ const skipped = [];
64295
+ let applied = 0, appliedBytes = 0;
64296
+ for (const file2 of manifest.files) {
64297
+ const dest = join106(root, file2.rel);
64298
+ if (existsSync62(dest) && ChunkStore.fileMatches(dest, file2.content)) {
64299
+ skipped.push(file2.rel);
64300
+ continue;
64301
+ }
64302
+ if (existsSync62(dest)) {
64303
+ rmSync6(dest, { force: true });
64304
+ if (DB_RE.test(file2.rel)) for (const sidecar of sidecarsOf(file2.rel)) {
64305
+ if (!newRels.has(sidecar) && existsSync62(join106(root, sidecar))) rmSync6(join106(root, sidecar), { force: true });
64306
+ }
64307
+ }
64308
+ await store.restoreFile(file2.content, dest, file2.mode);
64309
+ applied++;
64310
+ appliedBytes += file2.content.bytes;
64311
+ onProgress?.({ files: applied, bytes: appliedBytes });
64312
+ }
64313
+ if (lastState) {
64314
+ for (const [rel, sha2] of Object.entries(lastState.files)) {
64315
+ if (newRels.has(rel)) continue;
64316
+ const dest = join106(root, rel);
64317
+ if (!existsSync62(dest)) continue;
64318
+ const current2 = fileSha(dest);
64319
+ if (current2 !== sha2) {
64320
+ skipped.push(`${rel} \u2014 \u672C\u5730\u5DF2\u6539\u52A8\uFF0C\u672A\u5220\u9664`);
64321
+ continue;
64322
+ }
64323
+ unlinkSync17(dest);
64324
+ deleted.push(rel);
64325
+ if (DB_RE.test(rel)) for (const sidecar of sidecarsOf(rel)) {
64326
+ if (!newRels.has(sidecar) && existsSync62(join106(root, sidecar))) {
64327
+ unlinkSync17(join106(root, sidecar));
64328
+ deleted.push(sidecar);
64329
+ }
64330
+ }
64331
+ }
64332
+ }
64333
+ const files = {};
64334
+ for (const file2 of manifest.files) files[file2.rel] = file2.content.sha256;
64335
+ writeSyncState(root, files);
64336
+ return { applied, deleted, skipped };
64337
+ }
64338
+ function sidecarsOf(dbRel) {
64339
+ return [`${dbRel}-wal`, `${dbRel}-shm`];
64340
+ }
64341
+ var SYNC_STATE_FILE, DB_RE;
64342
+ var init_apply_tree = __esm({
64343
+ "src/travel/apply-tree.ts"() {
64344
+ "use strict";
64345
+ init_chunk_store();
64346
+ init_tree_manifest();
64347
+ SYNC_STATE_FILE = ".travel/sync-state.json";
64348
+ DB_RE = /\.(db|sqlite)$/;
64349
+ }
64350
+ });
64351
+
64352
+ // src/travel/sqlite-snapshot.ts
64353
+ import { DatabaseSync as DatabaseSync18 } from "node:sqlite";
64354
+ import { readdirSync as readdirSync22, statSync as statSync23, mkdirSync as mkdirSync43 } from "node:fs";
64355
+ import { dirname as dirname41, join as join107 } from "node:path";
64356
+ function walkSqlite(root) {
64357
+ const found = [];
64358
+ const walk = (dir, prefix2) => {
64359
+ let entries2;
64360
+ try {
64361
+ entries2 = readdirSync22(dir);
64362
+ } catch {
64363
+ return;
64364
+ }
64365
+ for (const name of entries2) {
64366
+ const rel = prefix2 ? prefix2 + "/" + name : name;
64367
+ const full = join107(dir, name);
64368
+ let isDir;
64369
+ try {
64370
+ isDir = statSync23(full).isDirectory();
64371
+ } catch {
64372
+ continue;
64373
+ }
64374
+ if (excludeReason(rel, isDir)) continue;
64375
+ if (isDir) walk(full, rel);
64376
+ else if (/\.(db|sqlite)$/.test(name)) found.push(rel);
64377
+ }
64378
+ };
64379
+ walk(root, "");
64380
+ return found.sort();
64381
+ }
64382
+ async function snapshotDatabases(stateDir, stagingDir) {
64383
+ const listed = [];
64384
+ for (const rel of walkSqlite(stateDir)) {
64385
+ const target = join107(stagingDir, rel);
64386
+ mkdirSync43(dirname41(target), { recursive: true });
64387
+ const source = new DatabaseSync18(join107(stateDir, rel));
64388
+ source.exec(`VACUUM INTO '${target.replaceAll("'", "''")}'`);
64389
+ source.close();
64390
+ listed.push(rel);
64391
+ }
64392
+ return listed;
64393
+ }
64394
+ async function verifyDatabases(dir) {
64395
+ return walkSqlite(dir).map((file2) => {
64396
+ try {
64397
+ const db2 = new DatabaseSync18(join107(dir, file2));
64398
+ const row = db2.prepare("PRAGMA integrity_check").get();
64399
+ db2.close();
64400
+ return { file: file2, ok: row?.integrity_check === "ok" };
64401
+ } catch {
64402
+ return { file: file2, ok: false };
64403
+ }
64404
+ });
64405
+ }
64406
+ var init_sqlite_snapshot = __esm({
64407
+ "src/travel/sqlite-snapshot.ts"() {
64408
+ "use strict";
64409
+ init_exclusions();
64410
+ }
64411
+ });
64412
+
64413
+ // src/travel/sync-worker.ts
64414
+ var sync_worker_exports = {};
64415
+ __export(sync_worker_exports, {
64416
+ WorkerConnection: () => WorkerConnection,
64417
+ runWorker: () => runWorker
64418
+ });
64419
+ import { join as join108 } from "node:path";
64420
+ import { createHash as createHash48 } from "node:crypto";
64421
+ async function runWorker(stateDir) {
64422
+ const store = openChunkStore(join108(stateDir, ".travel/chunks"));
64423
+ const reader = new ProtocolReader();
64424
+ process.stdin.on("data", (chunk) => reader.push(chunk));
64425
+ process.stdin.on("end", () => reader.end());
64426
+ const ended = new Promise((resolve45) => process.stdin.on("end", resolve45));
64427
+ let pendingManifest = null;
64428
+ for (; ; ) {
64429
+ const line = await reader.readLine();
64430
+ if (line === null) break;
64431
+ let reply = null;
64432
+ try {
64433
+ const op = JSON.parse(line);
64434
+ switch (op.op) {
64435
+ case "hello":
64436
+ reply = { ok: true, version: 2, stateDir };
64437
+ break;
64438
+ case "has": {
64439
+ const refs = op.refs ?? [];
64440
+ if (!Array.isArray(refs) || refs.length > 128) throw new Error("TRAVEL_TOO_MANY_REFS");
64441
+ const missing = [];
64442
+ for (const ref of refs) {
64443
+ validateChunkRef(ref);
64444
+ if (!await store.has(ref.sha256)) missing.push(ref.sha256);
64445
+ }
64446
+ reply = { ok: true, missing };
64447
+ break;
64448
+ }
64449
+ case "put": {
64450
+ const sha2 = op.sha256, bytes = op.bytes;
64451
+ if (typeof sha2 !== "string" || !/^[a-f0-9]{64}$/.test(sha2) || !Number.isSafeInteger(bytes) || bytes < 1 || bytes > CHUNK_BYTES2) throw new Error("TRAVEL_INVALID_CHUNK");
64452
+ const body = await reader.readBytes(bytes);
64453
+ if (body.length !== bytes || sha2562(body) !== sha2) throw new Error("TRAVEL_CHUNK_MISMATCH");
64454
+ await store.put(body);
64455
+ reply = { ok: true };
64456
+ break;
64457
+ }
64458
+ case "manifest":
64459
+ pendingManifest = parseTreeManifest(op.manifest);
64460
+ reply = { ok: true, received: pendingManifest.files.length };
64461
+ break;
64462
+ case "state":
64463
+ reply = { ok: true, state: readSyncState(stateDir) };
64464
+ break;
64465
+ case "get": {
64466
+ const sha2 = op.sha256, bytes = op.bytes;
64467
+ if (typeof sha2 !== "string" || !/^[a-f0-9]{64}$/.test(sha2) || !Number.isSafeInteger(bytes) || bytes < 1 || bytes > CHUNK_BYTES2) throw new Error("TRAVEL_INVALID_CHUNK");
64468
+ const body = await store.read(sha2, bytes);
64469
+ process.stdout.write(JSON.stringify({ ok: true, bytes: body.length }) + "\n");
64470
+ await new Promise((resolve45) => process.stdout.write(body, () => resolve45()));
64471
+ reply = null;
64472
+ break;
64473
+ }
64474
+ case "capture": {
64475
+ const days = typeof op.mediaWindowDays === "number" && op.mediaWindowDays > 0 ? Math.min(90, Math.floor(op.mediaWindowDays)) : 0;
64476
+ pendingManifest = await buildTreeManifest(stateDir, store, { exclude: syncExcludeWithDays(days) });
64477
+ reply = { ok: true, manifest: pendingManifest };
64478
+ break;
64479
+ }
64480
+ case "verify": {
64481
+ const bad = (await verifyDatabases(stateDir)).filter((db2) => !db2.ok);
64482
+ reply = { ok: bad.length === 0, bad: bad.map((db2) => db2.file) };
64483
+ break;
64484
+ }
64485
+ case "apply": {
64486
+ if (!pendingManifest) throw new Error("TRAVEL_NO_MANIFEST");
64487
+ const result = await applyTree(stateDir, pendingManifest, store, readSyncState(stateDir));
64488
+ reply = { ok: true, ...result };
64489
+ break;
64490
+ }
64491
+ default:
64492
+ throw new Error("TRAVEL_INVALID_OP");
64493
+ }
64494
+ } catch (error) {
64495
+ const message = error instanceof Error ? error.message : String(error);
64496
+ reply = /^TRAVEL_[A-Z_]+$/.test(message) ? { error: message } : { error: "TRAVEL_WORKER_ERROR", detail: message };
64497
+ }
64498
+ if (reply) process.stdout.write(JSON.stringify(reply) + "\n");
64499
+ }
64500
+ await ended;
64501
+ }
64502
+ var sha2562, ProtocolReader, WorkerConnection;
64503
+ var init_sync_worker = __esm({
64504
+ "src/travel/sync-worker.ts"() {
64505
+ "use strict";
64506
+ init_chunk_store();
64507
+ init_tree_manifest();
64508
+ init_apply_tree();
64509
+ init_sqlite_snapshot();
64510
+ sha2562 = (body) => createHash48("sha256").update(body).digest("hex");
64511
+ ProtocolReader = class {
64512
+ buffer = [];
64513
+ buffered = 0;
64514
+ ended = false;
64515
+ waiter = null;
64516
+ push(chunk) {
64517
+ this.buffer.push(chunk);
64518
+ this.buffered += chunk.length;
64519
+ this.drain();
64520
+ }
64521
+ end() {
64522
+ this.ended = true;
64523
+ this.drain();
64524
+ }
64525
+ readLine() {
64526
+ if (this.waiter) throw new Error("TRAVEL_PROTOCOL_BUSY");
64527
+ return new Promise((resolve45) => {
64528
+ this.waiter = { kind: "line", resolve: resolve45 };
64529
+ this.drain();
64530
+ });
64531
+ }
64532
+ readBytes(count) {
64533
+ if (this.waiter) throw new Error("TRAVEL_PROTOCOL_BUSY");
64534
+ return new Promise((resolve45) => {
64535
+ this.waiter = { kind: "bytes", count, resolve: resolve45 };
64536
+ this.drain();
64537
+ });
64538
+ }
64539
+ drain() {
64540
+ while (this.waiter) {
64541
+ if (this.waiter.kind === "line") {
64542
+ const total = Buffer.concat(this.buffer);
64543
+ const newline = total.indexOf(10);
64544
+ if (newline >= 0) {
64545
+ const line = total.subarray(0, newline).toString("utf8");
64546
+ const rest = total.subarray(newline + 1);
64547
+ this.buffer = rest.length ? [rest] : [];
64548
+ this.buffered = rest.length;
64549
+ const resolve45 = this.waiter.resolve;
64550
+ this.waiter = null;
64551
+ resolve45(line);
64552
+ continue;
64553
+ }
64554
+ break;
64555
+ }
64556
+ if (this.buffered >= this.waiter.count) {
64557
+ const total = Buffer.concat(this.buffer);
64558
+ const body = total.subarray(0, this.waiter.count);
64559
+ const rest = total.subarray(this.waiter.count);
64560
+ this.buffer = rest.length ? [rest] : [];
64561
+ this.buffered = rest.length;
64562
+ const resolve45 = this.waiter.resolve;
64563
+ this.waiter = null;
64564
+ resolve45(body);
64565
+ continue;
64566
+ }
64567
+ break;
64568
+ }
64569
+ if (!this.waiter || this.waiter.kind !== "line") return;
64570
+ if (this.ended && this.buffered === 0) {
64571
+ const resolve45 = this.waiter.resolve;
64572
+ this.waiter = null;
64573
+ resolve45(null);
64574
+ }
64575
+ }
64576
+ };
64577
+ WorkerConnection = class _WorkerConnection {
64578
+ constructor(child) {
64579
+ this.child = child;
64580
+ child.stdout.on("data", (chunk) => this.reader.push(chunk));
64581
+ child.stdout.on("end", () => this.reader.end());
64582
+ }
64583
+ reader = new ProtocolReader();
64584
+ chain = Promise.resolve();
64585
+ static from(child) {
64586
+ return new _WorkerConnection(child);
64587
+ }
64588
+ enqueue(operation) {
64589
+ const next = this.chain.then(operation, operation);
64590
+ this.chain = next.catch(() => {
64591
+ });
64592
+ return next;
64593
+ }
64594
+ request(header, payload) {
64595
+ return this.enqueue(async () => {
64596
+ const written = new Promise((resolve45) => this.child.stdin.write(JSON.stringify(header) + "\n", () => resolve45()));
64597
+ await written;
64598
+ if (payload) await new Promise((resolve45) => this.child.stdin.write(payload, () => resolve45()));
64599
+ const line = await this.reader.readLine();
64600
+ if (line === null) throw new Error("TRAVEL_CONNECTION_CLOSED");
64601
+ const reply = JSON.parse(line);
64602
+ if (reply?.error) throw new Error(reply.detail ? `${reply.error}: ${reply.detail}` : reply.error);
64603
+ return reply;
64604
+ });
64605
+ }
64606
+ hello() {
64607
+ return this.request({ op: "hello" });
64608
+ }
64609
+ async has(refs) {
64610
+ return (await this.request({ op: "has", refs })).missing;
64611
+ }
64612
+ async put(sha2563, bytes, body) {
64613
+ await this.request({ op: "put", sha256: sha2563, bytes }, body);
64614
+ }
64615
+ /** 拉块:应答行后跟原始明文字节(to-local 方向)。 */
64616
+ async get(sha2563, bytes) {
64617
+ return this.enqueue(async () => {
64618
+ this.child.stdin.write(JSON.stringify({ op: "get", sha256: sha2563, bytes }) + "\n");
64619
+ const line = await this.reader.readLine();
64620
+ if (line === null) throw new Error("TRAVEL_CONNECTION_CLOSED");
64621
+ const reply = JSON.parse(line);
64622
+ if (reply?.error) throw new Error(reply.detail ? `${reply.error}: ${reply.detail}` : reply.error);
64623
+ return await this.reader.readBytes(reply.bytes);
64624
+ });
64625
+ }
64626
+ async manifest(manifest) {
64627
+ return (await this.request({ op: "manifest", manifest })).received;
64628
+ }
64629
+ async state() {
64630
+ return (await this.request({ op: "state" })).state ?? null;
64631
+ }
64632
+ apply() {
64633
+ return this.request({ op: "apply" });
64634
+ }
64635
+ /** 对端自捕获树清单(to-local 方向:清单+块都在对端仓)。mediaWindowDays>0 时
64636
+ * 带回落期间新收的用户媒体(1122 方向规则)。 */
64637
+ async capture(mediaWindowDays = 0) {
64638
+ return (await this.request({ op: "capture", mediaWindowDays })).manifest;
64639
+ }
64640
+ async verify() {
64641
+ return (await this.request({ op: "verify" })).bad ?? [];
64642
+ }
64643
+ async close() {
64644
+ try {
64645
+ this.child.stdin.end();
64646
+ } catch {
64647
+ }
64648
+ await new Promise((resolve45) => this.child.on("exit", () => resolve45()));
64649
+ }
64650
+ };
64651
+ }
64652
+ });
64653
+
64654
+ // src/travel/sync-v2.ts
64655
+ var sync_v2_exports = {};
64656
+ __export(sync_v2_exports, {
64657
+ SSH_BASE_OPTS: () => SSH_BASE_OPTS,
64658
+ runSyncV2: () => runSyncV2
64659
+ });
64660
+ import { spawn as spawn6 } from "node:child_process";
64661
+ import { readFileSync as readFileSync77, writeFileSync as writeFileSync47, mkdirSync as mkdirSync44 } from "node:fs";
64662
+ import { join as join109, resolve as resolve40 } from "node:path";
64663
+ function stateDirFromConfig(configPath) {
64664
+ if (!configPath) throw new Error("\u9700\u8981 --config \u6216 stateDirOverride");
64665
+ const config = JSON.parse(readFileSync77(configPath, "utf8"));
64666
+ if (!config.stateDir) throw new Error("\u914D\u7F6E\u7F3A\u5C11 stateDir");
64667
+ return config.stateDir;
64668
+ }
64669
+ function spawnSsh(host, command, index, sshOpts) {
64670
+ const child = spawn6("ssh", [...sshOpts, host, command], { stdio: ["pipe", "pipe", "pipe"] });
64671
+ child.stderr?.on("data", (chunk) => {
64672
+ const text4 = chunk.toString("utf8").trim();
64673
+ if (text4) console.warn(`[travel-sync-worker#${index} ssh] ${text4}`);
64674
+ });
64675
+ return child;
64676
+ }
64677
+ async function pumpAll(items, workers, run, onDone) {
64678
+ const queues = workers.map(() => []);
64679
+ items.forEach((item, index) => queues[index % workers.length].push(item));
64680
+ const failures = [];
64681
+ await Promise.all(workers.map(async (worker, slot) => {
64682
+ for (const item of queues[slot]) {
64683
+ for (let attempt = 0; ; attempt++) {
64684
+ try {
64685
+ await run(worker, item);
64686
+ onDone?.(item);
64687
+ break;
64688
+ } catch (error) {
64689
+ if (attempt >= 2) {
64690
+ failures.push({ item, error });
64691
+ break;
64692
+ }
64693
+ }
64694
+ }
64695
+ }
64696
+ }));
64697
+ if (failures.length) {
64698
+ const first = failures[0].error;
64699
+ throw new Error(`TRAVEL_CHUNK_PUMP_FAILED (${failures.length} \u9879\u5931\u8D25)\uFF1A${first instanceof Error ? first.message : String(first)}`);
64700
+ }
64701
+ }
64702
+ function splitBatches(items, size) {
64703
+ const batches = [];
64704
+ for (let offset = 0; offset < items.length; offset += size) batches.push(items.slice(offset, offset + size));
64705
+ return batches;
64706
+ }
64707
+ async function captureLocalTree(stateDir, store, pre) {
64708
+ if (!pre) return buildTreeManifest(stateDir, store, { exclude: syncExcludeToCloud });
64709
+ const staged = join109(stateDir, ".travel-sync-staging");
64710
+ const { rmSync: rmSync10 } = await import("node:fs");
64711
+ rmSync10(staged, { recursive: true, force: true });
64712
+ const databases = await snapshotDatabases(stateDir, staged);
64713
+ const liveDb = /\.(db|sqlite)(-wal|-shm)?$/i;
64714
+ const main2 = await buildTreeManifest(stateDir, store, {
64715
+ exclude: (rel, isDir, size, mtimeMs) => liveDb.test(rel.split("/").pop() ?? "") ? "live database replaced by VACUUM snapshot" : syncExcludeToCloud(rel, isDir, size, mtimeMs)
64716
+ });
64717
+ if (databases.length) {
64718
+ const stagedManifest = await buildTreeManifest(staged, store);
64719
+ const merged = new Map(main2.files.map((file2) => [file2.rel, file2]));
64720
+ for (const file2 of stagedManifest.files) merged.set(file2.rel, file2);
64721
+ main2.files = [...merged.values()].sort((a, b) => a.rel < b.rel ? -1 : 1);
64722
+ rmSync10(staged, { recursive: true, force: true });
64723
+ }
64724
+ return main2;
64725
+ }
64726
+ async function runSyncV2(options) {
64727
+ const started = Date.now();
64728
+ const log = options.log ?? (() => {
64729
+ });
64730
+ const stateDir = resolve40(options.stateDirOverride ?? stateDirFromConfig(options.configPath));
64731
+ const parallel = Math.max(1, Math.min(8, options.parallel ?? 6));
64732
+ const sshOpts = options.sshOpts ?? SSH_BASE_OPTS;
64733
+ const spawnRemote = options.spawnRemote ?? ((_command, index, opts) => spawnSsh(options.host, _command, index, opts));
64734
+ const remoteCommand = `engine7 travel-sync-worker --state-dir '${options.remoteRoot.replace(/'/g, "'\\''")}'`;
64735
+ const openRemote = () => WorkerConnection.from(spawnRemote(remoteCommand, 0, sshOpts));
64736
+ const store = openChunkStore(join109(stateDir, ".travel/chunks"));
64737
+ const control2 = openRemote();
64738
+ try {
64739
+ const hello = await control2.hello();
64740
+ if (hello.version !== 2) throw new Error(`TRAVEL_PROTOCOL_MISMATCH\uFF08\u5BF9\u7AEF v${hello.version}\uFF0C\u9700\u8981 v2\u2014\u2014\u5347\u7EA7\u5BF9\u7AEF engine7\uFF09`);
64741
+ log(`[sync-v2] ${options.direction} \u901A\u9053\u5C31\u7EEA\uFF08${options.host}\uFF09`);
64742
+ let manifest;
64743
+ let applied;
64744
+ let deleted;
64745
+ let chunksPushed = 0, chunkBytes = 0;
64746
+ const reportManifest = (m) => {
64747
+ const byTop = /* @__PURE__ */ new Map();
64748
+ for (const file2 of m.files) {
64749
+ const top = file2.rel.split("/")[0];
64750
+ byTop.set(top, (byTop.get(top) ?? 0) + file2.content.bytes);
64751
+ }
64752
+ const tops = [...byTop.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6).map(([dir, bytes]) => `${dir}:${(bytes / 1048576).toFixed(0)}MB`).join(" ");
64753
+ const total = [...byTop.values()].reduce((sum, bytes) => sum + bytes, 0);
64754
+ log(`[sync-v2] \u6E05\u5355\u6784\u6210 ${(total / 1048576).toFixed(0)}MB \u2014\u2014 ${tops}`);
64755
+ };
64756
+ if (options.direction === "to-cloud") {
64757
+ log("[sync-v2] \u2460 \u672C\u5730\u6811\u6355\u83B7" + (options.pre ? "\uFF08--pre\uFF1A\u6D3B\u8DC3\u5E93\u8D70 VACUUM \u5FEB\u7167\uFF09" : "\uFF08\u9759\u6B62\u76F4\u4F20 db+wal\uFF09"));
64758
+ manifest = await captureLocalTree(stateDir, store, options.pre === true);
64759
+ log(`[sync-v2] \u6E05\u5355 ${manifest.files.length} \u6587\u4EF6 / \u6392\u9664 ${manifest.excluded.length} \u9879`);
64760
+ reportManifest(manifest);
64761
+ const allRefs = /* @__PURE__ */ new Map();
64762
+ for (const file2 of manifest.files) for (const ref of file2.content.chunks) allRefs.set(ref.sha256, ref);
64763
+ const refs = [...allRefs.values()];
64764
+ const missing = /* @__PURE__ */ new Set();
64765
+ for (const batch of splitBatches(refs, 128)) for (const sha2 of await control2.has(batch)) missing.add(sha2);
64766
+ log(`[sync-v2] \u2461 \u5BF9\u7AEF\u7F3A ${missing.size}/${refs.length} \u5757`);
64767
+ if (missing.size) {
64768
+ const pushers = [];
64769
+ for (let index = 0; index < parallel; index++) pushers.push(index === 0 ? control2 : WorkerConnection.from(spawnRemote(remoteCommand, index + 1, sshOpts)));
64770
+ try {
64771
+ const toPush = refs.filter((ref) => missing.has(ref.sha256));
64772
+ await pumpAll(toPush, pushers, async (worker, ref) => {
64773
+ const body = await store.read(ref.sha256, ref.bytes);
64774
+ await worker.put(ref.sha256, ref.bytes, body);
64775
+ chunksPushed++;
64776
+ chunkBytes += ref.bytes;
64777
+ });
64778
+ } finally {
64779
+ for (const pusher of pushers) if (pusher !== control2) await pusher.close().catch(() => {
64780
+ });
64781
+ }
64782
+ }
64783
+ log(`[sync-v2] \u2462 \u63A8\u5757\u5B8C\u6210 ${chunksPushed} \u5757 / ${(chunkBytes / 1048576).toFixed(1)}MB`);
64784
+ await control2.manifest(manifest);
64785
+ const result = await control2.apply();
64786
+ applied = result.applied;
64787
+ deleted = result.deleted;
64788
+ log(`[sync-v2] \u2463 \u5BF9\u7AEF\u843D\u4F4D applied=${applied} deleted=${deleted.length}`);
64789
+ const bad = await control2.verify();
64790
+ if (bad.length) throw new Error(`TRAVEL_REMOTE_VERIFY_FAILED: ${bad.join(", ")}`);
64791
+ log("[sync-v2] \u2464 \u5BF9\u7AEF\u5E93\u5B8C\u6574\u6027\u6821\u9A8C\u901A\u8FC7");
64792
+ } else {
64793
+ log("[sync-v2] \u2460 \u5BF9\u7AEF\u6811\u81EA\u6355\u83B7\uFF08\u56DE\u7A0B\u5A92\u4F53\u7A97\u53E3 14 \u5929\uFF09");
64794
+ manifest = await control2.capture(14);
64795
+ log(`[sync-v2] \u6E05\u5355 ${manifest.files.length} \u6587\u4EF6 / \u6392\u9664 ${manifest.excluded.length} \u9879`);
64796
+ reportManifest(manifest);
64797
+ const allRefs = /* @__PURE__ */ new Map();
64798
+ for (const file2 of manifest.files) for (const ref of file2.content.chunks) allRefs.set(ref.sha256, ref);
64799
+ const refs = [...allRefs.values()];
64800
+ const missing = [];
64801
+ for (const ref of refs) if (!await store.has(ref.sha256)) missing.push(ref);
64802
+ log(`[sync-v2] \u2461 \u672C\u5730\u7F3A ${missing.length}/${refs.length} \u5757`);
64803
+ if (missing.length) {
64804
+ const pullers = [];
64805
+ for (let index = 0; index < parallel; index++) pullers.push(index === 0 ? control2 : WorkerConnection.from(spawnRemote(remoteCommand, index + 1, sshOpts)));
64806
+ try {
64807
+ await pumpAll(missing, pullers, async (worker, ref) => {
64808
+ const body = await worker.get(ref.sha256, ref.bytes);
64809
+ if (body.length !== ref.bytes) throw new Error("TRAVEL_CHUNK_MISMATCH");
64810
+ await store.put(body);
64811
+ chunksPushed++;
64812
+ chunkBytes += ref.bytes;
64813
+ });
64814
+ } finally {
64815
+ for (const puller of pullers) if (puller !== control2) await puller.close().catch(() => {
64816
+ });
64817
+ }
64818
+ }
64819
+ log(`[sync-v2] \u2462 \u62C9\u5757\u5B8C\u6210 ${chunksPushed} \u5757 / ${(chunkBytes / 1048576).toFixed(1)}MB`);
64820
+ const result = await applyTree(stateDir, manifest, store, readSyncState(stateDir));
64821
+ applied = result.applied;
64822
+ deleted = result.deleted;
64823
+ log(`[sync-v2] \u2463 \u672C\u5730\u843D\u4F4D applied=${applied} deleted=${deleted.length}`);
64824
+ const bad = (await verifyDatabases(stateDir)).filter((db2) => !db2.ok);
64825
+ if (bad.length) throw new Error(`TRAVEL_LOCAL_VERIFY_FAILED: ${bad.map((db2) => db2.file).join(", ")}`);
64826
+ log("[sync-v2] \u2464 \u672C\u5730\u5E93\u5B8C\u6574\u6027\u6821\u9A8C\u901A\u8FC7");
64827
+ }
64828
+ const totalBytes = manifest.files.reduce((sum, file2) => sum + file2.content.bytes, 0);
64829
+ const summary3 = {
64830
+ files: manifest.files.length,
64831
+ bytes: totalBytes,
64832
+ chunksPushed,
64833
+ chunkBytes,
64834
+ deleted,
64835
+ applied,
64836
+ excluded: manifest.excluded,
64837
+ durationMs: Date.now() - started
64838
+ };
64839
+ mkdirSync44(join109(stateDir, ".travel"), { recursive: true });
64840
+ writeFileSync47(join109(stateDir, ".travel/last-sync.json"), JSON.stringify({ ...summary3, direction: options.direction, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 1));
64841
+ return summary3;
64842
+ } finally {
64843
+ await control2.close().catch(() => {
64844
+ });
64845
+ }
64846
+ }
64847
+ var SSH_BASE_OPTS;
64848
+ var init_sync_v2 = __esm({
64849
+ "src/travel/sync-v2.ts"() {
64850
+ "use strict";
64851
+ init_chunk_store();
64852
+ init_tree_manifest();
64853
+ init_apply_tree();
64854
+ init_sync_worker();
64855
+ init_exclusions();
64856
+ init_sqlite_snapshot();
64857
+ SSH_BASE_OPTS = [
64858
+ "-o",
64859
+ "ServerAliveInterval=15",
64860
+ "-o",
64861
+ "ServerAliveCountMax=4",
64862
+ "-o",
64863
+ "TCPKeepAlive=yes",
64864
+ "-o",
64865
+ "ConnectTimeout=10"
64866
+ ];
64867
+ }
64868
+ });
64869
+
64870
+ // src/travel/move.ts
64871
+ var move_exports = {};
64872
+ __export(move_exports, {
64873
+ cancelRunningMove: () => cancelRunningMove,
64874
+ matchEnginePids: () => matchEnginePids,
64875
+ rollbackPermitted: () => rollbackPermitted,
64876
+ runTravelMove: () => runTravelMove,
64877
+ writeMoveStatus: () => writeMoveStatus
64878
+ });
64879
+ import { readFileSync as readFileSync78, writeFileSync as writeFileSync48, mkdirSync as mkdirSync45, rmSync as rmSync7 } from "node:fs";
64880
+ import { randomUUID as randomUUID39 } from "node:crypto";
64881
+ import { join as join110, resolve as resolve41 } from "node:path";
64882
+ function writeMoveStatus(stateDir, step) {
64883
+ try {
64884
+ mkdirSync45(join110(stateDir, ".travel"), { recursive: true });
64885
+ writeFileSync48(join110(stateDir, ".travel", "status.json"), JSON.stringify({ step, updatedAt: Date.now() }));
64886
+ } catch {
64887
+ }
64888
+ }
64889
+ async function matchEnginePids(options) {
64890
+ const { run, absoluteConfig, stateDir } = options;
64891
+ const readPidFile = options.readPidFile ?? (() => {
64892
+ try {
64893
+ return readFileSync78(join110(stateDir, ".engine.pid"), "utf8").trim() || null;
64894
+ } catch {
64895
+ return null;
64896
+ }
64897
+ });
64898
+ const { stdout } = await run("bash", ["-c", `ps aux | grep -- "--engine-config" | grep -v grep || true`]);
64899
+ const candidates2 = stdout.split("\n").filter((line) => line.includes("--engine-config")).map((line) => Number(line.trim().split(/\s+/)[1])).filter((pid) => Number.isSafeInteger(pid) && pid > 0);
64900
+ const pids = /* @__PURE__ */ new Set();
64901
+ const commandOf = async (pid) => {
64902
+ try {
64903
+ const { stdout: stdout2 } = await run("bash", ["-c", `ps -o command= -p ${pid}`]);
64904
+ return stdout2.trim();
64905
+ } catch {
64906
+ return "";
64907
+ }
64908
+ };
64909
+ for (const pid of candidates2) {
64910
+ const command = await commandOf(pid);
64911
+ const match = /--engine-config\s+(\S+)/.exec(command);
64912
+ if (!match) continue;
64913
+ let cwdMatches = false;
64914
+ try {
64915
+ const { stdout: cwdOut } = await run("bash", ["-c", `lsof -a -p ${pid} -d cwd -Fn 2>/dev/null | grep '^n' | cut -c2- || true`]);
64916
+ const cwd = cwdOut.trim().split("\n")[0];
64917
+ cwdMatches = !!cwd && resolve41(cwd, match[1]) === absoluteConfig;
64918
+ } catch {
64919
+ }
64920
+ const pidFileMatches = (() => {
64921
+ const pidFromFile2 = Number(readPidFile(stateDir));
64922
+ return Number.isSafeInteger(pidFromFile2) && pidFromFile2 === pid;
64923
+ })();
64924
+ if (cwdMatches || pidFileMatches) pids.add(pid);
64925
+ }
64926
+ const pidFromFile = Number(readPidFile(stateDir));
64927
+ if (Number.isSafeInteger(pidFromFile) && pidFromFile > 0 && !pids.has(pidFromFile)) {
64928
+ const command = await commandOf(pidFromFile);
64929
+ if (command.includes("--engine-config")) pids.add(pidFromFile);
64930
+ }
64931
+ return [...pids];
64932
+ }
64933
+ function rollbackPermitted(stateDir, token) {
64934
+ if (!stateDir) return { ok: true, why: "" };
64935
+ let current2 = null;
64936
+ try {
64937
+ current2 = JSON.parse(readFileSync78(moveTokenPath(stateDir), "utf8"));
64938
+ } catch {
64939
+ current2 = null;
64940
+ }
64941
+ if (!current2 || current2.id !== token.id) return { ok: false, why: "move-token \u5DF2\u88AB\u63A5\u7BA1\u6216\u6D88\u5931" };
64942
+ try {
64943
+ const status = JSON.parse(readFileSync78(join110(stateDir, ".travel/status.json"), "utf8"));
64944
+ if (typeof status.updatedAt === "number" && status.updatedAt > token.startedAt && String(status.step ?? "").startsWith("\u2705")) {
64945
+ return { ok: false, why: "\u6B64\u540E\u5DF2\u6709\u4E00\u6B21\u6210\u529F\u7684\u642C\u79FB\uFF08\u2705\uFF09" };
64946
+ }
64947
+ } catch {
64948
+ }
64949
+ return { ok: true, why: "" };
64950
+ }
64951
+ function acquireMoveLock(stateDir) {
64952
+ mkdirSync45(join110(stateDir, ".travel"), { recursive: true });
64953
+ const lockPath2 = moveLockPath(stateDir);
64954
+ try {
64955
+ const existing = JSON.parse(readFileSync78(lockPath2, "utf8"));
64956
+ if (Number.isSafeInteger(existing?.pid) && existing.pid > 0) {
64957
+ let alive4 = true;
64958
+ try {
64959
+ process.kill(existing.pid, 0);
64960
+ } catch (error) {
64961
+ alive4 = error.code !== "ESRCH";
64962
+ }
64963
+ if (alive4) throw new Error(`TRAVEL_MOVE_LOCKED\uFF08pid=${existing.pid}\uFF09\u2014\u2014\u5DF2\u6709\u642C\u79FB\u5728\u8FDB\u884C\uFF1Bengine7 travel-move --cancel \u53EF\u53D6\u6D88`);
64964
+ console.warn(`[travel-move] \u63A5\u7BA1\u6B7B\u8FDB\u7A0B\u9501\uFF08pid=${existing.pid}\uFF09`);
64965
+ }
64966
+ } catch (error) {
64967
+ const message = error instanceof Error ? error.message : String(error);
64968
+ if (message.startsWith("TRAVEL_MOVE_LOCKED")) throw error;
64969
+ if (error?.code !== "ENOENT") console.warn(`[travel-move] \u9501\u6587\u4EF6\u5F02\u5E38\uFF0C\u91CD\u5EFA\uFF08${message}\uFF09`);
64970
+ }
64971
+ writeFileSync48(lockPath2, JSON.stringify({ pid: process.pid, at: Date.now() }));
64972
+ }
64973
+ function moveLockIsOurs(stateDir) {
64974
+ try {
64975
+ return JSON.parse(readFileSync78(moveLockPath(stateDir), "utf8")).pid === process.pid;
64976
+ } catch {
64977
+ return false;
64978
+ }
64979
+ }
64980
+ function cancelRunningMove(stateDir) {
64981
+ let pid = null;
64982
+ try {
64983
+ pid = JSON.parse(readFileSync78(moveLockPath(stateDir), "utf8")).pid ?? null;
64984
+ } catch {
64985
+ return { note: "\u65E0\u642C\u79FB\u9501\uFF08\u6CA1\u6709\u8FDB\u884C\u4E2D\u7684\u642C\u79FB\uFF09" };
64986
+ }
64987
+ if (!Number.isSafeInteger(pid) || pid <= 0) return { note: "\u9501\u6587\u4EF6\u65E0\u6709\u6548 pid" };
64988
+ try {
64989
+ process.kill(pid, "SIGTERM");
64990
+ } catch (error) {
64991
+ if (error?.code !== "ESRCH") return { note: `\u6740 pid=${pid} \u5931\u8D25\uFF1A${error.message}` };
64992
+ }
64993
+ try {
64994
+ rmSync7(moveLockPath(stateDir), { force: true });
64995
+ } catch {
64996
+ }
64997
+ writeMoveStatus(stateDir, "\u26D4 \u5DF2\u53D6\u6D88\uFF08--cancel\uFF09");
64998
+ return { note: `\u5DF2\u53D6\u6D88 pid=${pid}` };
64999
+ }
65000
+ async function runTravelMove(options) {
65001
+ const log = options.log ?? (() => {
65002
+ });
65003
+ const direction = options.to === "cloud" ? "to-cloud" : "to-local";
65004
+ const steps = options.steps ?? await defaultSteps(log);
65005
+ const where = options.to === "cloud" ? "\u4E91\u7AEF" : "\u672C\u673A";
65006
+ const stateDir = (() => {
65007
+ try {
65008
+ return String(JSON.parse(readFileSync78(resolve41(options.configPath), "utf8")).stateDir ?? "");
65009
+ } catch {
65010
+ return "";
65011
+ }
65012
+ })();
65013
+ const token = { id: randomUUID39(), startedAt: Date.now(), direction };
65014
+ let locked = false;
65015
+ if (stateDir) {
65016
+ acquireMoveLock(stateDir);
65017
+ locked = true;
65018
+ try {
65019
+ writeFileSync48(moveTokenPath(stateDir), JSON.stringify(token));
65020
+ } catch {
65021
+ }
65022
+ }
65023
+ const mark = (step) => {
65024
+ if (stateDir) writeMoveStatus(stateDir, step);
65025
+ options.onStep?.(step);
65026
+ };
65027
+ try {
65028
+ log(`[travel-move] \u2460 \u6392\u5E72\u5E76\u505C${options.to === "cloud" ? "\u672C\u673A" : "\u4E91\u7AEF"}\u5F15\u64CE`);
65029
+ mark("\u2460 \u505C\u5F15\u64CE");
65030
+ await steps.drainAndStop(options.configPath, direction, options.host, options.remoteRoot);
65031
+ log("[travel-move] \u2461 \u9759\u6B62\u589E\u91CF\u540C\u6B65");
65032
+ mark("\u2461 \u589E\u91CF\u540C\u6B65");
65033
+ await steps.sync(options.configPath, direction, options.host, options.remoteRoot);
65034
+ log(`[travel-move] \u2462 \u542F\u52A8${where}\u5F15\u64CE`);
65035
+ mark(`\u2462 \u542F\u52A8${where}\u5F15\u64CE`);
65036
+ await steps.startRemote(direction, options.host, options.remoteRoot, options.configPath);
65037
+ log("[travel-move] \u2463 \u5192\u70DF\u9A8C\u6536\uFF08N/N adapters + \u901A\u9053\u8FDE\u901A\uFF09");
65038
+ mark("\u2463 \u5192\u70DF\u9A8C\u6536");
65039
+ await steps.smoke(direction, options.host, options.remoteRoot, options.configPath);
65040
+ log(`[travel-move] \u2705 \u5DF2\u5207\u6362\u5230${where}`);
65041
+ mark(`\u2705 \u5DF2\u5207\u6362\u5230${where}`);
65042
+ return { outcome: "moved", detail: `switched ${direction}` };
65043
+ } catch (error) {
65044
+ const reason = error instanceof Error ? error.message : String(error);
65045
+ const guard = rollbackPermitted(stateDir, token);
65046
+ if (!guard.ok) {
65047
+ log(`[travel-move] \u26D4 \u62D2\u7EDD\u56DE\u6EDA\uFF08${guard.why}\uFF09\u2014\u2014\u672C\u6B21\u642C\u79FB\u5DF2\u8FC7\u671F\uFF0C\u4E24\u7AEF\u72B6\u6001\u4EE5\u76D8\u4E0A\u4E3A\u51C6\uFF1B\u5931\u8D25\u539F\u56E0\uFF1A${reason}`);
65048
+ if (stateDir) writeMoveStatus(stateDir, `\u26D4 \u62D2\u7EDD\u56DE\u6EDA\uFF08${guard.why}\uFF09\uFF1A${reason.slice(0, 100)}`);
65049
+ options.onStep?.("\u274C");
65050
+ return { outcome: "rolled-back", detail: `refused stale rollback\uFF08${guard.why}\uFF09\uFF1A${reason}` };
65051
+ }
65052
+ log(`[travel-move] \u274C \u5931\u8D25\uFF1A${reason} \u2014\u2014 \u56DE\u6EDA\u6E90\u7AEF`);
65053
+ if (stateDir) writeMoveStatus(stateDir, `\u274C \u5931\u8D25\u56DE\u6EDA\uFF1A${reason.slice(0, 120)}`);
65054
+ options.onStep?.("\u274C");
65055
+ try {
65056
+ if (direction === "to-cloud") {
65057
+ try {
65058
+ await steps.stopRemote?.(direction, options.host, options.remoteRoot, options.configPath);
65059
+ } catch (stopError) {
65060
+ log(`[travel-move] \u26A0\uFE0F \u505C\u4E91\u673A\u5931\u8D25\uFF08${stopError instanceof Error ? stopError.message : String(stopError)}\uFF09\u2014\u2014\u7EE7\u7EED\u6062\u590D\u672C\u673A`);
65061
+ }
65062
+ } else {
65063
+ try {
65064
+ await steps.stopLocal?.(options.configPath);
65065
+ } catch {
65066
+ }
65067
+ await steps.startRemote("to-cloud", options.host, options.remoteRoot, options.configPath);
65068
+ log("[travel-move] \u21A9\uFE0F \u6E90\u7AEF\uFF08\u4E91\u7AEF\uFF09\u5DF2\u6062\u590D\u8FD0\u884C");
65069
+ return { outcome: "rolled-back", detail: reason };
65070
+ }
65071
+ await steps.startLocal(options.configPath);
65072
+ log("[travel-move] \u21A9\uFE0F \u6E90\u7AEF\u5DF2\u6062\u590D\u8FD0\u884C");
65073
+ return { outcome: "rolled-back", detail: reason };
65074
+ } catch (rollbackError) {
65075
+ const rollbackReason = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
65076
+ log(`[travel-move] \u{1F534}\u{1F534} \u4E24\u7AEF\u90FD\u65E0\u6CD5\u542F\u52A8\uFF01\u5207\u6362\u5931\u8D25=${reason}\uFF1B\u56DE\u6EDA\u5931\u8D25=${rollbackReason} \u2014\u2014 \u9700\u4EBA\u5DE5\u4ECB\u5165`);
65077
+ return { outcome: "rolled-back", detail: `\u4E24\u7AEF\u90FD\u65E0\u6CD5\u542F\u52A8\uFF1A\u5207\u6362\u5931\u8D25=${reason}\uFF1B\u56DE\u6EDA\u5931\u8D25=${rollbackReason}` };
65078
+ }
65079
+ } finally {
65080
+ if (locked && stateDir && moveLockIsOurs(stateDir)) {
65081
+ try {
65082
+ rmSync7(moveLockPath(stateDir), { force: true });
65083
+ } catch {
65084
+ }
65085
+ }
65086
+ }
65087
+ }
65088
+ async function defaultSteps(log = () => {
65089
+ }) {
65090
+ const { execFile: execFile7 } = await import("node:child_process");
65091
+ const { promisify: promisify8 } = await import("node:util");
65092
+ const exec3 = promisify8(execFile7);
65093
+ const { basename: basename23 } = await import("node:path");
65094
+ const run = (command, args, options) => exec3(command, args, { maxBuffer: 32 * 1024 * 1024, ...options });
65095
+ const engineConfigPath = (configPath) => resolve41(configPath);
65096
+ const stateDirOf = (configPath) => {
65097
+ const config = JSON.parse(readFileSync78(engineConfigPath(configPath), "utf8"));
65098
+ return typeof config.stateDir === "string" ? config.stateDir : resolve41(engineConfigPath(configPath), "..", "..");
65099
+ };
65100
+ const tunnelDown = async (configPath) => {
65101
+ const { ensureTunnelDown: ensureTunnelDown2 } = await Promise.resolve().then(() => (init_gate2(), gate_exports2));
65102
+ await ensureTunnelDown2(stateDirOf(configPath));
65103
+ };
65104
+ let localChannelBaseline = null;
65105
+ const sshOptsOf = (_configPath) => ["-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4", "-o", "TCPKeepAlive=yes", "-o", "ConnectTimeout=10"];
65106
+ const withRetry = async (label, attempts, fn, guard) => {
65107
+ for (let i = 1; ; i++) {
65108
+ try {
65109
+ return await fn();
65110
+ } catch (error) {
65111
+ if (i >= attempts) throw error;
65112
+ if (guard && !guard()) throw new Error(`TRAVEL_MOVE_CANCELLED\uFF08${label}\uFF1A\u9501\u5DF2\u5931\u6548\uFF0C\u4E0D\u518D\u91CD\u8BD5\uFF09`);
65113
+ const reason = error instanceof Error ? error.message.slice(0, 160) : String(error);
65114
+ log(`[travel-move] ${label} \u7B2C ${i} \u6B21\u5931\u8D25\uFF08${reason}\uFF09\u2014\u2014\u91CD\u8BD5`);
65115
+ await new Promise((r) => setTimeout(r, 3e3 * i));
65116
+ }
65117
+ }
65118
+ };
65119
+ const stopLocalEngine = async (configPath) => {
65120
+ const absolute = engineConfigPath(configPath);
65121
+ const config = JSON.parse(readFileSync78(absolute, "utf8"));
65122
+ const stateDir = typeof config.stateDir === "string" ? config.stateDir : resolve41(absolute, "..", "..");
65123
+ const pids = await matchEnginePids({ run, absoluteConfig: absolute, stateDir });
65124
+ const port = config.api?.port ?? 16992;
65125
+ const portAlive = async () => {
65126
+ try {
65127
+ await run("curl", ["-sf", "-m", "2", `http://127.0.0.1:${port}/api/status`], { timeout: 5e3 });
65128
+ return true;
65129
+ } catch {
65130
+ return false;
65131
+ }
65132
+ };
65133
+ if (!pids.length) {
65134
+ if (await portAlive()) throw new Error(`\u5F15\u64CE\u7AEF\u53E3 ${port} \u6D3B\u7740\u4F46\u6309 ${absolute} \u627E\u4E0D\u5230\u8FDB\u7A0B\u2014\u2014\u5339\u914D\u5931\u8D25\uFF0C\u4E2D\u6B62\u5207\u6362\uFF08\u5C0F\u67EF P1-1\uFF09`);
65135
+ return;
65136
+ }
65137
+ for (const pid of pids) {
65138
+ try {
65139
+ process.kill(pid, "SIGTERM");
65140
+ } catch {
65141
+ }
65142
+ }
65143
+ const deadline = Date.now() + 9e4;
65144
+ let alive4 = () => pids.some((pid) => {
65145
+ try {
65146
+ process.kill(pid, 0);
65147
+ return true;
65148
+ } catch {
65149
+ return false;
65150
+ }
65151
+ });
65152
+ while (Date.now() < deadline && alive4()) await new Promise((r) => setTimeout(r, 1e3));
65153
+ for (const pid of pids) {
65154
+ try {
65155
+ process.kill(pid, "SIGKILL");
65156
+ } catch {
65157
+ }
65158
+ }
65159
+ await new Promise((r) => setTimeout(r, 2e3));
65160
+ if (alive4()) throw new Error(`\u672C\u673A\u5F15\u64CE\u672A\u80FD\u505C\u6B62\uFF08pids=${pids.join(",")}\uFF09\u2014\u2014\u4E2D\u6B62\u5207\u6362`);
65161
+ if (await portAlive()) throw new Error(`\u672C\u673A\u5F15\u64CE\u8FDB\u7A0B\u5DF2\u6740\u4F46\u7AEF\u53E3 ${port} \u4ECD\u6D3B\u2014\u2014\u53EF\u80FD\u5339\u914D\u6F0F\u6740\uFF0C\u4E2D\u6B62\u5207\u6362`);
65162
+ };
65163
+ return {
65164
+ async drainAndStop(configPath, direction, host, remoteRoot) {
65165
+ await tunnelDown(configPath);
65166
+ if (direction === "to-cloud") {
65167
+ const companion = JSON.parse(readFileSync78(engineConfigPath(configPath), "utf8")).agents?.defaults?.name ?? "companion";
65168
+ await run("ssh", [...sshOptsOf(configPath), host, `systemctl stop engine7-${unitIdFor(String(companion))}.service || true`], { timeout: 6e4 });
65169
+ try {
65170
+ const baselinePort = JSON.parse(readFileSync78(engineConfigPath(configPath), "utf8")).api?.port ?? 16992;
65171
+ const { stdout } = await run("curl", ["-sf", "-m", "3", `http://127.0.0.1:${baselinePort}/api/status`], { timeout: 5e3 });
65172
+ const channels = JSON.parse(stdout).channels;
65173
+ if (Array.isArray(channels)) localChannelBaseline = channels.map((c) => ({ name: c.name, enabled: c.enabled, hasCredentials: c.hasCredentials }));
65174
+ } catch {
65175
+ }
65176
+ await stopLocalEngine(configPath);
65177
+ } else {
65178
+ const companion = JSON.parse(readFileSync78(engineConfigPath(configPath), "utf8")).agents?.defaults?.name ?? "companion";
65179
+ await run("ssh", [...sshOptsOf(configPath), host, `systemctl stop engine7-${unitIdFor(String(companion))}.service`], { timeout: 6e4 });
65180
+ const deadline = Date.now() + 3e4;
65181
+ while (Date.now() < deadline) {
65182
+ const { stdout } = await run("ssh", [...sshOptsOf(configPath), host, `pgrep -f "${remoteRoot}/config[.]json" || true`], { timeout: 15e3 });
65183
+ if (!stdout.trim()) break;
65184
+ await new Promise((r) => setTimeout(r, 1e3));
65185
+ if (Date.now() >= deadline) throw new Error("\u8FDC\u7AEF\u5F15\u64CE 30 \u79D2\u5185\u672A\u505C\u6B62\u2014\u2014\u4E2D\u6B62\u5207\u6362");
65186
+ }
65187
+ }
65188
+ },
65189
+ async sync(configPath, direction, host, remoteRoot) {
65190
+ const stateDir = JSON.parse(readFileSync78(engineConfigPath(configPath), "utf8")).stateDir;
65191
+ if (!stateDir) throw new Error("config missing stateDir");
65192
+ const { runSyncV2: runSyncV22 } = await Promise.resolve().then(() => (init_sync_v2(), sync_v2_exports));
65193
+ await withRetry(
65194
+ direction === "to-cloud" ? "\u53BB\u7A0B\u5757\u540C\u6B65" : "\u56DE\u7A0B\u5757\u540C\u6B65",
65195
+ 2,
65196
+ () => runSyncV22({ direction, stateDirOverride: stateDir, host, remoteRoot, sshOpts: sshOptsOf(configPath), log: logQuiet }),
65197
+ () => moveLockIsOurs(stateDir)
65198
+ );
65199
+ },
65200
+ async startRemote(direction, host, remoteRoot, configPath) {
65201
+ if (direction === "to-local") {
65202
+ await tunnelDown(configPath);
65203
+ const stateDir = JSON.parse(readFileSync78(engineConfigPath(configPath), "utf8")).stateDir;
65204
+ const { spawn: spawn8 } = await import("node:child_process");
65205
+ const child = spawn8("engine7", ["start", "--config", engineConfigPath(configPath)], { detached: true, stdio: "ignore", cwd: stateDir });
65206
+ child.on("error", () => {
65207
+ });
65208
+ child.unref();
65209
+ } else {
65210
+ const companion = JSON.parse(readFileSync78(engineConfigPath(configPath), "utf8")).agents?.defaults?.name ?? "companion";
65211
+ await run("ssh", [...sshOptsOf(configPath), host, `systemctl start engine7-${unitIdFor(String(companion))}.service`], { timeout: 6e4 });
65212
+ }
65213
+ },
65214
+ async smoke(direction, host, remoteRoot, configPath) {
65215
+ const config = JSON.parse(readFileSync78(engineConfigPath(configPath), "utf8"));
65216
+ const port = config.api?.port ?? 16992;
65217
+ const expectedStateDir = direction === "to-cloud" ? remoteRoot : config.stateDir;
65218
+ const deadline = Date.now() + 9e4;
65219
+ while (Date.now() < deadline) {
65220
+ try {
65221
+ if (direction === "to-cloud") await run("ssh", [...sshOptsOf(configPath), host, `curl -sf -m 3 http://127.0.0.1:${port}/api/status > /dev/null`], { timeout: 1e4 });
65222
+ else await run("curl", ["-sf", "-m", "3", `http://127.0.0.1:${port}/api/status`], { timeout: 1e4 });
65223
+ break;
65224
+ } catch {
65225
+ await new Promise((r) => setTimeout(r, 3e3));
65226
+ }
65227
+ if (Date.now() >= deadline) throw new Error("\u5F15\u64CE 90 \u79D2\u5185\u672A\u5C31\u7EEA");
65228
+ }
65229
+ const { stdout } = direction === "to-cloud" ? await run("ssh", [...sshOptsOf(configPath), host, `curl -sf -m 5 http://127.0.0.1:${port}/api/status`], { timeout: 15e3 }) : await run("curl", ["-sf", "-m", "5", `http://127.0.0.1:${port}/api/status`], { timeout: 15e3 });
65230
+ const status = JSON.parse(stdout);
65231
+ if (status.stateDir !== expectedStateDir) throw new Error(`\u7AEF\u53E3 ${port} \u4E0A\u7684\u5F15\u64CE stateDir=${status.stateDir}\uFF0C\u9884\u671F ${expectedStateDir}\uFF08\u7591\u4F3C\u6B8B\u7559\u5B9E\u4F8B\uFF09`);
65232
+ const enabled = (status.channels ?? []).filter((c) => c.enabled);
65233
+ if (!enabled.length) throw new Error("\u6CA1\u6709\u5DF2\u542F\u7528\u7684\u901A\u9053");
65234
+ const baseline = new Map((localChannelBaseline ?? []).map((c) => [c.name, c]));
65235
+ const noCredentials = enabled.filter((c) => c.hasCredentials === false && baseline.get(c.name)?.hasCredentials === true);
65236
+ if (noCredentials.length) throw new Error(`\u901A\u9053\u51ED\u636E\u672A\u5C31\u4F4D: ${noCredentials.map((c) => c.name).join(",")}`);
65237
+ logQuiet(`smoke ok stateDir=${status.stateDir} channels=${enabled.map((c) => c.name).join(",")}`);
65238
+ },
65239
+ async stopRemote(_direction, host, remoteRoot, configPath) {
65240
+ const companion = JSON.parse(readFileSync78(engineConfigPath(configPath), "utf8")).agents?.defaults?.name ?? "companion";
65241
+ await run("ssh", [...sshOptsOf(configPath), host, `systemctl stop engine7-${unitIdFor(String(companion))}.service || true`], { timeout: 6e4 });
65242
+ const deadline = Date.now() + 3e4;
65243
+ while (Date.now() < deadline) {
65244
+ const { stdout } = await run("ssh", [...sshOptsOf(configPath), host, `pgrep -f "${remoteRoot}/config[.]json" || true`], { timeout: 15e3 });
65245
+ if (!stdout.trim()) return;
65246
+ await new Promise((r) => setTimeout(r, 1e3));
65247
+ }
65248
+ throw new Error("\u56DE\u6EDA\u505C\u4E91\u673A\uFF1A\u5F15\u64CE 30 \u79D2\u5185\u672A\u9000\u51FA");
65249
+ },
65250
+ async stopLocal(configPath) {
65251
+ await stopLocalEngine(configPath);
65252
+ },
65253
+ async startLocal(configPath) {
65254
+ await tunnelDown(configPath);
65255
+ const config = JSON.parse(readFileSync78(engineConfigPath(configPath), "utf8"));
65256
+ const { spawn: spawn8 } = await import("node:child_process");
65257
+ const child = spawn8("engine7", ["start", "--config", engineConfigPath(configPath)], { detached: true, stdio: "ignore", cwd: config.stateDir });
65258
+ child.on("error", () => {
65259
+ });
65260
+ child.unref();
65261
+ const port = config.api?.port ?? 16992;
65262
+ const deadline = Date.now() + 6e4;
65263
+ while (Date.now() < deadline) {
65264
+ try {
65265
+ await run("curl", ["-sf", "-m", "2", `http://127.0.0.1:${port}/api/status`], { timeout: 5e3 });
65266
+ return;
65267
+ } catch {
65268
+ await new Promise((r) => setTimeout(r, 2e3));
65269
+ }
65270
+ }
65271
+ throw new Error("\u672C\u673A\u5F15\u64CE\u56DE\u6EDA\u542F\u52A8\u8D85\u65F6");
65272
+ }
65273
+ };
65274
+ }
65275
+ function logQuiet(_line) {
65276
+ }
65277
+ var moveTokenPath, moveLockPath;
65278
+ var init_move = __esm({
65279
+ "src/travel/move.ts"() {
65280
+ "use strict";
65281
+ init_config_remap();
65282
+ moveTokenPath = (stateDir) => join110(stateDir, ".travel/move-token.json");
65283
+ moveLockPath = (stateDir) => join110(stateDir, ".travel/move.lock");
65284
+ }
65285
+ });
65286
+
65287
+ // src/travel/medicheck.ts
65288
+ var medicheck_exports = {};
65289
+ __export(medicheck_exports, {
65290
+ runMedicheck: () => runMedicheck
65291
+ });
65292
+ import { createHash as createHash49 } from "node:crypto";
65293
+ import { chmodSync as chmodSync5, copyFileSync as copyFileSync6, existsSync as existsSync63, mkdirSync as mkdirSync46, readdirSync as readdirSync23, readFileSync as readFileSync79 } from "node:fs";
65294
+ import { join as join111 } from "node:path";
65295
+ function runMedicheck(stateDir) {
65296
+ const pattern = /image-assets\/([a-f0-9]{64})\.(jpeg|jpg|png|webp|gif)/g;
65297
+ const refs = /* @__PURE__ */ new Set();
65298
+ for (const sessionsDir of [join111(stateDir, "agents/main/sessions"), join111(stateDir, "agents/main/sessions-cron")]) {
65299
+ if (!existsSync63(sessionsDir)) continue;
65300
+ for (const file2 of readdirSync23(sessionsDir)) {
65301
+ if (!file2.endsWith(".jsonl")) continue;
65302
+ const text4 = readFileSync79(join111(sessionsDir, file2), "utf8");
65303
+ for (const match of text4.matchAll(pattern)) refs.add(match[0]);
65304
+ }
65305
+ }
65306
+ const assetDir = join111(stateDir, "media/inbound/image-assets");
65307
+ const missing = [...refs].filter((ref) => !existsSync63(join111(assetDir, ref.split("/").pop())));
65308
+ if (!missing.length) return { fixed: [], stillMissing: [] };
65309
+ const binDir = join111(stateDir, "chan7-files");
65310
+ const sha2bin = /* @__PURE__ */ new Map();
65311
+ if (existsSync63(binDir)) {
65312
+ for (const name of readdirSync23(binDir)) {
65313
+ if (!name.endsWith(".bin")) continue;
65314
+ const digest6 = createHash49("sha256");
65315
+ digest6.update(readFileSync79(join111(binDir, name)));
65316
+ sha2bin.set(digest6.digest("hex"), join111(binDir, name));
65317
+ }
65318
+ }
65319
+ const fixed = [], stillMissing = [];
65320
+ for (const ref of missing) {
65321
+ const sha2 = ref.split(".")[0].split("/").pop();
65322
+ const bin = sha2bin.get(sha2);
65323
+ if (!bin) {
65324
+ stillMissing.push(ref);
65325
+ continue;
65326
+ }
65327
+ mkdirSync46(assetDir, { recursive: true });
65328
+ const dest = join111(assetDir, ref.split("/").pop());
65329
+ copyFileSync6(bin, dest);
65330
+ chmodSync5(dest, 384);
65331
+ fixed.push(ref);
65332
+ }
65333
+ return { fixed, stillMissing };
65334
+ }
65335
+ var init_medicheck = __esm({
65336
+ "src/travel/medicheck.ts"() {
65337
+ "use strict";
65338
+ }
65339
+ });
65340
+
65341
+ // src/travel/remote-setup.ts
65342
+ var remote_setup_exports = {};
65343
+ __export(remote_setup_exports, {
65344
+ setupRemote: () => setupRemote
65345
+ });
65346
+ import { execFile as execFile6 } from "node:child_process";
65347
+ import { promisify as promisify7 } from "node:util";
65348
+ import { readFileSync as readFileSync80, writeFileSync as writeFileSync49, mkdtempSync as mkdtempSync2, mkdirSync as mkdirSync47 } from "node:fs";
65349
+ import { tmpdir as tmpdir6 } from "node:os";
65350
+ import { dirname as dirname42, join as join112, resolve as resolve42 } from "node:path";
65351
+ import { fileURLToPath as fileURLToPath18 } from "node:url";
65352
+ function enginePackageRoot() {
65353
+ const here = dirname42(fileURLToPath18(import.meta.url));
65354
+ for (const dir of [join112(here, ".."), join112(here, "..", "..")]) {
65355
+ try {
65356
+ const pkg = JSON.parse(readFileSync80(join112(dir, "package.json"), "utf8"));
65357
+ if (pkg.name === "engine7") return dir;
65358
+ } catch {
65359
+ }
65360
+ }
65361
+ return null;
65362
+ }
65363
+ async function setupRemote(options) {
65364
+ const run = options.run ?? realRun;
65365
+ const log = options.log ?? (() => {
65366
+ });
65367
+ const host = options.host;
65368
+ const ssh = async (command) => run("ssh", [host, command]);
65369
+ await ssh(`mkdir -p ${options.remoteRoot}/workspace`);
65370
+ let nodeVersion = "";
65371
+ try {
65372
+ const { stdout } = await ssh("node --version");
65373
+ nodeVersion = stdout.trim();
65374
+ } catch {
65375
+ nodeVersion = "";
65376
+ }
65377
+ const major = Number(/^v(\d+)/.exec(nodeVersion)?.[1] ?? 0);
65378
+ if (!nodeVersion || major < 22) {
65379
+ log(`[setup-remote] node ${nodeVersion || "\u672A\u88C5"} \u2192 \u5B89\u88C5 22.x \u2026`);
65380
+ await ssh("curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && apt-get install -y nodejs");
65381
+ const { stdout } = await ssh("node --version");
65382
+ nodeVersion = stdout.trim();
65383
+ if (Number(/^v(\d+)/.exec(nodeVersion)?.[1] ?? 0) < 22) throw new Error(`\u8FDC\u7AEF node \u7248\u672C\u4E0D\u8DB3: ${nodeVersion}`);
65384
+ } else log(`[setup-remote] node ${nodeVersion} \u5DF2\u88C5`);
65385
+ const localVersion = options.localEngineVersion?.() ?? readEngineVersion2();
65386
+ let remoteVersion = "";
65387
+ try {
65388
+ const { stdout } = await ssh("engine7 --version 2>/dev/null || true");
65389
+ remoteVersion = /\d+\.\d+\.\d+/.exec(stdout)?.[0] ?? "";
65390
+ } catch {
65391
+ remoteVersion = "";
65392
+ }
65393
+ if (remoteVersion !== localVersion) {
65394
+ log(`[setup-remote] engine7 ${remoteVersion || "\u672A\u88C5"} \u2192 ${localVersion}\uFF08tarball \u76F4\u88C5\uFF09`);
65395
+ const packageRoot = enginePackageRoot();
65396
+ const staging = mkdtempSync2(join112(tmpdir6(), "e7-pkg-"));
65397
+ await run("npm", ["pack", "--ignore-scripts", "--pack-destination", staging], packageRoot ? { cwd: packageRoot } : void 0);
65398
+ const tarball = `engine7-${localVersion}.tgz`;
65399
+ await run("scp", [join112(staging, tarball), `${host}:/tmp/`]);
65400
+ await ssh(`npm install -g /tmp/${tarball} && rm /tmp/${tarball}`);
65401
+ }
65402
+ const config = JSON.parse(readFileSync80(options.configPath, "utf8"));
65403
+ const remapped = remapConfigForRemote(config, options.remoteRoot);
65404
+ const localTemp = mkdtempSync2(join112(tmpdir6(), "e7-cfg-"));
65405
+ const configFile = join112(localTemp, "config.json");
65406
+ writeFileSync49(configFile, JSON.stringify(remapped, null, 2));
65407
+ await run("scp", [configFile, `${host}:${options.remoteRoot}/config.json`]);
65408
+ const secretsPath = loadSecretsEnvForConfig(options.configPath);
65409
+ if (secretsPath) {
65410
+ await run("scp", [secretsPath, `${host}:${options.remoteRoot}/secrets.env`]);
65411
+ await ssh(`chmod 600 ${options.remoteRoot}/secrets.env`);
65412
+ log(`[setup-remote] secrets \u4E0A\u4F20\uFF08${options.remoteRoot}/secrets.env, 600\uFF09`);
65413
+ } else log("[setup-remote] \u26A0\uFE0F \u672A\u627E\u5230 secrets \u6587\u4EF6\u2014\u2014\u82E5\u914D\u7F6E\u7528 env: \u5360\u4F4D\u7B26\uFF0C\u8FDC\u7AEF\u5C06 401");
65414
+ const companion = remapped.agents?.defaults?.name ?? "companion";
65415
+ const { stdout: remotePaths } = await ssh("command -v node && command -v engine7");
65416
+ const [remoteNode = "node", remoteEngine = "engine7"] = remotePaths.split("\n").map((v) => v.trim()).filter(Boolean);
65417
+ const unit2 = buildSystemdUnit({ companion: String(companion), remoteRoot: options.remoteRoot, nodeBin: remoteNode, engineBin: remoteEngine });
65418
+ const unitId = unitIdFor(String(companion));
65419
+ const unitFile = join112(localTemp, `engine7-${unitId}.service`);
65420
+ writeFileSync49(unitFile, unit2);
65421
+ await run("scp", [unitFile, `${host}:/etc/systemd/system/engine7-${unitId}.service`]);
65422
+ await ssh(`systemctl daemon-reload && systemctl enable engine7-${unitId}.service`);
65423
+ log(`[setup-remote] \u5B8C\u6210\uFF1A${host}:${options.remoteRoot}\uFF08engine7-${unitId}.service\uFF09`);
65424
+ try {
65425
+ const stateDir = typeof config.stateDir === "string" ? config.stateDir : resolve42(options.configPath, "..", "..");
65426
+ mkdirSync47(join112(stateDir, ".travel"), { recursive: true });
65427
+ writeFileSync49(join112(stateDir, ".travel", "remote.json"), JSON.stringify({ host, remoteRoot: options.remoteRoot, savedAt: Date.now() }));
65428
+ } catch {
65429
+ }
65430
+ return { installed: true };
65431
+ }
65432
+ var realRun;
65433
+ var init_remote_setup = __esm({
65434
+ "src/travel/remote-setup.ts"() {
65435
+ "use strict";
65436
+ init_version();
65437
+ init_config_remap();
65438
+ init_secrets_env();
65439
+ realRun = async (command, args, options) => {
65440
+ const run = promisify7(execFile6);
65441
+ const { stdout } = await run(command, args, { maxBuffer: 32 * 1024 * 1024, ...options });
65442
+ return { stdout };
65443
+ };
65444
+ }
65445
+ });
65446
+
65447
+ // src/travel/sync-cli.ts
65448
+ var sync_cli_exports = {};
65449
+ __export(sync_cli_exports, {
65450
+ runTravelSync: () => runTravelSync
65451
+ });
65452
+ import { spawn as spawn7 } from "node:child_process";
65453
+ import { resolve as resolve43 } from "node:path";
65454
+ async function runTravelSync(options) {
65455
+ const log = options.log ?? (() => {
65456
+ });
65457
+ if (!options.pre && !options.quiescent) throw new Error("\u5FC5\u987B\u6307\u5B9A --pre\uFF08\u5F15\u64CE\u8FD0\u884C\u4E2D\uFF09\u6216 --quiescent\uFF08\u5F15\u64CE\u5DF2\u505C\uFF09\u4E4B\u4E00");
65458
+ let host = "local", remoteRoot = resolve43(options.to), sshOpts = [];
65459
+ let spawnRemote = options.spawnRemote;
65460
+ if (options.to.includes(":")) {
65461
+ const [first, ...rest] = options.to.split(":");
65462
+ host = first;
65463
+ remoteRoot = rest.join(":");
65464
+ sshOpts = SSH_BASE_OPTS;
65465
+ if (!host || !remoteRoot) throw new Error(`\u65E0\u6CD5\u89E3\u6790\u76EE\u6807\uFF1A${options.to}`);
65466
+ } else if (!spawnRemote) {
65467
+ const dest = remoteRoot;
65468
+ spawnRemote = (_command, index) => {
65469
+ const child = spawn7("engine7", ["travel-sync-worker", "--state-dir", dest], { stdio: ["pipe", "pipe", "pipe"] });
65470
+ child.stderr?.on("data", (chunk) => {
65471
+ const text4 = chunk.toString("utf8").trim();
65472
+ if (text4) console.warn(`[travel-sync-worker#${index}] ${text4}`);
65473
+ });
65474
+ return child;
65475
+ };
65476
+ }
65477
+ const summary3 = await runSyncV2({
65478
+ direction: "to-cloud",
65479
+ configPath: options.configPath,
65480
+ stateDirOverride: options.stateDirOverride,
65481
+ host,
65482
+ remoteRoot,
65483
+ sshOpts,
65484
+ pre: options.pre,
65485
+ parallel: options.parallel,
65486
+ spawnRemote,
65487
+ log
65488
+ });
65489
+ return { changed: summary3.applied, deleted: summary3.deleted.length, excludedTopLevel: summary3.excluded };
65490
+ }
65491
+ var init_sync_cli = __esm({
65492
+ "src/travel/sync-cli.ts"() {
65493
+ "use strict";
65494
+ init_sync_v2();
65495
+ }
65496
+ });
65497
+
63109
65498
  // src/cli-travel.ts
63110
65499
  var cli_travel_exports = {};
63111
65500
  __export(cli_travel_exports, {
@@ -63842,7 +66231,7 @@ init_feishu_quick_register();
63842
66231
  init_wechat();
63843
66232
  init_qr_render();
63844
66233
  import * as readline3 from "node:readline";
63845
- import { fileURLToPath as fileURLToPath18 } from "node:url";
66234
+ import { fileURLToPath as fileURLToPath19 } from "node:url";
63846
66235
 
63847
66236
  // src/config/soul-template.ts
63848
66237
  function isUnnamedAgentName(agentName) {
@@ -64212,7 +66601,7 @@ var headlessEmit = null;
64212
66601
  function describeCurrentToken(v) {
64213
66602
  return /^(?:env:|{{\s*)[A-Z0-9_]+/.test(v) ? "\u5DF2\u5B58\u5728 secrets \u4E2D" : v.slice(0, 12) + "...";
64214
66603
  }
64215
- var __filename3 = fileURLToPath18(import.meta.url);
66604
+ var __filename3 = fileURLToPath19(import.meta.url);
64216
66605
  var __dirname = path71.dirname(__filename3);
64217
66606
  function parseArgs2() {
64218
66607
  const args = process.argv.slice(2);
@@ -64302,9 +66691,9 @@ function createReadline() {
64302
66691
  }
64303
66692
  async function ask(rl, question, defaultValue) {
64304
66693
  const prompt = defaultValue ? `${question} [${defaultValue}]: ` : `${question}: `;
64305
- return new Promise((resolve40) => {
66694
+ return new Promise((resolve45) => {
64306
66695
  rl.question(prompt, (answer) => {
64307
- resolve40(answer.trim() || defaultValue || "");
66696
+ resolve45(answer.trim() || defaultValue || "");
64308
66697
  });
64309
66698
  });
64310
66699
  }
@@ -65248,6 +67637,133 @@ async function main() {
65248
67637
  process.exit(1);
65249
67638
  }
65250
67639
  }
67640
+ if (subcommand === "travel-move") {
67641
+ try {
67642
+ const { runTravelMove: runTravelMove2, cancelRunningMove: cancelRunningMove2 } = await Promise.resolve().then(() => (init_move(), move_exports));
67643
+ let to = "", configPath2 = "", host = "", remoteRoot = "", cancel = false;
67644
+ for (let i = 1; i < args.length; i++) {
67645
+ if (args[i] === "--to" && args[i + 1]) to = args[++i];
67646
+ else if (args[i] === "--config" && args[i + 1]) configPath2 = args[++i];
67647
+ else if (args[i] === "--host" && args[i + 1]) host = args[++i];
67648
+ else if (args[i] === "--remote-root" && args[i + 1]) remoteRoot = args[++i];
67649
+ else if (args[i] === "--cancel") cancel = true;
67650
+ }
67651
+ if (cancel) {
67652
+ if (!configPath2) {
67653
+ console.error("\u7528\u6CD5: engine7 travel-move --cancel --config <path>");
67654
+ process.exit(1);
67655
+ }
67656
+ const { readFileSync: readConfig4 } = await import("node:fs");
67657
+ const { resolve: resolvePath3 } = await import("node:path");
67658
+ const config3 = JSON.parse(readConfig4(resolvePath3(configPath2), "utf8"));
67659
+ const stateDir2 = typeof config3.stateDir === "string" ? config3.stateDir : resolvePath3(configPath2, "..", "..");
67660
+ const result2 = cancelRunningMove2(stateDir2);
67661
+ console.log(`[travel-move] ${result2.note}`);
67662
+ process.exit(0);
67663
+ }
67664
+ if (to !== "cloud" && to !== "local" || !configPath2 || !host || !remoteRoot) {
67665
+ console.error("\u7528\u6CD5: engine7 travel-move --to cloud|local --config <path> --host <ssh> --remote-root <path>\uFF08--cancel \u53EF\u53D6\u6D88\u5728\u8DD1\u7684\u642C\u79FB\uFF09");
67666
+ process.exit(1);
67667
+ }
67668
+ const { readFileSync: readConfig3 } = await import("node:fs");
67669
+ const { resolve: resolvePath2 } = await import("node:path");
67670
+ const { ensureGate: ensureGate2, ensureTunnelDown: ensureTunnelDown2, writeResidency: writeResidency2 } = await Promise.resolve().then(() => (init_gate2(), gate_exports2));
67671
+ const config2 = JSON.parse(readConfig3(resolvePath2(configPath2), "utf8"));
67672
+ const stateDir = typeof config2.stateDir === "string" ? config2.stateDir : resolvePath2(configPath2, "..", "..");
67673
+ const port = config2.api?.port ?? 16992;
67674
+ const log = (line) => console.log(line);
67675
+ await ensureTunnelDown2(stateDir);
67676
+ const gate = await ensureGate2({ stateDir, port });
67677
+ const onStep = (step) => {
67678
+ void gate.send(
67679
+ step.startsWith("\u2461") ? { cmd: "hold-progress" } : to === "cloud" && step.startsWith("\u2705") ? { cmd: "hold-cloud", host, port } : to === "cloud" && step.startsWith("\u274C") ? { cmd: "release" } : to === "local" && step.startsWith("\u2462") ? { cmd: "release" } : to === "local" && step.startsWith("\u274C") ? { cmd: "hold-cloud", host, port } : { cmd: "status" }
67680
+ );
67681
+ };
67682
+ log(`[gate] 16992 \u5168\u7A0B\u4E0D\u65AD\uFF1A\u5207\u6362\u4E2D\u663E\u793A\u8FDB\u5EA6\uFF0C\u5B8C\u6210\u540E\u81EA\u52A8\u6307\u5411\u5979\u6240\u5728\u7684\u4E00\u7AEF`);
67683
+ const result = await runTravelMove2({ to, configPath: configPath2, host, remoteRoot, log, onStep });
67684
+ const finalWhere = result.outcome === "moved" ? to === "cloud" ? "cloud" : "local" : to === "cloud" ? "local" : "cloud";
67685
+ writeResidency2(stateDir, finalWhere, finalWhere === "cloud" ? { host, port } : void 0);
67686
+ if (result.outcome === "moved" && to === "cloud") log(`[gate] \u4E91\u7AEF\u63A7\u5236\u53F0\u5DF2\u63A5\u7BA1 16992: http://127.0.0.1:${port}/console \uFF08\u5730\u5740\u4E0D\u53D8\uFF09`);
67687
+ if (result.outcome === "moved" && to === "local") await gate.send({ cmd: "release" });
67688
+ console.log(`[travel-move] ${result.outcome === "moved" ? "\u2705 \u5B8C\u6210" : "\u21A9\uFE0F \u5DF2\u56DE\u6EDA"}\uFF1A${result.detail}`);
67689
+ process.exit(result.outcome === "moved" ? 0 : 2);
67690
+ } catch (error) {
67691
+ console.error(error instanceof Error ? error.message : String(error));
67692
+ process.exit(1);
67693
+ }
67694
+ }
67695
+ if (subcommand === "travel-gate") {
67696
+ const { runGateFromArgv: runGateFromArgv2 } = await Promise.resolve().then(() => (init_gate2(), gate_exports2));
67697
+ runGateFromArgv2(args.slice(1));
67698
+ return;
67699
+ }
67700
+ if (subcommand === "travel-sync-worker") {
67701
+ let stateDir = "";
67702
+ for (let i = 1; i < args.length; i++) if (args[i] === "--state-dir" && args[i + 1]) stateDir = args[++i];
67703
+ if (!stateDir) {
67704
+ console.error("\u7528\u6CD5: engine7 travel-sync-worker --state-dir <path>");
67705
+ process.exit(1);
67706
+ }
67707
+ const { runWorker: runWorker2 } = await Promise.resolve().then(() => (init_sync_worker(), sync_worker_exports));
67708
+ await runWorker2(stateDir);
67709
+ process.exit(0);
67710
+ }
67711
+ if (subcommand === "travel-medicheck") {
67712
+ let stateDir = "";
67713
+ for (let i = 1; i < args.length; i++) if (args[i] === "--state-dir" && args[i + 1]) stateDir = args[++i];
67714
+ if (!stateDir) {
67715
+ console.error("\u7528\u6CD5: engine7 travel-medicheck --state-dir <path>");
67716
+ process.exit(1);
67717
+ }
67718
+ const { runMedicheck: runMedicheck2 } = await Promise.resolve().then(() => (init_medicheck(), medicheck_exports));
67719
+ const result = runMedicheck2(stateDir);
67720
+ for (const fixed of result.fixed) console.log(`[medicheck] \u5DF2\u7269\u5316 ${fixed}`);
67721
+ for (const miss of result.stillMissing) console.warn(`[medicheck] \u4ECD\u7F3A\uFF08\u65E0\u5339\u914D blob\uFF09${miss}`);
67722
+ console.log(`[medicheck] \u5B8C\u6210\uFF1A\u7269\u5316 ${result.fixed.length}\uFF0C\u4ECD\u7F3A ${result.stillMissing.length}`);
67723
+ process.exit(0);
67724
+ }
67725
+ if (subcommand === "travel-setup-remote") {
67726
+ try {
67727
+ const { setupRemote: setupRemote2 } = await Promise.resolve().then(() => (init_remote_setup(), remote_setup_exports));
67728
+ let host = "", configPath2 = "", remoteRoot = "";
67729
+ for (let i = 1; i < args.length; i++) {
67730
+ if (args[i] === "--host" && args[i + 1]) host = args[++i];
67731
+ else if (args[i] === "--config" && args[i + 1]) configPath2 = args[++i];
67732
+ else if (args[i] === "--remote-root" && args[i + 1]) remoteRoot = args[++i];
67733
+ }
67734
+ if (!host || !configPath2 || !remoteRoot) {
67735
+ console.error("\u7528\u6CD5: engine7 travel-setup-remote --host <ssh> --config <path> --remote-root <path>");
67736
+ process.exit(1);
67737
+ }
67738
+ await setupRemote2({ host, configPath: configPath2, remoteRoot, log: (line) => console.log(line) });
67739
+ process.exit(0);
67740
+ } catch (error) {
67741
+ console.error(error instanceof Error ? error.message : String(error));
67742
+ process.exit(1);
67743
+ }
67744
+ }
67745
+ if (subcommand === "travel-sync") {
67746
+ try {
67747
+ const { runTravelSync: runTravelSync2 } = await Promise.resolve().then(() => (init_sync_cli(), sync_cli_exports));
67748
+ let configPath2 = "", to = "", pre = false, quiescent = false;
67749
+ for (let i = 1; i < args.length; i++) {
67750
+ if (args[i] === "--config" && args[i + 1]) configPath2 = args[++i];
67751
+ else if (args[i] === "--to" && args[i + 1]) to = args[++i];
67752
+ else if (args[i] === "--pre") pre = true;
67753
+ else if (args[i] === "--quiescent") quiescent = true;
67754
+ }
67755
+ if (!to || !configPath2 || pre && quiescent) {
67756
+ console.error("\u7528\u6CD5: engine7 travel-sync --config <path> --to <host:/path|\u672C\u5730\u8DEF\u5F84> [--pre|--quiescent]\uFF08\u4E8C\u9009\u4E00\uFF09");
67757
+ process.exit(1);
67758
+ }
67759
+ const result = await runTravelSync2({ configPath: configPath2, to, pre, quiescent, log: (line) => console.log(line) });
67760
+ console.log(`[travel-sync] \u5B8C\u6210 changed=${result.changed} deleted=${result.deleted}`);
67761
+ process.exit(0);
67762
+ } catch (error) {
67763
+ console.error(error instanceof Error ? error.message : String(error));
67764
+ process.exit(1);
67765
+ }
67766
+ }
65251
67767
  if (subcommand === "export") {
65252
67768
  const { doExport: doExport2 } = await Promise.resolve().then(() => (init_cli_travel(), cli_travel_exports));
65253
67769
  let exportStateDir = "";
@@ -65340,7 +67856,7 @@ engine7 start \u2014 \u542F\u52A8 Engine
65340
67856
  console.error(" \u7528\u6CD5: engine7 start [configs/xxx.json | --config <path>]");
65341
67857
  process.exit(1);
65342
67858
  }
65343
- const { execSync: execSync4, spawn: spawn5 } = await import("node:child_process");
67859
+ const { execSync: execSync4, spawn: spawn8 } = await import("node:child_process");
65344
67860
  let enginePath;
65345
67861
  const localPath = path71.join("node_modules", "engine7", "dist", "main.mjs");
65346
67862
  if (fs66.existsSync(localPath)) {
@@ -65411,7 +67927,7 @@ engine7 start \u2014 \u542F\u52A8 Engine
65411
67927
  break;
65412
67928
  }
65413
67929
  }
65414
- const child = spawn5(process.execPath, [enginePath, "--engine-config", configPath2], {
67930
+ const child = spawn8(process.execPath, [enginePath, "--engine-config", configPath2], {
65415
67931
  stdio: "inherit",
65416
67932
  shell: false,
65417
67933
  env: envForChild
@@ -65531,15 +68047,15 @@ engine7 session \u2014 \u4F1A\u8BDD\u7BA1\u7406\u5DE5\u5177
65531
68047
  }
65532
68048
  }
65533
68049
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
65534
- const { readFileSync: readFileSync76, writeFileSync: writeFileSync46, renameSync: renameSync20 } = fs66;
68050
+ const { readFileSync: readFileSync83, writeFileSync: writeFileSync52, renameSync: renameSync23 } = fs66;
65535
68051
  if (mode === "archive") {
65536
68052
  const archiveName = `${sessionFileUUID}.jsonl.archived.${timestamp}`;
65537
- renameSync20(jsonlPath, path71.join(sessionsDir, archiveName));
68053
+ renameSync23(jsonlPath, path71.join(sessionsDir, archiveName));
65538
68054
  console.log(`
65539
68055
  \u2705 \u5F52\u6863\u5B8C\u6210: ${archiveName}`);
65540
68056
  console.log(` \u91CD\u542F\u540E\u5C06\u4ECE\u7A7A\u767D\u4F1A\u8BDD\u5F00\u59CB`);
65541
68057
  } else if (mode === "drop-last") {
65542
- const lines = readFileSync76(jsonlPath, "utf-8").trim().split("\n");
68058
+ const lines = readFileSync83(jsonlPath, "utf-8").trim().split("\n");
65543
68059
  const parsed = lines.map((l) => {
65544
68060
  try {
65545
68061
  return JSON.parse(l);
@@ -65558,12 +68074,12 @@ engine7 session \u2014 \u4F1A\u8BDD\u7BA1\u7406\u5DE5\u5177
65558
68074
  }
65559
68075
  const kept = parsed.slice(0, cutIndex);
65560
68076
  const newContent = kept.map((p) => JSON.stringify(p)).join("\n") + "\n";
65561
- writeFileSync46(jsonlPath, newContent);
68077
+ writeFileSync52(jsonlPath, newContent);
65562
68078
  console.log(`
65563
68079
  \u2705 \u780D\u6389\u6700\u8FD1 ${parsed.length - cutIndex} \u884C\uFF08${dropN} \u8F6E\uFF09`);
65564
68080
  console.log(` \u4FDD\u7559 ${kept.length} \u884C`);
65565
68081
  } else if (mode === "strip-images") {
65566
- const lines = readFileSync76(jsonlPath, "utf-8").trim().split("\n");
68082
+ const lines = readFileSync83(jsonlPath, "utf-8").trim().split("\n");
65567
68083
  let stripped = 0;
65568
68084
  const newLines = lines.map((line) => {
65569
68085
  try {
@@ -65604,7 +68120,7 @@ engine7 session \u2014 \u4F1A\u8BDD\u7BA1\u7406\u5DE5\u5177
65604
68120
  return line;
65605
68121
  }
65606
68122
  });
65607
- writeFileSync46(jsonlPath, newLines.join("\n") + "\n");
68123
+ writeFileSync52(jsonlPath, newLines.join("\n") + "\n");
65608
68124
  console.log(`
65609
68125
  \u2705 \u6458\u9664 ${stripped} \u884C\u56FE\u7247\u76F8\u5173\u5185\u5BB9`);
65610
68126
  }
@@ -65618,8 +68134,8 @@ engine7 session \u2014 \u4F1A\u8BDD\u7BA1\u7406\u5DE5\u5177
65618
68134
  }
65619
68135
  console.log(`
65620
68136
  \u{1F680} \u62C9\u8D77 engine...`);
65621
- const { spawn: spawn5 } = await import("node:child_process");
65622
- const child = spawn5(process.execPath, [enginePath, "--engine-config", configPath2], {
68137
+ const { spawn: spawn8 } = await import("node:child_process");
68138
+ const child = spawn8(process.execPath, [enginePath, "--engine-config", configPath2], {
65623
68139
  detached: true,
65624
68140
  stdio: "inherit"
65625
68141
  });