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.
@@ -830,6 +830,7 @@ function validateTravelChannels(stateDir, channels) {
830
830
  const root = stateDir || process.env.ENGINE7_TRAVEL_STATE_DIR || process.env.ENGINE_STATE_DIR;
831
831
  if (!root || !runtimeAuthorityFor(root)) return;
832
832
  validateTravelChannelConfiguration(channels);
833
+ if (["FEISHU_APP_SECRET", "LARK_APP_SECRET", "FEISHU_ACCESS_TOKEN", "DISCORD_TOKEN", "WECHAT_TOKEN"].some((k) => !!process.env[k])) throw new Error("TRAVEL_PLATFORM_SECRET_PRESENT");
833
834
  }
834
835
  function validateTravelChannelConfiguration(channels) {
835
836
  for (const [name, value] of Object.entries(channels ?? {})) {
@@ -837,7 +838,7 @@ function validateTravelChannelConfiguration(channels) {
837
838
  if (!["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
838
839
  if (value.mode !== "remote-only") throw new Error("TRAVEL_REMOTE_ONLY_REQUIRED");
839
840
  const hasPlatformSecret = (block) => block && typeof block === "object" && Object.entries(block).some(([key2, v]) => ["appSecret", "token", "accessToken", "tenantAccessToken", "app_secret", "botToken", "bot_token"].includes(key2) && typeof v === "string" && !!v.trim() || v && typeof v === "object" && hasPlatformSecret(v));
840
- if (hasPlatformSecret(value) || ["FEISHU_APP_SECRET", "LARK_APP_SECRET", "FEISHU_ACCESS_TOKEN", "DISCORD_TOKEN", "WECHAT_TOKEN"].some((k) => !!process.env[k])) throw new Error("TRAVEL_PLATFORM_SECRET_PRESENT");
841
+ if (hasPlatformSecret(value)) throw new Error("TRAVEL_PLATFORM_SECRET_PRESENT");
841
842
  let url;
842
843
  try {
843
844
  url = new URL(value.gatewayUrl);
@@ -12344,6 +12345,10 @@ function rowElements(state, rowCap) {
12344
12345
  }
12345
12346
  }
12346
12347
  flush();
12348
+ if (state.steerNotes?.length) {
12349
+ for (const s of state.steerNotes) lines.push(`\u21AA \u63D2\u8BDD\uFF1A${s.length > ARGS_MAX ? s.slice(0, ARGS_MAX - 1) + "\u2026" : s}`);
12350
+ flush();
12351
+ }
12347
12352
  const lt = state.liveThink;
12348
12353
  if (lt) {
12349
12354
  const sec = Math.max(1, Math.round((Date.now() - lt.start) / 1e3));
@@ -12354,6 +12359,9 @@ function rowElements(state, rowCap) {
12354
12359
  } else if (state.status === "run") {
12355
12360
  els.push({ tag: "div", text: { tag: "lark_md", content: `*${spinnerFrame()} ${state.verb}\u2026\uFF08${fmtDur(Math.max(1, Math.round((Date.now() - state.startedAt) / 1e3)))}\uFF09*` } });
12356
12361
  }
12362
+ if (state.stopAction && (state.status === "run" || state.status === "wait")) {
12363
+ els.push({ tag: "action", actions: [{ tag: "button", type: "default", text: { tag: "plain_text", content: "\u505C\u6B62" }, value: state.stopAction }] });
12364
+ }
12357
12365
  return { els, dropped };
12358
12366
  }
12359
12367
  function buildProcessCard(state, level = 2) {
@@ -12546,6 +12554,10 @@ function buildProcessCardV2At(state, level, panelCap) {
12546
12554
  }
12547
12555
  }
12548
12556
  flushPlain();
12557
+ if (state.steerNotes?.length) {
12558
+ for (const s of state.steerNotes) plain.push(`\u21AA \u63D2\u8BDD\uFF1A${capStr(s, ARGS_MAX)}`);
12559
+ flushPlain();
12560
+ }
12549
12561
  const lt = state.liveThink;
12550
12562
  if (lt) {
12551
12563
  const sec = Math.max(1, Math.round((Date.now() - lt.start) / 1e3));
@@ -12556,6 +12568,9 @@ function buildProcessCardV2At(state, level, panelCap) {
12556
12568
  } else if (state.status === "run") {
12557
12569
  els.push({ tag: "markdown", content: `*${spinnerFrame()} ${state.verb}\u2026\uFF08${fmtDur(Math.max(1, Math.round((Date.now() - state.startedAt) / 1e3)))}\uFF09*` });
12558
12570
  }
12571
+ if (state.stopAction && (state.status === "run" || state.status === "wait")) {
12572
+ els.push(buttonRow([{ tag: "button", type: "default", text: { tag: "plain_text", content: "\u505C\u6B62" }, value: state.stopAction }]));
12573
+ }
12559
12574
  const notes = [];
12560
12575
  if (state.usage) notes.push(state.usage);
12561
12576
  if (state.status === "wait") notes.push("\u70B9\u6309\u94AE\u5BA1\u6279\uFF0C\u4E5F\u53EF\u76F4\u63A5\u6253\u5B57");
@@ -12667,7 +12682,7 @@ var init_process_card = __esm({
12667
12682
  this.summarySent = false;
12668
12683
  this.terminal = null;
12669
12684
  this.patchFailures = 0;
12670
- 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 };
12685
+ 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 };
12671
12686
  this.lastPushKey = this.pushKey();
12672
12687
  this.messageId = null;
12673
12688
  this.channelV = null;
@@ -12688,7 +12703,10 @@ var init_process_card = __esm({
12688
12703
  }
12689
12704
  /** Mode decisions can start native progress without awaiting any channel I/O. */
12690
12705
  start() {
12691
- if (!this.ended && !this.started && (this.nativeCapable() || this.legacyCapable())) this.beginInBackground();
12706
+ if (!this.ended && !this.started && (this.nativeCapable() || this.legacyCapable() || this.progressCapable())) this.beginInBackground();
12707
+ }
12708
+ progressCapable() {
12709
+ return !!this.adapter.sendProgress && !!this.adapter.updateProgress && !!this.adapter.removeProgress;
12692
12710
  }
12693
12711
  nativeCapable() {
12694
12712
  const ad = this.adapter;
@@ -12702,10 +12720,16 @@ var init_process_card = __esm({
12702
12720
  }
12703
12721
  ensureStarted() {
12704
12722
  const ad = this.adapter;
12705
- if (this.options.autoStart && !this.started && (this.nativeCapable() || this.legacyCapable() || ad.sendPreview && ad.editPreview)) this.beginInBackground();
12723
+ if (this.options.autoStart && !this.started && (this.nativeCapable() || this.legacyCapable() || this.progressCapable() || ad.sendPreview && ad.editPreview)) this.beginInBackground();
12706
12724
  }
12707
12725
  async createCard() {
12708
12726
  const ad = this.adapter;
12727
+ if (this.progressCapable()) {
12728
+ this.messageId = await ad.sendProgress(this.target, structuredClone(this.state));
12729
+ this.channelV = "progress";
12730
+ this.lastPatchAt = Date.now();
12731
+ return;
12732
+ }
12709
12733
  if (!this.nativeCapable() && this.legacyCapable()) return this.createLegacyCard();
12710
12734
  if (!this.nativeCapable() && this.options.allowLegacyCard === false) {
12711
12735
  if (!ad.sendPreview || !ad.editPreview) throw new Error("\u65E0\u8FC7\u7A0B\u5361\u6216\u53EF\u7F16\u8F91\u6D88\u606F\u80FD\u529B");
@@ -12752,8 +12776,10 @@ var init_process_card = __esm({
12752
12776
  }
12753
12777
  async removeCard() {
12754
12778
  if (this.messageId) {
12755
- if (!this.adapter.deletePreview) throw new Error("\u65E0\u8FC7\u7A0B\u5361\u6E05\u7406\u80FD\u529B");
12756
- await this.adapter.deletePreview({ channelId: this.target, messageId: this.messageId });
12779
+ if (this.channelV === "progress" && this.adapter.removeProgress) {
12780
+ await this.adapter.removeProgress(this.messageId);
12781
+ } else if (!this.adapter.deletePreview) throw new Error("\u65E0\u8FC7\u7A0B\u5361\u6E05\u7406\u80FD\u529B");
12782
+ else await this.adapter.deletePreview({ channelId: this.target, messageId: this.messageId });
12757
12783
  }
12758
12784
  this.messageId = null;
12759
12785
  this.cardKitId = null;
@@ -12764,7 +12790,7 @@ var init_process_card = __esm({
12764
12790
  /** Shared heartbeat samples state; the push key suppresses unchanged cards. */
12765
12791
  startHeartbeat() {
12766
12792
  this.stopHeartbeat();
12767
- const interval = this.channelV === "cardkit" ? 800 : 2500;
12793
+ const interval = this.channelV === "cardkit" || this.channelV === "progress" ? 800 : 2500;
12768
12794
  this.heartbeat = setInterval(() => {
12769
12795
  if (this.state.status !== "run" && this.state.status !== "wait") {
12770
12796
  this.stopHeartbeat();
@@ -12778,10 +12804,10 @@ var init_process_card = __esm({
12778
12804
  if (this.heartbeat) clearInterval(this.heartbeat);
12779
12805
  this.heartbeat = null;
12780
12806
  }
12781
- onToolUse(name, input, id3) {
12807
+ onToolUse(name, input, id3, inputFull) {
12782
12808
  if (this.ended || this.disposed) return;
12783
12809
  this.ensureStarted();
12784
- this.state.rows.push({ kind: "tool", id: id3, name, args: stripCardUnsafe(typeof input === "string" ? input : toolArgsSummary(name, input)), state: "run", out: "", more: 0 });
12810
+ this.state.rows.push({ kind: "tool", id: id3, name, args: stripCardUnsafe(typeof input === "string" ? input : toolArgsSummary(name, input)), state: "run", out: "", more: 0, ...inputFull ? { inputFull: stripCardUnsafe(inputFull.slice(0, OUTFULL_MAX)) } : {} });
12785
12811
  if (this.state.status === "wait") this.state.status = "run";
12786
12812
  this.schedulePatch();
12787
12813
  }
@@ -12794,7 +12820,7 @@ var init_process_card = __esm({
12794
12820
  row = this.state.rows.at(-1);
12795
12821
  }
12796
12822
  if (!row) return;
12797
- const retain = match?.visible !== false || this.nativeCapable();
12823
+ const retain = match?.visible !== false || this.nativeCapable() || this.progressCapable();
12798
12824
  const lines = (out || "").split("\n").filter((line) => line.trim());
12799
12825
  row.state = retain && isError ? "err" : "ok";
12800
12826
  row.resultVisible = match?.visible;
@@ -12928,6 +12954,19 @@ var init_process_card = __esm({
12928
12954
  }
12929
12955
  return false;
12930
12956
  }
12957
+ /** 1119 cc-desk steer:忙时插话在卡片上留 ↪ 行(过程可见) */
12958
+ onSteer(text2) {
12959
+ if (this.ended || this.disposed) return;
12960
+ this.ensureStarted();
12961
+ this.state.steerNotes = [...this.state.steerNotes ?? [], stripCardUnsafe(oneLine(text2))].slice(-3);
12962
+ this.schedulePatch();
12963
+ }
12964
+ /** 1119 卡片停止钮:设置/清除停止按钮的 action value(run/wait 态渲染) */
12965
+ setStopAction(value) {
12966
+ if (this.ended || this.disposed) return;
12967
+ this.state.stopAction = value ?? void 0;
12968
+ this.schedulePatch();
12969
+ }
12931
12970
  turnEnd(finalText, usage, outcome) {
12932
12971
  return this.finish(outcome, finalText, usage);
12933
12972
  }
@@ -12963,7 +13002,7 @@ var init_process_card = __esm({
12963
13002
  return;
12964
13003
  }
12965
13004
  if (this.patchTimer) return;
12966
- const min = this.channelV === "cardkit" ? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
13005
+ const min = this.channelV === "cardkit" || this.channelV === "progress" ? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
12967
13006
  const wait2 = Math.max(0, min - (Date.now() - this.lastPatchAt));
12968
13007
  this.patchTimer = setTimeout(() => {
12969
13008
  this.patchTimer = null;
@@ -12978,7 +13017,7 @@ var init_process_card = __esm({
12978
13017
  await this.creation?.catch(() => {
12979
13018
  });
12980
13019
  if (this.disposed || this.ended && !final) return;
12981
- 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)) {
13020
+ 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)) {
12982
13021
  await this.removeCard().catch((error) => console.warn("[process-card] \u7A7A\u56DE\u5408\u6E05\u7406\u5931\u8D25:", error instanceof Error ? error.message : String(error)));
12983
13022
  return;
12984
13023
  }
@@ -13001,17 +13040,19 @@ var init_process_card = __esm({
13001
13040
  return `q${r.rid}:${r.settled}:${JSON.stringify(r.answers)}`;
13002
13041
  }).join("|");
13003
13042
  const bucket = Math.floor((Date.now() - s.startedAt) / LIVE_BUCKET_MS);
13004
- 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]);
13043
+ 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]);
13005
13044
  }
13006
13045
  async doPatch(final = false) {
13007
13046
  if (this.degraded || !this.messageId && this.channelV !== "cardkit") return false;
13008
13047
  const key2 = this.pushKey();
13009
13048
  if (key2 === this.lastPushKey) return true;
13010
13049
  this.lastPatchAt = Date.now();
13011
- const card = this.channelV === "patch-v1" ? buildProcessCard(this.state) : buildProcessCardV2(this.state) ?? (this.options.allowLegacyCard !== false ? buildProcessCard(this.state) : null);
13012
- if (this.channelV !== "preview" && !card) return false;
13050
+ const card = this.channelV === "progress" ? null : this.channelV === "patch-v1" ? buildProcessCard(this.state) : buildProcessCardV2(this.state) ?? (this.options.allowLegacyCard !== false ? buildProcessCard(this.state) : null);
13051
+ if (this.channelV !== "preview" && this.channelV !== "progress" && !card) return false;
13013
13052
  try {
13014
- if (this.channelV === "preview" && this.previewHandle && this.adapter.editPreview) {
13053
+ if (this.channelV === "progress" && this.messageId && this.adapter.updateProgress) {
13054
+ await this.adapter.updateProgress(this.messageId, structuredClone(this.state));
13055
+ } else if (this.channelV === "preview" && this.previewHandle && this.adapter.editPreview) {
13015
13056
  await this.adapter.editPreview(this.previewHandle, buildProcessText(this.state), this.repoName, final);
13016
13057
  } else if (this.channelV === "cardkit" && this.cardKitId && card) {
13017
13058
  this.seq++;
@@ -13070,6 +13111,12 @@ async function handleCcCardAction(data) {
13070
13111
  const fv = action?.form_value ?? {};
13071
13112
  const v = action?.value;
13072
13113
  if (!v || v.cc !== 1) return { toast: { type: "info", content: "\u672A\u77E5\u64CD\u4F5C" } };
13114
+ if (v.kind === "stop" && typeof v.key === "string") {
13115
+ const { ccDriverRouter: ccDriverRouter2 } = await Promise.resolve().then(() => (init_router(), router_exports));
13116
+ const session = ccDriverRouter2.hub?.forChatKey(v.key);
13117
+ const stopped = session ? session.stopAll() : false;
13118
+ return { toast: { type: stopped ? "success" : "info", content: stopped ? "\u5DF2\u505C\u6B62\u5F53\u524D\u4EFB\u52A1" : "\u5F53\u524D\u6CA1\u6709\u5728\u8DD1\u7684\u4EFB\u52A1" } };
13119
+ }
13073
13120
  if (v.kind === "perm" && v.rid) {
13074
13121
  const p = pendingPerms.get(v.rid);
13075
13122
  if (!p) return { toast: { type: "info", content: "\u8BE5\u5BA1\u6279\u5DF2\u5904\u7406\u6216\u5DF2\u5931\u6548" } };
@@ -13589,6 +13636,9 @@ var init_dep_downloader = __esm({
13589
13636
  function requestError(message, status = 409) {
13590
13637
  return Object.assign(new Error(message), { status });
13591
13638
  }
13639
+ function ccUserMsg(text2) {
13640
+ return { type: "user", message: { role: "user", content: text2 }, parent_tool_use_id: null };
13641
+ }
13592
13642
  function resultToText(content) {
13593
13643
  if (typeof content === "string") return content;
13594
13644
  if (Array.isArray(content)) {
@@ -13613,7 +13663,7 @@ function chunkText(text2, maxChars) {
13613
13663
  if (rest.trim()) chunks.push(rest);
13614
13664
  return chunks;
13615
13665
  }
13616
- var MAX_QUEUE, INTERIM_MIN_INTERVAL_MS, INTERIM_MIN_CHARS, MAX_INTERIM_PER_TURN, INTERIM_SNIPPET_CHARS, FINAL_CHUNK_CHARS, CcDriverSession, CcDriverHub;
13666
+ 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;
13617
13667
  var init_driver = __esm({
13618
13668
  "src/cc-driver/driver.ts"() {
13619
13669
  "use strict";
@@ -13628,6 +13678,53 @@ var init_driver = __esm({
13628
13678
  MAX_INTERIM_PER_TURN = 4;
13629
13679
  INTERIM_SNIPPET_CHARS = 600;
13630
13680
  FINAL_CHUNK_CHARS = 1500;
13681
+ SteerFeeder = class {
13682
+ pending = [];
13683
+ waiters = [];
13684
+ ended = false;
13685
+ /** 已 yield 给 CLI 的消息数(含首条) */
13686
+ yieldCount = 0;
13687
+ /** 最近一次 yield 的文本(续 turn 卡片的 prompt 用) */
13688
+ lastYield = "";
13689
+ /** 注入一条;返回 false = 已收口,进不了这个流了 */
13690
+ push(text2) {
13691
+ if (this.ended && this.pending.length === 0) return false;
13692
+ this.pending.push(text2);
13693
+ for (const w of this.waiters.splice(0)) w();
13694
+ return true;
13695
+ }
13696
+ /** 收口:吐完 pending 后生成器结束 */
13697
+ close() {
13698
+ this.ended = true;
13699
+ for (const w of this.waiters.splice(0)) w();
13700
+ }
13701
+ /** 还有没被 turn 消化的输入吗(未 shift 的 pending + 已 yield 未出 result 的) */
13702
+ expectsMoreTurns(turnsSeen) {
13703
+ return this.pending.length > 0 || this.yieldCount > turnsSeen;
13704
+ }
13705
+ /** 即将注入的下一条(1121:续 turn 卡片显示用——显示"接下来要处理的",不是刚答完的旧消息);无 pending 时 undefined */
13706
+ upcoming() {
13707
+ return this.pending[0];
13708
+ }
13709
+ async *stream(first) {
13710
+ this.yieldCount++;
13711
+ this.lastYield = first;
13712
+ yield ccUserMsg(first);
13713
+ while (true) {
13714
+ if (this.pending.length > 0) {
13715
+ const text2 = this.pending.shift();
13716
+ this.yieldCount++;
13717
+ this.lastYield = text2;
13718
+ yield ccUserMsg(text2);
13719
+ continue;
13720
+ }
13721
+ if (this.ended) return;
13722
+ await new Promise((resolve13) => this.waiters.push(resolve13));
13723
+ }
13724
+ }
13725
+ };
13726
+ defaultCcRuntimeLoader = (onProgress) => loadOptionalModule("cc-runtime", onProgress);
13727
+ ccRuntimeLoader = defaultCcRuntimeLoader;
13631
13728
  CcDriverSession = class {
13632
13729
  constructor(binding, cm, map, predecessor) {
13633
13730
  this.predecessor = predecessor;
@@ -13649,6 +13746,8 @@ var init_driver = __esm({
13649
13746
  revision = 0;
13650
13747
  idleWaiters = [];
13651
13748
  abort = null;
13749
+ /** 当前流式 chunk 的 steer 口(仅用户消息路径开;外部 ask/桌面路径为 null) */
13750
+ feeder = null;
13652
13751
  sessionId = null;
13653
13752
  sendChain = Promise.resolve();
13654
13753
  ui = null;
@@ -13673,11 +13772,16 @@ var init_driver = __esm({
13673
13772
  this.sessionId = null;
13674
13773
  return this.map.clear(this.key) || had;
13675
13774
  }
13676
- /** 入站一条消息:排队(busy 时 FIFO),队列满则提示。 */
13775
+ /** 入站一条消息:流式 chunk 开着 → steer 注入(1119);否则排队(busy 时 FIFO),队列满则提示。 */
13677
13776
  enqueue(text2) {
13678
13777
  const trimmed = text2.trim();
13679
13778
  if (!trimmed || this.closed) return;
13680
13779
  if (this.ui?.routeTyped(trimmed)) return;
13780
+ const feeder = this.feeder;
13781
+ if (feeder && feeder.push(trimmed)) {
13782
+ this.ui?.onSteer(trimmed);
13783
+ return;
13784
+ }
13681
13785
  if (this.queue.length >= MAX_QUEUE) {
13682
13786
  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`);
13683
13787
  return;
@@ -13714,9 +13818,22 @@ var init_driver = __esm({
13714
13818
  this.closed = true;
13715
13819
  this.revision++;
13716
13820
  for (const job of this.queue.splice(0)) job.reject?.(requestError("CC binding stopped before execution", 503));
13821
+ this.feeder?.close();
13717
13822
  this.stop();
13718
13823
  }
13719
- /** 中断当前 turn(队列里后续消息继续) */
13824
+ /**
13825
+ * 全停(1119 翀哥拍板):中断当前 turn + 清 FIFO(外部 ask 按取消拒)+ 关 steer 口。
13826
+ * abort 杀进程 → CLI 里已排队未消费的插话一并死——所见即所得的「全停」。
13827
+ */
13828
+ stopAll() {
13829
+ const hadQueued = this.queue.length > 0;
13830
+ for (const job of this.queue.splice(0)) job.reject?.(requestError("CC request cancelled (stop)", 499));
13831
+ this.feeder?.close();
13832
+ const active = this.busy;
13833
+ if (active) this.stop();
13834
+ return active || hadQueued;
13835
+ }
13836
+ /** 中断当前 turn(不清队列)——外部取消场景用;用户面全停走 stopAll() */
13720
13837
  stop() {
13721
13838
  this.abort?.abort();
13722
13839
  }
@@ -13738,10 +13855,14 @@ var init_driver = __esm({
13738
13855
  if (job.expectedSessionId !== void 0 && job.expectedSessionId !== this.sessionId) {
13739
13856
  throw requestError("CC session changed while this request was queued");
13740
13857
  }
13741
- const prompt = job.source ? `[cc_ask from ${job.source.replace(/[\r\n]/g, " ").slice(0, 160)}]
13742
- ${job.prompt}` : job.prompt;
13743
- const result = await this.runTurn(prompt, job.signal, !!job.source);
13744
- job.resolve?.(result);
13858
+ if (job.source) {
13859
+ const prompt = `[cc_ask from ${job.source.replace(/[\r\n]/g, " ").slice(0, 160)}]
13860
+ ${job.prompt}`;
13861
+ const result = await this.runTurn(prompt, job.signal, true);
13862
+ job.resolve?.(result);
13863
+ } else {
13864
+ await this.runStreaming(job);
13865
+ }
13745
13866
  } catch (err) {
13746
13867
  job.reject?.(err);
13747
13868
  console.error(`[cc-driver] turn \u5931\u8D25 key=${this.key}: ${err?.stack || err}`);
@@ -13775,15 +13896,11 @@ ${job.prompt}` : job.prompt;
13775
13896
  this.ui = null;
13776
13897
  }
13777
13898
  }
13778
- let textSoFar = "";
13779
- let gotPartial = false;
13780
- let lastInterimAt = Date.now();
13781
- let interimCount = 0;
13782
- let lastSentLen = 0;
13783
13899
  let finalText = "";
13784
13900
  let isError = false;
13785
13901
  let gotResult = false;
13786
13902
  let usage = "";
13903
+ const acc = this.makeStreamAccumulator();
13787
13904
  try {
13788
13905
  const desktops = resumedFrom ? await findDesktopTargets(this.workDir, resumedFrom) : [];
13789
13906
  if (desktops.length > 1) throw new Error("Multiple desktop writers claim this CC session; close the duplicate");
@@ -13799,7 +13916,7 @@ ${job.prompt}` : job.prompt;
13799
13916
  throw new Error("This CC session is open in another process; use cc-desktop to receive messages there");
13800
13917
  }
13801
13918
  let ccRuntimeNoticeSent = false;
13802
- const { query } = await loadOptionalModule("cc-runtime", (label, got, total) => {
13919
+ const { query } = await ccRuntimeLoader((label, got, total) => {
13803
13920
  if (ccRuntimeNoticeSent) return;
13804
13921
  ccRuntimeNoticeSent = true;
13805
13922
  const mb = total ? `\u7EA6 ${Math.round(total / 1024 / 1024)}M` : "\u7EA6 350M";
@@ -13843,43 +13960,7 @@ ${job.prompt}` : job.prompt;
13843
13960
  if (process.env.CC_DRIVER_DEBUG) console.log(`[cc-driver:dbg] type=${msg2.type} subtype=${msg2.subtype ?? "-"} sid=${msg2.session_id?.slice(0, 8) ?? "-"}`);
13844
13961
  const parentToolUseId = msg2.parent_tool_use_id;
13845
13962
  if (parentToolUseId) continue;
13846
- if (msg2.type === "stream_event") {
13847
- const ev = msg2.event;
13848
- if (ev.type === "content_block_start" && ev.content_block?.type === "thinking") this.ui?.onThinkingDelta("");
13849
- else if (ev.type === "content_block_delta" && ev.delta?.type === "thinking_delta" && typeof ev.delta.thinking === "string") this.ui?.onThinkingDelta(ev.delta.thinking);
13850
- else if (ev.type === "content_block_stop" && this.ui) this.ui.onThinkingEnd();
13851
- if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && typeof ev.delta.text === "string") {
13852
- gotPartial = true;
13853
- textSoFar += ev.delta.text;
13854
- const now2 = Date.now();
13855
- const newChars = textSoFar.length - lastSentLen;
13856
- if (!this.ui && now2 - lastInterimAt >= INTERIM_MIN_INTERVAL_MS && newChars >= INTERIM_MIN_CHARS && interimCount < MAX_INTERIM_PER_TURN) {
13857
- lastInterimAt = now2;
13858
- lastSentLen = textSoFar.length;
13859
- interimCount++;
13860
- const snippet = textSoFar.slice(-INTERIM_SNIPPET_CHARS);
13861
- void this.sendText(`\u2026${snippet}`);
13862
- }
13863
- }
13864
- } else if (msg2.type === "assistant") {
13865
- const content = msg2.message.content ?? [];
13866
- for (const block of content) {
13867
- if (block.type === "thinking" && block.thinking) this.ui?.onThinking(String(block.thinking));
13868
- else if (block.type === "tool_use" && block.id) this.ui?.onToolUse(String(block.name), block.input ?? {});
13869
- }
13870
- if (!gotPartial) {
13871
- for (const block of content) {
13872
- if (block.type === "text" && typeof block.text === "string") textSoFar += block.text;
13873
- }
13874
- }
13875
- } else if (msg2.type === "user") {
13876
- const content = msg2.message.content;
13877
- if (Array.isArray(content) && this.ui) {
13878
- for (const block of content) {
13879
- if (block.type === "tool_result") this.ui.onToolResult(resultToText(block.content), block.is_error === true);
13880
- }
13881
- }
13882
- } else if (msg2.type === "result") {
13963
+ if (msg2.type === "result") {
13883
13964
  const r = msg2;
13884
13965
  if (r.session_id) {
13885
13966
  turnSessionId = r.session_id;
@@ -13895,6 +13976,8 @@ ${job.prompt}` : job.prompt;
13895
13976
  turnSessionId = sid;
13896
13977
  if (this.revision === revision) this.sessionId = sid;
13897
13978
  }
13979
+ } else {
13980
+ await acc.handle(msg2);
13898
13981
  }
13899
13982
  }
13900
13983
  }
@@ -13903,22 +13986,22 @@ ${job.prompt}` : job.prompt;
13903
13986
  this.abort = null;
13904
13987
  signal?.removeEventListener("abort", cancel);
13905
13988
  }
13906
- const result = { sessionId: turnSessionId, text: finalText || textSoFar, isError: isError || ac.signal.aborted };
13989
+ const result = { sessionId: turnSessionId, text: finalText || acc.textSoFar, isError: isError || ac.signal.aborted };
13907
13990
  if (ac.signal.aborted) {
13908
13991
  if (this.ui && this.ui.alive) {
13909
13992
  await this.ui.turnEnd("", "", "aborted");
13910
- await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (textSoFar ? `
13993
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
13911
13994
  \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
13912
- ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13995
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13913
13996
  return { ...result, text: "[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" };
13914
13997
  }
13915
- await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (textSoFar ? `
13998
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
13916
13999
 
13917
14000
  \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
13918
- ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14001
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13919
14002
  return { ...result, text: "[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" };
13920
14003
  }
13921
- const answer = finalText || textSoFar;
14004
+ const answer = finalText || acc.textSoFar;
13922
14005
  if (this.ui && this.ui.alive) {
13923
14006
  await this.ui.turnEnd("", usage, isError ? "err" : "done");
13924
14007
  if (!answer.trim()) {
@@ -13937,6 +14020,215 @@ ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13937
14020
  }
13938
14021
  return result;
13939
14022
  }
14023
+ /**
14024
+ * stream_event / assistant / user 三类消息的共用处理(runTurn 与 runStreaming 共享;
14025
+ * result / system 两个分支各自的循环里处理——流式 chunk 是多 result 语义)。
14026
+ * 返回 per-turn 累积态访问器(reset 在每个 result 后调)。
14027
+ */
14028
+ makeStreamAccumulator() {
14029
+ let textSoFar = "";
14030
+ let gotPartial = false;
14031
+ let lastInterimAt = Date.now();
14032
+ let interimCount = 0;
14033
+ let lastSentLen = 0;
14034
+ return {
14035
+ reset: () => {
14036
+ textSoFar = "";
14037
+ gotPartial = false;
14038
+ lastInterimAt = Date.now();
14039
+ interimCount = 0;
14040
+ lastSentLen = 0;
14041
+ },
14042
+ handle: async (msg2) => {
14043
+ if (msg2.type === "stream_event") {
14044
+ const ev = msg2.event;
14045
+ if (ev.type === "content_block_start" && ev.content_block?.type === "thinking") this.ui?.onThinkingDelta("");
14046
+ else if (ev.type === "content_block_delta" && ev.delta?.type === "thinking_delta" && typeof ev.delta.thinking === "string") this.ui?.onThinkingDelta(ev.delta.thinking);
14047
+ else if (ev.type === "content_block_stop" && this.ui) this.ui.onThinkingEnd();
14048
+ if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && typeof ev.delta.text === "string") {
14049
+ gotPartial = true;
14050
+ textSoFar += ev.delta.text;
14051
+ const now2 = Date.now();
14052
+ const newChars = textSoFar.length - lastSentLen;
14053
+ if (!this.ui && now2 - lastInterimAt >= INTERIM_MIN_INTERVAL_MS && newChars >= INTERIM_MIN_CHARS && interimCount < MAX_INTERIM_PER_TURN) {
14054
+ lastInterimAt = now2;
14055
+ lastSentLen = textSoFar.length;
14056
+ interimCount++;
14057
+ const snippet = textSoFar.slice(-INTERIM_SNIPPET_CHARS);
14058
+ void this.sendText(`\u2026${snippet}`);
14059
+ }
14060
+ }
14061
+ } else if (msg2.type === "assistant") {
14062
+ const content = msg2.message.content ?? [];
14063
+ for (const block of content) {
14064
+ if (block.type === "thinking" && block.thinking) this.ui?.onThinking(String(block.thinking));
14065
+ else if (block.type === "tool_use" && block.id) this.ui?.onToolUse(String(block.name), block.input ?? {});
14066
+ }
14067
+ if (!gotPartial) {
14068
+ for (const block of content) {
14069
+ if (block.type === "text" && typeof block.text === "string") textSoFar += block.text;
14070
+ }
14071
+ }
14072
+ } else if (msg2.type === "user") {
14073
+ const content = msg2.message.content;
14074
+ if (Array.isArray(content) && this.ui) {
14075
+ for (const block of content) {
14076
+ if (block.type === "tool_result") this.ui.onToolResult(resultToText(block.content), block.is_error === true);
14077
+ }
14078
+ }
14079
+ }
14080
+ },
14081
+ get textSoFar() {
14082
+ return textSoFar;
14083
+ }
14084
+ };
14085
+ }
14086
+ /**
14087
+ * 用户消息的流式 chunk(1119 cc-desk steer):一次 query() 的 prompt 是 feeder 生成器,
14088
+ * busy 时 enqueue → feeder.push 注入(模型下一次 API 调用看到),同一进程可出多个
14089
+ * result(每 result 交付一轮答案);全部消化完 → close → 进程退出,空闲零进程不变。
14090
+ * 桌面托管 / 他进程占用 → 退回 runTurn 封闭路径(桌面桥无 steer)。
14091
+ */
14092
+ async runStreaming(job) {
14093
+ const resumedFrom = this.sessionId;
14094
+ const desktops = resumedFrom ? await findDesktopTargets(this.workDir, resumedFrom) : [];
14095
+ if (desktops.length > 0 || resumedFrom && nativeSessionOwners(resumedFrom).length) {
14096
+ await this.runTurn(job.prompt, job.signal, false);
14097
+ return;
14098
+ }
14099
+ const ac = new AbortController();
14100
+ this.abort = ac;
14101
+ const revision = this.revision;
14102
+ let turnSessionId = resumedFrom;
14103
+ const cancel = () => ac.abort();
14104
+ job.signal?.addEventListener("abort", cancel, { once: true });
14105
+ if (job.signal?.aborted) ac.abort();
14106
+ console.log(`[cc-driver] streaming turn start key=${this.key} resume=${resumedFrom ? resumedFrom.slice(0, 8) : "new"} cwd=${this.workDir}`);
14107
+ if (this.binding.channel === "feishu" && !this.uiTried) {
14108
+ this.uiTried = true;
14109
+ this.ui = await makeFeishuCardUi(this.cm, this.binding);
14110
+ }
14111
+ if (this.ui) {
14112
+ try {
14113
+ await this.ui.turnStart(job.prompt);
14114
+ this.ui.setStopAction({ cc: 1, kind: "stop", key: this.key });
14115
+ } catch (err) {
14116
+ console.warn(`[cc-driver:card] \u5F00\u5361\u5931\u8D25\uFF0C\u672C binding \u56DE\u9000\u7EAF\u6587\u672C\uFF1A${err?.message ?? err}`);
14117
+ this.ui = null;
14118
+ }
14119
+ }
14120
+ const feeder = new SteerFeeder();
14121
+ this.feeder = feeder;
14122
+ const acc = this.makeStreamAccumulator();
14123
+ let turnsSeen = 0;
14124
+ let deliveredAfterAbort = false;
14125
+ try {
14126
+ const { query } = await ccRuntimeLoader();
14127
+ const stream = query({
14128
+ prompt: feeder.stream(job.prompt),
14129
+ options: {
14130
+ abortController: ac,
14131
+ cwd: this.workDir,
14132
+ ...this.binding.permissionMode && this.binding.permissionMode !== "auto" ? { permissionMode: this.binding.permissionMode } : {},
14133
+ model: this.binding.model,
14134
+ resume: resumedFrom ?? void 0,
14135
+ includePartialMessages: true,
14136
+ ...this.ui ? {
14137
+ canUseTool: async (toolName, input, opts) => {
14138
+ if (!this.ui) return { behavior: "deny", message: "\u5361\u7247\u901A\u9053\u5DF2\u65AD\u5F00\uFF0C\u64CD\u4F5C\u88AB\u62D2\u7EDD\u3002" };
14139
+ if (toolName === "AskUserQuestion") {
14140
+ const questions = normalizeQuestions(input.questions);
14141
+ 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" };
14142
+ const r2 = await this.ui.askUser(questions, opts.signal);
14143
+ if (r2.answers) return { behavior: "allow", updatedInput: { ...input, answers: r2.answers } };
14144
+ 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" };
14145
+ }
14146
+ const r = await this.ui.askPermission(toolName, input, opts.signal, opts.suggestions);
14147
+ 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" };
14148
+ return {
14149
+ behavior: "allow",
14150
+ updatedInput: input,
14151
+ ...r.verdict === "always" && Array.isArray(opts.suggestions) && opts.suggestions.length > 0 ? { updatedPermissions: opts.suggestions } : {}
14152
+ };
14153
+ }
14154
+ } : {}
14155
+ }
14156
+ });
14157
+ try {
14158
+ for await (const msg2 of stream) {
14159
+ if (process.env.CC_DRIVER_DEBUG) console.log(`[cc-driver:dbg] type=${msg2.type} subtype=${msg2.subtype ?? "-"} sid=${msg2.session_id?.slice(0, 8) ?? "-"}`);
14160
+ const parentToolUseId = msg2.parent_tool_use_id;
14161
+ if (parentToolUseId) continue;
14162
+ if (msg2.type === "result") {
14163
+ const r = msg2;
14164
+ turnsSeen++;
14165
+ if (r.session_id) {
14166
+ turnSessionId = r.session_id;
14167
+ if (this.revision === revision) this.sessionId = r.session_id;
14168
+ }
14169
+ const isError = r.is_error === true;
14170
+ const finalText = typeof r.result === "string" ? r.result : "";
14171
+ const usage = r.usage ? `\u2193 ${fmtTok(r.usage.input_tokens)} \xB7 \u2191 ${fmtTok(r.usage.output_tokens)}` : "";
14172
+ if (turnSessionId && this.revision === revision) this.map.switchTo(this.key, turnSessionId, this.workDir);
14173
+ const more = feeder.expectsMoreTurns(turnsSeen);
14174
+ const answer = finalText || acc.textSoFar;
14175
+ if (ac.signal.aborted) deliveredAfterAbort = true;
14176
+ if (this.ui && this.ui.alive) {
14177
+ await this.ui.turnEnd("", usage, isError ? "err" : "done");
14178
+ }
14179
+ if (!answer.trim()) {
14180
+ 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");
14181
+ } else {
14182
+ for (const chunk of chunkText(answer, FINAL_CHUNK_CHARS)) await this.sendText(chunk);
14183
+ }
14184
+ acc.reset();
14185
+ if (ac.signal.aborted) break;
14186
+ if (!more) {
14187
+ feeder.close();
14188
+ break;
14189
+ }
14190
+ if (this.ui) {
14191
+ try {
14192
+ await this.ui.turnStart(`\u21AA ${feeder.upcoming() ?? feeder.lastYield}`);
14193
+ this.ui.setStopAction({ cc: 1, kind: "stop", key: this.key });
14194
+ } catch (err) {
14195
+ console.warn(`[cc-driver:card] \u7EED turn \u5F00\u5361\u5931\u8D25\uFF0C\u56DE\u9000\u7EAF\u6587\u672C\uFF1A${err?.message ?? err}`);
14196
+ this.ui = null;
14197
+ }
14198
+ }
14199
+ } else if (msg2.type === "system" && msg2.subtype === "init") {
14200
+ const sid = msg2.session_id;
14201
+ if (sid) {
14202
+ turnSessionId = sid;
14203
+ if (this.revision === revision) this.sessionId = sid;
14204
+ }
14205
+ } else {
14206
+ await acc.handle(msg2);
14207
+ }
14208
+ }
14209
+ } catch (err) {
14210
+ if (!(ac.signal.aborted || !feeder.expectsMoreTurns(turnsSeen))) throw err;
14211
+ }
14212
+ } finally {
14213
+ feeder.close();
14214
+ this.feeder = null;
14215
+ this.abort = null;
14216
+ job.signal?.removeEventListener("abort", cancel);
14217
+ }
14218
+ if (ac.signal.aborted && !deliveredAfterAbort) {
14219
+ if (this.ui && this.ui.alive) {
14220
+ await this.ui.turnEnd("", "", "aborted");
14221
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
14222
+ \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
14223
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14224
+ } else {
14225
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
14226
+
14227
+ \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
14228
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14229
+ }
14230
+ }
14231
+ }
13940
14232
  /** 串行发送器:wechat 3s 节流在适配器层,这里保证不并发、失败不炸链 */
13941
14233
  sendText(text2) {
13942
14234
  const task = this.sendChain.then(async () => {
@@ -13984,6 +14276,12 @@ ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13984
14276
  forChat(channel, chatId) {
13985
14277
  return this.sessions.get(`${channel}:${chatId}`);
13986
14278
  }
14279
+ /** 按 bindingKey(channel:chatId)找 session——卡片停止钮回调用(1119) */
14280
+ forChatKey(key2) {
14281
+ const idx = key2.indexOf(":");
14282
+ if (idx <= 0) return void 0;
14283
+ return this.sessions.get(key2);
14284
+ }
13987
14285
  /** 全部绑定的工作目录(去重;cc-progress 工具省参推断用) */
13988
14286
  get bindingWorkDirs() {
13989
14287
  return [...new Set([...this.sessions.values()].map((s) => s.workDir))];
@@ -14121,6 +14419,12 @@ var init_cc_driver = __esm({
14121
14419
  });
14122
14420
 
14123
14421
  // src/cc-driver/router.ts
14422
+ var router_exports = {};
14423
+ __export(router_exports, {
14424
+ autoBindHit: () => autoBindHit,
14425
+ ccDriverRouter: () => ccDriverRouter,
14426
+ markBindSelect: () => markBindSelect
14427
+ });
14124
14428
  import { existsSync as existsSync8 } from "node:fs";
14125
14429
  function autoBindHit(inbound) {
14126
14430
  if (inbound.channel !== "feishu" || inbound.channelType !== "dm") return null;
@@ -14150,6 +14454,14 @@ async function doAutoBind(inbound, workDir) {
14150
14454
  await cmRef.send(inbound.channel, inbound.channel_id, persisted ? `\u2705 \u5DF2\u63A5\u5165 CC\uFF08${workDir}\uFF09\u2014\u2014\u518D\u8BF4\u4E00\u53E5\u8BDD\u5C31\u5F00\u59CB\u3002
14151
14455
  /cc-list \u770B\u4F1A\u8BDD\uFF0C/cc-switch \u6362\u7EBF\u3002` : `\u26A0\uFE0F \u5DF2\u63A5\u5165 CC\uFF0C\u4F46\u914D\u7F6E\u6CA1\u5199\u8FDB\u6587\u4EF6\uFF08\u91CD\u542F\u540E\u4F1A\u56DE\u5230\u672A\u7ED1\u5B9A\uFF09\u2014\u2014\u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u6743\u9650\u540E\u91CD\u8BD5\u3002`);
14152
14456
  }
14457
+ function markBindSelect(channel, chatId) {
14458
+ pendingBind.set(`${channel}:${chatId}`, Date.now());
14459
+ while (pendingBind.size > 32) {
14460
+ const oldest = pendingBind.keys().next().value;
14461
+ if (oldest === void 0) break;
14462
+ pendingBind.delete(oldest);
14463
+ }
14464
+ }
14153
14465
  function peekBindNumber(inbound) {
14154
14466
  if (inbound.channelType !== "dm") return null;
14155
14467
  const ts = pendingBind.get(`${inbound.channel}:${inbound.channel_id}`);
@@ -18507,7 +18819,7 @@ import { createHash as createHash3 } from "node:crypto";
18507
18819
  // src/continuity/inventory.ts
18508
18820
  import { isAbsolute, join as join4, relative, resolve as resolve2, sep } from "node:path";
18509
18821
  var STATE = new Set(`workspace agents auth configs cron media mem7 memory runtime session-memory steer tasks teams todos tools topics topics-history .everos .calendar calendar proactive skills prompts goals.json goal-events.jsonl SESSION-STATE.md install-identity.json license.json report-failures.jsonl report-state.json service-suggestions.json weixin cc-driver engines.json settings.json onboarding.json onboarding-tips.json remote-watchers.json plans telegram state`.split(" "));
18510
- var CORE_DIRECTORIES = new Set(`agents auth configs cron mem7 memory runtime session-memory steer tasks teams todos tools .everos .calendar calendar .proactive proactive skills prompts .nudge hooks inner-voice goals plans private scripts state .voice-chat .desktopBuddy body`.split(" "));
18822
+ var CORE_DIRECTORIES = new Set(`agents auth configs cron mem7 memory runtime session-memory steer tasks teams todos tools .everos .calendar calendar .proactive proactive skills prompts topics .nudge hooks inner-voice goals plans private scripts state .voice-chat .desktopBuddy body`.split(" "));
18511
18823
  var CORE_OMITTED = new Set(`media images videos audio content content-library docs output outputs dogfood-output backup backups topics-history node_modules .venvs venv .venv asr .cache cache caches tmp temp .playwright-mcp lancedb`.split(" "));
18512
18824
  function validateRelativePath(path35) {
18513
18825
  if (typeof path35 !== "string" || !path35 || path35.length > 2048 || isAbsolute(path35)) throw new Error("INVALID_ARTIFACT_PATH");
@@ -19174,6 +19486,18 @@ var TravelGatewayStore = class {
19174
19486
  }
19175
19487
  /** Host-owned import of actual previously processed platform IDs. A receipt
19176
19488
  * is negative dedupe only: it cannot create input or enqueue a task. */
19489
+ async begin(principal, permit, channel) {
19490
+ this.active(principal, permit, "SEND");
19491
+ if (!["feishu", "discord", "wechat"].includes(channel)) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19492
+ const body = Buffer.from(JSON.stringify({ format: "engine7-gateway-engine-event-v1", channel, nodeId: permit.nodeId, bootId: permit.bootId, epoch: permit.epoch }));
19493
+ const ref = await this.options.objects.putContent(body);
19494
+ return this.transaction(() => {
19495
+ this.active(principal, permit, "SEND");
19496
+ const id3 = digest4("engine:" + randomUUID12());
19497
+ this.db.prepare("INSERT INTO inbox(event_id,body_hash,body_ref,session_hash,occurred_at,state,channel,node_id,boot_id,epoch) VALUES(?,?,?,?,?,'ENGINE',?,?,?,?)").run(id3, digest4(body), JSON.stringify(ref), digest4(id3), Date.now(), channel, permit.nodeId, permit.bootId, permit.epoch);
19498
+ return { id: id3 };
19499
+ });
19500
+ }
19177
19501
  importProcessedInputs(platformIds) {
19178
19502
  if (!Array.isArray(platformIds) || platformIds.length > 1e5 || platformIds.some((id3) => typeof id3 !== "string" || !id3 || id3.length > 512)) throw new Error("TRAVEL_GATEWAY_INVALID_EVENT");
19179
19503
  this.transaction(() => {
@@ -19599,7 +19923,7 @@ function createTravelGatewayServer(options) {
19599
19923
  return;
19600
19924
  }
19601
19925
  const action = req.url?.startsWith(prefix) ? req.url.slice(prefix.length) : "";
19602
- if (req.method !== "POST" || !recovering && !["preparation", "exit-dedupe", "claim", "ack", "finish", "produce", "produce-batch", "effects", "dispatch", "tool-start", "tool-finish", "tool-result", "resource"].includes(action)) {
19926
+ if (req.method !== "POST" || !recovering && !["preparation", "exit-dedupe", "begin", "claim", "ack", "finish", "produce", "produce-batch", "effects", "dispatch", "tool-start", "tool-finish", "tool-result", "resource"].includes(action)) {
19603
19927
  reply(404, { error: "TRAVEL_GATEWAY_NOT_FOUND" });
19604
19928
  req.resume();
19605
19929
  return;
@@ -19636,7 +19960,7 @@ function createTravelGatewayServer(options) {
19636
19960
  reply(200, store.applyRecoveryDeletedInputs(principal, input.bindings, input.floor));
19637
19961
  return;
19638
19962
  }
19639
- if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key2) => !["permit", "options", "eventId", "input", "inputs", "effectId", "dispatchId", "resultBase64", "index", "finalOutput"].includes(key2))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19963
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key2) => !["permit", "options", "eventId", "input", "inputs", "effectId", "dispatchId", "resultBase64", "index", "finalOutput", "channel"].includes(key2))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19640
19964
  if (action === "preparation") {
19641
19965
  if (Object.keys(input).length) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19642
19966
  reply(200, store.preparationEvidence(principal));
@@ -19652,6 +19976,11 @@ function createTravelGatewayServer(options) {
19652
19976
  reply(200, store.exitDedupeReceipt(principal, permit));
19653
19977
  return;
19654
19978
  }
19979
+ if (action === "begin") {
19980
+ if (typeof input.channel !== "string" || !["feishu", "discord", "wechat"].includes(input.channel)) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19981
+ reply(200, await store.begin(principal, permit, input.channel));
19982
+ return;
19983
+ }
19655
19984
  if (action === "claim") {
19656
19985
  const claims = await store.claim(principal, permit, input.options);
19657
19986
  reply(200, claims.map(({ body: body2, ...claim }) => ({ ...claim, bodyBase64: body2.toString("base64") })));
@@ -19819,6 +20148,12 @@ var TravelGatewayClient = class {
19819
20148
  async ack(permit, eventId) {
19820
20149
  await this.call("ack", { permit, eventId });
19821
20150
  }
20151
+ /** 1121:引擎主动开口——开一个 ENGINE 态事件承载 effect 台账。 */
20152
+ async begin(permit, channel) {
20153
+ const result = await this.call("begin", { permit, channel });
20154
+ if (!result || typeof result.id !== "string" || !/^[a-f0-9]{64}$/.test(result.id)) throw new Error("TRAVEL_GATEWAY_INVALID_RESPONSE");
20155
+ return result;
20156
+ }
19822
20157
  async finish(permit, eventId) {
19823
20158
  await this.call("finish", { permit, eventId });
19824
20159
  }
@@ -27308,7 +27643,7 @@ function assertImageAssetRef(ref) {
27308
27643
  throw new Error("Invalid or oversized image asset reference");
27309
27644
  }
27310
27645
  }
27311
- async function materializeImageMessages(messages, store, signal, maxBase64Bytes = REQUEST_IMAGE_MAX_BASE64_SIZE) {
27646
+ async function materializeImageMessages(messages, store, signal, maxBase64Bytes = REQUEST_IMAGE_MAX_BASE64_SIZE, opts = {}) {
27312
27647
  signal?.throwIfAborted();
27313
27648
  let total = 0;
27314
27649
  for (const message of messages) if (Array.isArray(message.content)) for (const block of message.content) {
@@ -27333,6 +27668,7 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
27333
27668
  return { ...message, content: content.length ? content : "[previous image omitted]" };
27334
27669
  });
27335
27670
  if (total > maxBase64Bytes) throw new Error(`Request image base64 exceeds ${maxBase64Bytes} byte limit`);
27671
+ const { strict = false } = opts;
27336
27672
  const cache = /* @__PURE__ */ new Map();
27337
27673
  const output = [];
27338
27674
  for (const message of requestView) {
@@ -27349,8 +27685,12 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
27349
27685
  }
27350
27686
  if (!store) throw new Error("Image asset store is required to materialize image refs");
27351
27687
  const key2 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
27352
- if (!cache.has(key2)) cache.set(key2, store.materialize(block.image));
27353
- content.push(await cache.get(key2));
27688
+ if (!cache.has(key2)) cache.set(key2, store.materialize(block.image).catch((error) => {
27689
+ if (strict) throw error;
27690
+ 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)}`);
27691
+ return null;
27692
+ }));
27693
+ content.push(await cache.get(key2) ?? { type: "text", text: "[\u56FE\u7247\u6587\u4EF6\u5DF2\u4E0D\u5728\u672C\u673A\uFF0C\u5185\u5BB9\u4E0D\u53EF\u89C1]" });
27354
27694
  signal?.throwIfAborted();
27355
27695
  }
27356
27696
  output.push({ ...message, content });
@@ -34767,6 +35107,7 @@ function createFeishuGatewayDispatcher(options) {
34767
35107
  body: Buffer.from(JSON.stringify({ format, event: { sender, message }, ...resources.length ? { resources } : {} }))
34768
35108
  });
34769
35109
  options.assertIngress?.();
35110
+ if (sender.sender_type !== "bot") options.onReceivedTyping?.(message.chat_id, sender.sender_id?.open_id, message.message_id);
34770
35111
  },
34771
35112
  "im.message.reaction.created_v1": async () => {
34772
35113
  },
@@ -34818,7 +35159,34 @@ function createFeishuGatewayPlatform(options) {
34818
35159
  return config;
34819
35160
  });
34820
35161
  let closed = false;
35162
+ const typing = /* @__PURE__ */ new Map(), openToChat = /* @__PURE__ */ new Map();
35163
+ const removeReaction = (messageId, reactionId) => client.im.messageReaction.delete({ path: { message_id: messageId, reaction_id: reactionId } }).catch(() => {
35164
+ });
35165
+ const startChatTyping = (chatId, openId, messageId) => {
35166
+ if (closed) return;
35167
+ if (openId) openToChat.set(openId, chatId);
35168
+ const current2 = typing.get(chatId);
35169
+ if (current2?.messageId === messageId) return;
35170
+ if (current2?.reactionId) removeReaction(current2.messageId, current2.reactionId);
35171
+ typing.set(chatId, { messageId });
35172
+ client.im.messageReaction.create({ path: { message_id: messageId }, data: { reaction_type: { emoji_type: "Typing" } } }).then((response) => {
35173
+ const reactionId = response?.data?.reaction_id, entry = typing.get(chatId);
35174
+ if (reactionId && entry && entry.messageId === messageId) entry.reactionId = reactionId;
35175
+ else if (reactionId) removeReaction(messageId, reactionId);
35176
+ }).catch(() => {
35177
+ });
35178
+ };
35179
+ const stopChatTyping = (target) => {
35180
+ const chatId = target.startsWith("ou_") ? openToChat.get(target) : target;
35181
+ if (!chatId) return;
35182
+ const entry = typing.get(chatId);
35183
+ if (!entry) return;
35184
+ typing.delete(chatId);
35185
+ if (entry.reactionId) removeReaction(entry.messageId, entry.reactionId);
35186
+ };
34821
35187
  return {
35188
+ startChatTyping,
35189
+ stopChatTyping,
34822
35190
  deliver: async (effect, body, assertCurrent) => {
34823
35191
  if (closed) throw new Error("TRAVEL_FEISHU_CLOSED");
34824
35192
  const media = effect.kind === "MEDIA" ? decodeGatewayMedia(body) : void 0;
@@ -34846,6 +35214,7 @@ function createFeishuGatewayPlatform(options) {
34846
35214
  assertCurrent();
34847
35215
  const result = await client.im.message.create({ params: { receive_id_type: packet.target.startsWith("ou_") ? "open_id" : "chat_id" }, data: { receive_id: packet.target, msg_type: msgType, content: JSON.stringify(content), uuid: effect.platformKey } });
34848
35216
  if (result.code !== 0 || typeof result.data?.message_id !== "string" || !result.data.message_id) throw new Error("TRAVEL_FEISHU_SEND_UNKNOWN");
35217
+ if (effect.kind === "REPLY") stopChatTyping(packet.target);
34849
35218
  return { messageId: result.data.message_id };
34850
35219
  });
34851
35220
  },
@@ -34978,78 +35347,101 @@ var RemoteTravelChannel = class {
34978
35347
  });
34979
35348
  }));
34980
35349
  }
34981
- async send(target, message, options) {
34982
- const context = travelEventContext();
34983
- if (!context || context.client !== this.options.client) throw new Error("TRAVEL_GATEWAY_CONTEXT_REQUIRED");
34984
- if (context.failed) throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
34985
- assertExternalEffectCurrent();
34986
- travelEventPermit(context);
34987
- const config = resolveBubbleSplit(this.name), bubbles = config.on && options?.bubbleSplit === true ? splitBubbles(message) : null;
34988
- const chunks = bubbles ?? (this.name === "feishu" ? splitFeishuGatewayText(message) : splitChannelGatewayText(message, this.name));
34989
- const kind = travelOutputKind(), ordinal = (context.ordinals[kind] ?? 0) + 1;
34990
- context.ordinals[kind] = ordinal + chunks.length - 1;
35350
+ /** 1121:主动开口的落点。有进站事件就在其上下文里发(原语义);没有(cron/
35351
+ * inner-voice/nudge 主动消息)就在网关开一个 ENGINE 事件承载 effect 台账,
35352
+ * 复用同一套 produce/dispatch/finish 对账,绝不绕开网关直发。 */
35353
+ async effect(run) {
35354
+ const existing = travelEventContext();
35355
+ if (existing) {
35356
+ if (existing.client !== this.options.client) throw new Error("TRAVEL_GATEWAY_CONTEXT_REQUIRED");
35357
+ return run(existing);
35358
+ }
35359
+ const permit = this.options.permit();
35360
+ const { id: id3 } = await this.options.client.begin(permit, this.name);
35361
+ const context = { eventId: id3, originalPermit: permit, permit: this.options.permit, client: this.options.client, ordinals: {}, queued: false, failed: false, complete: false };
34991
35362
  try {
34992
- const effects2 = await context.client.produceBatch(travelEventPermit(context), chunks.map((text2, index) => ({
34993
- eventId: context.eventId,
34994
- kind,
34995
- ordinal: ordinal + index,
34996
- version: 1,
34997
- body: Buffer.from(JSON.stringify({ channel: this.name, target, text: text2, format: this.name === "feishu" ? "post" : "text", ...index === 0 && options?.replyTo ? { replyTo: options.replyTo } : {} }))
34998
- })), { finalOutput: options?.extra?.travelFinalReply === true });
34999
- for (let index = 0; index < effects2.length; index++) {
35000
- assertExternalEffectCurrent();
35001
- await context.client.dispatch(travelEventPermit(context), effects2[index].id);
35002
- if (bubbles && index < effects2.length - 1 && config.gapMs > 0) await new Promise((resolve13) => setTimeout(resolve13, Math.min(config.gapMs, 6e4)));
35003
- }
35363
+ const value = await withTravelEventContext(context, () => run(context));
35364
+ await completeTravelEvent(context);
35365
+ return value;
35004
35366
  } catch (error) {
35005
35367
  context.failed = true;
35368
+ await this.options.client.finish(this.options.permit(), id3).catch(() => {
35369
+ });
35006
35370
  throw error;
35007
35371
  }
35008
35372
  }
35373
+ async send(target, message, options) {
35374
+ await this.effect(async (context) => {
35375
+ if (context.failed) throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
35376
+ assertExternalEffectCurrent();
35377
+ travelEventPermit(context);
35378
+ const config = resolveBubbleSplit(this.name), bubbles = config.on && options?.bubbleSplit === true ? splitBubbles(message) : null;
35379
+ const chunks = bubbles ?? (this.name === "feishu" ? splitFeishuGatewayText(message) : splitChannelGatewayText(message, this.name));
35380
+ const kind = travelOutputKind(), ordinal = (context.ordinals[kind] ?? 0) + 1;
35381
+ context.ordinals[kind] = ordinal + chunks.length - 1;
35382
+ try {
35383
+ const effects2 = await context.client.produceBatch(travelEventPermit(context), chunks.map((text2, index) => ({
35384
+ eventId: context.eventId,
35385
+ kind,
35386
+ ordinal: ordinal + index,
35387
+ version: 1,
35388
+ body: Buffer.from(JSON.stringify({ channel: this.name, target, text: text2, format: this.name === "feishu" ? "post" : "text", ...index === 0 && options?.replyTo ? { replyTo: options.replyTo } : {} }))
35389
+ })), { finalOutput: options?.extra?.travelFinalReply === true });
35390
+ for (let index = 0; index < effects2.length; index++) {
35391
+ assertExternalEffectCurrent();
35392
+ await context.client.dispatch(travelEventPermit(context), effects2[index].id);
35393
+ if (bubbles && index < effects2.length - 1 && config.gapMs > 0) await new Promise((resolve13) => setTimeout(resolve13, Math.min(config.gapMs, 6e4)));
35394
+ }
35395
+ } catch (error) {
35396
+ context.failed = true;
35397
+ throw error;
35398
+ }
35399
+ });
35400
+ }
35009
35401
  async sendFile(target, message, attachment) {
35010
- const context = travelEventContext();
35011
- if (!context || context.client !== this.options.client) throw new Error("TRAVEL_GATEWAY_CONTEXT_REQUIRED");
35012
- if (context.failed) throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
35013
- assertExternalEffectCurrent();
35014
- travelEventPermit(context);
35015
- const handle = await open2(attachment.path, "r");
35016
- let bytes2;
35017
- try {
35018
- const info = await handle.stat();
35019
- if (!info.isFile() || !info.size || info.size > gatewayMediaLimit) throw new Error("TRAVEL_GATEWAY_MEDIA_LIMIT");
35020
- bytes2 = Buffer.alloc(info.size);
35021
- let offset = 0;
35022
- while (offset < bytes2.length) {
35023
- const read2 = await handle.read(bytes2, offset, bytes2.length - offset, offset);
35024
- if (!read2.bytesRead) throw new Error("TRAVEL_GATEWAY_MEDIA_CHANGED");
35025
- offset += read2.bytesRead;
35026
- }
35027
- const after = await handle.stat();
35028
- if (info.size !== after.size || info.mtimeMs !== after.mtimeMs) throw new Error("TRAVEL_GATEWAY_MEDIA_CHANGED");
35029
- } finally {
35030
- await handle.close();
35031
- }
35032
- assertExternalEffectCurrent();
35033
- travelEventPermit(context);
35034
- const mimeType = attachment.mimeType ?? "application/octet-stream", filename = attachment.filename ?? basename7(attachment.path);
35035
- const captions = message && !mimeType.startsWith("image/") ? this.name === "feishu" ? splitFeishuGatewayText(message) : splitChannelGatewayText(message, this.name) : [];
35036
- const ordinal = (context.ordinals.MEDIA ?? 0) + 1;
35037
- context.ordinals.MEDIA = ordinal;
35038
- const kind = travelOutputKind(), replyOrdinal = (context.ordinals[kind] ?? 0) + 1;
35039
- context.ordinals[kind] = replyOrdinal + captions.length - 1;
35040
- try {
35041
- const effects2 = await context.client.produceBatch(travelEventPermit(context), [
35042
- { eventId: context.eventId, kind: "MEDIA", ordinal, version: 1, body: encodeGatewayMedia({ channel: this.name, target, text: mimeType.startsWith("image/") ? message : "", filename, mimeType, voiceDurationSec: attachment.voiceDurationSec }, bytes2) },
35043
- ...captions.map((text2, index) => ({ eventId: context.eventId, kind, ordinal: replyOrdinal + index, version: 1, body: Buffer.from(JSON.stringify({ channel: this.name, target, text: text2, format: this.name === "feishu" ? "post" : "text" })) }))
35044
- ]);
35045
- for (const effect of effects2) {
35046
- assertExternalEffectCurrent();
35047
- await context.client.dispatch(travelEventPermit(context), effect.id);
35402
+ await this.effect(async (context) => {
35403
+ if (context.failed) throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
35404
+ assertExternalEffectCurrent();
35405
+ travelEventPermit(context);
35406
+ const handle = await open2(attachment.path, "r");
35407
+ let bytes2;
35408
+ try {
35409
+ const info = await handle.stat();
35410
+ if (!info.isFile() || !info.size || info.size > gatewayMediaLimit) throw new Error("TRAVEL_GATEWAY_MEDIA_LIMIT");
35411
+ bytes2 = Buffer.alloc(info.size);
35412
+ let offset = 0;
35413
+ while (offset < bytes2.length) {
35414
+ const read2 = await handle.read(bytes2, offset, bytes2.length - offset, offset);
35415
+ if (!read2.bytesRead) throw new Error("TRAVEL_GATEWAY_MEDIA_CHANGED");
35416
+ offset += read2.bytesRead;
35417
+ }
35418
+ const after = await handle.stat();
35419
+ if (info.size !== after.size || info.mtimeMs !== after.mtimeMs) throw new Error("TRAVEL_GATEWAY_MEDIA_CHANGED");
35420
+ } finally {
35421
+ await handle.close();
35048
35422
  }
35049
- } catch (error) {
35050
- context.failed = true;
35051
- throw error;
35052
- }
35423
+ assertExternalEffectCurrent();
35424
+ travelEventPermit(context);
35425
+ const mimeType = attachment.mimeType ?? "application/octet-stream", filename = attachment.filename ?? basename7(attachment.path);
35426
+ const captions = message && !mimeType.startsWith("image/") ? this.name === "feishu" ? splitFeishuGatewayText(message) : splitChannelGatewayText(message, this.name) : [];
35427
+ const ordinal = (context.ordinals.MEDIA ?? 0) + 1;
35428
+ context.ordinals.MEDIA = ordinal;
35429
+ const kind = travelOutputKind(), replyOrdinal = (context.ordinals[kind] ?? 0) + 1;
35430
+ context.ordinals[kind] = replyOrdinal + captions.length - 1;
35431
+ try {
35432
+ const effects2 = await context.client.produceBatch(travelEventPermit(context), [
35433
+ { eventId: context.eventId, kind: "MEDIA", ordinal, version: 1, body: encodeGatewayMedia({ channel: this.name, target, text: mimeType.startsWith("image/") ? message : "", filename, mimeType, voiceDurationSec: attachment.voiceDurationSec }, bytes2) },
35434
+ ...captions.map((text2, index) => ({ eventId: context.eventId, kind, ordinal: replyOrdinal + index, version: 1, body: Buffer.from(JSON.stringify({ channel: this.name, target, text: text2, format: this.name === "feishu" ? "post" : "text" })) }))
35435
+ ]);
35436
+ for (const effect of effects2) {
35437
+ assertExternalEffectCurrent();
35438
+ await context.client.dispatch(travelEventPermit(context), effect.id);
35439
+ }
35440
+ } catch (error) {
35441
+ context.failed = true;
35442
+ throw error;
35443
+ }
35444
+ });
35053
35445
  }
35054
35446
  };
35055
35447
 
@@ -35671,6 +36063,7 @@ async function startTravelGateway(config) {
35671
36063
  encryptKey: config.feishu.encryptKey,
35672
36064
  assertIngress: assertKey,
35673
36065
  authorizeStop: (sender) => Array.isArray(config.feishu.stopAllowedUserIds) && config.feishu.stopAllowedUserIds.includes(sender.sender_id?.open_id),
36066
+ onReceivedTyping: (chatId, openId, messageId) => platform.startChatTyping(chatId, openId, messageId),
35674
36067
  downloadResource: async (messageId, key2, type) => {
35675
36068
  assertKey();
35676
36069
  return platform.downloadResource(messageId, key2, type);
@@ -35890,6 +36283,7 @@ async function startPairingControl(config) {
35890
36283
  }
35891
36284
  res.end(JSON.stringify({ ok: true, identity: config.identity, paired: true, ingress, checkpointDigest: gateway.authority.status(binding.local).checkpointDigest, publicKey: binding.publicKey }));
35892
36285
  } catch (error) {
36286
+ if (!(error instanceof Error && /^TRAVEL_[A-Z_]+$/.test(error.message))) console.error("[pair-control] masked-as TRAVEL_PAIRING_REFUSED, original:", error?.stack ?? error);
35893
36287
  res.statusCode = 409;
35894
36288
  res.end(JSON.stringify({ ok: false, error: error instanceof Error && /^TRAVEL_[A-Z_]+$/.test(error.message) ? error.message : "TRAVEL_PAIRING_REFUSED" }));
35895
36289
  }