engine7 7.1.141 → 7.1.142

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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);
@@ -12139,6 +12140,10 @@ function rowElements(state, rowCap) {
12139
12140
  }
12140
12141
  }
12141
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
+ }
12142
12147
  const lt = state.liveThink;
12143
12148
  if (lt) {
12144
12149
  const sec = Math.max(1, Math.round((Date.now() - lt.start) / 1e3));
@@ -12149,6 +12154,9 @@ function rowElements(state, rowCap) {
12149
12154
  } else if (state.status === "run") {
12150
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*` } });
12151
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
+ }
12152
12160
  return { els, dropped };
12153
12161
  }
12154
12162
  function buildProcessCard(state, level = 2) {
@@ -12341,6 +12349,10 @@ function buildProcessCardV2At(state, level, panelCap) {
12341
12349
  }
12342
12350
  }
12343
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
+ }
12344
12356
  const lt = state.liveThink;
12345
12357
  if (lt) {
12346
12358
  const sec = Math.max(1, Math.round((Date.now() - lt.start) / 1e3));
@@ -12351,6 +12363,9 @@ function buildProcessCardV2At(state, level, panelCap) {
12351
12363
  } else if (state.status === "run") {
12352
12364
  els.push({ tag: "markdown", content: `*${spinnerFrame()} ${state.verb}\u2026\uFF08${fmtDur(Math.max(1, Math.round((Date.now() - state.startedAt) / 1e3)))}\uFF09*` });
12353
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
+ }
12354
12369
  const notes = [];
12355
12370
  if (state.usage) notes.push(state.usage);
12356
12371
  if (state.status === "wait") notes.push("\u70B9\u6309\u94AE\u5BA1\u6279\uFF0C\u4E5F\u53EF\u76F4\u63A5\u6253\u5B57");
@@ -12462,7 +12477,7 @@ var init_process_card = __esm({
12462
12477
  this.summarySent = false;
12463
12478
  this.terminal = null;
12464
12479
  this.patchFailures = 0;
12465
- 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 };
12466
12481
  this.lastPushKey = this.pushKey();
12467
12482
  this.messageId = null;
12468
12483
  this.channelV = null;
@@ -12483,7 +12498,10 @@ var init_process_card = __esm({
12483
12498
  }
12484
12499
  /** Mode decisions can start native progress without awaiting any channel I/O. */
12485
12500
  start() {
12486
- 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;
12487
12505
  }
12488
12506
  nativeCapable() {
12489
12507
  const ad = this.adapter;
@@ -12497,10 +12515,16 @@ var init_process_card = __esm({
12497
12515
  }
12498
12516
  ensureStarted() {
12499
12517
  const ad = this.adapter;
12500
- 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();
12501
12519
  }
12502
12520
  async createCard() {
12503
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
+ }
12504
12528
  if (!this.nativeCapable() && this.legacyCapable()) return this.createLegacyCard();
12505
12529
  if (!this.nativeCapable() && this.options.allowLegacyCard === false) {
12506
12530
  if (!ad.sendPreview || !ad.editPreview) throw new Error("\u65E0\u8FC7\u7A0B\u5361\u6216\u53EF\u7F16\u8F91\u6D88\u606F\u80FD\u529B");
@@ -12547,8 +12571,10 @@ var init_process_card = __esm({
12547
12571
  }
12548
12572
  async removeCard() {
12549
12573
  if (this.messageId) {
12550
- if (!this.adapter.deletePreview) throw new Error("\u65E0\u8FC7\u7A0B\u5361\u6E05\u7406\u80FD\u529B");
12551
- 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 });
12552
12578
  }
12553
12579
  this.messageId = null;
12554
12580
  this.cardKitId = null;
@@ -12559,7 +12585,7 @@ var init_process_card = __esm({
12559
12585
  /** Shared heartbeat samples state; the push key suppresses unchanged cards. */
12560
12586
  startHeartbeat() {
12561
12587
  this.stopHeartbeat();
12562
- const interval = this.channelV === "cardkit" ? 800 : 2500;
12588
+ const interval = this.channelV === "cardkit" || this.channelV === "progress" ? 800 : 2500;
12563
12589
  this.heartbeat = setInterval(() => {
12564
12590
  if (this.state.status !== "run" && this.state.status !== "wait") {
12565
12591
  this.stopHeartbeat();
@@ -12573,10 +12599,10 @@ var init_process_card = __esm({
12573
12599
  if (this.heartbeat) clearInterval(this.heartbeat);
12574
12600
  this.heartbeat = null;
12575
12601
  }
12576
- onToolUse(name, input, id3) {
12602
+ onToolUse(name, input, id3, inputFull) {
12577
12603
  if (this.ended || this.disposed) return;
12578
12604
  this.ensureStarted();
12579
- 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)) } : {} });
12580
12606
  if (this.state.status === "wait") this.state.status = "run";
12581
12607
  this.schedulePatch();
12582
12608
  }
@@ -12589,7 +12615,7 @@ var init_process_card = __esm({
12589
12615
  row = this.state.rows.at(-1);
12590
12616
  }
12591
12617
  if (!row) return;
12592
- const retain = match?.visible !== false || this.nativeCapable();
12618
+ const retain = match?.visible !== false || this.nativeCapable() || this.progressCapable();
12593
12619
  const lines = (out || "").split("\n").filter((line) => line.trim());
12594
12620
  row.state = retain && isError ? "err" : "ok";
12595
12621
  row.resultVisible = match?.visible;
@@ -12723,6 +12749,19 @@ var init_process_card = __esm({
12723
12749
  }
12724
12750
  return false;
12725
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
+ }
12726
12765
  turnEnd(finalText, usage, outcome) {
12727
12766
  return this.finish(outcome, finalText, usage);
12728
12767
  }
@@ -12758,7 +12797,7 @@ var init_process_card = __esm({
12758
12797
  return;
12759
12798
  }
12760
12799
  if (this.patchTimer) return;
12761
- 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;
12762
12801
  const wait2 = Math.max(0, min - (Date.now() - this.lastPatchAt));
12763
12802
  this.patchTimer = setTimeout(() => {
12764
12803
  this.patchTimer = null;
@@ -12773,7 +12812,7 @@ var init_process_card = __esm({
12773
12812
  await this.creation?.catch(() => {
12774
12813
  });
12775
12814
  if (this.disposed || this.ended && !final) return;
12776
- 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)) {
12777
12816
  await this.removeCard().catch((error) => console.warn("[process-card] \u7A7A\u56DE\u5408\u6E05\u7406\u5931\u8D25:", error instanceof Error ? error.message : String(error)));
12778
12817
  return;
12779
12818
  }
@@ -12796,17 +12835,19 @@ var init_process_card = __esm({
12796
12835
  return `q${r.rid}:${r.settled}:${JSON.stringify(r.answers)}`;
12797
12836
  }).join("|");
12798
12837
  const bucket = Math.floor((Date.now() - s.startedAt) / LIVE_BUCKET_MS);
12799
- 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]);
12800
12839
  }
12801
12840
  async doPatch(final = false) {
12802
12841
  if (this.degraded || !this.messageId && this.channelV !== "cardkit") return false;
12803
12842
  const key2 = this.pushKey();
12804
12843
  if (key2 === this.lastPushKey) return true;
12805
12844
  this.lastPatchAt = Date.now();
12806
- const card = this.channelV === "patch-v1" ? buildProcessCard(this.state) : buildProcessCardV2(this.state) ?? (this.options.allowLegacyCard !== false ? buildProcessCard(this.state) : null);
12807
- 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;
12808
12847
  try {
12809
- 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) {
12810
12851
  await this.adapter.editPreview(this.previewHandle, buildProcessText(this.state), this.repoName, final);
12811
12852
  } else if (this.channelV === "cardkit" && this.cardKitId && card) {
12812
12853
  this.seq++;
@@ -12865,6 +12906,12 @@ async function handleCcCardAction(data) {
12865
12906
  const fv = action?.form_value ?? {};
12866
12907
  const v = action?.value;
12867
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
+ }
12868
12915
  if (v.kind === "perm" && v.rid) {
12869
12916
  const p = pendingPerms.get(v.rid);
12870
12917
  if (!p) return { toast: { type: "info", content: "\u8BE5\u5BA1\u6279\u5DF2\u5904\u7406\u6216\u5DF2\u5931\u6548" } };
@@ -13384,6 +13431,9 @@ var init_dep_downloader = __esm({
13384
13431
  function requestError(message, status = 409) {
13385
13432
  return Object.assign(new Error(message), { status });
13386
13433
  }
13434
+ function ccUserMsg(text2) {
13435
+ return { type: "user", message: { role: "user", content: text2 }, parent_tool_use_id: null };
13436
+ }
13387
13437
  function resultToText(content) {
13388
13438
  if (typeof content === "string") return content;
13389
13439
  if (Array.isArray(content)) {
@@ -13408,7 +13458,7 @@ function chunkText(text2, maxChars) {
13408
13458
  if (rest.trim()) chunks.push(rest);
13409
13459
  return chunks;
13410
13460
  }
13411
- 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;
13412
13462
  var init_driver = __esm({
13413
13463
  "src/cc-driver/driver.ts"() {
13414
13464
  "use strict";
@@ -13423,6 +13473,53 @@ var init_driver = __esm({
13423
13473
  MAX_INTERIM_PER_TURN = 4;
13424
13474
  INTERIM_SNIPPET_CHARS = 600;
13425
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;
13426
13523
  CcDriverSession = class {
13427
13524
  constructor(binding, cm, map, predecessor) {
13428
13525
  this.predecessor = predecessor;
@@ -13444,6 +13541,8 @@ var init_driver = __esm({
13444
13541
  revision = 0;
13445
13542
  idleWaiters = [];
13446
13543
  abort = null;
13544
+ /** 当前流式 chunk 的 steer 口(仅用户消息路径开;外部 ask/桌面路径为 null) */
13545
+ feeder = null;
13447
13546
  sessionId = null;
13448
13547
  sendChain = Promise.resolve();
13449
13548
  ui = null;
@@ -13468,11 +13567,16 @@ var init_driver = __esm({
13468
13567
  this.sessionId = null;
13469
13568
  return this.map.clear(this.key) || had;
13470
13569
  }
13471
- /** 入站一条消息:排队(busy 时 FIFO),队列满则提示。 */
13570
+ /** 入站一条消息:流式 chunk 开着 → steer 注入(1119);否则排队(busy 时 FIFO),队列满则提示。 */
13472
13571
  enqueue(text2) {
13473
13572
  const trimmed = text2.trim();
13474
13573
  if (!trimmed || this.closed) return;
13475
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
+ }
13476
13580
  if (this.queue.length >= MAX_QUEUE) {
13477
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`);
13478
13582
  return;
@@ -13509,9 +13613,22 @@ var init_driver = __esm({
13509
13613
  this.closed = true;
13510
13614
  this.revision++;
13511
13615
  for (const job of this.queue.splice(0)) job.reject?.(requestError("CC binding stopped before execution", 503));
13616
+ this.feeder?.close();
13512
13617
  this.stop();
13513
13618
  }
13514
- /** 中断当前 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() */
13515
13632
  stop() {
13516
13633
  this.abort?.abort();
13517
13634
  }
@@ -13533,10 +13650,14 @@ var init_driver = __esm({
13533
13650
  if (job.expectedSessionId !== void 0 && job.expectedSessionId !== this.sessionId) {
13534
13651
  throw requestError("CC session changed while this request was queued");
13535
13652
  }
13536
- const prompt = job.source ? `[cc_ask from ${job.source.replace(/[\r\n]/g, " ").slice(0, 160)}]
13537
- ${job.prompt}` : job.prompt;
13538
- const result = await this.runTurn(prompt, job.signal, !!job.source);
13539
- 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
+ }
13540
13661
  } catch (err) {
13541
13662
  job.reject?.(err);
13542
13663
  console.error(`[cc-driver] turn \u5931\u8D25 key=${this.key}: ${err?.stack || err}`);
@@ -13570,15 +13691,11 @@ ${job.prompt}` : job.prompt;
13570
13691
  this.ui = null;
13571
13692
  }
13572
13693
  }
13573
- let textSoFar = "";
13574
- let gotPartial = false;
13575
- let lastInterimAt = Date.now();
13576
- let interimCount = 0;
13577
- let lastSentLen = 0;
13578
13694
  let finalText = "";
13579
13695
  let isError = false;
13580
13696
  let gotResult = false;
13581
13697
  let usage = "";
13698
+ const acc = this.makeStreamAccumulator();
13582
13699
  try {
13583
13700
  const desktops = resumedFrom ? await findDesktopTargets(this.workDir, resumedFrom) : [];
13584
13701
  if (desktops.length > 1) throw new Error("Multiple desktop writers claim this CC session; close the duplicate");
@@ -13594,7 +13711,7 @@ ${job.prompt}` : job.prompt;
13594
13711
  throw new Error("This CC session is open in another process; use cc-desktop to receive messages there");
13595
13712
  }
13596
13713
  let ccRuntimeNoticeSent = false;
13597
- const { query } = await loadOptionalModule("cc-runtime", (label, got, total) => {
13714
+ const { query } = await ccRuntimeLoader((label, got, total) => {
13598
13715
  if (ccRuntimeNoticeSent) return;
13599
13716
  ccRuntimeNoticeSent = true;
13600
13717
  const mb = total ? `\u7EA6 ${Math.round(total / 1024 / 1024)}M` : "\u7EA6 350M";
@@ -13638,43 +13755,7 @@ ${job.prompt}` : job.prompt;
13638
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) ?? "-"}`);
13639
13756
  const parentToolUseId = msg2.parent_tool_use_id;
13640
13757
  if (parentToolUseId) continue;
13641
- if (msg2.type === "stream_event") {
13642
- const ev = msg2.event;
13643
- if (ev.type === "content_block_start" && ev.content_block?.type === "thinking") this.ui?.onThinkingDelta("");
13644
- else if (ev.type === "content_block_delta" && ev.delta?.type === "thinking_delta" && typeof ev.delta.thinking === "string") this.ui?.onThinkingDelta(ev.delta.thinking);
13645
- else if (ev.type === "content_block_stop" && this.ui) this.ui.onThinkingEnd();
13646
- if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && typeof ev.delta.text === "string") {
13647
- gotPartial = true;
13648
- textSoFar += ev.delta.text;
13649
- const now2 = Date.now();
13650
- const newChars = textSoFar.length - lastSentLen;
13651
- if (!this.ui && now2 - lastInterimAt >= INTERIM_MIN_INTERVAL_MS && newChars >= INTERIM_MIN_CHARS && interimCount < MAX_INTERIM_PER_TURN) {
13652
- lastInterimAt = now2;
13653
- lastSentLen = textSoFar.length;
13654
- interimCount++;
13655
- const snippet = textSoFar.slice(-INTERIM_SNIPPET_CHARS);
13656
- void this.sendText(`\u2026${snippet}`);
13657
- }
13658
- }
13659
- } else if (msg2.type === "assistant") {
13660
- const content = msg2.message.content ?? [];
13661
- for (const block of content) {
13662
- if (block.type === "thinking" && block.thinking) this.ui?.onThinking(String(block.thinking));
13663
- else if (block.type === "tool_use" && block.id) this.ui?.onToolUse(String(block.name), block.input ?? {});
13664
- }
13665
- if (!gotPartial) {
13666
- for (const block of content) {
13667
- if (block.type === "text" && typeof block.text === "string") textSoFar += block.text;
13668
- }
13669
- }
13670
- } else if (msg2.type === "user") {
13671
- const content = msg2.message.content;
13672
- if (Array.isArray(content) && this.ui) {
13673
- for (const block of content) {
13674
- if (block.type === "tool_result") this.ui.onToolResult(resultToText(block.content), block.is_error === true);
13675
- }
13676
- }
13677
- } else if (msg2.type === "result") {
13758
+ if (msg2.type === "result") {
13678
13759
  const r = msg2;
13679
13760
  if (r.session_id) {
13680
13761
  turnSessionId = r.session_id;
@@ -13690,6 +13771,8 @@ ${job.prompt}` : job.prompt;
13690
13771
  turnSessionId = sid;
13691
13772
  if (this.revision === revision) this.sessionId = sid;
13692
13773
  }
13774
+ } else {
13775
+ await acc.handle(msg2);
13693
13776
  }
13694
13777
  }
13695
13778
  }
@@ -13698,22 +13781,22 @@ ${job.prompt}` : job.prompt;
13698
13781
  this.abort = null;
13699
13782
  signal?.removeEventListener("abort", cancel);
13700
13783
  }
13701
- 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 };
13702
13785
  if (ac.signal.aborted) {
13703
13786
  if (this.ui && this.ui.alive) {
13704
13787
  await this.ui.turnEnd("", "", "aborted");
13705
- await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (textSoFar ? `
13788
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
13706
13789
  \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
13707
- ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13790
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13708
13791
  return { ...result, text: "[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" };
13709
13792
  }
13710
- await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (textSoFar ? `
13793
+ await this.sendText("[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" + (acc.textSoFar ? `
13711
13794
 
13712
13795
  \u5DF2\u4EA7\u51FA\u7684\u90E8\u5206\uFF1A
13713
- ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13796
+ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13714
13797
  return { ...result, text: "[\u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1]" };
13715
13798
  }
13716
- const answer = finalText || textSoFar;
13799
+ const answer = finalText || acc.textSoFar;
13717
13800
  if (this.ui && this.ui.alive) {
13718
13801
  await this.ui.turnEnd("", usage, isError ? "err" : "done");
13719
13802
  if (!answer.trim()) {
@@ -13732,6 +13815,215 @@ ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13732
13815
  }
13733
13816
  return result;
13734
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
+ }
13735
14027
  /** 串行发送器:wechat 3s 节流在适配器层,这里保证不并发、失败不炸链 */
13736
14028
  sendText(text2) {
13737
14029
  const task = this.sendChain.then(async () => {
@@ -13779,6 +14071,12 @@ ${textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
13779
14071
  forChat(channel, chatId) {
13780
14072
  return this.sessions.get(`${channel}:${chatId}`);
13781
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
+ }
13782
14080
  /** 全部绑定的工作目录(去重;cc-progress 工具省参推断用) */
13783
14081
  get bindingWorkDirs() {
13784
14082
  return [...new Set([...this.sessions.values()].map((s) => s.workDir))];
@@ -13916,6 +14214,12 @@ var init_cc_driver = __esm({
13916
14214
  });
13917
14215
 
13918
14216
  // src/cc-driver/router.ts
14217
+ var router_exports = {};
14218
+ __export(router_exports, {
14219
+ autoBindHit: () => autoBindHit,
14220
+ ccDriverRouter: () => ccDriverRouter,
14221
+ markBindSelect: () => markBindSelect
14222
+ });
13919
14223
  import { existsSync as existsSync8 } from "node:fs";
13920
14224
  function autoBindHit(inbound) {
13921
14225
  if (inbound.channel !== "feishu" || inbound.channelType !== "dm") return null;
@@ -13945,6 +14249,14 @@ async function doAutoBind(inbound, workDir) {
13945
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
13946
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`);
13947
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
+ }
13948
14260
  function peekBindNumber(inbound) {
13949
14261
  if (inbound.channelType !== "dm") return null;
13950
14262
  const ts = pendingBind.get(`${inbound.channel}:${inbound.channel_id}`);
@@ -18218,7 +18530,7 @@ import { createHash as createHash3 } from "node:crypto";
18218
18530
  // src/continuity/inventory.ts
18219
18531
  import { isAbsolute, join as join3, relative, resolve as resolve2, sep } from "node:path";
18220
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(" "));
18221
- 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(" "));
18222
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(" "));
18223
18535
  function validateRelativePath(path35) {
18224
18536
  if (typeof path35 !== "string" || !path35 || path35.length > 2048 || isAbsolute(path35)) throw new Error("INVALID_ARTIFACT_PATH");
@@ -18885,6 +19197,18 @@ var TravelGatewayStore = class {
18885
19197
  }
18886
19198
  /** Host-owned import of actual previously processed platform IDs. A receipt
18887
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
+ }
18888
19212
  importProcessedInputs(platformIds) {
18889
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");
18890
19214
  this.transaction(() => {
@@ -19310,7 +19634,7 @@ function createTravelGatewayServer(options) {
19310
19634
  return;
19311
19635
  }
19312
19636
  const action = req.url?.startsWith(prefix) ? req.url.slice(prefix.length) : "";
19313
- 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)) {
19314
19638
  reply(404, { error: "TRAVEL_GATEWAY_NOT_FOUND" });
19315
19639
  req.resume();
19316
19640
  return;
@@ -19347,7 +19671,7 @@ function createTravelGatewayServer(options) {
19347
19671
  reply(200, store.applyRecoveryDeletedInputs(principal, input.bindings, input.floor));
19348
19672
  return;
19349
19673
  }
19350
- 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");
19351
19675
  if (action === "preparation") {
19352
19676
  if (Object.keys(input).length) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19353
19677
  reply(200, store.preparationEvidence(principal));
@@ -19363,6 +19687,11 @@ function createTravelGatewayServer(options) {
19363
19687
  reply(200, store.exitDedupeReceipt(principal, permit));
19364
19688
  return;
19365
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
+ }
19366
19695
  if (action === "claim") {
19367
19696
  const claims = await store.claim(principal, permit, input.options);
19368
19697
  reply(200, claims.map(({ body: body2, ...claim }) => ({ ...claim, bodyBase64: body2.toString("base64") })));
@@ -19530,6 +19859,12 @@ var TravelGatewayClient = class {
19530
19859
  async ack(permit, eventId) {
19531
19860
  await this.call("ack", { permit, eventId });
19532
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
+ }
19533
19868
  async finish(permit, eventId) {
19534
19869
  await this.call("finish", { permit, eventId });
19535
19870
  }
@@ -27019,7 +27354,7 @@ function assertImageAssetRef(ref) {
27019
27354
  throw new Error("Invalid or oversized image asset reference");
27020
27355
  }
27021
27356
  }
27022
- 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 = {}) {
27023
27358
  signal?.throwIfAborted();
27024
27359
  let total = 0;
27025
27360
  for (const message of messages) if (Array.isArray(message.content)) for (const block of message.content) {
@@ -27044,6 +27379,7 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
27044
27379
  return { ...message, content: content.length ? content : "[previous image omitted]" };
27045
27380
  });
27046
27381
  if (total > maxBase64Bytes) throw new Error(`Request image base64 exceeds ${maxBase64Bytes} byte limit`);
27382
+ const { strict = false } = opts;
27047
27383
  const cache = /* @__PURE__ */ new Map();
27048
27384
  const output = [];
27049
27385
  for (const message of requestView) {
@@ -27060,8 +27396,12 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
27060
27396
  }
27061
27397
  if (!store) throw new Error("Image asset store is required to materialize image refs");
27062
27398
  const key2 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
27063
- if (!cache.has(key2)) cache.set(key2, store.materialize(block.image));
27064
- 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]" });
27065
27405
  signal?.throwIfAborted();
27066
27406
  }
27067
27407
  output.push({ ...message, content });
@@ -34478,6 +34818,7 @@ function createFeishuGatewayDispatcher(options) {
34478
34818
  body: Buffer.from(JSON.stringify({ format, event: { sender, message }, ...resources.length ? { resources } : {} }))
34479
34819
  });
34480
34820
  options.assertIngress?.();
34821
+ if (sender.sender_type !== "bot") options.onReceivedTyping?.(message.chat_id, sender.sender_id?.open_id, message.message_id);
34481
34822
  },
34482
34823
  "im.message.reaction.created_v1": async () => {
34483
34824
  },
@@ -34529,7 +34870,34 @@ function createFeishuGatewayPlatform(options) {
34529
34870
  return config;
34530
34871
  });
34531
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
+ };
34532
34898
  return {
34899
+ startChatTyping,
34900
+ stopChatTyping,
34533
34901
  deliver: async (effect, body, assertCurrent) => {
34534
34902
  if (closed) throw new Error("TRAVEL_FEISHU_CLOSED");
34535
34903
  const media = effect.kind === "MEDIA" ? decodeGatewayMedia(body) : void 0;
@@ -34557,6 +34925,7 @@ function createFeishuGatewayPlatform(options) {
34557
34925
  assertCurrent();
34558
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 } });
34559
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);
34560
34929
  return { messageId: result.data.message_id };
34561
34930
  });
34562
34931
  },
@@ -34689,78 +35058,101 @@ var RemoteTravelChannel = class {
34689
35058
  });
34690
35059
  }));
34691
35060
  }
34692
- async send(target, message, options) {
34693
- const context = travelEventContext();
34694
- if (!context || context.client !== this.options.client) throw new Error("TRAVEL_GATEWAY_CONTEXT_REQUIRED");
34695
- if (context.failed) throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
34696
- assertExternalEffectCurrent();
34697
- travelEventPermit(context);
34698
- const config = resolveBubbleSplit(this.name), bubbles = config.on && options?.bubbleSplit === true ? splitBubbles(message) : null;
34699
- const chunks = bubbles ?? (this.name === "feishu" ? splitFeishuGatewayText(message) : splitChannelGatewayText(message, this.name));
34700
- const kind = travelOutputKind(), ordinal = (context.ordinals[kind] ?? 0) + 1;
34701
- 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 };
34702
35073
  try {
34703
- const effects2 = await context.client.produceBatch(travelEventPermit(context), chunks.map((text2, index) => ({
34704
- eventId: context.eventId,
34705
- kind,
34706
- ordinal: ordinal + index,
34707
- version: 1,
34708
- body: Buffer.from(JSON.stringify({ channel: this.name, target, text: text2, format: this.name === "feishu" ? "post" : "text", ...index === 0 && options?.replyTo ? { replyTo: options.replyTo } : {} }))
34709
- })), { finalOutput: options?.extra?.travelFinalReply === true });
34710
- for (let index = 0; index < effects2.length; index++) {
34711
- assertExternalEffectCurrent();
34712
- await context.client.dispatch(travelEventPermit(context), effects2[index].id);
34713
- if (bubbles && index < effects2.length - 1 && config.gapMs > 0) await new Promise((resolve12) => setTimeout(resolve12, Math.min(config.gapMs, 6e4)));
34714
- }
35074
+ const value = await withTravelEventContext(context, () => run(context));
35075
+ await completeTravelEvent(context);
35076
+ return value;
34715
35077
  } catch (error) {
34716
35078
  context.failed = true;
35079
+ await this.options.client.finish(this.options.permit(), id3).catch(() => {
35080
+ });
34717
35081
  throw error;
34718
35082
  }
34719
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
+ }
34720
35112
  async sendFile(target, message, attachment) {
34721
- const context = travelEventContext();
34722
- if (!context || context.client !== this.options.client) throw new Error("TRAVEL_GATEWAY_CONTEXT_REQUIRED");
34723
- if (context.failed) throw new Error("TRAVEL_GATEWAY_UNKNOWN_EFFECT");
34724
- assertExternalEffectCurrent();
34725
- travelEventPermit(context);
34726
- const handle = await open2(attachment.path, "r");
34727
- let bytes2;
34728
- try {
34729
- const info = await handle.stat();
34730
- if (!info.isFile() || !info.size || info.size > gatewayMediaLimit) throw new Error("TRAVEL_GATEWAY_MEDIA_LIMIT");
34731
- bytes2 = Buffer.alloc(info.size);
34732
- let offset = 0;
34733
- while (offset < bytes2.length) {
34734
- const read2 = await handle.read(bytes2, offset, bytes2.length - offset, offset);
34735
- if (!read2.bytesRead) throw new Error("TRAVEL_GATEWAY_MEDIA_CHANGED");
34736
- offset += read2.bytesRead;
34737
- }
34738
- const after = await handle.stat();
34739
- if (info.size !== after.size || info.mtimeMs !== after.mtimeMs) throw new Error("TRAVEL_GATEWAY_MEDIA_CHANGED");
34740
- } finally {
34741
- await handle.close();
34742
- }
34743
- assertExternalEffectCurrent();
34744
- travelEventPermit(context);
34745
- const mimeType = attachment.mimeType ?? "application/octet-stream", filename = attachment.filename ?? basename7(attachment.path);
34746
- const captions = message && !mimeType.startsWith("image/") ? this.name === "feishu" ? splitFeishuGatewayText(message) : splitChannelGatewayText(message, this.name) : [];
34747
- const ordinal = (context.ordinals.MEDIA ?? 0) + 1;
34748
- context.ordinals.MEDIA = ordinal;
34749
- const kind = travelOutputKind(), replyOrdinal = (context.ordinals[kind] ?? 0) + 1;
34750
- context.ordinals[kind] = replyOrdinal + captions.length - 1;
34751
- try {
34752
- const effects2 = await context.client.produceBatch(travelEventPermit(context), [
34753
- { 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) },
34754
- ...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" })) }))
34755
- ]);
34756
- for (const effect of effects2) {
34757
- assertExternalEffectCurrent();
34758
- 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();
34759
35133
  }
34760
- } catch (error) {
34761
- context.failed = true;
34762
- throw error;
34763
- }
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
+ });
34764
35156
  }
34765
35157
  };
34766
35158
 
@@ -35382,6 +35774,7 @@ async function startTravelGateway(config) {
35382
35774
  encryptKey: config.feishu.encryptKey,
35383
35775
  assertIngress: assertKey,
35384
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),
35385
35778
  downloadResource: async (messageId, key2, type) => {
35386
35779
  assertKey();
35387
35780
  return platform.downloadResource(messageId, key2, type);