@cydm/pie 4.3.11 → 4.4.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.
@@ -11,6 +11,7 @@ import {
11
11
  composeForwardBody,
12
12
  configSnapshot,
13
13
  configurationIdentity,
14
+ currentConsumer,
14
15
  estimatePostRequestBytes,
15
16
  failureReason,
16
17
  hasConfigLayers,
@@ -26,10 +27,11 @@ import {
26
27
  resolveImForwardConfig,
27
28
  saveLocation,
28
29
  sessionLabel,
30
+ signEnvelope,
29
31
  truncateMarkdown,
30
32
  tryClaimConsumer,
31
33
  writeConfig
32
- } from "../../../chunks/chunk-DGXIR6CV.js";
34
+ } from "../../../chunks/chunk-AKXEZH7K.js";
33
35
  import {
34
36
  detectImageMime,
35
37
  readImageFormat
@@ -39,7 +41,7 @@ import "../../../chunks/chunk-LZQXQOPJ.js";
39
41
  // builtin/extensions/im-forward/runtime.ts
40
42
  import * as crypto from "node:crypto";
41
43
  import * as fs6 from "node:fs";
42
- import { basename, join as pathJoin, resolve as pathResolve } from "node:path";
44
+ import { basename, join as pathJoin, resolve as pathResolve, join as join7 } from "node:path";
43
45
  import * as os3 from "node:os";
44
46
 
45
47
  // builtin/extensions/im-forward/thread-registry.ts
@@ -357,7 +359,9 @@ function parsePanelCommand(text) {
357
359
  cmd = next?.[1] ?? "";
358
360
  rest = next?.[2] ?? "";
359
361
  }
360
- if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.help" && cmd !== "\u9762\u677F") return void 0;
362
+ if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.models" && cmd !== "panel.help" && cmd !== "\u9762\u677F") {
363
+ if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd)) return void 0;
364
+ }
361
365
  const leadingFlag = /^--restricted(?:\s+|$)/.exec(rest);
362
366
  const restricted = leadingFlag !== null;
363
367
  const payloadText = rest.slice(leadingFlag ? leadingFlag[0].length : 0).trim();
@@ -379,6 +383,7 @@ function scanPeers() {
379
383
  try {
380
384
  const parsed = JSON.parse(fs2.readFileSync(path3.join(dir, file), "utf8"));
381
385
  if (typeof parsed.sessionId !== "string" || typeof parsed.pid !== "number") continue;
386
+ if (typeof parsed.instanceId !== "string" || !parsed.instanceId) continue;
382
387
  try {
383
388
  process.kill(parsed.pid, 0);
384
389
  } catch {
@@ -386,9 +391,14 @@ function scanPeers() {
386
391
  }
387
392
  out.push({
388
393
  name: parsed.displayName ?? parsed.sessionId.slice(0, 12),
394
+ instanceId: parsed.instanceId,
389
395
  sessionId: parsed.sessionId,
390
396
  state: typeof parsed.state === "string" ? parsed.state : "?",
391
- unattended: parsed.unattended === true
397
+ unattended: parsed.unattended === true,
398
+ sessionTitle: typeof parsed.displaySessionName === "string" && parsed.displaySessionName.trim() ? parsed.displaySessionName.trim() : void 0,
399
+ project: typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd.split("/").filter(Boolean).at(-1) : void 0,
400
+ currentTool: typeof parsed.currentTool === "string" && parsed.currentTool ? parsed.currentTool : void 0,
401
+ model: typeof parsed.model === "string" && parsed.model ? parsed.model : void 0
392
402
  });
393
403
  } catch {
394
404
  }
@@ -399,10 +409,16 @@ function scanPeers() {
399
409
  }
400
410
  function composePanel() {
401
411
  const peers = scanPeers();
402
- const rows = peers.map((p) => `| ${p.unattended ? "\u{1F3E0}" : "\u{1F4BB}"} ${p.name} | ${p.state} |`);
412
+ const rows = peers.map((p) => {
413
+ const title = p.sessionTitle ?? p.name;
414
+ 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} | | |`;
418
+ });
403
419
  const body = [
404
- peers.length > 0 ? `| \u4F1A\u8BDD | \u72B6\u6001 |
405
- |---|---|
420
+ peers.length > 0 ? `| \u4F1A\u8BDD | \u6A21\u578B | \u72B6\u6001 |
421
+ |---|---|---|
406
422
  ${rows.join("\n")}` : "_\u6CA1\u6709\u5B58\u6D3B\u7684 pie \u4F1A\u8BDD_",
407
423
  ``,
408
424
  `\u5171 ${peers.length} \u4E2A\u4F1A\u8BDD \xB7 ${(/* @__PURE__ */ new Date()).toLocaleTimeString("zh-CN", { hour12: false })}`
@@ -417,15 +433,53 @@ ${rows.join("\n")}` : "_\u6CA1\u6709\u5B58\u6D3B\u7684 pie \u4F1A\u8BDD_",
417
433
  actions: [
418
434
  { id: "panel.refresh", label: "\u{1F504} \u5237\u65B0" },
419
435
  { id: "panel.summon", label: "\u{1F4CB} \u91CD\u65B0\u53EC\u5524" },
436
+ { id: "panel.models", label: "\u{1F39A} \u5207\u6A21\u578B" },
420
437
  { id: "panel.help", label: "\u2753 \u547D\u4EE4" }
421
438
  ]
422
439
  };
423
440
  }
441
+ function candidateModels() {
442
+ const out = /* @__PURE__ */ new Set();
443
+ try {
444
+ const configRoot = path3.dirname(path3.dirname(ipcDiscoveryRoot()));
445
+ const config = JSON.parse(fs2.readFileSync(path3.join(configRoot, "models.json"), "utf8"));
446
+ const d = config.defaults ?? {};
447
+ if (d.provider && d.modelId) out.add(`${d.provider}/${d.modelId}`);
448
+ for (const cls of Object.values(d.modelClasses ?? {})) {
449
+ if (cls?.provider && cls?.modelId) out.add(`${cls.provider}/${cls.modelId}`);
450
+ }
451
+ } catch {
452
+ }
453
+ return [...out];
454
+ }
424
455
  function executePanelCommand(input) {
456
+ if (input.cmd === "panel.models") {
457
+ const peers = scanPeers();
458
+ const models = candidateModels();
459
+ const rows = peers.map((p) => `| ${p.sessionTitle ?? p.name} | ${p.model ?? "\u2014"} |`);
460
+ const actions = peers.flatMap(
461
+ (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
+ ).slice(0, 18);
463
+ return { spec: {
464
+ title: "\u5207\u6362\u6A21\u578B",
465
+ subtitle: `${peers.length} \u4F1A\u8BDD \xD7 ${models.length} \u5019\u9009`,
466
+ color: "violet",
467
+ body: [
468
+ peers.length > 0 ? `| \u4F1A\u8BDD | \u5F53\u524D\u6A21\u578B |
469
+ |---|---|
470
+ ${rows.join("\n")}` : "_\u6CA1\u6709\u5B58\u6D3B\u7684 pie \u4F1A\u8BDD_",
471
+ ``,
472
+ `\u5019\u9009\uFF1A${models.join(" \xB7 ") || "\uFF08models.json \u4E0D\u53EF\u8BFB\uFF09"}`,
473
+ ``,
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"
475
+ ].join("\n"),
476
+ actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F \u8FD4\u56DE\u9762\u677F" }]
477
+ }, patchOrigin: false };
478
+ }
425
479
  if (input.cmd === "panel.help") {
426
480
  return { spec: {
427
481
  title: "\u9762\u677F\u547D\u4EE4",
428
- 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\u2753 \u672C\u8BF4\u660E\u3002\u7FA4\u5185\u4EFB\u4F55\u6210\u5458\u53EF\u70B9\uFF0C`--restricted` \u52A8\u4F5C\u9700 allowUsers \u767D\u540D\u5355\u3002",
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",
429
483
  actions: [{ id: "panel.summon", label: "\u56DE\u5230\u9762\u677F" }]
430
484
  }, patchOrigin: false };
431
485
  }
@@ -487,7 +541,12 @@ function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
487
541
  createdAt: Date.now(),
488
542
  text,
489
543
  sessionId: targetSessionId,
490
- waitMs: 0
544
+ waitMs: 0,
545
+ replyTo: void 0,
546
+ notifyCompletion: void 0,
547
+ control: void 0,
548
+ userAssigned: void 0,
549
+ subscriberSession: void 0
491
550
  };
492
551
  const payload = [envelope.v, envelope.id, envelope.from, envelope.to, envelope.kind, envelope.createdAt, envelope.sessionId ?? null, envelope.text ?? null, envelope.replyTo ?? null, envelope.waitMs ?? null, envelope.notifyCompletion ?? null, envelope.control ?? null, envelope.userAssigned ?? null, envelope.subscriberSession ?? null];
493
552
  const frame = JSON.stringify({ ...envelope, auth: createHmac("sha256", secret).update(JSON.stringify(payload)).digest("hex") });
@@ -683,6 +742,71 @@ function ipcDiscoveryRoot2() {
683
742
  const configDir = process.platform === "win32" ? raw : pathResolve(raw === "~" ? home : raw.startsWith("~/") ? pathJoin(home, raw.slice(2)) : raw);
684
743
  return pathJoin(configDir, "run", "ipc");
685
744
  }
745
+ async function applyModelControl(peerRef, model) {
746
+ const net2 = await import("node:net");
747
+ let target;
748
+ try {
749
+ const dir = ipcDiscoveryRoot2();
750
+ for (const file of fs6.readdirSync(dir).filter((f) => f.endsWith(".json"))) {
751
+ const parsed = JSON.parse(fs6.readFileSync(join7(dir, file), "utf8"));
752
+ if (!parsed.port || !parsed.secret || typeof parsed.pid !== "number" || !parsed.instanceId) continue;
753
+ const match = parsed.instanceId === peerRef || parsed.instanceId.startsWith(peerRef) || parsed.displayName === peerRef;
754
+ if (!match) continue;
755
+ try {
756
+ process.kill(parsed.pid, 0);
757
+ } catch {
758
+ continue;
759
+ }
760
+ target = { port: parsed.port, secret: parsed.secret, instanceId: parsed.instanceId };
761
+ break;
762
+ }
763
+ } catch {
764
+ }
765
+ if (!target) return { ok: false, detail: `\u672A\u627E\u5230\u4F1A\u8BDD\uFF1A${peerRef}` };
766
+ const envelope = signEnvelope({
767
+ v: IPC_PROTOCOL_VERSION,
768
+ id: `panel-model-${Date.now()}`,
769
+ from: "pie-panel0000000",
770
+ to: target.instanceId,
771
+ kind: "control",
772
+ createdAt: Date.now(),
773
+ text: JSON.stringify({ control: "model.set", payload: { model } })
774
+ }, target.secret);
775
+ return await new Promise((resolve4) => {
776
+ let settled = false;
777
+ const finish = (ok, detail) => {
778
+ if (settled) return;
779
+ settled = true;
780
+ try {
781
+ sock.destroy();
782
+ } catch {
783
+ }
784
+ resolve4({ ok, detail });
785
+ };
786
+ const sock = net2.connect({ host: "127.0.0.1", port: target.port }, () => {
787
+ sock.write(JSON.stringify(envelope) + "\n");
788
+ });
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)}`));
791
+ 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");
793
+ });
794
+ sock.on("data", (buffer) => {
795
+ for (const line of buffer.toString("utf8").split("\n")) {
796
+ if (!line.trim()) continue;
797
+ try {
798
+ const parsed = JSON.parse(line);
799
+ if (parsed.kind === "ack" || parsed.kind === "result") {
800
+ 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)"}`);
802
+ return;
803
+ }
804
+ } catch {
805
+ }
806
+ }
807
+ });
808
+ });
809
+ }
686
810
  function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
687
811
  const IM_INPUT_PREFIX = connection.sourcePrefix;
688
812
  const key = (id) => JSON.stringify([cfg.provider, id]);
@@ -702,12 +826,65 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
702
826
  return forwardingEnabled;
703
827
  }
704
828
  const STATUS_KEY = "im-forward";
829
+ let dispatchMode = false;
830
+ let lastDispatchReceivedAt;
831
+ const holderAlive = () => {
832
+ if (consumerLock) return true;
833
+ try {
834
+ return currentConsumer(bindingKey()).alive;
835
+ } catch {
836
+ return false;
837
+ }
838
+ };
705
839
  function updateFooterTag() {
706
840
  ctx.ui.setStatus?.(
707
841
  STATUS_KEY,
708
- configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : consumerReady ? "[IM]" : "[IM\u2026]" : void 0
842
+ configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : busStale ? "[IM-DEGRADED:bus]" : consumerReady ? "[IM]" : dispatchMode ? dispatchStale() ? "[IM-DEGRADED:dispatch]" : "[IM]" : "[IM\u2026]" : void 0
709
843
  );
710
844
  }
845
+ const DISPATCH_GRACE_MS = 10 * 6e4;
846
+ let dispatchStaleWarned = false;
847
+ let dispatchModeEnteredAt;
848
+ const dispatchStale = () => {
849
+ if (!dispatchMode) return false;
850
+ const anchor = Math.max(lastDispatchReceivedAt ?? 0, dispatchModeEnteredAt ?? 0);
851
+ if (anchor && Date.now() - anchor < DISPATCH_GRACE_MS) return false;
852
+ return holderAlive();
853
+ };
854
+ const noteDispatchReceived = () => {
855
+ lastDispatchReceivedAt = Date.now();
856
+ if (dispatchStaleWarned) {
857
+ dispatchStaleWarned = false;
858
+ ctx.log("im-forward: dispatched events flowing again");
859
+ }
860
+ updateFooterTag();
861
+ };
862
+ let busStale = false;
863
+ const probeBusHealth = async () => {
864
+ if (terminated || !connection.consumeBusHealth) return;
865
+ try {
866
+ const health = await connection.consumeBusHealth();
867
+ if (terminated || health === void 0) return;
868
+ const next = health === "stale";
869
+ if (next !== busStale) {
870
+ busStale = next;
871
+ if (next) {
872
+ 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");
873
+ 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");
874
+ }
875
+ updateFooterTag();
876
+ }
877
+ } catch {
878
+ }
879
+ if (dispatchMode) {
880
+ const stale = dispatchStale();
881
+ if (stale && !dispatchStaleWarned) {
882
+ dispatchStaleWarned = true;
883
+ ctx.log("im-forward: consumer holder alive but no dispatched events received past grace window");
884
+ }
885
+ updateFooterTag();
886
+ }
887
+ };
711
888
  function writeEnabledToConfig(next) {
712
889
  persistEnabled(next);
713
890
  }
@@ -754,7 +931,7 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
754
931
  if (!replyAnchor.has(sessionId)) {
755
932
  const persisted = loadPersistedAnchor(sessionId, anchorIdentity);
756
933
  if (persisted) {
757
- replyAnchor.set(sessionId, persisted);
934
+ replyAnchor.set(sessionId, { messageId: persisted.messageId, threadId: persisted.threadId ?? null, at: persisted.at });
758
935
  if (persisted.threadId) {
759
936
  const restoredAt = Date.now();
760
937
  routes.set(key(persisted.messageId), {
@@ -796,6 +973,27 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
796
973
  let lastSendError;
797
974
  let lastSendErrorAt = 0;
798
975
  let lastSendFailureNotifyAt = 0;
976
+ function settleDelivery(requests, delivered) {
977
+ if (!requests || requests.size === 0) return;
978
+ for (const [id, meta] of requests) {
979
+ if (inFlightDeliveries.get(id) === meta.gen) inFlightDeliveries.delete(id);
980
+ if (delivered) {
981
+ if (meta.final) {
982
+ deliveredPrune();
983
+ deliveredRequests.set(id, Date.now());
984
+ sealedByGeneration.set(id, meta.gen);
985
+ }
986
+ } else {
987
+ if (sealedByGeneration.get(id) === meta.gen) {
988
+ unsealDeliveredRequest(id);
989
+ sealedByGeneration.delete(id);
990
+ }
991
+ }
992
+ }
993
+ }
994
+ const sealedByGeneration = /* @__PURE__ */ new Map();
995
+ const sealGenerations = /* @__PURE__ */ new Map();
996
+ const inFlightDeliveries = /* @__PURE__ */ new Map();
799
997
  function notifySendFailure(error) {
800
998
  lastSendError = error;
801
999
  lastSendErrorAt = Date.now();
@@ -893,7 +1091,9 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
893
1091
  const text = event.text?.trim() ?? "";
894
1092
  if (isManager && /^\[pie-ipc\][^\n]*says:\s*\n?\[ipc-done\] requestId=[a-zA-Z0-9:-]+ (?:outcome=\S+ )?user_assigned=true(?:\s|$)/.test(text) && currentSessionId) {
895
1093
  const requestTag = /requestId=([a-zA-Z0-9:-]+)/.exec(text)?.[1] ?? "ipc-delivery";
896
- stampDeliveryDestination(`ipc-done:${requestTag}`);
1094
+ if (!stampDeliveryDestinationDeduped(`ipc-done:${requestTag}`, void 0, true)) {
1095
+ ctx.log(`im-forward: late/duplicate wake for ${requestTag} \u2014 result already delivered; turn output stays gated`);
1096
+ }
897
1097
  }
898
1098
  if (text && !text.startsWith(IM_INPUT_PREFIX) && !text.startsWith("/") && !text.startsWith("!!") && !/@\[[^\]]+\]\(file:/.test(text) && currentSessionId) {
899
1099
  pendingInputs.push({
@@ -907,24 +1107,60 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
907
1107
  }
908
1108
  return { action: "continue" };
909
1109
  });
910
- function outboundRoleAllows(attribution) {
1110
+ function outboundRoleAllows(attribution, consumed) {
911
1111
  if (!isManager) return true;
912
1112
  if (attribution !== void 0) return true;
913
1113
  pruneDeliveryDestinations();
914
1114
  const scope = `s:${currentSessionId}:`;
915
1115
  const mine = [...deliveryDestinations.keys()].filter((tag) => tag.startsWith(scope));
916
1116
  if (mine.length > 0) {
1117
+ let allowed = false;
1118
+ for (const tag of mine) {
1119
+ if (tag.startsWith(`${scope}ipc-done:`)) {
1120
+ const id = tag.slice(`${scope}ipc-done:`.length);
1121
+ if (inFlightDeliveries.has(id)) continue;
1122
+ const final = deliveryDestinations.get(tag)?.final === true;
1123
+ const gen = (sealGenerations.get(id) ?? 0) + 1;
1124
+ sealGenerations.set(id, gen);
1125
+ inFlightDeliveries.set(id, gen);
1126
+ consumed?.set(id, { gen, final });
1127
+ allowed = true;
1128
+ }
1129
+ }
917
1130
  for (const tag of mine) deliveryDestinations.delete(tag);
918
- return true;
1131
+ return allowed;
919
1132
  }
920
1133
  return false;
921
1134
  }
922
1135
  const deliveryDestinations = /* @__PURE__ */ new Map();
923
1136
  const DELIVERY_TAG_TTL_MS = 60 * 60 * 1e3;
924
- function stampDeliveryDestination(tag, replyTo) {
1137
+ const deliveredRequests = /* @__PURE__ */ new Map();
1138
+ const DELIVERED_REQUEST_TTL_MS = 6 * 60 * 60 * 1e3;
1139
+ function deliveredPrune(now = Date.now()) {
1140
+ for (const [key2, at] of deliveredRequests) {
1141
+ if (now - at > DELIVERED_REQUEST_TTL_MS) deliveredRequests.delete(key2);
1142
+ }
1143
+ while (deliveredRequests.size > 200) {
1144
+ const oldest = [...deliveredRequests.entries()].sort((a, b) => a[1] - b[1])[0];
1145
+ deliveredRequests.delete(oldest[0]);
1146
+ }
1147
+ }
1148
+ function stampDeliveryDestinationDeduped(tag, replyTo, final) {
1149
+ if (tag.startsWith("ipc-done:")) {
1150
+ const bare = tag.slice("ipc-done:".length);
1151
+ deliveredPrune();
1152
+ if (deliveredRequests.has(bare)) return false;
1153
+ }
1154
+ stampDeliveryDestination(tag, replyTo, final);
1155
+ return true;
1156
+ }
1157
+ function unsealDeliveredRequest(requestId) {
1158
+ deliveredRequests.delete(requestId);
1159
+ }
1160
+ function stampDeliveryDestination(tag, replyTo, final) {
925
1161
  pruneDeliveryDestinations();
926
1162
  const scoped = `s:${currentSessionId}:${tag}`;
927
- deliveryDestinations.set(scoped, { at: Date.now(), ...replyTo ? { replyTo } : {} });
1163
+ deliveryDestinations.set(scoped, { at: Date.now(), ...replyTo ? { replyTo } : {}, ...final !== void 0 ? { final } : {} });
928
1164
  }
929
1165
  function pruneDeliveryDestinations() {
930
1166
  const now = Date.now();
@@ -955,8 +1191,12 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
955
1191
  const wrappedNotify = stampedWake.exec(userText);
956
1192
  if (wrappedNotify) {
957
1193
  const requestTag = /requestId=([a-zA-Z0-9:-]+)/.exec(userText)?.[1] ?? "ipc-delivery";
958
- stampDeliveryDestination(`ipc-done:${requestTag}`);
959
- ctx.log(`im-forward: delivery tag stamped (ipc-done:${requestTag}) \u2014 the woken turn may deliver`);
1194
+ const isFinal = /^\[pie-ipc\][^\n]*says:\s*\n?\[ipc-(?:done|done-check)\] /.test(userText);
1195
+ if (!stampDeliveryDestinationDeduped(`ipc-done:${requestTag}`, void 0, isFinal)) {
1196
+ ctx.log(`im-forward: late/duplicate wake for ${requestTag} \u2014 result already delivered; turn output stays gated`);
1197
+ } else {
1198
+ ctx.log(`im-forward: delivery tag stamped (ipc-done:${requestTag}${isFinal ? "" : ", progress"}) \u2014 the woken turn may deliver`);
1199
+ }
960
1200
  }
961
1201
  }
962
1202
  if (!isForwardingEnabled()) return;
@@ -969,15 +1209,17 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
969
1209
  if (!sessionId) return;
970
1210
  const sequence = ++forwardCounter;
971
1211
  const attribution = resolveOutboundAttribution(sessionId);
972
- if (!outboundRoleAllows(attribution)) return;
973
- forwardMessage(
1212
+ const deliver = /* @__PURE__ */ new Map();
1213
+ if (!outboundRoleAllows(attribution, deliver)) return;
1214
+ void forwardMessage(
974
1215
  text,
975
1216
  sessionId,
976
1217
  sequence,
977
1218
  attribution?.caption,
978
1219
  attribution?.replyTo,
979
- attribution
980
- );
1220
+ attribution,
1221
+ deliver
1222
+ ).catch(() => void 0);
981
1223
  });
982
1224
  ctx.on("turn:failed", (event) => {
983
1225
  if (!isForwardingEnabled()) return;
@@ -986,15 +1228,18 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
986
1228
  const reason = failureReason(event.message ?? {});
987
1229
  const sequence = ++forwardCounter;
988
1230
  const attribution = resolveOutboundAttribution(sessionId);
989
- if (!outboundRoleAllows(attribution)) return;
1231
+ const deliverTf = /* @__PURE__ */ new Map();
1232
+ if (!outboundRoleAllows(attribution, deliverTf)) return;
990
1233
  void forwardMessage(
991
1234
  `\u26A0\uFE0F \u4EFB\u52A1\u5931\u8D25\uFF1A${reason}`,
992
1235
  sessionId,
993
1236
  sequence,
994
1237
  attribution?.caption,
995
1238
  attribution?.replyTo,
996
- attribution
997
- );
1239
+ attribution,
1240
+ deliverTf,
1241
+ true
1242
+ ).catch(() => void 0);
998
1243
  });
999
1244
  ctx.on("turn:cancelled", (event) => {
1000
1245
  if (!isForwardingEnabled()) return;
@@ -1002,17 +1247,30 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1002
1247
  if (!sessionId) return;
1003
1248
  const sequence = ++forwardCounter;
1004
1249
  const attribution = resolveOutboundAttribution(sessionId);
1005
- if (!outboundRoleAllows(attribution)) return;
1250
+ const deliverTc = /* @__PURE__ */ new Map();
1251
+ if (!outboundRoleAllows(attribution, deliverTc)) return;
1006
1252
  void forwardMessage(
1007
1253
  `\u26D4\uFE0F \u4EFB\u52A1\u5DF2\u53D6\u6D88\uFF1A${event.reason}`,
1008
1254
  sessionId,
1009
1255
  sequence,
1010
1256
  attribution?.caption,
1011
1257
  attribution?.replyTo,
1012
- attribution
1013
- );
1258
+ attribution,
1259
+ deliverTc,
1260
+ true
1261
+ ).catch(() => void 0);
1014
1262
  });
1015
- async function forwardMessage(text, sessionId, sequence, userInput, replyTo, attribution) {
1263
+ async function forwardMessage(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice) {
1264
+ let settled = false;
1265
+ try {
1266
+ return await forwardMessageInner(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice, () => {
1267
+ settled = true;
1268
+ });
1269
+ } finally {
1270
+ if (!settled) settleDelivery(deliverRequests, false);
1271
+ }
1272
+ }
1273
+ async function forwardMessageInner(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice, markSettled) {
1016
1274
  pruneState();
1017
1275
  const sessionName = ctx.getSessionDisplayName?.() ?? ctx.getSessionName?.();
1018
1276
  const composeMode = resolveSessionAnchor(sessionId).threadId ? "topic-reply" : "topic-root";
@@ -1023,7 +1281,10 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1023
1281
  text,
1024
1282
  composeMode
1025
1283
  );
1026
- if (terminated || !isForwardingEnabled()) return;
1284
+ if (terminated || !isForwardingEnabled()) {
1285
+ settleDelivery(deliverRequests, false);
1286
+ return false;
1287
+ }
1027
1288
  const [chunks] = chunkMarkdown(composed);
1028
1289
  const baseKey = `pie-im-forward-${cfg.provider}-${incarnation}-${sessionId}-${sequence}-${hashText(composed)}`;
1029
1290
  const sessionAnchor = resolveSessionAnchor(sessionId);
@@ -1124,7 +1385,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1124
1385
  }
1125
1386
  if (!stakeFlightToken && !anchor) {
1126
1387
  ctx.log(`im-forward: fallback stake unavailable for ${sessionId}; dropping re-send`);
1127
- return;
1388
+ settleDelivery(deliverRequests, false);
1389
+ return false;
1128
1390
  }
1129
1391
  sent = await sendChunk(0);
1130
1392
  }
@@ -1133,8 +1395,12 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1133
1395
  }
1134
1396
  if (!sent) {
1135
1397
  notifySendFailure(`${cfg.provider} send failed`);
1136
- return;
1398
+ settleDelivery(deliverRequests, false);
1399
+ markSettled?.();
1400
+ return false;
1137
1401
  }
1402
+ settleDelivery(deliverRequests, true);
1403
+ markSettled?.();
1138
1404
  registerRoute(sent, sessionId);
1139
1405
  const legacyUpgrade = !isManager && anchor !== void 0 && !sessionAnchor.threadId && sent.messageId !== anchor;
1140
1406
  const stakeNeeded = stakeFlightToken !== void 0;
@@ -1204,7 +1470,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1204
1470
  }
1205
1471
  registerRoute(next, sessionId);
1206
1472
  }
1207
- if (connection.sendFile && !terminated && isForwardingEnabled()) {
1473
+ if (connection.sendFile && !terminated && isForwardingEnabled() && !systemNotice) {
1208
1474
  const files = collectFileReferences(
1209
1475
  text,
1210
1476
  ctx.cwd,
@@ -1303,6 +1569,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1303
1569
  try {
1304
1570
  const parsed = JSON.parse(trimmed.slice(DISPATCH_PREFIX.length).trim());
1305
1571
  if (!parsed.event) return false;
1572
+ if (dispatchMode) noteDispatchReceived();
1306
1573
  void handleInboundEvent(parsed.event);
1307
1574
  return true;
1308
1575
  } catch {
@@ -1383,20 +1650,103 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1383
1650
  return { kind: "delivery-failed", owner: ownerSession };
1384
1651
  }
1385
1652
  }
1653
+ const panelCardOwners = /* @__PURE__ */ new Map();
1654
+ const rememberPanelCard = (messageId, sessionId, chatId) => {
1655
+ if (!messageId) return;
1656
+ panelCardOwners.set(messageId, { sessionId, epoch: inputEpoch, chatId });
1657
+ if (panelCardOwners.size > 100) {
1658
+ const oldest = [...panelCardOwners.keys()].slice(0, Math.ceil(panelCardOwners.size / 4));
1659
+ for (const k of oldest) panelCardOwners.delete(k);
1660
+ }
1661
+ };
1662
+ const runPanelCommand = async (panelCmd, event, sessionId, isCurrent) => {
1663
+ if (!isCurrent()) return;
1664
+ const started = Date.now();
1665
+ if (panelCmd.restricted && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id))) {
1666
+ ctx.log(`im-forward: restricted panel action ${panelCmd.cmd} refused for ${event.sender_id ?? "unknown"} (not in allowUsers)`);
1667
+ try {
1668
+ 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}`);
1669
+ } catch {
1670
+ }
1671
+ return;
1672
+ }
1673
+ const modelAction = /^panel\.model\.([A-Za-z0-9-]+)\.(.+)$/.exec(panelCmd.cmd);
1674
+ if (modelAction) {
1675
+ const [, peerRef, model] = modelAction;
1676
+ const receipt = await applyModelControl(peerRef, model);
1677
+ if (!isCurrent()) return;
1678
+ const spec = {
1679
+ title: "\u5207\u6362\u7ED3\u679C",
1680
+ body: `${receipt.ok ? "\u2705" : "\u26A0\uFE0F"} ${model} \u2192 ${peerRef}
1681
+
1682
+ ${receipt.detail}`,
1683
+ actions: [{ id: "panel.models", label: "\u21A9\uFE0F \u8FD4\u56DE\u6A21\u578B\u9762\u677F" }]
1684
+ };
1685
+ try {
1686
+ if (connection.sendCard) {
1687
+ const sent = await connection.sendCard(event.chat_id, spec, `panel-model-${event.event_id}`);
1688
+ if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
1689
+ } else await connection.send(event.chat_id, `**${spec.title}**
1690
+ ${spec.body}`, `panel-model-${event.event_id}`);
1691
+ } catch {
1692
+ }
1693
+ return;
1694
+ }
1695
+ const result = executePanelCommand({ ...panelCmd, senderId: event.sender_id, originCardId: event.message_id });
1696
+ try {
1697
+ if (result.patchOrigin && connection.patch && event.message_id) {
1698
+ const ok = await connection.patch(event.message_id, result.spec);
1699
+ if (ok) {
1700
+ if (isCurrent()) rememberPanelCard(event.message_id, sessionId, event.chat_id);
1701
+ ctx.log(`im-forward: panel card patched (${panelCmd.cmd}, runtimeMs=${Date.now() - started})`);
1702
+ return;
1703
+ }
1704
+ ctx.log("im-forward: panel patch failed; falling back to a fresh card");
1705
+ }
1706
+ if (!isCurrent()) return;
1707
+ if (connection.sendCard) {
1708
+ const sent = await connection.sendCard(event.chat_id, result.spec, `panel-${event.event_id}`);
1709
+ if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
1710
+ ctx.log(`im-forward: panel card sent (${panelCmd.cmd})`);
1711
+ } else {
1712
+ await connection.send(event.chat_id, `**${result.spec.title ?? "\u9762\u677F"}**
1713
+ ${result.spec.body}`, `panel-${event.event_id}`);
1714
+ }
1715
+ } catch (error) {
1716
+ ctx.log(`im-forward: panel command failed: ${error instanceof Error ? error.message : String(error)}`);
1717
+ }
1718
+ };
1386
1719
  async function handleInboundEventInner(event, retry) {
1387
1720
  const isGroup = event.chatType === "group";
1388
1721
  if (isGroup) {
1389
- if (cfg.groupAccess === "off") return;
1390
- if (cfg.groupAccess === "allowUsers" && (!event.sender_id || !cfg.allowUsers?.includes(event.sender_id)))
1722
+ if (cfg.groupAccess === "off") {
1723
+ ctx.log("im-forward: group event refused (off)");
1391
1724
  return;
1725
+ }
1726
+ if (cfg.groupAccess === "allowUsers" && (!event.sender_id || !cfg.allowUsers?.includes(event.sender_id))) {
1727
+ ctx.log("im-forward: group event refused (allowUsers)");
1728
+ return;
1729
+ }
1392
1730
  } else {
1393
1731
  const matchesTarget = cfg.targetKind === "user" ? event.sender_id === cfg.targetId && (event.chatType === void 0 || event.chatType === "p2p") : event.chat_id === cfg.targetId || event.chatType === "p2p";
1394
1732
  if (!matchesTarget) return;
1395
1733
  }
1396
- if (!isGroup && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id)))
1734
+ if (!isGroup && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id))) {
1735
+ ctx.log("im-forward: direct event refused (allowUsers)");
1397
1736
  return;
1737
+ }
1398
1738
  const messageId = event.message_id;
1399
1739
  if (!messageId) return;
1740
+ const owner = panelCardOwners.get(messageId);
1741
+ const fastEpoch = inputEpoch;
1742
+ if (owner && owner.sessionId === currentSessionId && owner.epoch === fastEpoch && owner.chatId === event.chat_id && event.text?.startsWith("/card ")) {
1743
+ const command = parsePanelCommand(event.text);
1744
+ if (command) {
1745
+ ctx.log(`im-forward: panel fast path (${command.cmd})`);
1746
+ await runPanelCommand(command, event, owner.sessionId, () => !terminated && inputEpoch === fastEpoch && currentSessionId === owner.sessionId && isForwardingEnabled());
1747
+ return;
1748
+ }
1749
+ }
1400
1750
  const address = resolveInboundAddress(event.text);
1401
1751
  if (address.kind === "other") {
1402
1752
  ctx.log(`im-forward: message addressed to "${address.name}" (another live session); ignoring here`);
@@ -1406,6 +1756,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1406
1756
  ctx.log(`im-forward: address "${address.name}" is unresolved (${address.reason}); dropping`);
1407
1757
  return;
1408
1758
  }
1759
+ if (!currentSessionId) return;
1409
1760
  const releaseInvalidatedEvent = () => {
1410
1761
  if (event.event_id) seenEventIds.delete(key(event.event_id));
1411
1762
  };
@@ -1533,34 +1884,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1533
1884
  {
1534
1885
  const panelCmd = parsePanelCommand(caption);
1535
1886
  if (panelCmd) {
1536
- if (panelCmd.restricted && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id))) {
1537
- ctx.log(`im-forward: restricted panel action ${panelCmd.cmd} refused for ${event.sender_id ?? "unknown"} (not in allowUsers)`);
1538
- try {
1539
- 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}`);
1540
- } catch {
1541
- }
1542
- return;
1543
- }
1544
- const result = executePanelCommand({ ...panelCmd, originCardId: event.message_id });
1545
- try {
1546
- if (result.patchOrigin && connection.patch && event.message_id) {
1547
- const ok = await connection.patch(event.message_id, result.spec);
1548
- if (ok) {
1549
- ctx.log(`im-forward: panel card patched (${panelCmd.cmd})`);
1550
- return;
1551
- }
1552
- ctx.log("im-forward: panel patch failed; falling back to a fresh card");
1553
- }
1554
- if (connection.sendCard) {
1555
- await connection.sendCard(event.chat_id, result.spec, `panel-${event.event_id}`);
1556
- ctx.log(`im-forward: panel card sent (${panelCmd.cmd})`);
1557
- } else {
1558
- await connection.send(event.chat_id, `**${result.spec.title ?? "\u9762\u677F"}**
1559
- ${result.spec.body}`, `panel-${event.event_id}`);
1560
- }
1561
- } catch (error) {
1562
- ctx.log(`im-forward: panel command failed: ${error instanceof Error ? error.message : String(error)}`);
1563
- }
1887
+ await runPanelCommand(panelCmd, event, sessionId, () => scope.isCurrent());
1564
1888
  return;
1565
1889
  }
1566
1890
  }
@@ -1578,16 +1902,21 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1578
1902
  }
1579
1903
  }
1580
1904
  if (currentAfterSubmit) {
1905
+ const rejectReason = scope.lastRejectReason;
1906
+ 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"}`;
1581
1907
  ctx.ui.notify(
1582
1908
  "im-forward: message was not accepted; no input submitted.",
1583
1909
  "warning"
1584
1910
  );
1585
1911
  await forwardMessage(
1586
- `\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"}`,
1912
+ notice,
1587
1913
  route.sessionId,
1588
1914
  ++forwardCounter,
1589
1915
  caption,
1590
- messageId
1916
+ messageId,
1917
+ void 0,
1918
+ void 0,
1919
+ true
1591
1920
  );
1592
1921
  }
1593
1922
  return;
@@ -1639,7 +1968,10 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1639
1968
  boundSession ?? currentSessionId ?? "",
1640
1969
  ++forwardCounter,
1641
1970
  void 0,
1642
- event.message_id
1971
+ event.message_id,
1972
+ void 0,
1973
+ void 0,
1974
+ true
1643
1975
  );
1644
1976
  }
1645
1977
  return;
@@ -1806,12 +2138,17 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1806
2138
  if (consumerLock) return true;
1807
2139
  if (!needsCanonicalResolution()) return acquireClaimedSlot(resolveBindingKeySync());
1808
2140
  const resolved = await resolveBindingKey();
1809
- return acquireClaimedSlot(resolved);
2141
+ return resolved ? acquireClaimedSlot(resolved) : false;
1810
2142
  }
1811
2143
  function acquireClaimedSlot(binding) {
1812
2144
  if (consumerLock) return true;
1813
2145
  if (!isManager && residentAliveSomewhere()) {
1814
- ctx.log("im-forward: a live resident owns the feed class; standing down (dispatch mode)");
2146
+ if (!dispatchMode) {
2147
+ dispatchMode = true;
2148
+ dispatchModeEnteredAt = Date.now();
2149
+ ctx.log("im-forward: a live resident owns the feed class; standing down (dispatch mode)");
2150
+ updateFooterTag();
2151
+ }
1815
2152
  return false;
1816
2153
  }
1817
2154
  const claim = tryClaimConsumer(
@@ -1837,9 +2174,20 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1837
2174
  isManager ? void 0 : () => residentAliveSomewhere()
1838
2175
  );
1839
2176
  if (!claim) {
1840
- ctx.log("im-forward: another consumer owns the event-hub slot; dispatch mode");
2177
+ if (!dispatchMode) {
2178
+ dispatchMode = true;
2179
+ dispatchModeEnteredAt = Date.now();
2180
+ ctx.log("im-forward: another consumer owns the event-hub slot; dispatch mode");
2181
+ updateFooterTag();
2182
+ }
1841
2183
  return false;
1842
2184
  }
2185
+ if (dispatchMode) {
2186
+ dispatchMode = false;
2187
+ dispatchModeEnteredAt = void 0;
2188
+ ctx.log("im-forward: consumer slot acquired; leaving dispatch mode");
2189
+ updateFooterTag();
2190
+ }
1843
2191
  consumerLock = claim;
1844
2192
  return true;
1845
2193
  }
@@ -1994,9 +2342,20 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1994
2342
  };
1995
2343
  };
1996
2344
  updateFooterTag();
2345
+ const busHealthTimer = setInterval(() => {
2346
+ void probeBusHealth();
2347
+ }, 5 * 60 * 1e3);
2348
+ busHealthTimer.unref?.();
2349
+ void probeBusHealth();
2350
+ const dispatchTagTimer = setInterval(() => {
2351
+ if (dispatchMode) updateFooterTag();
2352
+ }, 3e4);
2353
+ dispatchTagTimer.unref?.();
1997
2354
  ctx.registerCleanup?.(async () => {
1998
2355
  inputEpoch++;
1999
2356
  terminated = true;
2357
+ clearInterval(busHealthTimer);
2358
+ clearInterval(dispatchTagTimer);
2000
2359
  registerDispatchReceiver(void 0);
2001
2360
  registerTurnImDriver(void 0);
2002
2361
  consumerLock?.release();
@@ -2032,6 +2391,17 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2032
2391
  ...cfg.appId ? [`- app: ${cfg.appId}`] : [],
2033
2392
  `- allowed senders: ${cfg.allowUsers?.join(", ") ?? "(anyone in target)"}`,
2034
2393
  `- consumer: ${terminated ? "stopped" : consumer ? consumerReady ? "ready" : "starting" : "idle (waits for first session)"}${consumerLastExit ? ` (last exit: ${consumerLastExit})` : ""}, restarts=${consumerRestarts}`,
2394
+ ...dispatchMode ? [
2395
+ `- dispatch mode: resident holds the feed (holder ${(() => {
2396
+ try {
2397
+ const c = currentConsumer(bindingKey());
2398
+ return c.info ? `${c.info.holder} pid=${c.info.pid} ${c.alive ? "alive" : "STALE"}` : "(no lock file)";
2399
+ } catch {
2400
+ return "(unreadable)";
2401
+ }
2402
+ })()}); this runtime receives events over pie-ipc`,
2403
+ `- last dispatched event: ${lastDispatchReceivedAt ? new Date(lastDispatchReceivedAt).toISOString() : "(none since start)"}${dispatchStale() ? " \u2014 STALE past grace window" : ""}`
2404
+ ] : [],
2035
2405
  `- routes: ${routes.size} forwarded message(s) routable (${threadRoutes.size} thread(s), ${replyAnchor.size} anchor(s))`,
2036
2406
  `- current session: ${currentSessionId ?? "(none)"}`
2037
2407
  ];
@@ -2089,7 +2459,7 @@ async function runSetup(ctx, dir, providers, signal, isCurrent = () => !signal.a
2089
2459
  ctx.ui.notify("IM forwarding setup: invalid provider settings; nothing was saved.", "error");
2090
2460
  return;
2091
2461
  }
2092
- const profile = typeof settings.larkCliProfile === "string" ? settings.larkCliProfile : void 0;
2462
+ const profile = typeof settings.larkCliProfile === "string" ? String(settings.larkCliProfile) : void 0;
2093
2463
  const profileLine = profile ? `
2094
2464
  lark-cli profile: ${String(profile)}` : "";
2095
2465
  const appLine = resolved.appId ? `
@@ -2455,7 +2825,8 @@ var COLOR_TEMPLATE = {
2455
2825
  blue: "blue",
2456
2826
  green: "green",
2457
2827
  grey: "grey",
2458
- red: "red"
2828
+ red: "red",
2829
+ violet: "violet"
2459
2830
  };
2460
2831
  function compileCard(spec) {
2461
2832
  const elements = [];
@@ -2499,7 +2870,7 @@ function compileCard(spec) {
2499
2870
  doc.header = {
2500
2871
  ...spec.title === void 0 ? {} : { title: { tag: "plain_text", content: spec.title } },
2501
2872
  ...spec.subtitle === void 0 ? {} : { subtitle: { tag: "plain_text", content: spec.subtitle } },
2502
- template: COLOR_TEMPLATE[spec.color ?? "blue"]
2873
+ template: COLOR_TEMPLATE[spec.color ?? "blue"] ?? "blue"
2503
2874
  };
2504
2875
  }
2505
2876
  return doc;
@@ -3220,26 +3591,30 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
3220
3591
  };
3221
3592
  let canonicalAppIdCache = null;
3222
3593
  let canonicalResolved = false;
3594
+ const BUS_RECONNECT_GRACE_MS = 10 * 60 * 1e3;
3595
+ async function canonicalAppIdNow() {
3596
+ if (canonicalResolved) return canonicalAppIdCache || void 0;
3597
+ if (!profile) {
3598
+ canonicalResolved = true;
3599
+ return void 0;
3600
+ }
3601
+ try {
3602
+ const result = await native(binary, ["profile", "list"], 1e4, void 0, { signal: lifetime.signal });
3603
+ const profiles = result.error ? null : parseProfiles(result.stdout);
3604
+ if (!profiles) return void 0;
3605
+ const appId = profiles.find((item) => item.name === profile)?.appId;
3606
+ if (!appId) return void 0;
3607
+ canonicalAppIdCache = appId;
3608
+ canonicalResolved = true;
3609
+ return appId;
3610
+ } catch {
3611
+ return void 0;
3612
+ }
3613
+ }
3223
3614
  return {
3224
3615
  sourcePrefix: "[Feishu]",
3225
3616
  async canonicalAppId() {
3226
- if (canonicalResolved) return canonicalAppIdCache || void 0;
3227
- if (!profile) {
3228
- canonicalResolved = true;
3229
- return void 0;
3230
- }
3231
- try {
3232
- const result = await native(binary, ["profile", "list"], 1e4, void 0, { signal: lifetime.signal });
3233
- const profiles = result.error ? null : parseProfiles(result.stdout);
3234
- if (!profiles) return void 0;
3235
- const appId = profiles.find((item) => item.name === profile)?.appId;
3236
- if (!appId) return void 0;
3237
- canonicalAppIdCache = appId;
3238
- canonicalResolved = true;
3239
- return canonicalAppIdCache;
3240
- } catch {
3241
- return void 0;
3242
- }
3617
+ return canonicalAppIdNow();
3243
3618
  },
3244
3619
  async dispose() {
3245
3620
  lifetime.abort();
@@ -3320,7 +3695,30 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
3320
3695
  let closed = false;
3321
3696
  let failed = false;
3322
3697
  let lastErrorLine = "";
3323
- const children = [];
3698
+ const children = /* @__PURE__ */ new Set();
3699
+ const optionalRespawnAttempts = /* @__PURE__ */ new Map();
3700
+ const optionalRespawnTimers = /* @__PURE__ */ new Map();
3701
+ const optionalMaps = /* @__PURE__ */ new Map();
3702
+ const scheduleOptionalRespawn = (eventKey, map) => {
3703
+ optionalMaps.set(eventKey, map);
3704
+ if (stopped) return;
3705
+ if (optionalRespawnTimers.has(eventKey)) return;
3706
+ const attempt = optionalRespawnAttempts.get(eventKey) ?? 0;
3707
+ const delay2 = Math.min(5e3 * 2 ** attempt, 12e4);
3708
+ optionalRespawnAttempts.set(eventKey, attempt + 1);
3709
+ const timer = setTimeout(() => {
3710
+ optionalRespawnTimers.delete(eventKey);
3711
+ if (stopped) return;
3712
+ try {
3713
+ const map2 = optionalMaps.get(eventKey) ?? map;
3714
+ spawnConsume(eventKey, map2, false);
3715
+ } catch {
3716
+ scheduleOptionalRespawn(eventKey, map);
3717
+ }
3718
+ }, delay2);
3719
+ timer.unref?.();
3720
+ optionalRespawnTimers.set(eventKey, timer);
3721
+ };
3324
3722
  const spawnConsume = (eventKey, map, required) => {
3325
3723
  const child2 = spawn4(binary.command, [...binary.prefix, "event", "consume", eventKey, "--as", "bot", ...profile ? ["--profile", profile] : []], { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, detached: process.platform !== "win32" });
3326
3724
  child2.stdin?.on("error", () => void 0);
@@ -3333,7 +3731,10 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
3333
3731
  const errors = lineReader((line) => {
3334
3732
  const text = line.trim();
3335
3733
  if (!text) return;
3336
- if (text.startsWith("[event] ready")) return;
3734
+ if (text.startsWith("[event] ready")) {
3735
+ if (!required) optionalRespawnAttempts.set(eventKey, 0);
3736
+ return;
3737
+ }
3337
3738
  if (safeErrorPatterns.some((pattern) => pattern.test(text)) && text.length <= 200) lastErrorLine = text;
3338
3739
  }, 4096);
3339
3740
  child2.stdout?.on("data", output.write);
@@ -3348,11 +3749,17 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
3348
3749
  fail(`Feishu consumer code=${code} signal=${signal} (${eventKey})`);
3349
3750
  });
3350
3751
  } else {
3351
- child2.on("error", () => void 0);
3352
- child2.on("exit", () => void 0);
3353
- child2.on("close", () => void 0);
3752
+ let ended = false;
3753
+ const endedOnce = () => {
3754
+ if (ended) return;
3755
+ ended = true;
3756
+ if (!stopped && !closed && !failed) scheduleOptionalRespawn(eventKey, map);
3757
+ };
3758
+ child2.on("error", endedOnce);
3759
+ child2.on("close", endedOnce);
3354
3760
  }
3355
- children.push(child2);
3761
+ children.add(child2);
3762
+ child2.once("close", () => children.delete(child2));
3356
3763
  return child2;
3357
3764
  };
3358
3765
  const safeErrorPatterns = [
@@ -3400,6 +3807,7 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
3400
3807
  const ev = normalizeCardAction(line);
3401
3808
  if (!ev) return null;
3402
3809
  void resolveChatType(ev.chat_id).then((t) => {
3810
+ if (stopped || closed || failed) return;
3403
3811
  if (t) ev.chatType = t;
3404
3812
  callbacks.event(ev);
3405
3813
  });
@@ -3413,11 +3821,55 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
3413
3821
  }
3414
3822
  return { async stop() {
3415
3823
  stopped = true;
3416
- await Promise.allSettled(children.map((child2) => shutdownConsumer(child2)));
3824
+ for (const timer of optionalRespawnTimers.values()) clearTimeout(timer);
3825
+ optionalRespawnTimers.clear();
3826
+ await Promise.allSettled([...children].map((child2) => shutdownConsumer(child2)));
3417
3827
  } };
3828
+ },
3829
+ // 4.3.14 bus health: read the shared daemon's log tail and decide whether
3830
+ // the CLOUD websocket looks dead. Signal: the LAST `[SDK] disconnected`
3831
+ // line older than the reconnect grace with no newer connect (measured:
3832
+ // healthy reconnects land within ~2min; the aged 11h case stayed
3833
+ // disconnected until a manual `event stop --force`). Missing/unparsed log
3834
+ // = undefined (no signal, not an alarm) — escalate only on a POSITIVE
3835
+ // stale reading.
3836
+ async consumeBusHealth() {
3837
+ const appId = await canonicalAppIdNow();
3838
+ if (!appId) return void 0;
3839
+ const larkHome = process.env.PIE_LARK_CLI_HOME && process.env.PIE_LARK_CLI_HOME.trim() ? process.env.PIE_LARK_CLI_HOME : os4.homedir();
3840
+ const logPath = path11.join(larkHome, ".lark-cli", "events", appId, "bus.log");
3841
+ let tail;
3842
+ try {
3843
+ const fd = fs9.openSync(logPath, "r");
3844
+ try {
3845
+ const size = fs9.fstatSync(fd).size;
3846
+ const start = Math.max(0, size - 64 * 1024);
3847
+ const buf = Buffer.alloc(size - start);
3848
+ fs9.readSync(fd, buf, 0, buf.length, start);
3849
+ tail = buf.toString("utf8");
3850
+ } finally {
3851
+ fs9.closeSync(fd);
3852
+ }
3853
+ } catch {
3854
+ return void 0;
3855
+ }
3856
+ return parseBusHealth(tail, Date.now(), BUS_RECONNECT_GRACE_MS);
3418
3857
  }
3419
3858
  };
3420
3859
  }
3860
+ function parseBusHealth(tail, now, graceMs = 10 * 6e4) {
3861
+ const lines = tail.split("\n");
3862
+ for (let i = lines.length - 1; i >= 0; i--) {
3863
+ const line = lines[i];
3864
+ const m = /^(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2}) \[SDK\] (connected|disconnected) to /.exec(line);
3865
+ if (!m) continue;
3866
+ const when = new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]).getTime();
3867
+ if (!Number.isFinite(when)) return void 0;
3868
+ if (m[7] === "connected") return "ok";
3869
+ return now - when > graceMs ? "stale" : void 0;
3870
+ }
3871
+ return void 0;
3872
+ }
3421
3873
  var feishuProvider = {
3422
3874
  id: "feishu",
3423
3875
  label: "Feishu (Lark)",