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.
@@ -625,6 +625,7 @@ function validateTravelChannels(stateDir, channels) {
625
625
  const root = stateDir || process.env.ENGINE7_TRAVEL_STATE_DIR || process.env.ENGINE_STATE_DIR;
626
626
  if (!root || !runtimeAuthorityFor(root)) return;
627
627
  validateTravelChannelConfiguration(channels);
628
+ 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");
628
629
  }
629
630
  function validateTravelChannelConfiguration(channels) {
630
631
  for (const [name, value] of Object.entries(channels ?? {})) {
@@ -632,7 +633,7 @@ function validateTravelChannelConfiguration(channels) {
632
633
  if (!["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
633
634
  if (value.mode !== "remote-only") throw new Error("TRAVEL_REMOTE_ONLY_REQUIRED");
634
635
  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));
635
- 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");
636
+ if (hasPlatformSecret(value)) throw new Error("TRAVEL_PLATFORM_SECRET_PRESENT");
636
637
  let url;
637
638
  try {
638
639
  url = new URL(value.gatewayUrl);
@@ -11836,6 +11837,16 @@ function recoverCwd(file2) {
11836
11837
  }
11837
11838
  return null;
11838
11839
  }
11840
+ function userText(content) {
11841
+ if (typeof content === "string") return content.trim() ? content : null;
11842
+ if (Array.isArray(content)) {
11843
+ const text2 = content.filter(
11844
+ (b) => !!b && typeof b === "object" && b.type === "text" && typeof b.text === "string"
11845
+ ).map((b) => b.text).join(" ");
11846
+ return text2.trim() ? text2 : null;
11847
+ }
11848
+ return null;
11849
+ }
11839
11850
  function firstUserText(file2) {
11840
11851
  try {
11841
11852
  const text2 = headBytes(file2, 65536).toString("utf-8");
@@ -11847,9 +11858,12 @@ function firstUserText(file2) {
11847
11858
  } catch {
11848
11859
  continue;
11849
11860
  }
11850
- if (entry.type === "user" && typeof entry.message?.content === "string") {
11851
- const s = entry.message.content.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
11852
- if (s) return s.length > 40 ? s.slice(0, 40) + "\u2026" : s;
11861
+ if (entry.type === "user") {
11862
+ const t = userText(entry.message?.content);
11863
+ if (t) {
11864
+ const s = t.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
11865
+ if (s) return s.length > 40 ? s.slice(0, 40) + "\u2026" : s;
11866
+ }
11853
11867
  }
11854
11868
  }
11855
11869
  } catch {
@@ -12126,6 +12140,10 @@ function rowElements(state, rowCap) {
12126
12140
  }
12127
12141
  }
12128
12142
  flush();
12143
+ if (state.steerNotes?.length) {
12144
+ for (const s of state.steerNotes) lines.push(`\u21AA \u63D2\u8BDD\uFF1A${s.length > ARGS_MAX ? s.slice(0, ARGS_MAX - 1) + "\u2026" : s}`);
12145
+ flush();
12146
+ }
12129
12147
  const lt = state.liveThink;
12130
12148
  if (lt) {
12131
12149
  const sec = Math.max(1, Math.round((Date.now() - lt.start) / 1e3));
@@ -12136,6 +12154,9 @@ function rowElements(state, rowCap) {
12136
12154
  } else if (state.status === "run") {
12137
12155
  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*` } });
12138
12156
  }
12157
+ if (state.stopAction && (state.status === "run" || state.status === "wait")) {
12158
+ els.push({ tag: "action", actions: [{ tag: "button", type: "default", text: { tag: "plain_text", content: "\u505C\u6B62" }, value: state.stopAction }] });
12159
+ }
12139
12160
  return { els, dropped };
12140
12161
  }
12141
12162
  function buildProcessCard(state, level = 2) {
@@ -12328,6 +12349,10 @@ function buildProcessCardV2At(state, level, panelCap) {
12328
12349
  }
12329
12350
  }
12330
12351
  flushPlain();
12352
+ if (state.steerNotes?.length) {
12353
+ for (const s of state.steerNotes) plain.push(`\u21AA \u63D2\u8BDD\uFF1A${capStr(s, ARGS_MAX)}`);
12354
+ flushPlain();
12355
+ }
12331
12356
  const lt = state.liveThink;
12332
12357
  if (lt) {
12333
12358
  const sec = Math.max(1, Math.round((Date.now() - lt.start) / 1e3));
@@ -12338,6 +12363,9 @@ function buildProcessCardV2At(state, level, panelCap) {
12338
12363
  } else if (state.status === "run") {
12339
12364
  els.push({ tag: "markdown", content: `*${spinnerFrame()} ${state.verb}\u2026\uFF08${fmtDur(Math.max(1, Math.round((Date.now() - state.startedAt) / 1e3)))}\uFF09*` });
12340
12365
  }
12366
+ if (state.stopAction && (state.status === "run" || state.status === "wait")) {
12367
+ els.push(buttonRow([{ tag: "button", type: "default", text: { tag: "plain_text", content: "\u505C\u6B62" }, value: state.stopAction }]));
12368
+ }
12341
12369
  const notes = [];
12342
12370
  if (state.usage) notes.push(state.usage);
12343
12371
  if (state.status === "wait") notes.push("\u70B9\u6309\u94AE\u5BA1\u6279\uFF0C\u4E5F\u53EF\u76F4\u63A5\u6253\u5B57");
@@ -12449,7 +12477,7 @@ var init_process_card = __esm({
12449
12477
  this.summarySent = false;
12450
12478
  this.terminal = null;
12451
12479
  this.patchFailures = 0;
12452
- 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 };
12480
+ 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 };
12453
12481
  this.lastPushKey = this.pushKey();
12454
12482
  this.messageId = null;
12455
12483
  this.channelV = null;
@@ -12470,7 +12498,10 @@ var init_process_card = __esm({
12470
12498
  }
12471
12499
  /** Mode decisions can start native progress without awaiting any channel I/O. */
12472
12500
  start() {
12473
- if (!this.ended && !this.started && (this.nativeCapable() || this.legacyCapable())) this.beginInBackground();
12501
+ if (!this.ended && !this.started && (this.nativeCapable() || this.legacyCapable() || this.progressCapable())) this.beginInBackground();
12502
+ }
12503
+ progressCapable() {
12504
+ return !!this.adapter.sendProgress && !!this.adapter.updateProgress && !!this.adapter.removeProgress;
12474
12505
  }
12475
12506
  nativeCapable() {
12476
12507
  const ad = this.adapter;
@@ -12484,10 +12515,16 @@ var init_process_card = __esm({
12484
12515
  }
12485
12516
  ensureStarted() {
12486
12517
  const ad = this.adapter;
12487
- if (this.options.autoStart && !this.started && (this.nativeCapable() || this.legacyCapable() || ad.sendPreview && ad.editPreview)) this.beginInBackground();
12518
+ if (this.options.autoStart && !this.started && (this.nativeCapable() || this.legacyCapable() || this.progressCapable() || ad.sendPreview && ad.editPreview)) this.beginInBackground();
12488
12519
  }
12489
12520
  async createCard() {
12490
12521
  const ad = this.adapter;
12522
+ if (this.progressCapable()) {
12523
+ this.messageId = await ad.sendProgress(this.target, structuredClone(this.state));
12524
+ this.channelV = "progress";
12525
+ this.lastPatchAt = Date.now();
12526
+ return;
12527
+ }
12491
12528
  if (!this.nativeCapable() && this.legacyCapable()) return this.createLegacyCard();
12492
12529
  if (!this.nativeCapable() && this.options.allowLegacyCard === false) {
12493
12530
  if (!ad.sendPreview || !ad.editPreview) throw new Error("\u65E0\u8FC7\u7A0B\u5361\u6216\u53EF\u7F16\u8F91\u6D88\u606F\u80FD\u529B");
@@ -12534,8 +12571,10 @@ var init_process_card = __esm({
12534
12571
  }
12535
12572
  async removeCard() {
12536
12573
  if (this.messageId) {
12537
- if (!this.adapter.deletePreview) throw new Error("\u65E0\u8FC7\u7A0B\u5361\u6E05\u7406\u80FD\u529B");
12538
- await this.adapter.deletePreview({ channelId: this.target, messageId: this.messageId });
12574
+ if (this.channelV === "progress" && this.adapter.removeProgress) {
12575
+ await this.adapter.removeProgress(this.messageId);
12576
+ } else if (!this.adapter.deletePreview) throw new Error("\u65E0\u8FC7\u7A0B\u5361\u6E05\u7406\u80FD\u529B");
12577
+ else await this.adapter.deletePreview({ channelId: this.target, messageId: this.messageId });
12539
12578
  }
12540
12579
  this.messageId = null;
12541
12580
  this.cardKitId = null;
@@ -12546,7 +12585,7 @@ var init_process_card = __esm({
12546
12585
  /** Shared heartbeat samples state; the push key suppresses unchanged cards. */
12547
12586
  startHeartbeat() {
12548
12587
  this.stopHeartbeat();
12549
- const interval = this.channelV === "cardkit" ? 800 : 2500;
12588
+ const interval = this.channelV === "cardkit" || this.channelV === "progress" ? 800 : 2500;
12550
12589
  this.heartbeat = setInterval(() => {
12551
12590
  if (this.state.status !== "run" && this.state.status !== "wait") {
12552
12591
  this.stopHeartbeat();
@@ -12560,10 +12599,10 @@ var init_process_card = __esm({
12560
12599
  if (this.heartbeat) clearInterval(this.heartbeat);
12561
12600
  this.heartbeat = null;
12562
12601
  }
12563
- onToolUse(name, input, id3) {
12602
+ onToolUse(name, input, id3, inputFull) {
12564
12603
  if (this.ended || this.disposed) return;
12565
12604
  this.ensureStarted();
12566
- this.state.rows.push({ kind: "tool", id: id3, name, args: stripCardUnsafe(typeof input === "string" ? input : toolArgsSummary(name, input)), state: "run", out: "", more: 0 });
12605
+ 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)) } : {} });
12567
12606
  if (this.state.status === "wait") this.state.status = "run";
12568
12607
  this.schedulePatch();
12569
12608
  }
@@ -12576,7 +12615,7 @@ var init_process_card = __esm({
12576
12615
  row = this.state.rows.at(-1);
12577
12616
  }
12578
12617
  if (!row) return;
12579
- const retain = match?.visible !== false || this.nativeCapable();
12618
+ const retain = match?.visible !== false || this.nativeCapable() || this.progressCapable();
12580
12619
  const lines = (out || "").split("\n").filter((line) => line.trim());
12581
12620
  row.state = retain && isError ? "err" : "ok";
12582
12621
  row.resultVisible = match?.visible;
@@ -12710,6 +12749,19 @@ var init_process_card = __esm({
12710
12749
  }
12711
12750
  return false;
12712
12751
  }
12752
+ /** 1119 cc-desk steer:忙时插话在卡片上留 ↪ 行(过程可见) */
12753
+ onSteer(text2) {
12754
+ if (this.ended || this.disposed) return;
12755
+ this.ensureStarted();
12756
+ this.state.steerNotes = [...this.state.steerNotes ?? [], stripCardUnsafe(oneLine(text2))].slice(-3);
12757
+ this.schedulePatch();
12758
+ }
12759
+ /** 1119 卡片停止钮:设置/清除停止按钮的 action value(run/wait 态渲染) */
12760
+ setStopAction(value) {
12761
+ if (this.ended || this.disposed) return;
12762
+ this.state.stopAction = value ?? void 0;
12763
+ this.schedulePatch();
12764
+ }
12713
12765
  turnEnd(finalText, usage, outcome) {
12714
12766
  return this.finish(outcome, finalText, usage);
12715
12767
  }
@@ -12745,7 +12797,7 @@ var init_process_card = __esm({
12745
12797
  return;
12746
12798
  }
12747
12799
  if (this.patchTimer) return;
12748
- const min = this.channelV === "cardkit" ? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
12800
+ const min = this.channelV === "cardkit" || this.channelV === "progress" ? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
12749
12801
  const wait2 = Math.max(0, min - (Date.now() - this.lastPatchAt));
12750
12802
  this.patchTimer = setTimeout(() => {
12751
12803
  this.patchTimer = null;
@@ -12760,7 +12812,7 @@ var init_process_card = __esm({
12760
12812
  await this.creation?.catch(() => {
12761
12813
  });
12762
12814
  if (this.disposed || this.ended && !final) return;
12763
- 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)) {
12815
+ 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)) {
12764
12816
  await this.removeCard().catch((error) => console.warn("[process-card] \u7A7A\u56DE\u5408\u6E05\u7406\u5931\u8D25:", error instanceof Error ? error.message : String(error)));
12765
12817
  return;
12766
12818
  }
@@ -12783,17 +12835,19 @@ var init_process_card = __esm({
12783
12835
  return `q${r.rid}:${r.settled}:${JSON.stringify(r.answers)}`;
12784
12836
  }).join("|");
12785
12837
  const bucket = Math.floor((Date.now() - s.startedAt) / LIVE_BUCKET_MS);
12786
- 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]);
12838
+ 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]);
12787
12839
  }
12788
12840
  async doPatch(final = false) {
12789
12841
  if (this.degraded || !this.messageId && this.channelV !== "cardkit") return false;
12790
12842
  const key2 = this.pushKey();
12791
12843
  if (key2 === this.lastPushKey) return true;
12792
12844
  this.lastPatchAt = Date.now();
12793
- const card = this.channelV === "patch-v1" ? buildProcessCard(this.state) : buildProcessCardV2(this.state) ?? (this.options.allowLegacyCard !== false ? buildProcessCard(this.state) : null);
12794
- if (this.channelV !== "preview" && !card) return false;
12845
+ const card = this.channelV === "progress" ? null : this.channelV === "patch-v1" ? buildProcessCard(this.state) : buildProcessCardV2(this.state) ?? (this.options.allowLegacyCard !== false ? buildProcessCard(this.state) : null);
12846
+ if (this.channelV !== "preview" && this.channelV !== "progress" && !card) return false;
12795
12847
  try {
12796
- if (this.channelV === "preview" && this.previewHandle && this.adapter.editPreview) {
12848
+ if (this.channelV === "progress" && this.messageId && this.adapter.updateProgress) {
12849
+ await this.adapter.updateProgress(this.messageId, structuredClone(this.state));
12850
+ } else if (this.channelV === "preview" && this.previewHandle && this.adapter.editPreview) {
12797
12851
  await this.adapter.editPreview(this.previewHandle, buildProcessText(this.state), this.repoName, final);
12798
12852
  } else if (this.channelV === "cardkit" && this.cardKitId && card) {
12799
12853
  this.seq++;
@@ -12852,6 +12906,12 @@ async function handleCcCardAction(data) {
12852
12906
  const fv = action?.form_value ?? {};
12853
12907
  const v = action?.value;
12854
12908
  if (!v || v.cc !== 1) return { toast: { type: "info", content: "\u672A\u77E5\u64CD\u4F5C" } };
12909
+ if (v.kind === "stop" && typeof v.key === "string") {
12910
+ const { ccDriverRouter: ccDriverRouter2 } = await Promise.resolve().then(() => (init_router(), router_exports));
12911
+ const session = ccDriverRouter2.hub?.forChatKey(v.key);
12912
+ const stopped = session ? session.stopAll() : false;
12913
+ return { toast: { type: stopped ? "success" : "info", content: stopped ? "\u5DF2\u505C\u6B62\u5F53\u524D\u4EFB\u52A1" : "\u5F53\u524D\u6CA1\u6709\u5728\u8DD1\u7684\u4EFB\u52A1" } };
12914
+ }
12855
12915
  if (v.kind === "perm" && v.rid) {
12856
12916
  const p = pendingPerms.get(v.rid);
12857
12917
  if (!p) return { toast: { type: "info", content: "\u8BE5\u5BA1\u6279\u5DF2\u5904\u7406\u6216\u5DF2\u5931\u6548" } };
@@ -13371,6 +13431,9 @@ var init_dep_downloader = __esm({
13371
13431
  function requestError(message, status = 409) {
13372
13432
  return Object.assign(new Error(message), { status });
13373
13433
  }
13434
+ function ccUserMsg(text2) {
13435
+ return { type: "user", message: { role: "user", content: text2 }, parent_tool_use_id: null };
13436
+ }
13374
13437
  function resultToText(content) {
13375
13438
  if (typeof content === "string") return content;
13376
13439
  if (Array.isArray(content)) {
@@ -13395,7 +13458,7 @@ function chunkText(text2, maxChars) {
13395
13458
  if (rest.trim()) chunks.push(rest);
13396
13459
  return chunks;
13397
13460
  }
13398
- var MAX_QUEUE, INTERIM_MIN_INTERVAL_MS, INTERIM_MIN_CHARS, MAX_INTERIM_PER_TURN, INTERIM_SNIPPET_CHARS, FINAL_CHUNK_CHARS, CcDriverSession, CcDriverHub;
13461
+ 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;
13399
13462
  var init_driver = __esm({
13400
13463
  "src/cc-driver/driver.ts"() {
13401
13464
  "use strict";
@@ -13410,6 +13473,53 @@ var init_driver = __esm({
13410
13473
  MAX_INTERIM_PER_TURN = 4;
13411
13474
  INTERIM_SNIPPET_CHARS = 600;
13412
13475
  FINAL_CHUNK_CHARS = 1500;
13476
+ SteerFeeder = class {
13477
+ pending = [];
13478
+ waiters = [];
13479
+ ended = false;
13480
+ /** 已 yield 给 CLI 的消息数(含首条) */
13481
+ yieldCount = 0;
13482
+ /** 最近一次 yield 的文本(续 turn 卡片的 prompt 用) */
13483
+ lastYield = "";
13484
+ /** 注入一条;返回 false = 已收口,进不了这个流了 */
13485
+ push(text2) {
13486
+ if (this.ended && this.pending.length === 0) return false;
13487
+ this.pending.push(text2);
13488
+ for (const w of this.waiters.splice(0)) w();
13489
+ return true;
13490
+ }
13491
+ /** 收口:吐完 pending 后生成器结束 */
13492
+ close() {
13493
+ this.ended = true;
13494
+ for (const w of this.waiters.splice(0)) w();
13495
+ }
13496
+ /** 还有没被 turn 消化的输入吗(未 shift 的 pending + 已 yield 未出 result 的) */
13497
+ expectsMoreTurns(turnsSeen) {
13498
+ return this.pending.length > 0 || this.yieldCount > turnsSeen;
13499
+ }
13500
+ /** 即将注入的下一条(1121:续 turn 卡片显示用——显示"接下来要处理的",不是刚答完的旧消息);无 pending 时 undefined */
13501
+ upcoming() {
13502
+ return this.pending[0];
13503
+ }
13504
+ async *stream(first) {
13505
+ this.yieldCount++;
13506
+ this.lastYield = first;
13507
+ yield ccUserMsg(first);
13508
+ while (true) {
13509
+ if (this.pending.length > 0) {
13510
+ const text2 = this.pending.shift();
13511
+ this.yieldCount++;
13512
+ this.lastYield = text2;
13513
+ yield ccUserMsg(text2);
13514
+ continue;
13515
+ }
13516
+ if (this.ended) return;
13517
+ await new Promise((resolve12) => this.waiters.push(resolve12));
13518
+ }
13519
+ }
13520
+ };
13521
+ defaultCcRuntimeLoader = (onProgress) => loadOptionalModule("cc-runtime", onProgress);
13522
+ ccRuntimeLoader = defaultCcRuntimeLoader;
13413
13523
  CcDriverSession = class {
13414
13524
  constructor(binding, cm, map, predecessor) {
13415
13525
  this.predecessor = predecessor;
@@ -13431,6 +13541,8 @@ var init_driver = __esm({
13431
13541
  revision = 0;
13432
13542
  idleWaiters = [];
13433
13543
  abort = null;
13544
+ /** 当前流式 chunk 的 steer 口(仅用户消息路径开;外部 ask/桌面路径为 null) */
13545
+ feeder = null;
13434
13546
  sessionId = null;
13435
13547
  sendChain = Promise.resolve();
13436
13548
  ui = null;
@@ -13455,11 +13567,16 @@ var init_driver = __esm({
13455
13567
  this.sessionId = null;
13456
13568
  return this.map.clear(this.key) || had;
13457
13569
  }
13458
- /** 入站一条消息:排队(busy 时 FIFO),队列满则提示。 */
13570
+ /** 入站一条消息:流式 chunk 开着 → steer 注入(1119);否则排队(busy 时 FIFO),队列满则提示。 */
13459
13571
  enqueue(text2) {
13460
13572
  const trimmed = text2.trim();
13461
13573
  if (!trimmed || this.closed) return;
13462
13574
  if (this.ui?.routeTyped(trimmed)) return;
13575
+ const feeder = this.feeder;
13576
+ if (feeder && feeder.push(trimmed)) {
13577
+ this.ui?.onSteer(trimmed);
13578
+ return;
13579
+ }
13463
13580
  if (this.queue.length >= MAX_QUEUE) {
13464
13581
  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`);
13465
13582
  return;
@@ -13496,9 +13613,22 @@ var init_driver = __esm({
13496
13613
  this.closed = true;
13497
13614
  this.revision++;
13498
13615
  for (const job of this.queue.splice(0)) job.reject?.(requestError("CC binding stopped before execution", 503));
13616
+ this.feeder?.close();
13499
13617
  this.stop();
13500
13618
  }
13501
- /** 中断当前 turn(队列里后续消息继续) */
13619
+ /**
13620
+ * 全停(1119 翀哥拍板):中断当前 turn + 清 FIFO(外部 ask 按取消拒)+ 关 steer 口。
13621
+ * abort 杀进程 → CLI 里已排队未消费的插话一并死——所见即所得的「全停」。
13622
+ */
13623
+ stopAll() {
13624
+ const hadQueued = this.queue.length > 0;
13625
+ for (const job of this.queue.splice(0)) job.reject?.(requestError("CC request cancelled (stop)", 499));
13626
+ this.feeder?.close();
13627
+ const active = this.busy;
13628
+ if (active) this.stop();
13629
+ return active || hadQueued;
13630
+ }
13631
+ /** 中断当前 turn(不清队列)——外部取消场景用;用户面全停走 stopAll() */
13502
13632
  stop() {
13503
13633
  this.abort?.abort();
13504
13634
  }
@@ -13520,10 +13650,14 @@ var init_driver = __esm({
13520
13650
  if (job.expectedSessionId !== void 0 && job.expectedSessionId !== this.sessionId) {
13521
13651
  throw requestError("CC session changed while this request was queued");
13522
13652
  }
13523
- const prompt = job.source ? `[cc_ask from ${job.source.replace(/[\r\n]/g, " ").slice(0, 160)}]
13524
- ${job.prompt}` : job.prompt;
13525
- const result = await this.runTurn(prompt, job.signal, !!job.source);
13526
- job.resolve?.(result);
13653
+ if (job.source) {
13654
+ const prompt = `[cc_ask from ${job.source.replace(/[\r\n]/g, " ").slice(0, 160)}]
13655
+ ${job.prompt}`;
13656
+ const result = await this.runTurn(prompt, job.signal, true);
13657
+ job.resolve?.(result);
13658
+ } else {
13659
+ await this.runStreaming(job);
13660
+ }
13527
13661
  } catch (err) {
13528
13662
  job.reject?.(err);
13529
13663
  console.error(`[cc-driver] turn \u5931\u8D25 key=${this.key}: ${err?.stack || err}`);
@@ -13557,15 +13691,11 @@ ${job.prompt}` : job.prompt;
13557
13691
  this.ui = null;
13558
13692
  }
13559
13693
  }
13560
- let textSoFar = "";
13561
- let gotPartial = false;
13562
- let lastInterimAt = Date.now();
13563
- let interimCount = 0;
13564
- let lastSentLen = 0;
13565
13694
  let finalText = "";
13566
13695
  let isError = false;
13567
13696
  let gotResult = false;
13568
13697
  let usage = "";
13698
+ const acc = this.makeStreamAccumulator();
13569
13699
  try {
13570
13700
  const desktops = resumedFrom ? await findDesktopTargets(this.workDir, resumedFrom) : [];
13571
13701
  if (desktops.length > 1) throw new Error("Multiple desktop writers claim this CC session; close the duplicate");
@@ -13581,7 +13711,7 @@ ${job.prompt}` : job.prompt;
13581
13711
  throw new Error("This CC session is open in another process; use cc-desktop to receive messages there");
13582
13712
  }
13583
13713
  let ccRuntimeNoticeSent = false;
13584
- const { query } = await loadOptionalModule("cc-runtime", (label, got, total) => {
13714
+ const { query } = await ccRuntimeLoader((label, got, total) => {
13585
13715
  if (ccRuntimeNoticeSent) return;
13586
13716
  ccRuntimeNoticeSent = true;
13587
13717
  const mb = total ? `\u7EA6 ${Math.round(total / 1024 / 1024)}M` : "\u7EA6 350M";
@@ -13625,43 +13755,7 @@ ${job.prompt}` : job.prompt;
13625
13755
  if (process.env.CC_DRIVER_DEBUG) console.log(`[cc-driver:dbg] type=${msg2.type} subtype=${msg2.subtype ?? "-"} sid=${msg2.session_id?.slice(0, 8) ?? "-"}`);
13626
13756
  const parentToolUseId = msg2.parent_tool_use_id;
13627
13757
  if (parentToolUseId) continue;
13628
- if (msg2.type === "stream_event") {
13629
- const ev = msg2.event;
13630
- if (ev.type === "content_block_start" && ev.content_block?.type === "thinking") this.ui?.onThinkingDelta("");
13631
- else if (ev.type === "content_block_delta" && ev.delta?.type === "thinking_delta" && typeof ev.delta.thinking === "string") this.ui?.onThinkingDelta(ev.delta.thinking);
13632
- else if (ev.type === "content_block_stop" && this.ui) this.ui.onThinkingEnd();
13633
- if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && typeof ev.delta.text === "string") {
13634
- gotPartial = true;
13635
- textSoFar += ev.delta.text;
13636
- const now2 = Date.now();
13637
- const newChars = textSoFar.length - lastSentLen;
13638
- if (!this.ui && now2 - lastInterimAt >= INTERIM_MIN_INTERVAL_MS && newChars >= INTERIM_MIN_CHARS && interimCount < MAX_INTERIM_PER_TURN) {
13639
- lastInterimAt = now2;
13640
- lastSentLen = textSoFar.length;
13641
- interimCount++;
13642
- const snippet = textSoFar.slice(-INTERIM_SNIPPET_CHARS);
13643
- void this.sendText(`\u2026${snippet}`);
13644
- }
13645
- }
13646
- } else if (msg2.type === "assistant") {
13647
- const content = msg2.message.content ?? [];
13648
- for (const block of content) {
13649
- if (block.type === "thinking" && block.thinking) this.ui?.onThinking(String(block.thinking));
13650
- else if (block.type === "tool_use" && block.id) this.ui?.onToolUse(String(block.name), block.input ?? {});
13651
- }
13652
- if (!gotPartial) {
13653
- for (const block of content) {
13654
- if (block.type === "text" && typeof block.text === "string") textSoFar += block.text;
13655
- }
13656
- }
13657
- } else if (msg2.type === "user") {
13658
- const content = msg2.message.content;
13659
- if (Array.isArray(content) && this.ui) {
13660
- for (const block of content) {
13661
- if (block.type === "tool_result") this.ui.onToolResult(resultToText(block.content), block.is_error === true);
13662
- }
13663
- }
13664
- } else if (msg2.type === "result") {
13758
+ if (msg2.type === "result") {
13665
13759
  const r = msg2;
13666
13760
  if (r.session_id) {
13667
13761
  turnSessionId = r.session_id;
@@ -13677,6 +13771,8 @@ ${job.prompt}` : job.prompt;
13677
13771
  turnSessionId = sid;
13678
13772
  if (this.revision === revision) this.sessionId = sid;
13679
13773
  }
13774
+ } else {
13775
+ await acc.handle(msg2);
13680
13776
  }
13681
13777
  }
13682
13778
  }
@@ -13685,22 +13781,22 @@ ${job.prompt}` : job.prompt;
13685
13781
  this.abort = null;
13686
13782
  signal?.removeEventListener("abort", cancel);
13687
13783
  }
13688
- const result = { sessionId: turnSessionId, text: finalText || textSoFar, isError: isError || ac.signal.aborted };
13784
+ const result = { sessionId: turnSessionId, text: finalText || acc.textSoFar, isError: isError || ac.signal.aborted };
13689
13785
  if (ac.signal.aborted) {
13690
13786
  if (this.ui && this.ui.alive) {
13691
13787
  await this.ui.turnEnd("", "", "aborted");
13692
- await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (textSoFar ? `
13788
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
13693
13789
  \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
13694
- ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13790
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13695
13791
  return { ...result, text: "[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" };
13696
13792
  }
13697
- await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (textSoFar ? `
13793
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
13698
13794
 
13699
13795
  \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
13700
- ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13796
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13701
13797
  return { ...result, text: "[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" };
13702
13798
  }
13703
- const answer = finalText || textSoFar;
13799
+ const answer = finalText || acc.textSoFar;
13704
13800
  if (this.ui && this.ui.alive) {
13705
13801
  await this.ui.turnEnd("", usage, isError ? "err" : "done");
13706
13802
  if (!answer.trim()) {
@@ -13719,6 +13815,215 @@ ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13719
13815
  }
13720
13816
  return result;
13721
13817
  }
13818
+ /**
13819
+ * stream_event / assistant / user 三类消息的共用处理(runTurn 与 runStreaming 共享;
13820
+ * result / system 两个分支各自的循环里处理——流式 chunk 是多 result 语义)。
13821
+ * 返回 per-turn 累积态访问器(reset 在每个 result 后调)。
13822
+ */
13823
+ makeStreamAccumulator() {
13824
+ let textSoFar = "";
13825
+ let gotPartial = false;
13826
+ let lastInterimAt = Date.now();
13827
+ let interimCount = 0;
13828
+ let lastSentLen = 0;
13829
+ return {
13830
+ reset: () => {
13831
+ textSoFar = "";
13832
+ gotPartial = false;
13833
+ lastInterimAt = Date.now();
13834
+ interimCount = 0;
13835
+ lastSentLen = 0;
13836
+ },
13837
+ handle: async (msg2) => {
13838
+ if (msg2.type === "stream_event") {
13839
+ const ev = msg2.event;
13840
+ if (ev.type === "content_block_start" && ev.content_block?.type === "thinking") this.ui?.onThinkingDelta("");
13841
+ else if (ev.type === "content_block_delta" && ev.delta?.type === "thinking_delta" && typeof ev.delta.thinking === "string") this.ui?.onThinkingDelta(ev.delta.thinking);
13842
+ else if (ev.type === "content_block_stop" && this.ui) this.ui.onThinkingEnd();
13843
+ if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && typeof ev.delta.text === "string") {
13844
+ gotPartial = true;
13845
+ textSoFar += ev.delta.text;
13846
+ const now2 = Date.now();
13847
+ const newChars = textSoFar.length - lastSentLen;
13848
+ if (!this.ui && now2 - lastInterimAt >= INTERIM_MIN_INTERVAL_MS && newChars >= INTERIM_MIN_CHARS && interimCount < MAX_INTERIM_PER_TURN) {
13849
+ lastInterimAt = now2;
13850
+ lastSentLen = textSoFar.length;
13851
+ interimCount++;
13852
+ const snippet = textSoFar.slice(-INTERIM_SNIPPET_CHARS);
13853
+ void this.sendText(`\u2026${snippet}`);
13854
+ }
13855
+ }
13856
+ } else if (msg2.type === "assistant") {
13857
+ const content = msg2.message.content ?? [];
13858
+ for (const block of content) {
13859
+ if (block.type === "thinking" && block.thinking) this.ui?.onThinking(String(block.thinking));
13860
+ else if (block.type === "tool_use" && block.id) this.ui?.onToolUse(String(block.name), block.input ?? {});
13861
+ }
13862
+ if (!gotPartial) {
13863
+ for (const block of content) {
13864
+ if (block.type === "text" && typeof block.text === "string") textSoFar += block.text;
13865
+ }
13866
+ }
13867
+ } else if (msg2.type === "user") {
13868
+ const content = msg2.message.content;
13869
+ if (Array.isArray(content) && this.ui) {
13870
+ for (const block of content) {
13871
+ if (block.type === "tool_result") this.ui.onToolResult(resultToText(block.content), block.is_error === true);
13872
+ }
13873
+ }
13874
+ }
13875
+ },
13876
+ get textSoFar() {
13877
+ return textSoFar;
13878
+ }
13879
+ };
13880
+ }
13881
+ /**
13882
+ * 用户消息的流式 chunk(1119 cc-desk steer):一次 query() 的 prompt 是 feeder 生成器,
13883
+ * busy 时 enqueue → feeder.push 注入(模型下一次 API 调用看到),同一进程可出多个
13884
+ * result(每 result 交付一轮答案);全部消化完 → close → 进程退出,空闲零进程不变。
13885
+ * 桌面托管 / 他进程占用 → 退回 runTurn 封闭路径(桌面桥无 steer)。
13886
+ */
13887
+ async runStreaming(job) {
13888
+ const resumedFrom = this.sessionId;
13889
+ const desktops = resumedFrom ? await findDesktopTargets(this.workDir, resumedFrom) : [];
13890
+ if (desktops.length > 0 || resumedFrom && nativeSessionOwners(resumedFrom).length) {
13891
+ await this.runTurn(job.prompt, job.signal, false);
13892
+ return;
13893
+ }
13894
+ const ac = new AbortController();
13895
+ this.abort = ac;
13896
+ const revision = this.revision;
13897
+ let turnSessionId = resumedFrom;
13898
+ const cancel = () => ac.abort();
13899
+ job.signal?.addEventListener("abort", cancel, { once: true });
13900
+ if (job.signal?.aborted) ac.abort();
13901
+ console.log(`[cc-driver] streaming turn start key=${this.key} resume=${resumedFrom ? resumedFrom.slice(0, 8) : "new"} cwd=${this.workDir}`);
13902
+ if (this.binding.channel === "feishu" && !this.uiTried) {
13903
+ this.uiTried = true;
13904
+ this.ui = await makeFeishuCardUi(this.cm, this.binding);
13905
+ }
13906
+ if (this.ui) {
13907
+ try {
13908
+ await this.ui.turnStart(job.prompt);
13909
+ this.ui.setStopAction({ cc: 1, kind: "stop", key: this.key });
13910
+ } catch (err) {
13911
+ console.warn(`[cc-driver:card] \u5F00\u5361\u5931\u8D25\uFF0C\u672C binding \u56DE\u9000\u7EAF\u6587\u672C\uFF1A${err?.message ?? err}`);
13912
+ this.ui = null;
13913
+ }
13914
+ }
13915
+ const feeder = new SteerFeeder();
13916
+ this.feeder = feeder;
13917
+ const acc = this.makeStreamAccumulator();
13918
+ let turnsSeen = 0;
13919
+ let deliveredAfterAbort = false;
13920
+ try {
13921
+ const { query } = await ccRuntimeLoader();
13922
+ const stream = query({
13923
+ prompt: feeder.stream(job.prompt),
13924
+ options: {
13925
+ abortController: ac,
13926
+ cwd: this.workDir,
13927
+ ...this.binding.permissionMode && this.binding.permissionMode !== "auto" ? { permissionMode: this.binding.permissionMode } : {},
13928
+ model: this.binding.model,
13929
+ resume: resumedFrom ?? void 0,
13930
+ includePartialMessages: true,
13931
+ ...this.ui ? {
13932
+ canUseTool: async (toolName, input, opts) => {
13933
+ if (!this.ui) return { behavior: "deny", message: "\u5361\u7247\u901A\u9053\u5DF2\u65AD\u5F00\uFF0C\u64CD\u4F5C\u88AB\u62D2\u7EDD\u3002" };
13934
+ if (toolName === "AskUserQuestion") {
13935
+ const questions = normalizeQuestions(input.questions);
13936
+ 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" };
13937
+ const r2 = await this.ui.askUser(questions, opts.signal);
13938
+ if (r2.answers) return { behavior: "allow", updatedInput: { ...input, answers: r2.answers } };
13939
+ 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" };
13940
+ }
13941
+ const r = await this.ui.askPermission(toolName, input, opts.signal, opts.suggestions);
13942
+ 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" };
13943
+ return {
13944
+ behavior: "allow",
13945
+ updatedInput: input,
13946
+ ...r.verdict === "always" && Array.isArray(opts.suggestions) && opts.suggestions.length > 0 ? { updatedPermissions: opts.suggestions } : {}
13947
+ };
13948
+ }
13949
+ } : {}
13950
+ }
13951
+ });
13952
+ try {
13953
+ for await (const msg2 of stream) {
13954
+ if (process.env.CC_DRIVER_DEBUG) console.log(`[cc-driver:dbg] type=${msg2.type} subtype=${msg2.subtype ?? "-"} sid=${msg2.session_id?.slice(0, 8) ?? "-"}`);
13955
+ const parentToolUseId = msg2.parent_tool_use_id;
13956
+ if (parentToolUseId) continue;
13957
+ if (msg2.type === "result") {
13958
+ const r = msg2;
13959
+ turnsSeen++;
13960
+ if (r.session_id) {
13961
+ turnSessionId = r.session_id;
13962
+ if (this.revision === revision) this.sessionId = r.session_id;
13963
+ }
13964
+ const isError = r.is_error === true;
13965
+ const finalText = typeof r.result === "string" ? r.result : "";
13966
+ const usage = r.usage ? `\u2193 ${fmtTok(r.usage.input_tokens)} \xB7 \u2191 ${fmtTok(r.usage.output_tokens)}` : "";
13967
+ if (turnSessionId && this.revision === revision) this.map.switchTo(this.key, turnSessionId, this.workDir);
13968
+ const more = feeder.expectsMoreTurns(turnsSeen);
13969
+ const answer = finalText || acc.textSoFar;
13970
+ if (ac.signal.aborted) deliveredAfterAbort = true;
13971
+ if (this.ui && this.ui.alive) {
13972
+ await this.ui.turnEnd("", usage, isError ? "err" : "done");
13973
+ }
13974
+ if (!answer.trim()) {
13975
+ 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");
13976
+ } else {
13977
+ for (const chunk of chunkText(answer, FINAL_CHUNK_CHARS)) await this.sendText(chunk);
13978
+ }
13979
+ acc.reset();
13980
+ if (ac.signal.aborted) break;
13981
+ if (!more) {
13982
+ feeder.close();
13983
+ break;
13984
+ }
13985
+ if (this.ui) {
13986
+ try {
13987
+ await this.ui.turnStart(`\u21AA ${feeder.upcoming() ?? feeder.lastYield}`);
13988
+ this.ui.setStopAction({ cc: 1, kind: "stop", key: this.key });
13989
+ } catch (err) {
13990
+ console.warn(`[cc-driver:card] \u7EED turn \u5F00\u5361\u5931\u8D25\uFF0C\u56DE\u9000\u7EAF\u6587\u672C\uFF1A${err?.message ?? err}`);
13991
+ this.ui = null;
13992
+ }
13993
+ }
13994
+ } else if (msg2.type === "system" && msg2.subtype === "init") {
13995
+ const sid = msg2.session_id;
13996
+ if (sid) {
13997
+ turnSessionId = sid;
13998
+ if (this.revision === revision) this.sessionId = sid;
13999
+ }
14000
+ } else {
14001
+ await acc.handle(msg2);
14002
+ }
14003
+ }
14004
+ } catch (err) {
14005
+ if (!(ac.signal.aborted || !feeder.expectsMoreTurns(turnsSeen))) throw err;
14006
+ }
14007
+ } finally {
14008
+ feeder.close();
14009
+ this.feeder = null;
14010
+ this.abort = null;
14011
+ job.signal?.removeEventListener("abort", cancel);
14012
+ }
14013
+ if (ac.signal.aborted && !deliveredAfterAbort) {
14014
+ if (this.ui && this.ui.alive) {
14015
+ await this.ui.turnEnd("", "", "aborted");
14016
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
14017
+ \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
14018
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14019
+ } else {
14020
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
14021
+
14022
+ \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
14023
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14024
+ }
14025
+ }
14026
+ }
13722
14027
  /** 串行发送器:wechat 3s 节流在适配器层,这里保证不并发、失败不炸链 */
13723
14028
  sendText(text2) {
13724
14029
  const task = this.sendChain.then(async () => {
@@ -13766,6 +14071,12 @@ ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13766
14071
  forChat(channel, chatId) {
13767
14072
  return this.sessions.get(`${channel}:${chatId}`);
13768
14073
  }
14074
+ /** 按 bindingKey(channel:chatId)找 session——卡片停止钮回调用(1119) */
14075
+ forChatKey(key2) {
14076
+ const idx = key2.indexOf(":");
14077
+ if (idx <= 0) return void 0;
14078
+ return this.sessions.get(key2);
14079
+ }
13769
14080
  /** 全部绑定的工作目录(去重;cc-progress 工具省参推断用) */
13770
14081
  get bindingWorkDirs() {
13771
14082
  return [...new Set([...this.sessions.values()].map((s) => s.workDir))];
@@ -13903,6 +14214,12 @@ var init_cc_driver = __esm({
13903
14214
  });
13904
14215
 
13905
14216
  // src/cc-driver/router.ts
14217
+ var router_exports = {};
14218
+ __export(router_exports, {
14219
+ autoBindHit: () => autoBindHit,
14220
+ ccDriverRouter: () => ccDriverRouter,
14221
+ markBindSelect: () => markBindSelect
14222
+ });
13906
14223
  import { existsSync as existsSync8 } from "node:fs";
13907
14224
  function autoBindHit(inbound) {
13908
14225
  if (inbound.channel !== "feishu" || inbound.channelType !== "dm") return null;
@@ -13932,6 +14249,14 @@ async function doAutoBind(inbound, workDir) {
13932
14249
  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
13933
14250
  /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`);
13934
14251
  }
14252
+ function markBindSelect(channel, chatId) {
14253
+ pendingBind.set(`${channel}:${chatId}`, Date.now());
14254
+ while (pendingBind.size > 32) {
14255
+ const oldest = pendingBind.keys().next().value;
14256
+ if (oldest === void 0) break;
14257
+ pendingBind.delete(oldest);
14258
+ }
14259
+ }
13935
14260
  function peekBindNumber(inbound) {
13936
14261
  if (inbound.channelType !== "dm") return null;
13937
14262
  const ts = pendingBind.get(`${inbound.channel}:${inbound.channel_id}`);
@@ -17761,6 +18086,9 @@ var TravelAuthority = class {
17761
18086
  CREATE TABLE IF NOT EXISTS recovery_branches(identity TEXT NOT NULL,common TEXT NOT NULL,local TEXT NOT NULL,
17762
18087
  chain TEXT NOT NULL,PRIMARY KEY(identity,common,local));`);
17763
18088
  this.db.exec("CREATE TABLE IF NOT EXISTS retirement_sources(identity TEXT PRIMARY KEY,body TEXT NOT NULL)");
18089
+ if (!this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='leased_seats'").get()) {
18090
+ this.transaction(() => this.db.exec("CREATE TABLE leased_seats(identity TEXT PRIMARY KEY); INSERT INTO leased_seats SELECT identity FROM seats"));
18091
+ }
17764
18092
  if (this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_AUTHORITY_CORRUPT");
17765
18093
  this.transaction(() => {
17766
18094
  this.db.exec("UPDATE seats SET epoch=epoch+1,active_node=NULL,active_boot=NULL,frozen=0 WHERE retired IS NULL");
@@ -17825,7 +18153,7 @@ var TravelAuthority = class {
17825
18153
  }
17826
18154
  /** Trusted pairing owner binds the first real H to an unused reservation.
17827
18155
  * This does not grant a lease and never rewrites a used seat's history. */
17828
- bindInitialCheckpoint(principal, digest7, buildManifestId) {
18156
+ bindInitialCheckpoint(principal, digest7, buildManifestId, previousDigest) {
17829
18157
  if (!HASH2.test(digest7) || digest7 === "0".repeat(64)) throw new Error("TRAVEL_INITIAL_BASELINE");
17830
18158
  id(buildManifestId);
17831
18159
  const text2 = identityText(principal);
@@ -17834,7 +18162,9 @@ var TravelAuthority = class {
17834
18162
  this.principal(principal);
17835
18163
  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");
17836
18164
  if (row.checkpoint === digest7) return;
17837
- if (row.checkpoint !== "0".repeat(64)) throw new Error("TRAVEL_INITIAL_BASELINE");
18165
+ if (this.db.prepare("SELECT 1 FROM leased_seats WHERE identity=?").get(text2)) throw new Error("TRAVEL_INITIAL_BASELINE");
18166
+ if (previousDigest !== void 0 && (!HASH2.test(previousDigest) || row.checkpoint !== previousDigest)) throw new Error("TRAVEL_INITIAL_BASELINE");
18167
+ if (row.checkpoint !== "0".repeat(64) && previousDigest !== row.checkpoint) throw new Error("TRAVEL_INITIAL_BASELINE");
17838
18168
  this.db.prepare("DELETE FROM checkpoints WHERE identity=?").run(text2);
17839
18169
  this.db.prepare("INSERT INTO checkpoints VALUES(?,?,NULL,1)").run(text2, digest7);
17840
18170
  this.db.prepare("UPDATE seats SET checkpoint=? WHERE identity=?").run(digest7, text2);
@@ -17905,6 +18235,7 @@ var TravelAuthority = class {
17905
18235
  if (row.active_node && ((this.deadlines.get(text2) ?? 0) <= this.monotonicNow() || row.active_boot !== node.boot)) row.epoch++;
17906
18236
  row.active_node = principal.nodeId;
17907
18237
  row.active_boot = String(node.boot);
18238
+ this.db.prepare("INSERT OR IGNORE INTO leased_seats VALUES(?)").run(text2);
17908
18239
  this.db.prepare("UPDATE seats SET epoch=?,active_node=?,active_boot=? WHERE identity=?").run(row.epoch, row.active_node, row.active_boot, text2);
17909
18240
  this.deadlines.set(text2, this.monotonicNow() + this.leaseMs);
17910
18241
  this.healthy.set(text2 + principal.nodeId, this.monotonicNow() + this.leaseMs);
@@ -18199,7 +18530,7 @@ import { createHash as createHash3 } from "node:crypto";
18199
18530
  // src/continuity/inventory.ts
18200
18531
  import { isAbsolute, join as join3, relative, resolve as resolve2, sep } from "node:path";
18201
18532
  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(" "));
18202
- 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(" "));
18533
+ 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(" "));
18203
18534
  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(" "));
18204
18535
  function validateRelativePath(path35) {
18205
18536
  if (typeof path35 !== "string" || !path35 || path35.length > 2048 || isAbsolute(path35)) throw new Error("INVALID_ARTIFACT_PATH");
@@ -18866,6 +19197,18 @@ var TravelGatewayStore = class {
18866
19197
  }
18867
19198
  /** Host-owned import of actual previously processed platform IDs. A receipt
18868
19199
  * is negative dedupe only: it cannot create input or enqueue a task. */
19200
+ async begin(principal, permit, channel) {
19201
+ this.active(principal, permit, "SEND");
19202
+ if (!["feishu", "discord", "wechat"].includes(channel)) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19203
+ const body = Buffer.from(JSON.stringify({ format: "engine7-gateway-engine-event-v1", channel, nodeId: permit.nodeId, bootId: permit.bootId, epoch: permit.epoch }));
19204
+ const ref = await this.options.objects.putContent(body);
19205
+ return this.transaction(() => {
19206
+ this.active(principal, permit, "SEND");
19207
+ const id3 = digest4("engine:" + randomUUID11());
19208
+ 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);
19209
+ return { id: id3 };
19210
+ });
19211
+ }
18869
19212
  importProcessedInputs(platformIds) {
18870
19213
  if (!Array.isArray(platformIds) || platformIds.length > 1e5 || platformIds.some((id3) => typeof id3 !== "string" || !id3 || id3.length > 512)) throw new Error("TRAVEL_GATEWAY_INVALID_EVENT");
18871
19214
  this.transaction(() => {
@@ -19291,7 +19634,7 @@ function createTravelGatewayServer(options) {
19291
19634
  return;
19292
19635
  }
19293
19636
  const action = req.url?.startsWith(prefix) ? req.url.slice(prefix.length) : "";
19294
- 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)) {
19637
+ 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)) {
19295
19638
  reply(404, { error: "TRAVEL_GATEWAY_NOT_FOUND" });
19296
19639
  req.resume();
19297
19640
  return;
@@ -19328,7 +19671,7 @@ function createTravelGatewayServer(options) {
19328
19671
  reply(200, store.applyRecoveryDeletedInputs(principal, input.bindings, input.floor));
19329
19672
  return;
19330
19673
  }
19331
- 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");
19674
+ 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");
19332
19675
  if (action === "preparation") {
19333
19676
  if (Object.keys(input).length) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19334
19677
  reply(200, store.preparationEvidence(principal));
@@ -19344,6 +19687,11 @@ function createTravelGatewayServer(options) {
19344
19687
  reply(200, store.exitDedupeReceipt(principal, permit));
19345
19688
  return;
19346
19689
  }
19690
+ if (action === "begin") {
19691
+ if (typeof input.channel !== "string" || !["feishu", "discord", "wechat"].includes(input.channel)) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19692
+ reply(200, await store.begin(principal, permit, input.channel));
19693
+ return;
19694
+ }
19347
19695
  if (action === "claim") {
19348
19696
  const claims = await store.claim(principal, permit, input.options);
19349
19697
  reply(200, claims.map(({ body: body2, ...claim }) => ({ ...claim, bodyBase64: body2.toString("base64") })));
@@ -19511,6 +19859,12 @@ var TravelGatewayClient = class {
19511
19859
  async ack(permit, eventId) {
19512
19860
  await this.call("ack", { permit, eventId });
19513
19861
  }
19862
+ /** 1121:引擎主动开口——开一个 ENGINE 态事件承载 effect 台账。 */
19863
+ async begin(permit, channel) {
19864
+ const result = await this.call("begin", { permit, channel });
19865
+ if (!result || typeof result.id !== "string" || !/^[a-f0-9]{64}$/.test(result.id)) throw new Error("TRAVEL_GATEWAY_INVALID_RESPONSE");
19866
+ return result;
19867
+ }
19514
19868
  async finish(permit, eventId) {
19515
19869
  await this.call("finish", { permit, eventId });
19516
19870
  }
@@ -27000,7 +27354,7 @@ function assertImageAssetRef(ref) {
27000
27354
  throw new Error("Invalid or oversized image asset reference");
27001
27355
  }
27002
27356
  }
27003
- async function materializeImageMessages(messages, store, signal, maxBase64Bytes = REQUEST_IMAGE_MAX_BASE64_SIZE) {
27357
+ async function materializeImageMessages(messages, store, signal, maxBase64Bytes = REQUEST_IMAGE_MAX_BASE64_SIZE, opts = {}) {
27004
27358
  signal?.throwIfAborted();
27005
27359
  let total = 0;
27006
27360
  for (const message of messages) if (Array.isArray(message.content)) for (const block of message.content) {
@@ -27025,6 +27379,7 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
27025
27379
  return { ...message, content: content.length ? content : "[previous image omitted]" };
27026
27380
  });
27027
27381
  if (total > maxBase64Bytes) throw new Error(`Request image base64 exceeds ${maxBase64Bytes} byte limit`);
27382
+ const { strict = false } = opts;
27028
27383
  const cache = /* @__PURE__ */ new Map();
27029
27384
  const output = [];
27030
27385
  for (const message of requestView) {
@@ -27041,8 +27396,12 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
27041
27396
  }
27042
27397
  if (!store) throw new Error("Image asset store is required to materialize image refs");
27043
27398
  const key2 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
27044
- if (!cache.has(key2)) cache.set(key2, store.materialize(block.image));
27045
- content.push(await cache.get(key2));
27399
+ if (!cache.has(key2)) cache.set(key2, store.materialize(block.image).catch((error) => {
27400
+ if (strict) throw error;
27401
+ 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)}`);
27402
+ return null;
27403
+ }));
27404
+ content.push(await cache.get(key2) ?? { type: "text", text: "[\u56FE\u7247\u6587\u4EF6\u5DF2\u4E0D\u5728\u672C\u673A\uFF0C\u5185\u5BB9\u4E0D\u53EF\u89C1]" });
27046
27405
  signal?.throwIfAborted();
27047
27406
  }
27048
27407
  output.push({ ...message, content });
@@ -34459,6 +34818,7 @@ function createFeishuGatewayDispatcher(options) {
34459
34818
  body: Buffer.from(JSON.stringify({ format, event: { sender, message }, ...resources.length ? { resources } : {} }))
34460
34819
  });
34461
34820
  options.assertIngress?.();
34821
+ if (sender.sender_type !== "bot") options.onReceivedTyping?.(message.chat_id, sender.sender_id?.open_id, message.message_id);
34462
34822
  },
34463
34823
  "im.message.reaction.created_v1": async () => {
34464
34824
  },
@@ -34510,7 +34870,34 @@ function createFeishuGatewayPlatform(options) {
34510
34870
  return config;
34511
34871
  });
34512
34872
  let closed = false;
34873
+ const typing = /* @__PURE__ */ new Map(), openToChat = /* @__PURE__ */ new Map();
34874
+ const removeReaction = (messageId, reactionId) => client.im.messageReaction.delete({ path: { message_id: messageId, reaction_id: reactionId } }).catch(() => {
34875
+ });
34876
+ const startChatTyping = (chatId, openId, messageId) => {
34877
+ if (closed) return;
34878
+ if (openId) openToChat.set(openId, chatId);
34879
+ const current2 = typing.get(chatId);
34880
+ if (current2?.messageId === messageId) return;
34881
+ if (current2?.reactionId) removeReaction(current2.messageId, current2.reactionId);
34882
+ typing.set(chatId, { messageId });
34883
+ client.im.messageReaction.create({ path: { message_id: messageId }, data: { reaction_type: { emoji_type: "Typing" } } }).then((response) => {
34884
+ const reactionId = response?.data?.reaction_id, entry = typing.get(chatId);
34885
+ if (reactionId && entry && entry.messageId === messageId) entry.reactionId = reactionId;
34886
+ else if (reactionId) removeReaction(messageId, reactionId);
34887
+ }).catch(() => {
34888
+ });
34889
+ };
34890
+ const stopChatTyping = (target) => {
34891
+ const chatId = target.startsWith("ou_") ? openToChat.get(target) : target;
34892
+ if (!chatId) return;
34893
+ const entry = typing.get(chatId);
34894
+ if (!entry) return;
34895
+ typing.delete(chatId);
34896
+ if (entry.reactionId) removeReaction(entry.messageId, entry.reactionId);
34897
+ };
34513
34898
  return {
34899
+ startChatTyping,
34900
+ stopChatTyping,
34514
34901
  deliver: async (effect, body, assertCurrent) => {
34515
34902
  if (closed) throw new Error("TRAVEL_FEISHU_CLOSED");
34516
34903
  const media = effect.kind === "MEDIA" ? decodeGatewayMedia(body) : void 0;
@@ -34538,6 +34925,7 @@ function createFeishuGatewayPlatform(options) {
34538
34925
  assertCurrent();
34539
34926
  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 } });
34540
34927
  if (result.code !== 0 || typeof result.data?.message_id !== "string" || !result.data.message_id) throw new Error("TRAVEL_FEISHU_SEND_UNKNOWN");
34928
+ if (effect.kind === "REPLY") stopChatTyping(packet.target);
34541
34929
  return { messageId: result.data.message_id };
34542
34930
  });
34543
34931
  },
@@ -34670,78 +35058,101 @@ var RemoteTravelChannel = class {
34670
35058
  });
34671
35059
  }));
34672
35060
  }
34673
- async send(target, message, options) {
34674
- const context = travelEventContext();
34675
- if (!context || context.client !== this.options.client) throw new Error("TRAVEL_GATEWAY_CONTEXT_REQUIRED");
34676
- if (context.failed) throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
34677
- assertExternalEffectCurrent();
34678
- travelEventPermit(context);
34679
- const config = resolveBubbleSplit(this.name), bubbles = config.on && options?.bubbleSplit === true ? splitBubbles(message) : null;
34680
- const chunks = bubbles ?? (this.name === "feishu" ? splitFeishuGatewayText(message) : splitChannelGatewayText(message, this.name));
34681
- const kind = travelOutputKind(), ordinal = (context.ordinals[kind] ?? 0) + 1;
34682
- context.ordinals[kind] = ordinal + chunks.length - 1;
35061
+ /** 1121:主动开口的落点。有进站事件就在其上下文里发(原语义);没有(cron/
35062
+ * inner-voice/nudge 主动消息)就在网关开一个 ENGINE 事件承载 effect 台账,
35063
+ * 复用同一套 produce/dispatch/finish 对账,绝不绕开网关直发。 */
35064
+ async effect(run) {
35065
+ const existing = travelEventContext();
35066
+ if (existing) {
35067
+ if (existing.client !== this.options.client) throw new Error("TRAVEL_GATEWAY_CONTEXT_REQUIRED");
35068
+ return run(existing);
35069
+ }
35070
+ const permit = this.options.permit();
35071
+ const { id: id3 } = await this.options.client.begin(permit, this.name);
35072
+ const context = { eventId: id3, originalPermit: permit, permit: this.options.permit, client: this.options.client, ordinals: {}, queued: false, failed: false, complete: false };
34683
35073
  try {
34684
- const effects2 = await context.client.produceBatch(travelEventPermit(context), chunks.map((text2, index) => ({
34685
- eventId: context.eventId,
34686
- kind,
34687
- ordinal: ordinal + index,
34688
- version: 1,
34689
- body: Buffer.from(JSON.stringify({ channel: this.name, target, text: text2, format: this.name === "feishu" ? "post" : "text", ...index === 0 && options?.replyTo ? { replyTo: options.replyTo } : {} }))
34690
- })), { finalOutput: options?.extra?.travelFinalReply === true });
34691
- for (let index = 0; index < effects2.length; index++) {
34692
- assertExternalEffectCurrent();
34693
- await context.client.dispatch(travelEventPermit(context), effects2[index].id);
34694
- if (bubbles && index < effects2.length - 1 && config.gapMs > 0) await new Promise((resolve12) => setTimeout(resolve12, Math.min(config.gapMs, 6e4)));
34695
- }
35074
+ const value = await withTravelEventContext(context, () => run(context));
35075
+ await completeTravelEvent(context);
35076
+ return value;
34696
35077
  } catch (error) {
34697
35078
  context.failed = true;
35079
+ await this.options.client.finish(this.options.permit(), id3).catch(() => {
35080
+ });
34698
35081
  throw error;
34699
35082
  }
34700
35083
  }
35084
+ async send(target, message, options) {
35085
+ await this.effect(async (context) => {
35086
+ if (context.failed) throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
35087
+ assertExternalEffectCurrent();
35088
+ travelEventPermit(context);
35089
+ const config = resolveBubbleSplit(this.name), bubbles = config.on && options?.bubbleSplit === true ? splitBubbles(message) : null;
35090
+ const chunks = bubbles ?? (this.name === "feishu" ? splitFeishuGatewayText(message) : splitChannelGatewayText(message, this.name));
35091
+ const kind = travelOutputKind(), ordinal = (context.ordinals[kind] ?? 0) + 1;
35092
+ context.ordinals[kind] = ordinal + chunks.length - 1;
35093
+ try {
35094
+ const effects2 = await context.client.produceBatch(travelEventPermit(context), chunks.map((text2, index) => ({
35095
+ eventId: context.eventId,
35096
+ kind,
35097
+ ordinal: ordinal + index,
35098
+ version: 1,
35099
+ body: Buffer.from(JSON.stringify({ channel: this.name, target, text: text2, format: this.name === "feishu" ? "post" : "text", ...index === 0 && options?.replyTo ? { replyTo: options.replyTo } : {} }))
35100
+ })), { finalOutput: options?.extra?.travelFinalReply === true });
35101
+ for (let index = 0; index < effects2.length; index++) {
35102
+ assertExternalEffectCurrent();
35103
+ await context.client.dispatch(travelEventPermit(context), effects2[index].id);
35104
+ if (bubbles && index < effects2.length - 1 && config.gapMs > 0) await new Promise((resolve12) => setTimeout(resolve12, Math.min(config.gapMs, 6e4)));
35105
+ }
35106
+ } catch (error) {
35107
+ context.failed = true;
35108
+ throw error;
35109
+ }
35110
+ });
35111
+ }
34701
35112
  async sendFile(target, message, attachment) {
34702
- const context = travelEventContext();
34703
- if (!context || context.client !== this.options.client) throw new Error("TRAVEL_GATEWAY_CONTEXT_REQUIRED");
34704
- if (context.failed) throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
34705
- assertExternalEffectCurrent();
34706
- travelEventPermit(context);
34707
- const handle = await open2(attachment.path, "r");
34708
- let bytes2;
34709
- try {
34710
- const info = await handle.stat();
34711
- if (!info.isFile() || !info.size || info.size > gatewayMediaLimit) throw new Error("TRAVEL_GATEWAY_MEDIA_LIMIT");
34712
- bytes2 = Buffer.alloc(info.size);
34713
- let offset = 0;
34714
- while (offset < bytes2.length) {
34715
- const read2 = await handle.read(bytes2, offset, bytes2.length - offset, offset);
34716
- if (!read2.bytesRead) throw new Error("TRAVEL_GATEWAY_MEDIA_CHANGED");
34717
- offset += read2.bytesRead;
34718
- }
34719
- const after = await handle.stat();
34720
- if (info.size !== after.size || info.mtimeMs !== after.mtimeMs) throw new Error("TRAVEL_GATEWAY_MEDIA_CHANGED");
34721
- } finally {
34722
- await handle.close();
34723
- }
34724
- assertExternalEffectCurrent();
34725
- travelEventPermit(context);
34726
- const mimeType = attachment.mimeType ?? "application/octet-stream", filename = attachment.filename ?? basename7(attachment.path);
34727
- const captions = message && !mimeType.startsWith("image/") ? this.name === "feishu" ? splitFeishuGatewayText(message) : splitChannelGatewayText(message, this.name) : [];
34728
- const ordinal = (context.ordinals.MEDIA ?? 0) + 1;
34729
- context.ordinals.MEDIA = ordinal;
34730
- const kind = travelOutputKind(), replyOrdinal = (context.ordinals[kind] ?? 0) + 1;
34731
- context.ordinals[kind] = replyOrdinal + captions.length - 1;
34732
- try {
34733
- const effects2 = await context.client.produceBatch(travelEventPermit(context), [
34734
- { 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) },
34735
- ...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" })) }))
34736
- ]);
34737
- for (const effect of effects2) {
34738
- assertExternalEffectCurrent();
34739
- await context.client.dispatch(travelEventPermit(context), effect.id);
35113
+ await this.effect(async (context) => {
35114
+ if (context.failed) throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
35115
+ assertExternalEffectCurrent();
35116
+ travelEventPermit(context);
35117
+ const handle = await open2(attachment.path, "r");
35118
+ let bytes2;
35119
+ try {
35120
+ const info = await handle.stat();
35121
+ if (!info.isFile() || !info.size || info.size > gatewayMediaLimit) throw new Error("TRAVEL_GATEWAY_MEDIA_LIMIT");
35122
+ bytes2 = Buffer.alloc(info.size);
35123
+ let offset = 0;
35124
+ while (offset < bytes2.length) {
35125
+ const read2 = await handle.read(bytes2, offset, bytes2.length - offset, offset);
35126
+ if (!read2.bytesRead) throw new Error("TRAVEL_GATEWAY_MEDIA_CHANGED");
35127
+ offset += read2.bytesRead;
35128
+ }
35129
+ const after = await handle.stat();
35130
+ if (info.size !== after.size || info.mtimeMs !== after.mtimeMs) throw new Error("TRAVEL_GATEWAY_MEDIA_CHANGED");
35131
+ } finally {
35132
+ await handle.close();
34740
35133
  }
34741
- } catch (error) {
34742
- context.failed = true;
34743
- throw error;
34744
- }
35134
+ assertExternalEffectCurrent();
35135
+ travelEventPermit(context);
35136
+ const mimeType = attachment.mimeType ?? "application/octet-stream", filename = attachment.filename ?? basename7(attachment.path);
35137
+ const captions = message && !mimeType.startsWith("image/") ? this.name === "feishu" ? splitFeishuGatewayText(message) : splitChannelGatewayText(message, this.name) : [];
35138
+ const ordinal = (context.ordinals.MEDIA ?? 0) + 1;
35139
+ context.ordinals.MEDIA = ordinal;
35140
+ const kind = travelOutputKind(), replyOrdinal = (context.ordinals[kind] ?? 0) + 1;
35141
+ context.ordinals[kind] = replyOrdinal + captions.length - 1;
35142
+ try {
35143
+ const effects2 = await context.client.produceBatch(travelEventPermit(context), [
35144
+ { 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) },
35145
+ ...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" })) }))
35146
+ ]);
35147
+ for (const effect of effects2) {
35148
+ assertExternalEffectCurrent();
35149
+ await context.client.dispatch(travelEventPermit(context), effect.id);
35150
+ }
35151
+ } catch (error) {
35152
+ context.failed = true;
35153
+ throw error;
35154
+ }
35155
+ });
34745
35156
  }
34746
35157
  };
34747
35158
 
@@ -35363,6 +35774,7 @@ async function startTravelGateway(config) {
35363
35774
  encryptKey: config.feishu.encryptKey,
35364
35775
  assertIngress: assertKey,
35365
35776
  authorizeStop: (sender) => Array.isArray(config.feishu.stopAllowedUserIds) && config.feishu.stopAllowedUserIds.includes(sender.sender_id?.open_id),
35777
+ onReceivedTyping: (chatId, openId, messageId) => platform.startChatTyping(chatId, openId, messageId),
35366
35778
  downloadResource: async (messageId, key2, type) => {
35367
35779
  assertKey();
35368
35780
  return platform.downloadResource(messageId, key2, type);