engine7 7.1.140 → 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);
@@ -12041,6 +12042,16 @@ function recoverCwd(file2) {
12041
12042
  }
12042
12043
  return null;
12043
12044
  }
12045
+ function userText(content) {
12046
+ if (typeof content === "string") return content.trim() ? content : null;
12047
+ if (Array.isArray(content)) {
12048
+ const text2 = content.filter(
12049
+ (b) => !!b && typeof b === "object" && b.type === "text" && typeof b.text === "string"
12050
+ ).map((b) => b.text).join(" ");
12051
+ return text2.trim() ? text2 : null;
12052
+ }
12053
+ return null;
12054
+ }
12044
12055
  function firstUserText(file2) {
12045
12056
  try {
12046
12057
  const text2 = headBytes(file2, 65536).toString("utf-8");
@@ -12052,9 +12063,12 @@ function firstUserText(file2) {
12052
12063
  } catch {
12053
12064
  continue;
12054
12065
  }
12055
- if (entry.type === "user" && typeof entry.message?.content === "string") {
12056
- const s = entry.message.content.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
12057
- if (s) return s.length > 40 ? s.slice(0, 40) + "\u2026" : s;
12066
+ if (entry.type === "user") {
12067
+ const t = userText(entry.message?.content);
12068
+ if (t) {
12069
+ const s = t.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
12070
+ if (s) return s.length > 40 ? s.slice(0, 40) + "\u2026" : s;
12071
+ }
12058
12072
  }
12059
12073
  }
12060
12074
  } catch {
@@ -12331,6 +12345,10 @@ function rowElements(state, rowCap) {
12331
12345
  }
12332
12346
  }
12333
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
+ }
12334
12352
  const lt = state.liveThink;
12335
12353
  if (lt) {
12336
12354
  const sec = Math.max(1, Math.round((Date.now() - lt.start) / 1e3));
@@ -12341,6 +12359,9 @@ function rowElements(state, rowCap) {
12341
12359
  } else if (state.status === "run") {
12342
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*` } });
12343
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
+ }
12344
12365
  return { els, dropped };
12345
12366
  }
12346
12367
  function buildProcessCard(state, level = 2) {
@@ -12533,6 +12554,10 @@ function buildProcessCardV2At(state, level, panelCap) {
12533
12554
  }
12534
12555
  }
12535
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
+ }
12536
12561
  const lt = state.liveThink;
12537
12562
  if (lt) {
12538
12563
  const sec = Math.max(1, Math.round((Date.now() - lt.start) / 1e3));
@@ -12543,6 +12568,9 @@ function buildProcessCardV2At(state, level, panelCap) {
12543
12568
  } else if (state.status === "run") {
12544
12569
  els.push({ tag: "markdown", content: `*${spinnerFrame()} ${state.verb}\u2026\uFF08${fmtDur(Math.max(1, Math.round((Date.now() - state.startedAt) / 1e3)))}\uFF09*` });
12545
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
+ }
12546
12574
  const notes = [];
12547
12575
  if (state.usage) notes.push(state.usage);
12548
12576
  if (state.status === "wait") notes.push("\u70B9\u6309\u94AE\u5BA1\u6279\uFF0C\u4E5F\u53EF\u76F4\u63A5\u6253\u5B57");
@@ -12654,7 +12682,7 @@ var init_process_card = __esm({
12654
12682
  this.summarySent = false;
12655
12683
  this.terminal = null;
12656
12684
  this.patchFailures = 0;
12657
- 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 };
12658
12686
  this.lastPushKey = this.pushKey();
12659
12687
  this.messageId = null;
12660
12688
  this.channelV = null;
@@ -12675,7 +12703,10 @@ var init_process_card = __esm({
12675
12703
  }
12676
12704
  /** Mode decisions can start native progress without awaiting any channel I/O. */
12677
12705
  start() {
12678
- 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;
12679
12710
  }
12680
12711
  nativeCapable() {
12681
12712
  const ad = this.adapter;
@@ -12689,10 +12720,16 @@ var init_process_card = __esm({
12689
12720
  }
12690
12721
  ensureStarted() {
12691
12722
  const ad = this.adapter;
12692
- 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();
12693
12724
  }
12694
12725
  async createCard() {
12695
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
+ }
12696
12733
  if (!this.nativeCapable() && this.legacyCapable()) return this.createLegacyCard();
12697
12734
  if (!this.nativeCapable() && this.options.allowLegacyCard === false) {
12698
12735
  if (!ad.sendPreview || !ad.editPreview) throw new Error("\u65E0\u8FC7\u7A0B\u5361\u6216\u53EF\u7F16\u8F91\u6D88\u606F\u80FD\u529B");
@@ -12739,8 +12776,10 @@ var init_process_card = __esm({
12739
12776
  }
12740
12777
  async removeCard() {
12741
12778
  if (this.messageId) {
12742
- if (!this.adapter.deletePreview) throw new Error("\u65E0\u8FC7\u7A0B\u5361\u6E05\u7406\u80FD\u529B");
12743
- 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 });
12744
12783
  }
12745
12784
  this.messageId = null;
12746
12785
  this.cardKitId = null;
@@ -12751,7 +12790,7 @@ var init_process_card = __esm({
12751
12790
  /** Shared heartbeat samples state; the push key suppresses unchanged cards. */
12752
12791
  startHeartbeat() {
12753
12792
  this.stopHeartbeat();
12754
- const interval = this.channelV === "cardkit" ? 800 : 2500;
12793
+ const interval = this.channelV === "cardkit" || this.channelV === "progress" ? 800 : 2500;
12755
12794
  this.heartbeat = setInterval(() => {
12756
12795
  if (this.state.status !== "run" && this.state.status !== "wait") {
12757
12796
  this.stopHeartbeat();
@@ -12765,10 +12804,10 @@ var init_process_card = __esm({
12765
12804
  if (this.heartbeat) clearInterval(this.heartbeat);
12766
12805
  this.heartbeat = null;
12767
12806
  }
12768
- onToolUse(name, input, id3) {
12807
+ onToolUse(name, input, id3, inputFull) {
12769
12808
  if (this.ended || this.disposed) return;
12770
12809
  this.ensureStarted();
12771
- 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)) } : {} });
12772
12811
  if (this.state.status === "wait") this.state.status = "run";
12773
12812
  this.schedulePatch();
12774
12813
  }
@@ -12781,7 +12820,7 @@ var init_process_card = __esm({
12781
12820
  row = this.state.rows.at(-1);
12782
12821
  }
12783
12822
  if (!row) return;
12784
- const retain = match?.visible !== false || this.nativeCapable();
12823
+ const retain = match?.visible !== false || this.nativeCapable() || this.progressCapable();
12785
12824
  const lines = (out || "").split("\n").filter((line) => line.trim());
12786
12825
  row.state = retain && isError ? "err" : "ok";
12787
12826
  row.resultVisible = match?.visible;
@@ -12915,6 +12954,19 @@ var init_process_card = __esm({
12915
12954
  }
12916
12955
  return false;
12917
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
+ }
12918
12970
  turnEnd(finalText, usage, outcome) {
12919
12971
  return this.finish(outcome, finalText, usage);
12920
12972
  }
@@ -12950,7 +13002,7 @@ var init_process_card = __esm({
12950
13002
  return;
12951
13003
  }
12952
13004
  if (this.patchTimer) return;
12953
- 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;
12954
13006
  const wait2 = Math.max(0, min - (Date.now() - this.lastPatchAt));
12955
13007
  this.patchTimer = setTimeout(() => {
12956
13008
  this.patchTimer = null;
@@ -12965,7 +13017,7 @@ var init_process_card = __esm({
12965
13017
  await this.creation?.catch(() => {
12966
13018
  });
12967
13019
  if (this.disposed || this.ended && !final) return;
12968
- 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)) {
12969
13021
  await this.removeCard().catch((error) => console.warn("[process-card] \u7A7A\u56DE\u5408\u6E05\u7406\u5931\u8D25:", error instanceof Error ? error.message : String(error)));
12970
13022
  return;
12971
13023
  }
@@ -12988,17 +13040,19 @@ var init_process_card = __esm({
12988
13040
  return `q${r.rid}:${r.settled}:${JSON.stringify(r.answers)}`;
12989
13041
  }).join("|");
12990
13042
  const bucket = Math.floor((Date.now() - s.startedAt) / LIVE_BUCKET_MS);
12991
- 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]);
12992
13044
  }
12993
13045
  async doPatch(final = false) {
12994
13046
  if (this.degraded || !this.messageId && this.channelV !== "cardkit") return false;
12995
13047
  const key2 = this.pushKey();
12996
13048
  if (key2 === this.lastPushKey) return true;
12997
13049
  this.lastPatchAt = Date.now();
12998
- const card = this.channelV === "patch-v1" ? buildProcessCard(this.state) : buildProcessCardV2(this.state) ?? (this.options.allowLegacyCard !== false ? buildProcessCard(this.state) : null);
12999
- 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;
13000
13052
  try {
13001
- 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) {
13002
13056
  await this.adapter.editPreview(this.previewHandle, buildProcessText(this.state), this.repoName, final);
13003
13057
  } else if (this.channelV === "cardkit" && this.cardKitId && card) {
13004
13058
  this.seq++;
@@ -13057,6 +13111,12 @@ async function handleCcCardAction(data) {
13057
13111
  const fv = action?.form_value ?? {};
13058
13112
  const v = action?.value;
13059
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
+ }
13060
13120
  if (v.kind === "perm" && v.rid) {
13061
13121
  const p = pendingPerms.get(v.rid);
13062
13122
  if (!p) return { toast: { type: "info", content: "\u8BE5\u5BA1\u6279\u5DF2\u5904\u7406\u6216\u5DF2\u5931\u6548" } };
@@ -13576,6 +13636,9 @@ var init_dep_downloader = __esm({
13576
13636
  function requestError(message, status = 409) {
13577
13637
  return Object.assign(new Error(message), { status });
13578
13638
  }
13639
+ function ccUserMsg(text2) {
13640
+ return { type: "user", message: { role: "user", content: text2 }, parent_tool_use_id: null };
13641
+ }
13579
13642
  function resultToText(content) {
13580
13643
  if (typeof content === "string") return content;
13581
13644
  if (Array.isArray(content)) {
@@ -13600,7 +13663,7 @@ function chunkText(text2, maxChars) {
13600
13663
  if (rest.trim()) chunks.push(rest);
13601
13664
  return chunks;
13602
13665
  }
13603
- 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;
13604
13667
  var init_driver = __esm({
13605
13668
  "src/cc-driver/driver.ts"() {
13606
13669
  "use strict";
@@ -13615,6 +13678,53 @@ var init_driver = __esm({
13615
13678
  MAX_INTERIM_PER_TURN = 4;
13616
13679
  INTERIM_SNIPPET_CHARS = 600;
13617
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;
13618
13728
  CcDriverSession = class {
13619
13729
  constructor(binding, cm, map, predecessor) {
13620
13730
  this.predecessor = predecessor;
@@ -13636,6 +13746,8 @@ var init_driver = __esm({
13636
13746
  revision = 0;
13637
13747
  idleWaiters = [];
13638
13748
  abort = null;
13749
+ /** 当前流式 chunk 的 steer 口(仅用户消息路径开;外部 ask/桌面路径为 null) */
13750
+ feeder = null;
13639
13751
  sessionId = null;
13640
13752
  sendChain = Promise.resolve();
13641
13753
  ui = null;
@@ -13660,11 +13772,16 @@ var init_driver = __esm({
13660
13772
  this.sessionId = null;
13661
13773
  return this.map.clear(this.key) || had;
13662
13774
  }
13663
- /** 入站一条消息:排队(busy 时 FIFO),队列满则提示。 */
13775
+ /** 入站一条消息:流式 chunk 开着 → steer 注入(1119);否则排队(busy 时 FIFO),队列满则提示。 */
13664
13776
  enqueue(text2) {
13665
13777
  const trimmed = text2.trim();
13666
13778
  if (!trimmed || this.closed) return;
13667
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
+ }
13668
13785
  if (this.queue.length >= MAX_QUEUE) {
13669
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`);
13670
13787
  return;
@@ -13701,9 +13818,22 @@ var init_driver = __esm({
13701
13818
  this.closed = true;
13702
13819
  this.revision++;
13703
13820
  for (const job of this.queue.splice(0)) job.reject?.(requestError("CC binding stopped before execution", 503));
13821
+ this.feeder?.close();
13704
13822
  this.stop();
13705
13823
  }
13706
- /** 中断当前 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() */
13707
13837
  stop() {
13708
13838
  this.abort?.abort();
13709
13839
  }
@@ -13725,10 +13855,14 @@ var init_driver = __esm({
13725
13855
  if (job.expectedSessionId !== void 0 && job.expectedSessionId !== this.sessionId) {
13726
13856
  throw requestError("CC session changed while this request was queued");
13727
13857
  }
13728
- const prompt = job.source ? `[cc_ask from ${job.source.replace(/[\r\n]/g, " ").slice(0, 160)}]
13729
- ${job.prompt}` : job.prompt;
13730
- const result = await this.runTurn(prompt, job.signal, !!job.source);
13731
- 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
+ }
13732
13866
  } catch (err) {
13733
13867
  job.reject?.(err);
13734
13868
  console.error(`[cc-driver] turn \u5931\u8D25 key=${this.key}: ${err?.stack || err}`);
@@ -13762,15 +13896,11 @@ ${job.prompt}` : job.prompt;
13762
13896
  this.ui = null;
13763
13897
  }
13764
13898
  }
13765
- let textSoFar = "";
13766
- let gotPartial = false;
13767
- let lastInterimAt = Date.now();
13768
- let interimCount = 0;
13769
- let lastSentLen = 0;
13770
13899
  let finalText = "";
13771
13900
  let isError = false;
13772
13901
  let gotResult = false;
13773
13902
  let usage = "";
13903
+ const acc = this.makeStreamAccumulator();
13774
13904
  try {
13775
13905
  const desktops = resumedFrom ? await findDesktopTargets(this.workDir, resumedFrom) : [];
13776
13906
  if (desktops.length > 1) throw new Error("Multiple desktop writers claim this CC session; close the duplicate");
@@ -13786,7 +13916,7 @@ ${job.prompt}` : job.prompt;
13786
13916
  throw new Error("This CC session is open in another process; use cc-desktop to receive messages there");
13787
13917
  }
13788
13918
  let ccRuntimeNoticeSent = false;
13789
- const { query } = await loadOptionalModule("cc-runtime", (label, got, total) => {
13919
+ const { query } = await ccRuntimeLoader((label, got, total) => {
13790
13920
  if (ccRuntimeNoticeSent) return;
13791
13921
  ccRuntimeNoticeSent = true;
13792
13922
  const mb = total ? `\u7EA6 ${Math.round(total / 1024 / 1024)}M` : "\u7EA6 350M";
@@ -13830,43 +13960,7 @@ ${job.prompt}` : job.prompt;
13830
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) ?? "-"}`);
13831
13961
  const parentToolUseId = msg2.parent_tool_use_id;
13832
13962
  if (parentToolUseId) continue;
13833
- if (msg2.type === "stream_event") {
13834
- const ev = msg2.event;
13835
- if (ev.type === "content_block_start" && ev.content_block?.type === "thinking") this.ui?.onThinkingDelta("");
13836
- else if (ev.type === "content_block_delta" && ev.delta?.type === "thinking_delta" && typeof ev.delta.thinking === "string") this.ui?.onThinkingDelta(ev.delta.thinking);
13837
- else if (ev.type === "content_block_stop" && this.ui) this.ui.onThinkingEnd();
13838
- if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && typeof ev.delta.text === "string") {
13839
- gotPartial = true;
13840
- textSoFar += ev.delta.text;
13841
- const now2 = Date.now();
13842
- const newChars = textSoFar.length - lastSentLen;
13843
- if (!this.ui && now2 - lastInterimAt >= INTERIM_MIN_INTERVAL_MS && newChars >= INTERIM_MIN_CHARS && interimCount < MAX_INTERIM_PER_TURN) {
13844
- lastInterimAt = now2;
13845
- lastSentLen = textSoFar.length;
13846
- interimCount++;
13847
- const snippet = textSoFar.slice(-INTERIM_SNIPPET_CHARS);
13848
- void this.sendText(`\u2026${snippet}`);
13849
- }
13850
- }
13851
- } else if (msg2.type === "assistant") {
13852
- const content = msg2.message.content ?? [];
13853
- for (const block of content) {
13854
- if (block.type === "thinking" && block.thinking) this.ui?.onThinking(String(block.thinking));
13855
- else if (block.type === "tool_use" && block.id) this.ui?.onToolUse(String(block.name), block.input ?? {});
13856
- }
13857
- if (!gotPartial) {
13858
- for (const block of content) {
13859
- if (block.type === "text" && typeof block.text === "string") textSoFar += block.text;
13860
- }
13861
- }
13862
- } else if (msg2.type === "user") {
13863
- const content = msg2.message.content;
13864
- if (Array.isArray(content) && this.ui) {
13865
- for (const block of content) {
13866
- if (block.type === "tool_result") this.ui.onToolResult(resultToText(block.content), block.is_error === true);
13867
- }
13868
- }
13869
- } else if (msg2.type === "result") {
13963
+ if (msg2.type === "result") {
13870
13964
  const r = msg2;
13871
13965
  if (r.session_id) {
13872
13966
  turnSessionId = r.session_id;
@@ -13882,6 +13976,8 @@ ${job.prompt}` : job.prompt;
13882
13976
  turnSessionId = sid;
13883
13977
  if (this.revision === revision) this.sessionId = sid;
13884
13978
  }
13979
+ } else {
13980
+ await acc.handle(msg2);
13885
13981
  }
13886
13982
  }
13887
13983
  }
@@ -13890,22 +13986,22 @@ ${job.prompt}` : job.prompt;
13890
13986
  this.abort = null;
13891
13987
  signal?.removeEventListener("abort", cancel);
13892
13988
  }
13893
- 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 };
13894
13990
  if (ac.signal.aborted) {
13895
13991
  if (this.ui && this.ui.alive) {
13896
13992
  await this.ui.turnEnd("", "", "aborted");
13897
- await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (textSoFar ? `
13993
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
13898
13994
  \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
13899
- ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13995
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13900
13996
  return { ...result, text: "[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" };
13901
13997
  }
13902
- await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (textSoFar ? `
13998
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
13903
13999
 
13904
14000
  \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
13905
- ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14001
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13906
14002
  return { ...result, text: "[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" };
13907
14003
  }
13908
- const answer = finalText || textSoFar;
14004
+ const answer = finalText || acc.textSoFar;
13909
14005
  if (this.ui && this.ui.alive) {
13910
14006
  await this.ui.turnEnd("", usage, isError ? "err" : "done");
13911
14007
  if (!answer.trim()) {
@@ -13924,6 +14020,215 @@ ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13924
14020
  }
13925
14021
  return result;
13926
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
+ }
13927
14232
  /** 串行发送器:wechat 3s 节流在适配器层,这里保证不并发、失败不炸链 */
13928
14233
  sendText(text2) {
13929
14234
  const task = this.sendChain.then(async () => {
@@ -13971,6 +14276,12 @@ ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13971
14276
  forChat(channel, chatId) {
13972
14277
  return this.sessions.get(`${channel}:${chatId}`);
13973
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
+ }
13974
14285
  /** 全部绑定的工作目录(去重;cc-progress 工具省参推断用) */
13975
14286
  get bindingWorkDirs() {
13976
14287
  return [...new Set([...this.sessions.values()].map((s) => s.workDir))];
@@ -14108,6 +14419,12 @@ var init_cc_driver = __esm({
14108
14419
  });
14109
14420
 
14110
14421
  // src/cc-driver/router.ts
14422
+ var router_exports = {};
14423
+ __export(router_exports, {
14424
+ autoBindHit: () => autoBindHit,
14425
+ ccDriverRouter: () => ccDriverRouter,
14426
+ markBindSelect: () => markBindSelect
14427
+ });
14111
14428
  import { existsSync as existsSync8 } from "node:fs";
14112
14429
  function autoBindHit(inbound) {
14113
14430
  if (inbound.channel !== "feishu" || inbound.channelType !== "dm") return null;
@@ -14137,6 +14454,14 @@ async function doAutoBind(inbound, workDir) {
14137
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
14138
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`);
14139
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
+ }
14140
14465
  function peekBindNumber(inbound) {
14141
14466
  if (inbound.channelType !== "dm") return null;
14142
14467
  const ts = pendingBind.get(`${inbound.channel}:${inbound.channel_id}`);
@@ -17967,6 +18292,9 @@ var TravelAuthority = class {
17967
18292
  CREATE TABLE IF NOT EXISTS recovery_branches(identity TEXT NOT NULL,common TEXT NOT NULL,local TEXT NOT NULL,
17968
18293
  chain TEXT NOT NULL,PRIMARY KEY(identity,common,local));`);
17969
18294
  this.db.exec("CREATE TABLE IF NOT EXISTS retirement_sources(identity TEXT PRIMARY KEY,body TEXT NOT NULL)");
18295
+ if (!this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='leased_seats'").get()) {
18296
+ this.transaction(() => this.db.exec("CREATE TABLE leased_seats(identity TEXT PRIMARY KEY); INSERT INTO leased_seats SELECT identity FROM seats"));
18297
+ }
17970
18298
  if (this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_AUTHORITY_CORRUPT");
17971
18299
  this.transaction(() => {
17972
18300
  this.db.exec("UPDATE seats SET epoch=epoch+1,active_node=NULL,active_boot=NULL,frozen=0 WHERE retired IS NULL");
@@ -18031,7 +18359,7 @@ var TravelAuthority = class {
18031
18359
  }
18032
18360
  /** Trusted pairing owner binds the first real H to an unused reservation.
18033
18361
  * This does not grant a lease and never rewrites a used seat's history. */
18034
- bindInitialCheckpoint(principal, digest7, buildManifestId) {
18362
+ bindInitialCheckpoint(principal, digest7, buildManifestId, previousDigest) {
18035
18363
  if (!HASH2.test(digest7) || digest7 === "0".repeat(64)) throw new Error("TRAVEL_INITIAL_BASELINE");
18036
18364
  id(buildManifestId);
18037
18365
  const text2 = identityText2(principal);
@@ -18040,7 +18368,9 @@ var TravelAuthority = class {
18040
18368
  this.principal(principal);
18041
18369
  if (!row || row.active_node !== null || row.active_boot !== null || row.frozen || row.retired !== null || row.floor !== 0 || row.build !== buildManifestId || this.db.prepare("SELECT 1 FROM handoffs WHERE identity=? LIMIT 1").get(text2)) throw new Error("TRAVEL_INITIAL_BASELINE");
18042
18370
  if (row.checkpoint === digest7) return;
18043
- if (row.checkpoint !== "0".repeat(64)) throw new Error("TRAVEL_INITIAL_BASELINE");
18371
+ if (this.db.prepare("SELECT 1 FROM leased_seats WHERE identity=?").get(text2)) throw new Error("TRAVEL_INITIAL_BASELINE");
18372
+ if (previousDigest !== void 0 && (!HASH2.test(previousDigest) || row.checkpoint !== previousDigest)) throw new Error("TRAVEL_INITIAL_BASELINE");
18373
+ if (row.checkpoint !== "0".repeat(64) && previousDigest !== row.checkpoint) throw new Error("TRAVEL_INITIAL_BASELINE");
18044
18374
  this.db.prepare("DELETE FROM checkpoints WHERE identity=?").run(text2);
18045
18375
  this.db.prepare("INSERT INTO checkpoints VALUES(?,?,NULL,1)").run(text2, digest7);
18046
18376
  this.db.prepare("UPDATE seats SET checkpoint=? WHERE identity=?").run(digest7, text2);
@@ -18111,6 +18441,7 @@ var TravelAuthority = class {
18111
18441
  if (row.active_node && ((this.deadlines.get(text2) ?? 0) <= this.monotonicNow() || row.active_boot !== node.boot)) row.epoch++;
18112
18442
  row.active_node = principal.nodeId;
18113
18443
  row.active_boot = String(node.boot);
18444
+ this.db.prepare("INSERT OR IGNORE INTO leased_seats VALUES(?)").run(text2);
18114
18445
  this.db.prepare("UPDATE seats SET epoch=?,active_node=?,active_boot=? WHERE identity=?").run(row.epoch, row.active_node, row.active_boot, text2);
18115
18446
  this.deadlines.set(text2, this.monotonicNow() + this.leaseMs);
18116
18447
  this.healthy.set(text2 + principal.nodeId, this.monotonicNow() + this.leaseMs);
@@ -18488,7 +18819,7 @@ import { createHash as createHash3 } from "node:crypto";
18488
18819
  // src/continuity/inventory.ts
18489
18820
  import { isAbsolute, join as join4, relative, resolve as resolve2, sep } from "node:path";
18490
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(" "));
18491
- 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(" "));
18492
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(" "));
18493
18824
  function validateRelativePath(path35) {
18494
18825
  if (typeof path35 !== "string" || !path35 || path35.length > 2048 || isAbsolute(path35)) throw new Error("INVALID_ARTIFACT_PATH");
@@ -19155,6 +19486,18 @@ var TravelGatewayStore = class {
19155
19486
  }
19156
19487
  /** Host-owned import of actual previously processed platform IDs. A receipt
19157
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
+ }
19158
19501
  importProcessedInputs(platformIds) {
19159
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");
19160
19503
  this.transaction(() => {
@@ -19580,7 +19923,7 @@ function createTravelGatewayServer(options) {
19580
19923
  return;
19581
19924
  }
19582
19925
  const action = req.url?.startsWith(prefix) ? req.url.slice(prefix.length) : "";
19583
- 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)) {
19584
19927
  reply(404, { error: "TRAVEL_GATEWAY_NOT_FOUND" });
19585
19928
  req.resume();
19586
19929
  return;
@@ -19617,7 +19960,7 @@ function createTravelGatewayServer(options) {
19617
19960
  reply(200, store.applyRecoveryDeletedInputs(principal, input.bindings, input.floor));
19618
19961
  return;
19619
19962
  }
19620
- 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");
19621
19964
  if (action === "preparation") {
19622
19965
  if (Object.keys(input).length) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19623
19966
  reply(200, store.preparationEvidence(principal));
@@ -19633,6 +19976,11 @@ function createTravelGatewayServer(options) {
19633
19976
  reply(200, store.exitDedupeReceipt(principal, permit));
19634
19977
  return;
19635
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
+ }
19636
19984
  if (action === "claim") {
19637
19985
  const claims = await store.claim(principal, permit, input.options);
19638
19986
  reply(200, claims.map(({ body: body2, ...claim }) => ({ ...claim, bodyBase64: body2.toString("base64") })));
@@ -19800,6 +20148,12 @@ var TravelGatewayClient = class {
19800
20148
  async ack(permit, eventId) {
19801
20149
  await this.call("ack", { permit, eventId });
19802
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
+ }
19803
20157
  async finish(permit, eventId) {
19804
20158
  await this.call("finish", { permit, eventId });
19805
20159
  }
@@ -27289,7 +27643,7 @@ function assertImageAssetRef(ref) {
27289
27643
  throw new Error("Invalid or oversized image asset reference");
27290
27644
  }
27291
27645
  }
27292
- 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 = {}) {
27293
27647
  signal?.throwIfAborted();
27294
27648
  let total = 0;
27295
27649
  for (const message of messages) if (Array.isArray(message.content)) for (const block of message.content) {
@@ -27314,6 +27668,7 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
27314
27668
  return { ...message, content: content.length ? content : "[previous image omitted]" };
27315
27669
  });
27316
27670
  if (total > maxBase64Bytes) throw new Error(`Request image base64 exceeds ${maxBase64Bytes} byte limit`);
27671
+ const { strict = false } = opts;
27317
27672
  const cache = /* @__PURE__ */ new Map();
27318
27673
  const output = [];
27319
27674
  for (const message of requestView) {
@@ -27330,8 +27685,12 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
27330
27685
  }
27331
27686
  if (!store) throw new Error("Image asset store is required to materialize image refs");
27332
27687
  const key2 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
27333
- if (!cache.has(key2)) cache.set(key2, store.materialize(block.image));
27334
- 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]" });
27335
27694
  signal?.throwIfAborted();
27336
27695
  }
27337
27696
  output.push({ ...message, content });
@@ -34748,6 +35107,7 @@ function createFeishuGatewayDispatcher(options) {
34748
35107
  body: Buffer.from(JSON.stringify({ format, event: { sender, message }, ...resources.length ? { resources } : {} }))
34749
35108
  });
34750
35109
  options.assertIngress?.();
35110
+ if (sender.sender_type !== "bot") options.onReceivedTyping?.(message.chat_id, sender.sender_id?.open_id, message.message_id);
34751
35111
  },
34752
35112
  "im.message.reaction.created_v1": async () => {
34753
35113
  },
@@ -34799,7 +35159,34 @@ function createFeishuGatewayPlatform(options) {
34799
35159
  return config;
34800
35160
  });
34801
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
+ };
34802
35187
  return {
35188
+ startChatTyping,
35189
+ stopChatTyping,
34803
35190
  deliver: async (effect, body, assertCurrent) => {
34804
35191
  if (closed) throw new Error("TRAVEL_FEISHU_CLOSED");
34805
35192
  const media = effect.kind === "MEDIA" ? decodeGatewayMedia(body) : void 0;
@@ -34827,6 +35214,7 @@ function createFeishuGatewayPlatform(options) {
34827
35214
  assertCurrent();
34828
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 } });
34829
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);
34830
35218
  return { messageId: result.data.message_id };
34831
35219
  });
34832
35220
  },
@@ -34959,78 +35347,101 @@ var RemoteTravelChannel = class {
34959
35347
  });
34960
35348
  }));
34961
35349
  }
34962
- async send(target, message, options) {
34963
- const context = travelEventContext();
34964
- if (!context || context.client !== this.options.client) throw new Error("TRAVEL_GATEWAY_CONTEXT_REQUIRED");
34965
- if (context.failed) throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
34966
- assertExternalEffectCurrent();
34967
- travelEventPermit(context);
34968
- const config = resolveBubbleSplit(this.name), bubbles = config.on && options?.bubbleSplit === true ? splitBubbles(message) : null;
34969
- const chunks = bubbles ?? (this.name === "feishu" ? splitFeishuGatewayText(message) : splitChannelGatewayText(message, this.name));
34970
- const kind = travelOutputKind(), ordinal = (context.ordinals[kind] ?? 0) + 1;
34971
- 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 };
34972
35362
  try {
34973
- const effects2 = await context.client.produceBatch(travelEventPermit(context), chunks.map((text2, index) => ({
34974
- eventId: context.eventId,
34975
- kind,
34976
- ordinal: ordinal + index,
34977
- version: 1,
34978
- body: Buffer.from(JSON.stringify({ channel: this.name, target, text: text2, format: this.name === "feishu" ? "post" : "text", ...index === 0 && options?.replyTo ? { replyTo: options.replyTo } : {} }))
34979
- })), { finalOutput: options?.extra?.travelFinalReply === true });
34980
- for (let index = 0; index < effects2.length; index++) {
34981
- assertExternalEffectCurrent();
34982
- await context.client.dispatch(travelEventPermit(context), effects2[index].id);
34983
- if (bubbles && index < effects2.length - 1 && config.gapMs > 0) await new Promise((resolve13) => setTimeout(resolve13, Math.min(config.gapMs, 6e4)));
34984
- }
35363
+ const value = await withTravelEventContext(context, () => run(context));
35364
+ await completeTravelEvent(context);
35365
+ return value;
34985
35366
  } catch (error) {
34986
35367
  context.failed = true;
35368
+ await this.options.client.finish(this.options.permit(), id3).catch(() => {
35369
+ });
34987
35370
  throw error;
34988
35371
  }
34989
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
+ }
34990
35401
  async sendFile(target, message, attachment) {
34991
- const context = travelEventContext();
34992
- if (!context || context.client !== this.options.client) throw new Error("TRAVEL_GATEWAY_CONTEXT_REQUIRED");
34993
- if (context.failed) throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
34994
- assertExternalEffectCurrent();
34995
- travelEventPermit(context);
34996
- const handle = await open2(attachment.path, "r");
34997
- let bytes2;
34998
- try {
34999
- const info = await handle.stat();
35000
- if (!info.isFile() || !info.size || info.size > gatewayMediaLimit) throw new Error("TRAVEL_GATEWAY_MEDIA_LIMIT");
35001
- bytes2 = Buffer.alloc(info.size);
35002
- let offset = 0;
35003
- while (offset < bytes2.length) {
35004
- const read2 = await handle.read(bytes2, offset, bytes2.length - offset, offset);
35005
- if (!read2.bytesRead) throw new Error("TRAVEL_GATEWAY_MEDIA_CHANGED");
35006
- offset += read2.bytesRead;
35007
- }
35008
- const after = await handle.stat();
35009
- if (info.size !== after.size || info.mtimeMs !== after.mtimeMs) throw new Error("TRAVEL_GATEWAY_MEDIA_CHANGED");
35010
- } finally {
35011
- await handle.close();
35012
- }
35013
- assertExternalEffectCurrent();
35014
- travelEventPermit(context);
35015
- const mimeType = attachment.mimeType ?? "application/octet-stream", filename = attachment.filename ?? basename7(attachment.path);
35016
- const captions = message && !mimeType.startsWith("image/") ? this.name === "feishu" ? splitFeishuGatewayText(message) : splitChannelGatewayText(message, this.name) : [];
35017
- const ordinal = (context.ordinals.MEDIA ?? 0) + 1;
35018
- context.ordinals.MEDIA = ordinal;
35019
- const kind = travelOutputKind(), replyOrdinal = (context.ordinals[kind] ?? 0) + 1;
35020
- context.ordinals[kind] = replyOrdinal + captions.length - 1;
35021
- try {
35022
- const effects2 = await context.client.produceBatch(travelEventPermit(context), [
35023
- { 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) },
35024
- ...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" })) }))
35025
- ]);
35026
- for (const effect of effects2) {
35027
- assertExternalEffectCurrent();
35028
- 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();
35029
35422
  }
35030
- } catch (error) {
35031
- context.failed = true;
35032
- throw error;
35033
- }
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
+ });
35034
35445
  }
35035
35446
  };
35036
35447
 
@@ -35652,6 +36063,7 @@ async function startTravelGateway(config) {
35652
36063
  encryptKey: config.feishu.encryptKey,
35653
36064
  assertIngress: assertKey,
35654
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),
35655
36067
  downloadResource: async (messageId, key2, type) => {
35656
36068
  assertKey();
35657
36069
  return platform.downloadResource(messageId, key2, type);
@@ -35842,7 +36254,7 @@ async function startPairingControl(config) {
35842
36254
  chunks.push(chunk);
35843
36255
  }
35844
36256
  const input = JSON.parse(Buffer.concat(chunks).toString());
35845
- if (JSON.stringify(input.identity) !== JSON.stringify(config.identity) || !["status", "enable_ingress", "disable_ingress", "bind_initial", "exit_dedupe"].includes(input.action) || Object.keys(input).some((name) => !["identity", "action", "digest"].includes(name))) throw new Error("TRAVEL_PAIRING_REQUEST");
36257
+ if (JSON.stringify(input.identity) !== JSON.stringify(config.identity) || !["status", "enable_ingress", "disable_ingress", "bind_initial", "exit_dedupe"].includes(input.action) || Object.keys(input).some((name) => !["identity", "action", "digest", "previousDigest"].includes(name)) || input.previousDigest !== void 0 && (input.action !== "bind_initial" || typeof input.previousDigest !== "string")) throw new Error("TRAVEL_PAIRING_REQUEST");
35846
36258
  if (input.action === "exit_dedupe") {
35847
36259
  res.end(JSON.stringify({ ok: true, receipt: gateway.store.recoveryDedupeReceipt(binding.local, input.digest) }));
35848
36260
  return;
@@ -35864,13 +36276,14 @@ async function startPairingControl(config) {
35864
36276
  gateway = await startTravelGateway(gatewayConfig);
35865
36277
  ingress = false;
35866
36278
  }
35867
- if (input.action === "bind_initial") gateway.authority.bindInitialCheckpoint(binding.local, input.digest, config.buildManifestId);
36279
+ if (input.action === "bind_initial") gateway.authority.bindInitialCheckpoint(binding.local, input.digest, config.buildManifestId, input.previousDigest);
35868
36280
  } finally {
35869
36281
  changing = false;
35870
36282
  }
35871
36283
  }
35872
36284
  res.end(JSON.stringify({ ok: true, identity: config.identity, paired: true, ingress, checkpointDigest: gateway.authority.status(binding.local).checkpointDigest, publicKey: binding.publicKey }));
35873
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);
35874
36287
  res.statusCode = 409;
35875
36288
  res.end(JSON.stringify({ ok: false, error: error instanceof Error && /^TRAVEL_[A-Z_]+$/.test(error.message) ? error.message : "TRAVEL_PAIRING_REFUSED" }));
35876
36289
  }