@cydm/pie 4.4.2 → 4.5.0

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.
Files changed (48) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +6 -6
  2. package/dist/builtin/extensions/changelog/index.js +1 -1
  3. package/dist/builtin/extensions/cron/index.js +55 -7
  4. package/dist/builtin/extensions/document-attachments/index.js +1 -1
  5. package/dist/builtin/extensions/herdr-agent-state/index.js +1 -1
  6. package/dist/builtin/extensions/im-forward/README.md +3 -1
  7. package/dist/builtin/extensions/im-forward/index.js +364 -118
  8. package/dist/builtin/extensions/init/index.js +1 -1
  9. package/dist/builtin/extensions/mcp-adapter/index.js +2 -2
  10. package/dist/builtin/extensions/memory/index.js +9 -11
  11. package/dist/builtin/extensions/pie-ipc/index.js +70 -19
  12. package/dist/builtin/extensions/pie-proc/index.js +27 -13
  13. package/dist/builtin/extensions/plan-mode/index.js +6 -6
  14. package/dist/builtin/extensions/subagent/index.js +9 -11
  15. package/dist/builtin/extensions/todo/index.js +6 -6
  16. package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +24 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +86 -21
  18. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-cli.js +6 -1
  19. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  20. package/dist/builtin/skills/chrome-devtools-axi/{cli-CHC7XYFU.js → cli-NLPMVDGG.js} +32 -4
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +220 -22
  22. package/dist/chunks/{auth-storage-RABPRJ6T.js → auth-storage-C3FZMT7J.js} +3 -3
  23. package/dist/chunks/{chunk-OFLKAWI4.js → chunk-2CJIENLY.js} +90 -100
  24. package/dist/chunks/{chunk-R7VO46EK.js → chunk-3W3SXVPB.js} +5 -4
  25. package/dist/chunks/{chunk-IPLMGAML.js → chunk-5KI4Y4LA.js} +1 -1
  26. package/dist/chunks/{chunk-YNTIOWCD.js → chunk-BLDI2GRF.js} +5 -5
  27. package/dist/chunks/{chunk-UCKOXAME.js → chunk-CBDQJMUI.js} +9 -44
  28. package/dist/chunks/chunk-CGSFBWOM.js +100 -0
  29. package/dist/chunks/{chunk-7LTQLJJF.js → chunk-LAJXWOKS.js} +15 -10
  30. package/dist/chunks/{chunk-RZGYXAJU.js → chunk-LZQXQOPJ.js} +1 -12
  31. package/dist/chunks/{chunk-EQOI6RZV.js → chunk-NHV2CALB.js} +3 -5
  32. package/dist/chunks/{chunk-OV7SLSHR.js → chunk-SW2E33UL.js} +2 -4
  33. package/dist/chunks/{chunk-BPSCGGVF.js → chunk-XXGYUYXI.js} +1 -1
  34. package/dist/chunks/{chunk-XO3NM7BB.js → chunk-Y3I2UV5Y.js} +3 -3
  35. package/dist/chunks/{chunk-IZDNZW3S.js → chunk-Z2FKA2ZH.js} +8 -8
  36. package/dist/chunks/chunk-ZPJ3BNQB.js +126 -0
  37. package/dist/chunks/{config-HF2PDLN5.js → config-4EOI5NOU.js} +2 -4
  38. package/dist/chunks/{manager-cli-BYCF4RKN.js → manager-cli-2ATPC47M.js} +35 -5
  39. package/dist/chunks/manager-upgrade-5CPKTRJ7.js +562 -0
  40. package/dist/chunks/{model-registry-7FNIUYPF.js → model-registry-3XAHXXTA.js} +5 -5
  41. package/dist/chunks/{src-OVWRBWKU.js → src-B44QWSGM.js} +4 -4
  42. package/dist/chunks/{src-A5YI46OD.js → src-CLE5ILN4.js} +6 -6
  43. package/dist/chunks/{src-OA3TP6DS.js → src-EGXFJ3WA.js} +5 -5
  44. package/dist/chunks/{src-TF2RAGRU.js → src-Q7LU27C2.js} +3 -3
  45. package/dist/chunks/{test-stream-7YZDGBPO.js → test-stream-OR3EJBNF.js} +3 -3
  46. package/dist/cli.js +173 -136
  47. package/package.json +3 -3
  48. package/dist/chunks/chunk-7KLWHWZD.js +0 -164
@@ -20,6 +20,7 @@ import {
20
20
  readLiveConfig,
21
21
  readLiveEnabled,
22
22
  registerDispatchReceiver,
23
+ registerImBinding,
23
24
  registerTurnImDriver,
24
25
  resolveAddress,
25
26
  resolveConfig,
@@ -31,17 +32,18 @@ import {
31
32
  truncateMarkdown,
32
33
  tryClaimConsumer,
33
34
  writeConfig
34
- } from "../../../chunks/chunk-OFLKAWI4.js";
35
+ } from "../../../chunks/chunk-2CJIENLY.js";
35
36
  import {
36
37
  detectImageMime,
37
38
  readImageFormat
38
39
  } from "../../../chunks/chunk-F7EBZTZO.js";
39
- import "../../../chunks/chunk-RZGYXAJU.js";
40
+ import "../../../chunks/chunk-ZPJ3BNQB.js";
41
+ import "../../../chunks/chunk-LZQXQOPJ.js";
40
42
 
41
43
  // builtin/extensions/im-forward/runtime.ts
42
44
  import * as crypto from "node:crypto";
43
45
  import * as fs6 from "node:fs";
44
- import { basename, join as pathJoin, resolve as pathResolve, join as join7 } from "node:path";
46
+ import { basename, join as pathJoin, resolve as pathResolve, join as join7, dirname as pathDirname } from "node:path";
45
47
  import * as os3 from "node:os";
46
48
 
47
49
  // builtin/extensions/im-forward/thread-registry.ts
@@ -331,6 +333,7 @@ function threadOwner(input) {
331
333
  import * as fs2 from "node:fs";
332
334
  import * as os2 from "node:os";
333
335
  import * as path3 from "node:path";
336
+ import { fileURLToPath } from "node:url";
334
337
 
335
338
  // builtin/extensions/im-forward/discovery.ts
336
339
  import * as os from "node:os";
@@ -359,7 +362,7 @@ function parsePanelCommand(text) {
359
362
  cmd = next?.[1] ?? "";
360
363
  rest = next?.[2] ?? "";
361
364
  }
362
- if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.models" && cmd !== "panel.help" && cmd !== "\u9762\u677F") {
365
+ if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.models" && cmd !== "panel.upgrade" && cmd !== "panel.upgrade.confirm" && cmd !== "panel.help" && cmd !== "\u9762\u677F") {
363
366
  if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd)) return void 0;
364
367
  }
365
368
  const leadingFlag = /^--restricted(?:\s+|$)/.exec(rest);
@@ -398,7 +401,8 @@ function scanPeers() {
398
401
  sessionTitle: typeof parsed.displaySessionName === "string" && parsed.displaySessionName.trim() ? parsed.displaySessionName.trim() : void 0,
399
402
  project: typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd.split("/").filter(Boolean).at(-1) : void 0,
400
403
  currentTool: typeof parsed.currentTool === "string" && parsed.currentTool ? parsed.currentTool : void 0,
401
- model: typeof parsed.model === "string" && parsed.model ? parsed.model : void 0
404
+ model: typeof parsed.model === "string" && parsed.model ? parsed.model : void 0,
405
+ version: typeof parsed.version === "string" && parsed.version ? parsed.version : void 0
402
406
  });
403
407
  } catch {
404
408
  }
@@ -412,32 +416,67 @@ function composePanel() {
412
416
  const rows = peers.map((p) => {
413
417
  const title = p.sessionTitle ?? p.name;
414
418
  const state = p.state === "working" && p.currentTool ? `working\xB7${p.currentTool}` : p.state;
415
- const project = p.project && p.project !== title ? `\uFF08${p.project}\uFF09` : "";
416
- return `| ${title}${project} | ${p.model ?? "\u2014"} | ${state} |
417
- | \u21B3 ${p.name} | | |`;
419
+ const project = p.project && p.project !== title ? ` (${p.project})` : "";
420
+ return `| ${title}${project} | ${p.model ?? "\u2014"} | ${state} | ${p.version ?? "\u2014"} |
421
+ | \u21B3 ${p.name} | | | |`;
418
422
  });
423
+ const upgradeLine = upgradeSummaryLine();
419
424
  const body = [
420
- peers.length > 0 ? `| \u4F1A\u8BDD | \u6A21\u578B | \u72B6\u6001 |
421
- |---|---|---|
422
- ${rows.join("\n")}` : "_\u6CA1\u6709\u5B58\u6D3B\u7684 pie \u4F1A\u8BDD_",
425
+ peers.length > 0 ? `| Session | Model | State | Ver |
426
+ |---|---|---|---|
427
+ ${rows.join("\n")}` : "_No live pie sessions_",
423
428
  ``,
424
- `\u5171 ${peers.length} \u4E2A\u4F1A\u8BDD \xB7 ${(/* @__PURE__ */ new Date()).toLocaleTimeString("zh-CN", { hour12: false })}`
425
- ].join("\n");
429
+ upgradeLine,
430
+ `${peers.length} session(s) \xB7 ${(/* @__PURE__ */ new Date()).toLocaleTimeString("en-GB", { hour12: false })}`
431
+ ].filter((line) => line !== void 0).join("\n");
426
432
  return {
427
- title: "Pie \u7BA1\u7406\u9762\u677F",
428
- subtitle: `${os2.hostname()} \xB7 ${peers.length} \u4F1A\u8BDD`,
433
+ title: "Pie Panel",
434
+ subtitle: `${os2.hostname()} \xB7 ${peers.length} session(s) \xB7 pie ${pieVersion()}`,
429
435
  color: "blue",
430
436
  body,
431
437
  // r1-P2: only REGISTERED commands get buttons — unmapped ids would fall
432
438
  // through to an LLM turn (a button press must never spend a model turn).
433
439
  actions: [
434
- { id: "panel.refresh", label: "\u{1F504} \u5237\u65B0" },
435
- { id: "panel.summon", label: "\u{1F4CB} \u91CD\u65B0\u53EC\u5524" },
436
- { id: "panel.models", label: "\u{1F39A} \u5207\u6A21\u578B" },
437
- { id: "panel.help", label: "\u2753 \u547D\u4EE4" }
440
+ { id: "panel.refresh", label: "\u{1F504} Refresh" },
441
+ { id: "panel.summon", label: "\u{1F4CB} Resummon" },
442
+ { id: "panel.models", label: "\u{1F39A} Model" },
443
+ { id: "panel.upgrade", label: "\u2B06\uFE0F Upgrade" },
444
+ { id: "panel.help", label: "\u2753 Help" }
438
445
  ]
439
446
  };
440
447
  }
448
+ function pieVersion() {
449
+ try {
450
+ const here = path3.dirname(fileURLToPath(import.meta.url));
451
+ for (const up of [3, 4, 5, 6]) {
452
+ const pkgPath = path3.resolve(here, ...Array(up).fill(".."), "package.json");
453
+ if (!fs2.existsSync(pkgPath)) continue;
454
+ const parsed = JSON.parse(fs2.readFileSync(pkgPath, "utf8"));
455
+ if (parsed.name === "@cydm/pie" && typeof parsed.version === "string") return parsed.version;
456
+ }
457
+ } catch {
458
+ }
459
+ return "unknown";
460
+ }
461
+ function readUpgradeSnapshot() {
462
+ try {
463
+ const configRoot = path3.dirname(path3.dirname(ipcDiscoveryRoot()));
464
+ return JSON.parse(fs2.readFileSync(path3.join(configRoot, "manager", "upgrade.json"), "utf8"));
465
+ } catch {
466
+ return void 0;
467
+ }
468
+ }
469
+ function upgradeSummaryLine() {
470
+ const snap = readUpgradeSnapshot();
471
+ if (!snap) return `pie ${pieVersion()} \xB7 no upgrade yet`;
472
+ const when = typeof snap.at === "number" ? new Date(snap.at).toLocaleString("en-GB", { hour12: false }) : "?";
473
+ if (snap.ok === true) {
474
+ const recycled = snap.workersRecycled?.length ?? 0;
475
+ const skipped = snap.workersSkipped?.length ?? 0;
476
+ return `pie ${pieVersion()} \xB7 upgraded ${snap.fromVersion ?? "?"} \u2192 ${snap.toVersion ?? "?"} at ${when} (workers: ${recycled} recycled, ${skipped} left busy)`;
477
+ }
478
+ return `pie ${pieVersion()} \xB7 last upgrade FAILED at ${snap.stage ?? "?"} (${when}): ${snap.detail ?? "unknown"}`;
479
+ }
441
480
  function candidateModels() {
442
481
  const out = /* @__PURE__ */ new Set();
443
482
  try {
@@ -461,26 +500,51 @@ function executePanelCommand(input) {
461
500
  (p) => models.map((m) => ({ id: `panel.model.${p.instanceId}.${m}`, label: `${p.name.slice(0, 10)}\u2192${m.split("/")[1]?.slice(0, 14) ?? m}` }))
462
501
  ).slice(0, 18);
463
502
  return { spec: {
464
- title: "\u5207\u6362\u6A21\u578B",
465
- subtitle: `${peers.length} \u4F1A\u8BDD \xD7 ${models.length} \u5019\u9009`,
503
+ title: "Switch Model",
504
+ subtitle: `${peers.length} session(s) \xD7 ${models.length} candidates`,
466
505
  color: "violet",
467
506
  body: [
468
- peers.length > 0 ? `| \u4F1A\u8BDD | \u5F53\u524D\u6A21\u578B |
507
+ peers.length > 0 ? `| Session | Model |
469
508
  |---|---|
470
- ${rows.join("\n")}` : "_\u6CA1\u6709\u5B58\u6D3B\u7684 pie \u4F1A\u8BDD_",
509
+ ${rows.join("\n")}` : "_No live pie sessions_",
510
+ ``,
511
+ `Candidates: ${models.join(" \xB7 ") || "(models.json unreadable)"}`,
512
+ ``,
513
+ "Each button maps a session to a model. Tapping sends a model.set control frame (zero LLM, nothing enters the peer history)."
514
+ ].join("\n"),
515
+ actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
516
+ }, patchOrigin: false };
517
+ }
518
+ if (input.cmd === "panel.upgrade") {
519
+ const snap = readUpgradeSnapshot();
520
+ const current = pieVersion();
521
+ const when = snap && typeof snap.at === "number" ? new Date(snap.at).toLocaleString("en-GB", { hour12: false }) : void 0;
522
+ const last = snap ? snap.ok === true ? `Last upgrade: ${snap.fromVersion ?? "?"} \u2192 ${snap.toVersion ?? "?"} at ${when} \u2713` : `Last upgrade FAILED at "${snap.stage ?? "?"}" (${when}): ${snap.detail ?? "unknown"}` : "No upgrade has run on this machine yet.";
523
+ return { spec: {
524
+ title: "Upgrade Pie",
525
+ subtitle: `current ${current} \xB7 target latest`,
526
+ color: "violet",
527
+ body: [
528
+ `Current: **${current}** \xB7 Target: **latest** (resolved by npm at run time)`,
471
529
  ``,
472
- `\u5019\u9009\uFF1A${models.join(" \xB7 ") || "\uFF08models.json \u4E0D\u53EF\u8BFB\uFF09"}`,
530
+ last,
473
531
  ``,
474
- "\u6309\u94AE\u683C\u5F0F\uFF1A\u4F1A\u8BDD\u2192\u6A21\u578B\u3002\u70B9\u6309\u5373\u53D1 model.set \u63A7\u5236\u5E27\uFF08\u96F6 LLM\u3001\u4E0D\u8FDB\u5BF9\u65B9\u5386\u53F2\uFF09\u3002"
532
+ "Upgrade = `npm install -g @cydm/pie@latest` + restart the manager resident (IM pauses ~15s). Idle workers are recycled; busy ones keep running. Desktop TUI sessions keep their code until you restart them.",
533
+ "The confirm button requires allowUsers membership."
475
534
  ].join("\n"),
476
- actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F \u8FD4\u56DE\u9762\u677F" }]
535
+ actions: [
536
+ // requireAllowUsers: the compiled callback carries --restricted; a
537
+ // non-allowlisted clicker is refused by runPanelCommand's gate.
538
+ { id: "panel.upgrade.confirm", label: "\u2B06\uFE0F Install latest + restart", style: "primary", requireAllowUsers: true },
539
+ { id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }
540
+ ]
477
541
  }, patchOrigin: false };
478
542
  }
479
543
  if (input.cmd === "panel.help") {
480
544
  return { spec: {
481
- title: "\u9762\u677F\u547D\u4EE4",
482
- body: "`/panel` \u6216 `/\u9762\u677F` \u53EC\u5524\u72B6\u6001\u9762\u677F\u3002\u5361\u7247\u6309\u94AE\uFF1A\u{1F504} \u5237\u65B0\uFF08\u539F\u5730\u66F4\u65B0\uFF09\u3001\u{1F4CB} \u91CD\u65B0\u53EC\u5524\u3001\u{1F39A} \u5207\u6A21\u578B\u3001\u2753 \u672C\u8BF4\u660E\u3002\u7FA4\u5185\u4EFB\u4F55\u6210\u5458\u53EF\u70B9\uFF0C`--restricted` \u52A8\u4F5C\u9700 allowUsers \u767D\u540D\u5355\u3002",
483
- actions: [{ id: "panel.summon", label: "\u56DE\u5230\u9762\u677F" }]
545
+ title: "Panel Commands",
546
+ body: "`/panel` summons the status panel. Card buttons: \u{1F504} Refresh (in-place update), \u{1F4CB} Resummon, \u{1F39A} Model, \u2B06\uFE0F Upgrade (npm install + manager restart), \u2753 Help. Any group member may tap; `--restricted` actions require the allowUsers whitelist.",
547
+ actions: [{ id: "panel.summon", label: "Back to panel" }]
484
548
  }, patchOrigin: false };
485
549
  }
486
550
  return { spec: composePanel(), patchOrigin: input.cmd === "panel.refresh" && input.originCardId !== void 0 };
@@ -525,12 +589,40 @@ function findOwnerInstance(sessionId) {
525
589
  candidates.sort((a, b) => b.startedAt - a.startedAt);
526
590
  return candidates[0].file;
527
591
  }
592
+ function findNamedOwnerInstance(name, binding) {
593
+ let entries;
594
+ try {
595
+ entries = fs3.readdirSync(discoveryDir()).filter((entry) => entry.endsWith(".json"));
596
+ } catch {
597
+ return void 0;
598
+ }
599
+ if (entries.length > 256) return void 0;
600
+ const matches = [];
601
+ for (const entry of entries) {
602
+ try {
603
+ const peer = JSON.parse(fs3.readFileSync(path4.join(discoveryDir(), entry), "utf8"));
604
+ if (peer.sessionName?.trim() !== name || !pidAlive2(peer.pid)) continue;
605
+ matches.push(peer);
606
+ } catch {
607
+ return void 0;
608
+ }
609
+ }
610
+ if (matches.length !== 1) return void 0;
611
+ const owner = matches[0];
612
+ if (owner.imBinding !== binding || owner.protocol !== IPC_PROTOCOL_VERSION || !/^pie-[a-z0-9]{12}$/.test(owner.instanceId) || !entries.includes(`${owner.instanceId}.json`) || typeof owner.sessionId !== "string" || !owner.sessionId || !Number.isInteger(owner.port) || !owner.port || owner.port < 1 || owner.port > 65535 || typeof owner.secret !== "string") return void 0;
613
+ return owner;
614
+ }
615
+ async function dispatchEventToName(name, binding, eventText) {
616
+ const owner = findNamedOwnerInstance(name, binding);
617
+ if (!owner?.port || !owner.secret) return void 0;
618
+ return await deliverOnce(owner.port, owner.secret, eventText, owner.sessionId, owner.instanceId) ? owner.instanceId : void 0;
619
+ }
528
620
  var SYNTHETIC_SENDER = (() => {
529
621
  const hex = randomUUID2().replace(/-/g, "");
530
622
  return `pie-${hex.slice(0, 12)}`;
531
623
  })();
532
624
  function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
533
- return new Promise((resolve4) => {
625
+ return new Promise((resolve5) => {
534
626
  const id = randomUUID2();
535
627
  const envelope = {
536
628
  v: IPC_PROTOCOL_VERSION,
@@ -558,7 +650,7 @@ function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
558
650
  settled = true;
559
651
  clearTimeout(timer);
560
652
  socket.destroy();
561
- resolve4(ok);
653
+ resolve5(ok);
562
654
  };
563
655
  const timer = setTimeout(() => finish(false), 5e3);
564
656
  socket.once("error", () => finish(false));
@@ -704,7 +796,7 @@ var RESTART_BACKOFF_MIN_MS = 5e3;
704
796
  var RESTART_BACKOFF_MAX_MS = 6e4;
705
797
  var SEND_FAILURE_NOTIFY_THROTTLE_MS = 5 * 60 * 1e3;
706
798
  var CHUNK_RETRY_DELAY_MS = 2e3;
707
- var delay = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms));
799
+ var delay = (ms) => new Promise((resolve5) => setTimeout(resolve5, ms));
708
800
  var MAX_INBOUND_RETRIES = 3;
709
801
  var DEFAULT_INBOUND_RETRY_BACKOFF_MS = 5e3;
710
802
  var MAX_PENDING_IM_INPUTS = 50;
@@ -742,6 +834,26 @@ function ipcDiscoveryRoot2() {
742
834
  const configDir = process.platform === "win32" ? raw : pathResolve(raw === "~" ? home : raw.startsWith("~/") ? pathJoin(home, raw.slice(2)) : raw);
743
835
  return pathJoin(configDir, "run", "ipc");
744
836
  }
837
+ function liveManagerForBinding(binding) {
838
+ try {
839
+ for (const file of fs6.readdirSync(ipcDiscoveryRoot2())) {
840
+ if (!file.endsWith(".json")) continue;
841
+ try {
842
+ const peer = JSON.parse(fs6.readFileSync(pathJoin(ipcDiscoveryRoot2(), file), "utf8"));
843
+ if (peer.pid === process.pid || peer.isManager !== true || peer.imBinding !== binding || !Number.isInteger(peer.pid) || !peer.pid || peer.pid <= 0) continue;
844
+ try {
845
+ process.kill(peer.pid, 0);
846
+ return true;
847
+ } catch (error) {
848
+ if (error.code !== "ESRCH") return true;
849
+ }
850
+ } catch {
851
+ }
852
+ }
853
+ } catch {
854
+ }
855
+ return false;
856
+ }
745
857
  async function applyModelControl(peerRef, model) {
746
858
  const net2 = await import("node:net");
747
859
  let target;
@@ -749,7 +861,7 @@ async function applyModelControl(peerRef, model) {
749
861
  const dir = ipcDiscoveryRoot2();
750
862
  for (const file of fs6.readdirSync(dir).filter((f) => f.endsWith(".json"))) {
751
863
  const parsed = JSON.parse(fs6.readFileSync(join7(dir, file), "utf8"));
752
- if (!parsed.port || !parsed.secret || typeof parsed.pid !== "number" || !parsed.instanceId) continue;
864
+ if (!parsed.port || !parsed.secret || typeof parsed.pid !== "number" || !parsed.instanceId || typeof parsed.sessionId !== "string" || !parsed.sessionId) continue;
753
865
  const match = parsed.instanceId === peerRef || parsed.instanceId.startsWith(peerRef) || parsed.displayName === peerRef;
754
866
  if (!match) continue;
755
867
  try {
@@ -757,22 +869,23 @@ async function applyModelControl(peerRef, model) {
757
869
  } catch {
758
870
  continue;
759
871
  }
760
- target = { port: parsed.port, secret: parsed.secret, instanceId: parsed.instanceId };
872
+ target = { port: parsed.port, secret: parsed.secret, instanceId: parsed.instanceId, sessionId: parsed.sessionId };
761
873
  break;
762
874
  }
763
875
  } catch {
764
876
  }
765
- if (!target) return { ok: false, detail: `\u672A\u627E\u5230\u4F1A\u8BDD\uFF1A${peerRef}` };
877
+ if (!target) return { ok: false, detail: `Session not found: ${peerRef}` };
766
878
  const envelope = signEnvelope({
767
879
  v: IPC_PROTOCOL_VERSION,
768
880
  id: `panel-model-${Date.now()}`,
769
881
  from: "pie-panel0000000",
770
882
  to: target.instanceId,
771
883
  kind: "control",
884
+ sessionId: target.sessionId,
772
885
  createdAt: Date.now(),
773
886
  text: JSON.stringify({ control: "model.set", payload: { model } })
774
887
  }, target.secret);
775
- return await new Promise((resolve4) => {
888
+ return await new Promise((resolve5) => {
776
889
  let settled = false;
777
890
  const finish = (ok, detail) => {
778
891
  if (settled) return;
@@ -781,15 +894,15 @@ async function applyModelControl(peerRef, model) {
781
894
  sock.destroy();
782
895
  } catch {
783
896
  }
784
- resolve4({ ok, detail });
897
+ resolve5({ ok, detail });
785
898
  };
786
899
  const sock = net2.connect({ host: "127.0.0.1", port: target.port }, () => {
787
900
  sock.write(JSON.stringify(envelope) + "\n");
788
901
  });
789
- sock.setTimeout(6e3, () => finish(false, "\u5BF9\u7AEF 6 \u79D2\u65E0\u56DE\u6267\uFF08\u53EF\u80FD\u6B63\u91CD\u542F\uFF1B\u63A7\u5236\u5E27\u5E42\u7B49\uFF0C\u91CD\u70B9\u5B89\u5168\uFF09"));
790
- sock.on("error", (error) => finish(false, `\u8FDE\u63A5\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`));
902
+ sock.setTimeout(6e3, () => finish(false, "Peer gave no receipt within 6s (it may be restarting; the control frame is idempotent \u2014 resending is safe)"));
903
+ sock.on("error", (error) => finish(false, `Connection failed: ${error instanceof Error ? error.message : String(error)}`));
791
904
  sock.on("close", () => {
792
- if (!settled) finish(false, "\u5BF9\u7AEF\u5173\u95ED\u4E86\u8FDE\u63A5\uFF08\u7B56\u7565\u62D2\u7EDD\u6216\u5E27\u88AB\u62D2\uFF1B\u91CD\u53D1\u5B89\u5168\uFF09");
905
+ if (!settled) finish(false, "Peer closed the connection (policy refusal or rejected frame; resending is safe)");
793
906
  });
794
907
  sock.on("data", (buffer) => {
795
908
  for (const line of buffer.toString("utf8").split("\n")) {
@@ -798,7 +911,7 @@ async function applyModelControl(peerRef, model) {
798
911
  const parsed = JSON.parse(line);
799
912
  if (parsed.kind === "ack" || parsed.kind === "result") {
800
913
  const refused = /"ok"\s*:\s*false|error|拒绝|invalid|unknown|refus|denied/i.test(parsed.text ?? "");
801
- finish(!refused, `\u5BF9\u7AEF\u56DE\u6267\uFF1A${parsed.text ?? "(\u7A7A)"}`);
914
+ finish(!refused, `Peer receipt: ${parsed.text ?? "(empty)"}`);
802
915
  return;
803
916
  }
804
917
  } catch {
@@ -874,7 +987,7 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
874
987
  busStale = next;
875
988
  if (next) {
876
989
  ctx.log("im-forward: event bus cloud websocket stale (aged disconnect without reconnect); card callbacks will not arrive until `lark-cli event stop --force` + restart");
877
- ctx.ui.notify("IM \u8F6C\u53D1\uFF1A\u4E8B\u4EF6\u603B\u7EBF\u4E91\u7AEF\u8FDE\u63A5\u7591\u4F3C\u8001\u5316\uFF08\u9762\u677F\u6309\u94AE\u53EF\u80FD\u65E0\u54CD\u5E94\uFF09\u3002\u4FEE\u590D\uFF1Alark-cli event stop --force \u540E\u91CD\u542F\u3002", "warning");
990
+ ctx.ui.notify("IM forward: the event-bus cloud connection looks aged (panel buttons may not respond). Fix: lark-cli event stop --force, then restart.", "warning");
878
991
  }
879
992
  updateFooterTag();
880
993
  }
@@ -1238,9 +1351,9 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1238
1351
  const attribution = resolveOutboundAttribution(sessionId);
1239
1352
  const deliverTf = /* @__PURE__ */ new Map();
1240
1353
  if (!outboundRoleAllows(attribution, deliverTf)) return;
1241
- const recoveryHint = `\u8F93\u5165\u4ECD\u5728\u4F1A\u8BDD\u4E2D\uFF0C\u56DE\u590D\u201C\u91CD\u7B54\u4E0A\u4E00\u6761\u201D\u5373\u53EF\u57FA\u4E8E\u5B83\u91CD\u65B0\u4F5C\u7B54\uFF0C\u65E0\u9700\u91CD\u53D1\u539F\u59CB\u8BF7\u6C42\u3002`;
1354
+ const recoveryHint = `Your input is still in the session \u2014 reply "\u91CD\u7B54\u4E0A\u4E00\u6761" (redo the last one) to answer from it again without resending the original request.`;
1242
1355
  void forwardMessage(
1243
- `\u26A0\uFE0F \u4EFB\u52A1\u5931\u8D25\uFF1A${reason}\uFF08\u91CD\u8BD5\u5DF2\u7528\u5C3D\uFF09
1356
+ `\u26A0\uFE0F Task failed: ${reason} (retries exhausted)
1244
1357
  ${recoveryHint}`,
1245
1358
  sessionId,
1246
1359
  sequence,
@@ -1260,7 +1373,7 @@ ${recoveryHint}`,
1260
1373
  const deliverTc = /* @__PURE__ */ new Map();
1261
1374
  if (!outboundRoleAllows(attribution, deliverTc)) return;
1262
1375
  void forwardMessage(
1263
- `\u26D4\uFE0F \u4EFB\u52A1\u5DF2\u53D6\u6D88\uFF1A${event.reason}`,
1376
+ `\u26D4\uFE0F Task cancelled: ${event.reason}`,
1264
1377
  sessionId,
1265
1378
  sequence,
1266
1379
  attribution?.caption,
@@ -1310,8 +1423,8 @@ ${recoveryHint}`,
1310
1423
  };
1311
1424
  const claimStake = () => {
1312
1425
  let release;
1313
- const token = new Promise((resolve4) => {
1314
- release = resolve4;
1426
+ const token = new Promise((resolve5) => {
1427
+ release = resolve5;
1315
1428
  });
1316
1429
  token.release = release;
1317
1430
  anchorStakeFlights.set(sessionId, token);
@@ -1471,7 +1584,7 @@ ${recoveryHint}`,
1471
1584
  "send notice",
1472
1585
  () => connection.send(
1473
1586
  cfg.targetId,
1474
- `\u2026(\u7B2C ${index}/${chunks.length} \u6BB5\u4E4B\u540E\u7684\u5206\u6BB5\u53D1\u9001\u5931\u8D25\uFF0C\u5B8C\u6574\u5185\u5BB9\u89C1\u7EC8\u7AEF)`,
1587
+ `\u2026(chunked delivery failed after part ${index}/${chunks.length}; full content is in the terminal)`,
1475
1588
  chunkKey(baseKey, index, "fail"),
1476
1589
  anchor
1477
1590
  )
@@ -1524,12 +1637,12 @@ ${recoveryHint}`,
1524
1637
  }
1525
1638
  if (failedFiles.length > 0 && !terminated && isForwardingEnabled()) {
1526
1639
  const names = failedFiles.slice(0, 5).map((name) => name.replace(/[\r\n]/g, " ").slice(0, 80)).join("\u3001");
1527
- const extra = failedFiles.length > 5 ? `\uFF08\u53E6 ${failedFiles.length - 5} \u4E2A\uFF09` : "";
1640
+ const extra = failedFiles.length > 5 ? ` (+${failedFiles.length - 5} more)` : "";
1528
1641
  await providerCall(
1529
1642
  "send attachment notice",
1530
1643
  () => connection.send(
1531
1644
  cfg.targetId,
1532
- `\u9644\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF1A${names}${extra}\u3002\u8BF7\u5728\u7EC8\u7AEF\u67E5\u770B\u6587\u4EF6\u3002`,
1645
+ `Attachment upload failed: ${names}${extra}. Check the files in the terminal.`,
1533
1646
  chunkKey(baseKey, files.length, "fail"),
1534
1647
  anchor
1535
1648
  )
@@ -1677,7 +1790,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1677
1790
  if (panelCmd.restricted && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id))) {
1678
1791
  ctx.log(`im-forward: restricted panel action ${panelCmd.cmd} refused for ${event.sender_id ?? "unknown"} (not in allowUsers)`);
1679
1792
  try {
1680
- await connection.send(event.chat_id, "\u26D4\uFE0F \u6B64\u64CD\u4F5C\u9700\u8981\u7BA1\u7406\u5458\u6743\u9650\uFF08allowUsers\uFF09\u3002", `panel-refused-${event.event_id}`);
1793
+ await connection.send(event.chat_id, "\u26D4\uFE0F This action requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
1681
1794
  } catch {
1682
1795
  }
1683
1796
  return;
@@ -1688,11 +1801,11 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1688
1801
  const receipt = await applyModelControl(peerRef, model);
1689
1802
  if (!isCurrent()) return;
1690
1803
  const spec = {
1691
- title: "\u5207\u6362\u7ED3\u679C",
1804
+ title: "Model Switch Result",
1692
1805
  body: `${receipt.ok ? "\u2705" : "\u26A0\uFE0F"} ${model} \u2192 ${peerRef}
1693
1806
 
1694
1807
  ${receipt.detail}`,
1695
- actions: [{ id: "panel.models", label: "\u21A9\uFE0F \u8FD4\u56DE\u6A21\u578B\u9762\u677F" }]
1808
+ actions: [{ id: "panel.models", label: "\u21A9\uFE0F Back to model panel" }]
1696
1809
  };
1697
1810
  try {
1698
1811
  if (connection.sendCard) {
@@ -1704,6 +1817,89 @@ ${spec.body}`, `panel-model-${event.event_id}`);
1704
1817
  }
1705
1818
  return;
1706
1819
  }
1820
+ if (panelCmd.cmd === "panel.upgrade.confirm") {
1821
+ if (!cfg.allowUsers || !event.sender_id || !cfg.allowUsers.includes(event.sender_id)) {
1822
+ ctx.log(`im-forward: panel.upgrade.confirm refused for ${event.sender_id ?? "unknown"} (execution-sink gate: allowUsers membership required)`);
1823
+ try {
1824
+ await connection.send(event.chat_id, "\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
1825
+ } catch {
1826
+ }
1827
+ return;
1828
+ }
1829
+ const spawn5 = await import("node:child_process");
1830
+ const started2 = Date.now();
1831
+ let actorOk = false;
1832
+ let actorDetail = "";
1833
+ try {
1834
+ const entry = process.argv[1] ? pathResolve(process.argv[1]) : "";
1835
+ if (!entry) throw new Error("cannot resolve the pie entry point");
1836
+ const configRoot = pathDirname(pathDirname(ipcDiscoveryRoot2()));
1837
+ const logFile = join7(configRoot, "manager", "upgrade-actor.log");
1838
+ let out;
1839
+ try {
1840
+ fs6.mkdirSync(pathDirname(logFile), { recursive: true });
1841
+ out = fs6.openSync(logFile, "a");
1842
+ } catch {
1843
+ out = void 0;
1844
+ }
1845
+ const child = spawn5.spawn(process.execPath, [entry, "manager", "upgrade"], {
1846
+ cwd: process.cwd(),
1847
+ detached: true,
1848
+ stdio: out !== void 0 ? ["ignore", out, out] : "ignore",
1849
+ windowsHide: true,
1850
+ env: process.env
1851
+ });
1852
+ const spawnOutcome = await new Promise((resolve5) => {
1853
+ let settled = false;
1854
+ const settle = (v) => {
1855
+ if (!settled) {
1856
+ settled = true;
1857
+ resolve5(v);
1858
+ }
1859
+ };
1860
+ child.once("spawn", () => settle("spawned"));
1861
+ child.once("error", (error) => {
1862
+ ctx.log(`im-forward: upgrade actor spawn error: ${error instanceof Error ? error.message : String(error)}`);
1863
+ settle("error");
1864
+ });
1865
+ setTimeout(() => settle("timeout"), 3e3).unref?.();
1866
+ });
1867
+ child.unref();
1868
+ if (out !== void 0) {
1869
+ try {
1870
+ fs6.closeSync(out);
1871
+ } catch {
1872
+ }
1873
+ }
1874
+ if (spawnOutcome === "error") {
1875
+ actorDetail = "the actor process failed to spawn (see the manager log)";
1876
+ } else {
1877
+ actorOk = true;
1878
+ actorDetail = `actor pid ${child.pid}${spawnOutcome === "timeout" ? " (spawn unconfirmed \u2014 will report via /panel)" : ""} \xB7 log ${logFile}`;
1879
+ }
1880
+ } catch (error) {
1881
+ actorDetail = error instanceof Error ? error.message : String(error);
1882
+ }
1883
+ ctx.log(`im-forward: panel.upgrade.confirm actor spawn ${actorOk ? "ok" : "failed"} (${actorDetail}, runtimeMs=${Date.now() - started2})`);
1884
+ const spec = {
1885
+ title: actorOk ? "Upgrade Started" : "Upgrade Failed to Start",
1886
+ body: actorOk ? `\u2B06\uFE0F npm install + manager restart running in the background.
1887
+
1888
+ ${actorDetail}
1889
+
1890
+ IM pauses briefly during the restart; tap \u{1F504} Refresh afterwards \u2014 the panel's footer line shows the outcome (old \u2192 new version).` : `Could not spawn the upgrade actor: ${actorDetail}`,
1891
+ actions: actorOk ? [{ id: "panel.refresh", label: "\u{1F504} Refresh" }] : [{ id: "panel.upgrade", label: "\u21A9\uFE0F Back to upgrade card" }]
1892
+ };
1893
+ try {
1894
+ if (connection.sendCard) {
1895
+ const sent = await connection.sendCard(event.chat_id, spec, `panel-upgrade-${event.event_id}`);
1896
+ if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
1897
+ } else await connection.send(event.chat_id, `**${spec.title}**
1898
+ ${spec.body}`, `panel-upgrade-${event.event_id}`);
1899
+ } catch {
1900
+ }
1901
+ return;
1902
+ }
1707
1903
  const result = executePanelCommand({ ...panelCmd, senderId: event.sender_id, originCardId: event.message_id });
1708
1904
  try {
1709
1905
  if (result.patchOrigin && connection.patch && event.message_id) {
@@ -1721,7 +1917,7 @@ ${spec.body}`, `panel-model-${event.event_id}`);
1721
1917
  if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
1722
1918
  ctx.log(`im-forward: panel card sent (${panelCmd.cmd})`);
1723
1919
  } else {
1724
- await connection.send(event.chat_id, `**${result.spec.title ?? "\u9762\u677F"}**
1920
+ await connection.send(event.chat_id, `**${result.spec.title ?? "Panel"}**
1725
1921
  ${result.spec.body}`, `panel-${event.event_id}`);
1726
1922
  }
1727
1923
  } catch (error) {
@@ -1729,8 +1925,13 @@ ${result.spec.body}`, `panel-${event.event_id}`);
1729
1925
  }
1730
1926
  };
1731
1927
  async function handleInboundEventInner(event, retry) {
1928
+ let nonBoundGroup = false;
1732
1929
  const isGroup = event.chatType === "group";
1733
1930
  if (isGroup) {
1931
+ nonBoundGroup = cfg.targetKind === "chat" && !!cfg.targetId && event.chat_id !== cfg.targetId;
1932
+ if (nonBoundGroup) {
1933
+ ctx.log(`im-forward: group event from non-bound chat ${event.chat_id} (owned-thread dispatch only)`);
1934
+ }
1734
1935
  if (cfg.groupAccess === "off") {
1735
1936
  ctx.log("im-forward: group event refused (off)");
1736
1937
  return;
@@ -1761,7 +1962,21 @@ ${result.spec.body}`, `panel-${event.event_id}`);
1761
1962
  }
1762
1963
  const address = resolveInboundAddress(event.text);
1763
1964
  if (address.kind === "other") {
1764
- ctx.log(`im-forward: message addressed to "${address.name}" (another live session); ignoring here`);
1965
+ if (isGroup && (nonBoundGroup || event.isBotMentioned === false)) {
1966
+ const meta = await fetchMessageMeta(messageId).catch(() => void 0);
1967
+ if (nonBoundGroup || !meta?.threadId) {
1968
+ ctx.log("im-forward: group address outside the bound chat or without bot mention/thread; ignoring");
1969
+ return;
1970
+ }
1971
+ }
1972
+ if (consumerLock) {
1973
+ const epoch2 = inputEpoch;
1974
+ const session = currentSessionId;
1975
+ const payload = `${DISPATCH_PREFIX} ${JSON.stringify({ v: 1, binding: bindingKey(), event })}`;
1976
+ if (terminated || suspended || !isForwardingEnabled() || inputEpoch !== epoch2 || currentSessionId !== session) return;
1977
+ const owner2 = await dispatchEventToName(address.name, bindingKey(), payload);
1978
+ ctx.log(owner2 ? `im-forward: explicit address "${address.name}" dispatched to ${owner2}` : `im-forward: explicit address "${address.name}" has no deliverable unique owner`);
1979
+ }
1765
1980
  return;
1766
1981
  }
1767
1982
  if (address.kind === "ambiguous") {
@@ -1795,6 +2010,11 @@ ${result.spec.body}`, `panel-${event.event_id}`);
1795
2010
  releaseInvalidatedEvent();
1796
2011
  return;
1797
2012
  }
2013
+ if (isGroup && event.isBotMentioned === false && !meta.threadId) {
2014
+ ctx.log("im-forward: group message without bot mention outside any thread; ignoring");
2015
+ releaseInvalidatedEvent();
2016
+ return;
2017
+ }
1798
2018
  const pinnedSession = event.event_id ? retrySessionIds.get(key(event.event_id)) : void 0;
1799
2019
  if (pinnedSession !== void 0 && pinnedSession !== sessionId) {
1800
2020
  ctx.log(`im-forward: retry crossed a session switch (${pinnedSession} -> ${sessionId}); releasing for redelivery`);
@@ -1815,7 +2035,7 @@ ${result.spec.body}`, `panel-${event.event_id}`);
1815
2035
  return;
1816
2036
  }
1817
2037
  const unanchored = !meta.replyTo && !meta.threadId;
1818
- if (isManager && unanchored) {
2038
+ if (isManager && unanchored && !nonBoundGroup) {
1819
2039
  const residentRoute = {
1820
2040
  messageId: "",
1821
2041
  threadId: meta.threadId ?? null,
@@ -1849,7 +2069,7 @@ ${result.spec.body}`, `panel-${event.event_id}`);
1849
2069
  ctx.log(`im-forward: thread ownership unreadable for ${messageId}; dropping (fail closed)`);
1850
2070
  return;
1851
2071
  }
1852
- if (isManager && meta.threadId && (event.chatType === "group" || event.chatType === "p2p")) {
2072
+ if (isManager && meta.threadId && !nonBoundGroup && (event.chatType === "group" || event.chatType === "p2p")) {
1853
2073
  if (!scope.isCurrent()) {
1854
2074
  releaseInvalidatedEvent();
1855
2075
  return;
@@ -1879,6 +2099,11 @@ ${result.spec.body}`, `panel-${event.event_id}`);
1879
2099
  releaseInvalidatedEvent();
1880
2100
  return;
1881
2101
  }
2102
+ if (nonBoundGroup) {
2103
+ ctx.log(`im-forward: non-bound-group message ${messageId} resolves locally; staying quiet after re-bind`);
2104
+ releaseInvalidatedEvent();
2105
+ return;
2106
+ }
1882
2107
  await acceptRoutedMessage(route, event, meta, scope, address, sessionId);
1883
2108
  } finally {
1884
2109
  scopes.delete(scope);
@@ -1915,7 +2140,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1915
2140
  }
1916
2141
  if (currentAfterSubmit) {
1917
2142
  const rejectReason = scope.lastRejectReason;
1918
- const notice = rejectReason ? `\u26A0\uFE0F \u6D88\u606F\u672A\u80FD\u63D0\u4EA4\uFF1A${rejectReason}` : `\u26A0\uFE0F \u6D88\u606F\u63A5\u6536\u5931\u8D25\uFF0C\u672A\u63D0\u4EA4\u4EFB\u52A1\u3002${imageKeys.length ? "\u8BF7\u68C0\u67E5\u9644\u4EF6\u540E\u91CD\u8BD5\u3002" : "\u8BF7\u91CD\u8BD5\u3002"}`;
2143
+ const notice = rejectReason ? `\u26A0\uFE0F Message not submitted: ${rejectReason}` : `\u26A0\uFE0F Message intake failed; the task was not submitted. ${imageKeys.length ? "Check the attachments and retry." : "Please retry."}`;
1919
2144
  ctx.ui.notify(
1920
2145
  "im-forward: message was not accepted; no input submitted.",
1921
2146
  "warning"
@@ -1976,7 +2201,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1976
2201
  const boundSession = retrySessionIds.get(eventId);
1977
2202
  retrySessionIds.delete(eventId);
1978
2203
  void forwardMessage(
1979
- `\u26A0\uFE0F \u6D88\u606F\u63A5\u6536\u5931\u8D25\uFF08\u91CD\u8BD5\u7528\u5C3D\uFF09\u3002\u8BF7\u5728 Pie \u7EC8\u7AEF\u67E5\u770B\u65E5\u5FD7\u3002`,
2204
+ `\u26A0\uFE0F Message intake failed (retries exhausted). Check the Pie terminal logs.`,
1980
2205
  boundSession ?? currentSessionId ?? "",
1981
2206
  ++forwardCounter,
1982
2207
  void 0,
@@ -2088,12 +2313,15 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2088
2313
  function stopGeneration(gen) {
2089
2314
  if (gen.startup) clearTimeout(gen.startup);
2090
2315
  return gen.stopping ??= Promise.resolve().then(() => gen.handle?.stop()).catch(() => {
2316
+ gen.stopFailed = true;
2091
2317
  ctx.log(`im-forward: ${cfg.provider} consumer stop failed`);
2092
2318
  }).then(() => {
2093
2319
  gen.retired = true;
2094
2320
  });
2095
2321
  }
2096
2322
  let consumerLock;
2323
+ let consumerSlotRetiring = false;
2324
+ let releaseImBinding;
2097
2325
  let resolvedBindingKey;
2098
2326
  function bindingKey() {
2099
2327
  return resolvedBindingKey ?? `${cfg.provider}:${cfg.appId ?? (cfg.profile ? `profile:${cfg.profile}` : cfg.targetId)}`;
@@ -2115,28 +2343,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2115
2343
  }
2116
2344
  let consumerStartupInFlight = false;
2117
2345
  function residentAliveSomewhere() {
2118
- if (isManager) return false;
2119
- try {
2120
- const dir = ipcDiscoveryRoot2();
2121
- const entries = fs6.readdirSync(dir);
2122
- for (const name of entries) {
2123
- if (!name.endsWith(".json")) continue;
2124
- try {
2125
- const parsed = JSON.parse(fs6.readFileSync(pathJoin(dir, name), "utf8"));
2126
- const unattended = parsed.unattended === true;
2127
- if (unattended && typeof parsed.pid === "number" && parsed.pid > 0) {
2128
- try {
2129
- process.kill(parsed.pid, 0);
2130
- return true;
2131
- } catch {
2132
- }
2133
- }
2134
- } catch {
2135
- }
2136
- }
2137
- } catch {
2138
- }
2139
- return false;
2346
+ return !isManager && liveManagerForBinding(bindingKey());
2140
2347
  }
2141
2348
  function needsCanonicalResolution() {
2142
2349
  return !resolvedBindingKey && !cfg.appId && !!cfg.profile && connection.canonicalAppId !== void 0;
@@ -2153,6 +2360,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2153
2360
  return resolved ? acquireClaimedSlot(resolved) : false;
2154
2361
  }
2155
2362
  function acquireClaimedSlot(binding) {
2363
+ if (!releaseImBinding) releaseImBinding = registerImBinding(binding);
2156
2364
  if (consumerLock) return true;
2157
2365
  if (!isManager && residentAliveSomewhere()) {
2158
2366
  if (!dispatchMode) {
@@ -2166,17 +2374,26 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2166
2374
  const claim = tryClaimConsumer(
2167
2375
  binding,
2168
2376
  `pie-${currentSessionId ?? "unknown"}`,
2169
- () => {
2170
- ctx.log("im-forward: event-hub slot lost to another consumer; retiring ours");
2377
+ async () => {
2378
+ consumerSlotRetiring = true;
2379
+ ctx.log("im-forward: retiring event-hub consumer before releasing slot");
2380
+ if (restartTimer) clearTimeout(restartTimer);
2381
+ const retiringGeneration = generation;
2382
+ if (retiringGeneration) {
2383
+ await stopGeneration(retiringGeneration);
2384
+ if (retiringGeneration.stopFailed) throw new Error("Consumer stop failed; retaining slot");
2385
+ }
2386
+ consumer = null;
2387
+ consumerRecovering = false;
2388
+ consumerReady = false;
2171
2389
  consumerLock = void 0;
2172
- if (consumer || consumerRecovering) {
2173
- void stopGeneration(generation ?? { handle: null, installed: false, failed: false, retired: true }).catch(() => void 0);
2174
- consumer = null;
2175
- consumerRecovering = false;
2176
- consumerReady = false;
2390
+ if (!terminated) {
2391
+ restartTimer = setTimeout(() => {
2392
+ consumerSlotRetiring = false;
2393
+ void spawnConsumer();
2394
+ }, 15e3);
2395
+ restartTimer.unref?.();
2177
2396
  }
2178
- restartTimer = setTimeout(spawnConsumer, 15e3);
2179
- restartTimer.unref?.();
2180
2397
  },
2181
2398
  // STAND-IN GAP FIX part 2 (dogfood 11-13): the claim-time gate alone was
2182
2399
  // not enough — a TUI that had ALREADY claimed kept the feed while a
@@ -2206,14 +2423,14 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2206
2423
  async function spawnConsumer() {
2207
2424
  restartTimer = void 0;
2208
2425
  restartDueAt = void 0;
2209
- if (terminated || suspended || consumer || consumerRecovering) return;
2426
+ if (terminated || suspended || consumerSlotRetiring || generation?.stopFailed || consumer || consumerRecovering) return;
2210
2427
  if (needsCanonicalResolution()) {
2211
2428
  if (consumerStartupInFlight) return;
2212
2429
  consumerStartupInFlight = true;
2213
2430
  let key2;
2214
2431
  try {
2215
2432
  key2 = await resolveBindingKey();
2216
- if (terminated || suspended || consumer || consumerRecovering) return;
2433
+ if (terminated || suspended || consumerSlotRetiring || generation?.stopFailed || consumer || consumerRecovering) return;
2217
2434
  } finally {
2218
2435
  consumerStartupInFlight = false;
2219
2436
  }
@@ -2247,7 +2464,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2247
2464
  const recover = () => {
2248
2465
  if (!gen.installed) return;
2249
2466
  void stopGeneration(gen).then(() => {
2250
- if (generation !== gen) return;
2467
+ if (generation !== gen || gen.stopFailed || consumerSlotRetiring) return;
2251
2468
  consumer = null;
2252
2469
  consumerRecovering = false;
2253
2470
  if (terminated || suspended) return;
@@ -2325,6 +2542,8 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2325
2542
  };
2326
2543
  inputEpoch++;
2327
2544
  suspended = true;
2545
+ releaseImBinding?.();
2546
+ releaseImBinding = void 0;
2328
2547
  const gen = generation;
2329
2548
  if (restartTimer) {
2330
2549
  suspendedRestartInMs = restartDueAt !== void 0 ? Math.max(0, restartDueAt - Date.now()) : 0;
@@ -2366,12 +2585,13 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2366
2585
  ctx.registerCleanup?.(async () => {
2367
2586
  inputEpoch++;
2368
2587
  terminated = true;
2588
+ releaseImBinding?.();
2589
+ releaseImBinding = void 0;
2369
2590
  clearInterval(busHealthTimer);
2370
2591
  clearInterval(dispatchTagTimer);
2371
2592
  registerDispatchReceiver(void 0);
2372
2593
  registerTurnImDriver(void 0);
2373
- consumerLock?.release();
2374
- consumerLock = void 0;
2594
+ consumerSlotRetiring = true;
2375
2595
  const resources = [...scopes];
2376
2596
  scopes.clear();
2377
2597
  for (const { timer } of retryTimers.values()) clearTimeout(timer);
@@ -2388,6 +2608,10 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2388
2608
  Promise.resolve().then(() => connection.dispose?.()),
2389
2609
  generation ? stopGeneration(generation) : Promise.resolve()
2390
2610
  ]);
2611
+ if (!generation?.stopFailed && !results.some((result) => result.status === "rejected")) {
2612
+ consumerLock?.release();
2613
+ consumerLock = void 0;
2614
+ }
2391
2615
  consumer = null;
2392
2616
  if (results.some((result) => result.status === "rejected"))
2393
2617
  ctx.log(`im-forward: ${cfg.provider} resource cleanup failed`);
@@ -2493,12 +2717,12 @@ async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
2493
2717
  const { spawn: spawn5 } = await import("node:child_process");
2494
2718
  const binary = binaryOverride ?? await settingsProbeBinary();
2495
2719
  if (!binary) return;
2496
- await new Promise((resolve4) => {
2720
+ await new Promise((resolve5) => {
2497
2721
  let settled = false;
2498
2722
  const done = () => {
2499
2723
  if (!settled) {
2500
2724
  settled = true;
2501
- resolve4();
2725
+ resolve5();
2502
2726
  }
2503
2727
  };
2504
2728
  const timer = setTimeout(() => {
@@ -2607,7 +2831,7 @@ function stopOwnedTreeInner(child, signal) {
2607
2831
  }
2608
2832
  }
2609
2833
  }
2610
- return new Promise((resolve4) => {
2834
+ return new Promise((resolve5) => {
2611
2835
  let done = false;
2612
2836
  let killer;
2613
2837
  const finish = (ok) => {
@@ -2620,7 +2844,7 @@ function stopOwnedTreeInner(child, signal) {
2620
2844
  } catch {
2621
2845
  }
2622
2846
  }
2623
- resolve4(ok);
2847
+ resolve5(ok);
2624
2848
  };
2625
2849
  const timer = setTimeout(() => {
2626
2850
  try {
@@ -2675,14 +2899,14 @@ function shutdownConsumer(child) {
2675
2899
  }
2676
2900
  async function shutdownConsumerInner(child) {
2677
2901
  let closed = false;
2678
- const close = new Promise((resolve4) => child.once("close", () => {
2902
+ const close = new Promise((resolve5) => child.once("close", () => {
2679
2903
  closed = true;
2680
- resolve4();
2904
+ resolve5();
2681
2905
  }));
2682
2906
  const wait = async (ms) => {
2683
2907
  let timer;
2684
- await Promise.race([close, new Promise((resolve4) => {
2685
- timer = setTimeout(resolve4, ms);
2908
+ await Promise.race([close, new Promise((resolve5) => {
2909
+ timer = setTimeout(resolve5, ms);
2686
2910
  })]);
2687
2911
  clearTimeout(timer);
2688
2912
  };
@@ -2706,9 +2930,9 @@ async function shutdownConsumerInner(child) {
2706
2930
 
2707
2931
  // builtin/extensions/im-forward/lark-cli.ts
2708
2932
  async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
2709
- return new Promise((resolve4) => {
2933
+ return new Promise((resolve5) => {
2710
2934
  if (options.signal?.aborted) {
2711
- resolve4({ stdout: "", error: "cancelled" });
2935
+ resolve5({ stdout: "", error: "cancelled" });
2712
2936
  return;
2713
2937
  }
2714
2938
  let child;
@@ -2723,7 +2947,7 @@ async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
2723
2947
  ...cwd ? { cwd } : {}
2724
2948
  });
2725
2949
  } catch {
2726
- resolve4({ stdout: "", error: "spawn failed" });
2950
+ resolve5({ stdout: "", error: "spawn failed" });
2727
2951
  return;
2728
2952
  }
2729
2953
  let stdout = "";
@@ -2741,7 +2965,7 @@ async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
2741
2965
  clearTimeout(killTimer);
2742
2966
  clearTimeout(closeTimer);
2743
2967
  options.signal?.removeEventListener("abort", abort);
2744
- resolve4(result);
2968
+ resolve5(result);
2745
2969
  };
2746
2970
  const terminatedResult = () => ({ stdout: termination?.startsWith("timeout") ? stdout : "", error: termination });
2747
2971
  const stop = (signal) => {
@@ -2951,7 +3175,7 @@ async function openBrowser(url, signal, seam = {}) {
2951
3175
  if (signal.aborted || !/^https:\/\/[^\s\x00-\x1f\x7f]+$/.test(url)) return "failed";
2952
3176
  const spec = browserLaunch(seam.platform);
2953
3177
  if (!spec) return "failed";
2954
- return new Promise((resolve4) => {
3178
+ return new Promise((resolve5) => {
2955
3179
  let child;
2956
3180
  let settled = false;
2957
3181
  let stopping = false;
@@ -2966,7 +3190,7 @@ async function openBrowser(url, signal, seam = {}) {
2966
3190
  child?.stdin?.destroy();
2967
3191
  child?.stdout?.destroy();
2968
3192
  child?.stderr?.destroy();
2969
- resolve4(result);
3193
+ resolve5(result);
2970
3194
  };
2971
3195
  const stop = () => {
2972
3196
  if (settled || stopping) return;
@@ -3501,7 +3725,8 @@ ${detect.error ?? ""}`);
3501
3725
  }
3502
3726
 
3503
3727
  // builtin/extensions/im-forward/providers/feishu/index.ts
3504
- function normalizeEvent(line) {
3728
+ var selfEchoDrops = { count: 0 };
3729
+ function normalizeEvent(line, botOpenId) {
3505
3730
  let raw;
3506
3731
  try {
3507
3732
  raw = JSON.parse(line);
@@ -3514,13 +3739,17 @@ function normalizeEvent(line) {
3514
3739
  const mentions = Array.isArray(raw.mentions) ? raw.mentions.filter((m) => isRecord(m)).map((m) => ({ id: typeof m.id === "string" ? m.id : void 0, name: typeof m.name === "string" ? m.name : void 0 })) : void 0;
3515
3740
  let text = extractInboundText(raw.content).replace(/\[Image:\s*img_[A-Za-z0-9_-]+\]/g, "").trim();
3516
3741
  const chatType = raw.chat_type === void 0 ? void 0 : typeof raw.chat_type === "string" ? raw.chat_type : "invalid";
3517
- if (chatType === "group" && mentions?.length) {
3518
- const first = mentions[0];
3519
- if (first?.name) {
3520
- const esc = first.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3521
- text = text.replace(new RegExp(`^(?:[^\\n]*\\n)?@${esc}\\s*`), "").trim();
3522
- }
3742
+ if (botOpenId && typeof raw.sender_id === "string" && raw.sender_id === botOpenId) {
3743
+ selfEchoDrops.count += 1;
3744
+ if (selfEchoDrops.count <= 3) console.warn(`[im-forward] dropped self-echo event (message_id=${String(id ?? "?")}); subscription delivers our own messages`);
3745
+ return null;
3523
3746
  }
3747
+ const selfMention = botOpenId ? mentions?.find((m) => m.id === botOpenId) : mentions?.[0];
3748
+ if (chatType === "group" && selfMention?.name) {
3749
+ const esc = selfMention.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3750
+ text = text.replace(new RegExp(`^(?:[^\\n]*\\n)?@${esc}\\s*`), "").trim();
3751
+ }
3752
+ const isBotMentioned = chatType === "group" ? botOpenId ? mentions?.some((m) => m.id === botOpenId) === true : Boolean(mentions?.length) : void 0;
3524
3753
  return {
3525
3754
  event_id: raw.event_id,
3526
3755
  message_id: id,
@@ -3529,7 +3758,8 @@ function normalizeEvent(line) {
3529
3758
  chatType,
3530
3759
  mentions: mentions?.length ? mentions : void 0,
3531
3760
  text,
3532
- images: extractImageKeys(raw.content)
3761
+ images: extractImageKeys(raw.content),
3762
+ isBotMentioned
3533
3763
  };
3534
3764
  }
3535
3765
  function normalizeCardAction(line) {
@@ -3808,7 +4038,23 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
3808
4038
  return void 0;
3809
4039
  }
3810
4040
  };
3811
- const child = spawnConsume("im.message.receive_v1", normalizeEvent, true);
4041
+ const botIdentity = { openId: void 0, attempts: 0, pending: false };
4042
+ const resolveBotIdentity = () => {
4043
+ if (botIdentity.openId || botIdentity.pending || botIdentity.attempts >= 3) return;
4044
+ botIdentity.pending = true;
4045
+ botIdentity.attempts += 1;
4046
+ void call(["api", "GET", "/open-apis/bot/v3/info", "--as", "bot"]).then((info) => {
4047
+ if (typeof info?.open_id === "string") botIdentity.openId = info.open_id;
4048
+ else console.warn(`[im-forward] bot identity lookup returned no open_id (attempt ${botIdentity.attempts}); gating stays on any-mention semantics`);
4049
+ }).catch(() => console.warn(`[im-forward] bot identity lookup failed (attempt ${botIdentity.attempts}); gating stays on any-mention semantics`)).finally(() => {
4050
+ botIdentity.pending = false;
4051
+ });
4052
+ };
4053
+ const child = spawnConsume("im.message.receive_v1", (line) => {
4054
+ const event = normalizeEvent(line, botIdentity.openId);
4055
+ if (event?.chatType === "group" || event?.chatType === "p2p") resolveBotIdentity();
4056
+ return event;
4057
+ }, true);
3812
4058
  {
3813
4059
  const errors = lineReader((line) => {
3814
4060
  const text = line.trim();