@cydm/pie 2.8.1 → 4.0.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 (42) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +8 -4
  2. package/dist/builtin/extensions/changelog/index.js +2 -2
  3. package/dist/builtin/extensions/cron/index.js +295 -33
  4. package/dist/builtin/extensions/document-attachments/index.js +1 -1
  5. package/dist/builtin/extensions/herdr-agent-state/index.js +2 -2
  6. package/dist/builtin/extensions/im-forward/README.md +20 -5
  7. package/dist/builtin/extensions/im-forward/index.js +415 -142
  8. package/dist/builtin/extensions/memory/index.js +83 -30
  9. package/dist/builtin/extensions/pie-ipc/README.md +2 -2
  10. package/dist/builtin/extensions/pie-ipc/index.js +269 -30
  11. package/dist/builtin/extensions/pie-proc/README.md +93 -0
  12. package/dist/builtin/extensions/pie-proc/index.js +630 -0
  13. package/dist/builtin/extensions/pie-proc/package.json +11 -0
  14. package/dist/builtin/extensions/plan-mode/index.js +4 -4
  15. package/dist/builtin/extensions/subagent/index.js +6 -6
  16. package/dist/builtin/extensions/todo/index.js +4 -4
  17. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +106 -2
  18. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-cli.js +1 -0
  19. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  20. package/dist/builtin/skills/chrome-devtools-axi/{chunk-BNSAEVRT.js → chunk-WOGAQ4P5.js} +2 -2
  21. package/dist/builtin/skills/chrome-devtools-axi/{cli-AO2ZTPRM.js → cli-CHC7XYFU.js} +27 -3
  22. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +2 -2
  23. package/dist/builtin/skills/computer-use-axi/computer-use-axi-cli.js +1 -0
  24. package/dist/builtin/skills/computer-use-axi/scripts/setup-helper.mjs +6 -2
  25. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +179 -9
  26. package/dist/chunks/{chunk-PK72LVWQ.js → chunk-FDLLNPIE.js} +143 -53
  27. package/dist/chunks/{chunk-3BC5KGDQ.js → chunk-JQRZLVPY.js} +12 -1
  28. package/dist/chunks/{chunk-GH4VW2OT.js → chunk-NCP264ZE.js} +8 -2
  29. package/dist/chunks/{chunk-YRR6C43W.js → chunk-QX6WS73C.js} +1 -1
  30. package/dist/chunks/{chunk-3NHP7HK5.js → chunk-TDKNKNPL.js} +6 -5
  31. package/dist/chunks/{chunk-GDIYSMTS.js → chunk-UOZHQ73X.js} +25 -17
  32. package/dist/chunks/{chunk-RSL7E4R7.js → chunk-WK4N5HT5.js} +66 -23
  33. package/dist/chunks/chunk-X6LBWHK3.js +37 -0
  34. package/dist/chunks/concierge-cli-PIOGXKDR.js +939 -0
  35. package/dist/chunks/{model-registry-LI5THXV4.js → model-registry-YA6U366L.js} +2 -2
  36. package/dist/chunks/{src-BPSQMSSC.js → src-AB7PLORG.js} +6 -4
  37. package/dist/chunks/{src-YG5M2H44.js → src-ODLT57PQ.js} +2 -2
  38. package/dist/chunks/{src-66XSMIAM.js → src-XSLD2IQ2.js} +1 -1
  39. package/dist/chunks/{src-OPPYTPWG.js → src-ZZZO4HSR.js} +11 -3
  40. package/dist/chunks/{test-stream-JBWXKOQA.js → test-stream-GIUD5JWS.js} +1 -1
  41. package/dist/cli.js +1433 -235
  42. package/package.json +105 -105
@@ -117,7 +117,26 @@ function scanFenceLines(text) {
117
117
  const openedBy = [];
118
118
  const closedBy = [];
119
119
  let open = null;
120
- for (const line of lines) {
120
+ let listIndent = 0;
121
+ const expandLeadingTabs = (value) => {
122
+ const match = /^([ \t]+)/.exec(value);
123
+ if (!match || !match[1].includes(" ")) return value;
124
+ let column = 0;
125
+ for (const ch of match[1]) column = ch === " " ? Math.ceil((column + 1) / 4) * 4 : column + 1;
126
+ return " ".repeat(column) + value.slice(match[0].length);
127
+ };
128
+ for (let i = 0; i < lines.length; i++) {
129
+ const source = lines[i].replace(/^(?: {0,3}> ?)+/, "");
130
+ let line = expandLeadingTabs(source);
131
+ const marker = !open && /^( {0,3})(?:[-*+]|\d{1,9}[.)])(?:\t| {1,4})(?=\S)/.exec(line);
132
+ if (marker) {
133
+ listIndent = marker[0].length;
134
+ line = line.slice(listIndent);
135
+ } else if (listIndent && line.startsWith(" ".repeat(listIndent))) {
136
+ line = line.slice(listIndent);
137
+ } else if (line.trim() && !open) {
138
+ listIndent = 0;
139
+ }
121
140
  stateAtLineStart.push(open);
122
141
  let opened = null;
123
142
  let closed = null;
@@ -134,6 +153,21 @@ function scanFenceLines(text) {
134
153
  open = null;
135
154
  }
136
155
  }
156
+ const dedentColumns = expandLeadingTabs(source).length - line.length;
157
+ const rawDedent = (raw, columns) => {
158
+ if (columns <= 0) return raw;
159
+ if (!raw.includes(" ")) return raw.slice(columns);
160
+ let column = 0, index = 0;
161
+ while (index < raw.length && column < columns) {
162
+ const ch = raw[index];
163
+ const next = ch === " " ? Math.ceil((column + 1) / 4) * 4 : column + 1;
164
+ if (ch === " " && next > columns) break;
165
+ column = next;
166
+ index++;
167
+ }
168
+ return raw.slice(index);
169
+ };
170
+ lines[i] = stateAtLineStart[i] || opened ? rawDedent(source, dedentColumns) : source;
137
171
  openedBy.push(opened);
138
172
  closedBy.push(closed);
139
173
  stateAtLineEnd.push(open);
@@ -268,11 +302,21 @@ function collectFileReferences(text, cwd, fsStat, options) {
268
302
  const maxBytes = options?.maxBytes ?? MAX_ATTACHMENT_BYTES;
269
303
  const canonicalRoot = options?.canonicalize ? options.canonicalize(cwd) : cwd;
270
304
  if (canonicalRoot === null) return [];
271
- const rootPrefix = canonicalRoot.endsWith("/") ? canonicalRoot : canonicalRoot + "/";
305
+ const rootSegments = canonicalRoot.split(/[\\/]+/).filter((segment) => segment.length > 0);
306
+ const driveRoot = /^[A-Za-z]:$/.test(rootSegments[0] ?? "");
307
+ const isInsideRoot = (candidate) => {
308
+ if (candidate === canonicalRoot) return true;
309
+ const segments = candidate.split(/[\\/]+/).filter((segment) => segment.length > 0);
310
+ if (segments.length <= rootSegments.length) return false;
311
+ for (let index = 0; index < rootSegments.length; index++) {
312
+ const a = rootSegments[index], b = segments[index];
313
+ if (driveRoot ? a.toLowerCase() !== b.toLowerCase() : a !== b) return false;
314
+ }
315
+ return true;
316
+ };
272
317
  const seen = /* @__PURE__ */ new Set();
273
318
  const results = [];
274
- const normalized = text.split("\n").map((line) => line.replace(/^(?: {0,3}> ?)+/, ""));
275
- const scan = scanFenceLines(normalized.join("\n"));
319
+ const scan = scanFenceLines(text);
276
320
  let outside = "";
277
321
  const indentColumns = (line) => {
278
322
  let column = 0;
@@ -309,7 +353,7 @@ function collectFileReferences(text, cwd, fsStat, options) {
309
353
  if (!stat || !stat.isFile || stat.size > maxBytes || stat.size === 0) continue;
310
354
  const canonical = options?.canonicalize ? options.canonicalize(absolute) : absolute;
311
355
  if (canonical === null) continue;
312
- if (canonical !== canonicalRoot && !canonical.startsWith(rootPrefix)) continue;
356
+ if (!isInsideRoot(canonical)) continue;
313
357
  if (seen.has(canonical)) continue;
314
358
  seen.add(absolute);
315
359
  seen.add(canonical);
@@ -318,13 +362,14 @@ function collectFileReferences(text, cwd, fsStat, options) {
318
362
  return results;
319
363
  }
320
364
  function nodePathResolve(cwd, relative) {
365
+ const separator = cwd.includes("\\") && !cwd.includes("/") ? "\\" : "/";
321
366
  const normalized = relative.split("/").filter((part) => part.length > 0);
322
- const base = cwd.replace(/\/$/, "").split("/");
367
+ const base = cwd.replace(/[\\/]$/, "").split(/[\\/]/);
323
368
  for (const part of normalized) {
324
369
  if (part === ".") continue;
325
370
  base.push(part);
326
371
  }
327
- return base.join("/");
372
+ return base.join(separator);
328
373
  }
329
374
  function failureReason(message) {
330
375
  const detail = message.errorMessage?.trim();
@@ -509,7 +554,9 @@ function resolveImForwardConfig(cwd, dir) {
509
554
  }
510
555
 
511
556
  // builtin/extensions/im-forward/runtime.ts
557
+ import * as crypto from "node:crypto";
512
558
  import * as fs2 from "node:fs";
559
+ import { basename } from "node:path";
513
560
  var ROUTE_TTL_MS = 24 * 60 * 60 * 1e3;
514
561
  var MAX_ROUTES = 500;
515
562
  var MAX_SEEN_EVENTS = 1e3;
@@ -526,11 +573,19 @@ var PENDING_IM_INPUT_TTL_MS = 60 * 60 * 1e3;
526
573
  function summarizeFailureReason(reason) {
527
574
  if (!reason) return { summary: "", persistent: false };
528
575
  const text = reason.toLowerCase();
529
- if (/another event bus|already connected/.test(text)) return { summary: "the app's event connection is occupied by another instance (possibly another machine); run /tools/im-forward setup with another app/profile, or stop the other consumer", persistent: true };
530
- if (/no active profile|not configured/.test(text)) return { summary: "provider not configured", persistent: false };
531
- if (/auth|unauthorized|token|credential|login/.test(text)) return { summary: "authentication problem", persistent: false };
532
- if (/permission|forbidden|scope/.test(text)) return { summary: "permission problem", persistent: false };
533
- if (/network|dns|connect|timeout|unreachable/.test(text)) return { summary: "network problem", persistent: false };
576
+ if (/another event bus|already connected/.test(text))
577
+ return {
578
+ summary: "the app's event connection is occupied by another instance (possibly another machine); run /tools/im-forward setup with another app/profile, or stop the other consumer",
579
+ persistent: true
580
+ };
581
+ if (/no active profile|not configured/.test(text))
582
+ return { summary: "provider not configured", persistent: false };
583
+ if (/auth|unauthorized|token|credential|login/.test(text))
584
+ return { summary: "authentication problem", persistent: false };
585
+ if (/permission|forbidden|scope/.test(text))
586
+ return { summary: "permission problem", persistent: false };
587
+ if (/network|dns|connect|timeout|unreachable/.test(text))
588
+ return { summary: "network problem", persistent: false };
534
589
  return { summary: "provider exited", persistent: false };
535
590
  }
536
591
  var IM_INPUT_FALLBACK_CAPTION = "\u8BF7\u67E5\u770B\u8FD9\u4E9B\u56FE\u7247\u5E76\u5904\u7406\u3002";
@@ -560,7 +615,10 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
560
615
  }
561
616
  const STATUS_KEY = "im-forward";
562
617
  function updateFooterTag() {
563
- ctx.ui.setStatus?.(STATUS_KEY, configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : consumerReady ? "[IM]" : "[IM\u2026]" : void 0);
618
+ ctx.ui.setStatus?.(
619
+ STATUS_KEY,
620
+ configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : consumerReady ? "[IM]" : "[IM\u2026]" : void 0
621
+ );
564
622
  }
565
623
  function writeEnabledToConfig(next) {
566
624
  persistEnabled(next);
@@ -572,7 +630,10 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
572
630
  try {
573
631
  writeEnabledToConfig(!forwardingEnabled);
574
632
  } catch {
575
- ctx.ui.notify("IM forwarding: could not save configuration; state unchanged.", "error");
633
+ ctx.ui.notify(
634
+ "IM forwarding: could not save configuration; state unchanged.",
635
+ "error"
636
+ );
576
637
  return;
577
638
  }
578
639
  forwardingEnabled = !forwardingEnabled;
@@ -598,9 +659,11 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
598
659
  const replyAnchor = /* @__PURE__ */ new Map();
599
660
  const routes = /* @__PURE__ */ new Map();
600
661
  const threadRoutes = /* @__PURE__ */ new Map();
662
+ let hasForwarded = false;
601
663
  const seenEventIds = /* @__PURE__ */ new Map();
602
664
  const retryTimers = /* @__PURE__ */ new Map();
603
665
  let forwardCounter = 0;
666
+ const incarnation = crypto.randomUUID();
604
667
  let anchorFallbacks = 0;
605
668
  let lastSendError;
606
669
  let lastSendErrorAt = 0;
@@ -626,7 +689,8 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
626
689
  if (route.threadId) threadRoutes.delete(key(route.threadId));
627
690
  removeThreadAliasesOf(route);
628
691
  const anchor = replyAnchor.get(route.sessionId);
629
- if (anchor && key(anchor.messageId) === id) replyAnchor.delete(route.sessionId);
692
+ if (anchor && key(anchor.messageId) === id)
693
+ replyAnchor.delete(route.sessionId);
630
694
  }
631
695
  }
632
696
  while (routes.size > MAX_ROUTES) {
@@ -640,7 +704,8 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
640
704
  removeThreadAliasesOf(oldest);
641
705
  }
642
706
  const cutoff = now - PENDING_IM_INPUT_TTL_MS;
643
- while (pendingInputs.length && pendingInputs[0].at <= cutoff) pendingInputs.shift();
707
+ while (pendingInputs.length && pendingInputs[0].at <= cutoff)
708
+ pendingInputs.shift();
644
709
  while (pendingInputs.length > MAX_PENDING_IM_INPUTS) pendingInputs.shift();
645
710
  for (const [eventId, at] of seenEventIds) {
646
711
  if (now - at > ROUTE_TTL_MS) seenEventIds.delete(eventId);
@@ -660,7 +725,9 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
660
725
  for (let i = messages.length - 1; i >= 0; i--) {
661
726
  const message = messages[i];
662
727
  if (!isRecord(message) || message.role !== "user") continue;
663
- const joined = (typeof message.content === "string" ? message.content : Array.isArray(message.content) ? message.content.map((block) => isRecord(block) && typeof block.text === "string" ? block.text : "").join("") : "").trim();
728
+ const joined = (typeof message.content === "string" ? message.content : Array.isArray(message.content) ? message.content.map(
729
+ (block) => isRecord(block) && typeof block.text === "string" ? block.text : ""
730
+ ).join("") : "").trim();
664
731
  if (joined) {
665
732
  lastUserText = joined;
666
733
  break;
@@ -674,7 +741,11 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
674
741
  ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
675
742
  if (lastUserText === expected) {
676
743
  pendingInputs.splice(j, 1);
677
- return { caption: pending.caption || `${IM_INPUT_PREFIX} images`, replyTo: pending.messageId || void 0, threadId: pending.threadId };
744
+ return {
745
+ caption: pending.caption || `${IM_INPUT_PREFIX} images`,
746
+ replyTo: pending.messageId || void 0,
747
+ threadId: pending.threadId
748
+ };
678
749
  }
679
750
  }
680
751
  return void 0;
@@ -693,7 +764,13 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
693
764
  ctx.on("terminal:input", (event) => {
694
765
  const text = event.text?.trim() ?? "";
695
766
  if (text && !text.startsWith(IM_INPUT_PREFIX) && !text.startsWith("/") && !text.startsWith("!!") && !/@\[[^\]]+\]\(file:/.test(text) && currentSessionId) {
696
- pendingInputs.push({ sessionId: currentSessionId, caption: text, messageId: "", threadId: null, at: Date.now() });
767
+ pendingInputs.push({
768
+ sessionId: currentSessionId,
769
+ caption: text,
770
+ messageId: "",
771
+ threadId: null,
772
+ at: Date.now()
773
+ });
697
774
  pruneState();
698
775
  }
699
776
  return { action: "continue" };
@@ -709,7 +786,13 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
709
786
  if (!sessionId) return;
710
787
  const sequence = ++forwardCounter;
711
788
  const attribution = resolveOutboundAttribution(sessionId);
712
- void forwardMessage(text, sessionId, sequence, attribution?.caption, attribution?.replyTo);
789
+ void forwardMessage(
790
+ text,
791
+ sessionId,
792
+ sequence,
793
+ attribution?.caption,
794
+ attribution?.replyTo
795
+ );
713
796
  });
714
797
  ctx.on("turn:failed", (event) => {
715
798
  if (!isForwardingEnabled()) return;
@@ -718,7 +801,13 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
718
801
  const reason = failureReason(event.message ?? {});
719
802
  const sequence = ++forwardCounter;
720
803
  const attribution = resolveOutboundAttribution(sessionId);
721
- void forwardMessage(`\u26A0\uFE0F \u4EFB\u52A1\u5931\u8D25\uFF1A${reason}`, sessionId, sequence, attribution?.caption, attribution?.replyTo);
804
+ void forwardMessage(
805
+ `\u26A0\uFE0F \u4EFB\u52A1\u5931\u8D25\uFF1A${reason}`,
806
+ sessionId,
807
+ sequence,
808
+ attribution?.caption,
809
+ attribution?.replyTo
810
+ );
722
811
  });
723
812
  ctx.on("turn:cancelled", (event) => {
724
813
  if (!isForwardingEnabled()) return;
@@ -726,23 +815,38 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
726
815
  if (!sessionId) return;
727
816
  const sequence = ++forwardCounter;
728
817
  const attribution = resolveOutboundAttribution(sessionId);
729
- void forwardMessage(`\u26D4\uFE0F \u4EFB\u52A1\u5DF2\u53D6\u6D88\uFF1A${event.reason}`, sessionId, sequence, attribution?.caption, attribution?.replyTo);
818
+ void forwardMessage(
819
+ `\u26D4\uFE0F \u4EFB\u52A1\u5DF2\u53D6\u6D88\uFF1A${event.reason}`,
820
+ sessionId,
821
+ sequence,
822
+ attribution?.caption,
823
+ attribution?.replyTo
824
+ );
730
825
  });
731
826
  async function forwardMessage(text, sessionId, sequence, userInput, replyTo) {
732
827
  pruneState();
733
828
  const sessionName = ctx.getSessionName?.();
734
- const composed = composeForwardBody(sessionId, sessionName, userInput, text);
829
+ const composed = composeForwardBody(
830
+ sessionId,
831
+ sessionName,
832
+ userInput,
833
+ text
834
+ );
735
835
  if (terminated || !isForwardingEnabled()) return;
736
836
  const [chunks] = chunkMarkdown(composed);
737
- const baseKey = `pie-im-forward-${cfg.provider}-${sessionId}-${sequence}-${hashText(composed)}`;
837
+ const baseKey = `pie-im-forward-${cfg.provider}-${incarnation}-${sessionId}-${sequence}-${hashText(composed)}`;
738
838
  let anchor = replyTo ?? replyAnchor.get(sessionId)?.messageId;
739
839
  const sendChunk = async (index) => {
740
840
  const key2 = chunkKey(baseKey, index);
741
- return providerCall("send", () => connection.send(cfg.targetId, chunks[index], key2, anchor));
841
+ return providerCall(
842
+ "send",
843
+ () => connection.send(cfg.targetId, chunks[index], key2, anchor)
844
+ );
742
845
  };
743
846
  let sent = await sendChunk(0);
744
847
  if (!sent && anchor && !terminated && isForwardingEnabled()) {
745
- if (replyAnchor.get(sessionId)?.messageId === anchor) replyAnchor.delete(sessionId);
848
+ if (replyAnchor.get(sessionId)?.messageId === anchor)
849
+ replyAnchor.delete(sessionId);
746
850
  anchorFallbacks++;
747
851
  anchor = void 0;
748
852
  sent = await sendChunk(0);
@@ -763,43 +867,89 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
763
867
  if (!next && (terminated || !isForwardingEnabled())) return;
764
868
  }
765
869
  if (!next) {
766
- notifySendFailure(`${cfg.provider} send failed (part ${index + 1}/${chunks.length})`);
767
- void providerCall("send notice", () => connection.send(cfg.targetId, `\u2026(\u7B2C ${index}/${chunks.length} \u6BB5\u4E4B\u540E\u7684\u5206\u6BB5\u53D1\u9001\u5931\u8D25\uFF0C\u5B8C\u6574\u5185\u5BB9\u89C1\u7EC8\u7AEF)`, chunkKey(baseKey, index, "fail"), anchor));
870
+ notifySendFailure(
871
+ `${cfg.provider} send failed (part ${index + 1}/${chunks.length})`
872
+ );
873
+ void providerCall(
874
+ "send notice",
875
+ () => connection.send(
876
+ cfg.targetId,
877
+ `\u2026(\u7B2C ${index}/${chunks.length} \u6BB5\u4E4B\u540E\u7684\u5206\u6BB5\u53D1\u9001\u5931\u8D25\uFF0C\u5B8C\u6574\u5185\u5BB9\u89C1\u7EC8\u7AEF)`,
878
+ chunkKey(baseKey, index, "fail"),
879
+ anchor
880
+ )
881
+ );
768
882
  return;
769
883
  }
770
884
  registerRoute(next, sessionId);
771
885
  }
772
886
  if (connection.sendFile && !terminated && isForwardingEnabled()) {
773
- const files = collectFileReferences(text, ctx.cwd, (path7) => {
774
- try {
775
- const stat = fs2.statSync(path7);
776
- return { isFile: stat.isFile(), size: stat.size };
777
- } catch {
778
- return null;
779
- }
780
- }, { canonicalize: (path7) => {
781
- try {
782
- return fs2.realpathSync(path7);
783
- } catch {
784
- return null;
887
+ const files = collectFileReferences(
888
+ text,
889
+ ctx.cwd,
890
+ (path7) => {
891
+ try {
892
+ const stat = fs2.statSync(path7);
893
+ return { isFile: stat.isFile(), size: stat.size };
894
+ } catch {
895
+ return null;
896
+ }
897
+ },
898
+ {
899
+ canonicalize: (path7) => {
900
+ try {
901
+ return fs2.realpathSync(path7);
902
+ } catch {
903
+ return null;
904
+ }
905
+ }
785
906
  }
786
- } });
907
+ );
908
+ const failedFiles = [];
787
909
  for (const [index, file] of files.entries()) {
788
910
  if (terminated || !isForwardingEnabled()) return;
789
- const attachment = await providerCall("send file", () => connection.sendFile(cfg.targetId, file, chunkKey(baseKey, index, "file"), anchor));
911
+ const attachment = await providerCall(
912
+ "send file",
913
+ () => connection.sendFile(
914
+ cfg.targetId,
915
+ file,
916
+ chunkKey(baseKey, index, "file"),
917
+ anchor
918
+ )
919
+ );
790
920
  if (attachment) {
791
921
  registerRoute(attachment, sessionId);
792
922
  ctx.log(`im-forward: attached ${file}`);
793
923
  } else if (!terminated && isForwardingEnabled()) {
794
924
  ctx.log(`im-forward: attachment upload failed: ${file}`);
925
+ failedFiles.push(basename(file));
795
926
  }
796
927
  }
928
+ if (failedFiles.length > 0 && !terminated && isForwardingEnabled()) {
929
+ const names = failedFiles.slice(0, 5).map((name) => name.replace(/[\r\n]/g, " ").slice(0, 80)).join("\u3001");
930
+ const extra = failedFiles.length > 5 ? `\uFF08\u53E6 ${failedFiles.length - 5} \u4E2A\uFF09` : "";
931
+ await providerCall(
932
+ "send attachment notice",
933
+ () => connection.send(
934
+ cfg.targetId,
935
+ `\u9644\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF1A${names}${extra}\u3002\u8BF7\u5728\u7EC8\u7AEF\u67E5\u770B\u6587\u4EF6\u3002`,
936
+ chunkKey(baseKey, files.length, "fail"),
937
+ anchor
938
+ )
939
+ );
940
+ }
797
941
  }
798
942
  }
799
943
  function registerRoute(sent, sessionId) {
800
- const route = { messageId: sent.messageId, threadId: sent.threadId, sessionId, sentAt: Date.now() };
944
+ const route = {
945
+ messageId: sent.messageId,
946
+ threadId: sent.threadId,
947
+ sessionId,
948
+ sentAt: Date.now()
949
+ };
801
950
  routes.set(key(sent.messageId), route);
802
951
  if (sent.threadId) threadRoutes.set(key(sent.threadId), route);
952
+ hasForwarded = true;
803
953
  ctx.log(`im-forward: forwarded session=${sessionId} as ${sent.messageId}`);
804
954
  }
805
955
  ctx.on("session:changed", (event) => {
@@ -820,7 +970,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
820
970
  if (!isForwardingEnabled()) {
821
971
  if (!viaRetry) return;
822
972
  }
823
- if (!retrySessionIds.has(eventId) && currentSessionId) retrySessionIds.set(eventId, currentSessionId);
973
+ if (!retrySessionIds.has(eventId) && currentSessionId)
974
+ retrySessionIds.set(eventId, currentSessionId);
824
975
  seenEventIds.set(eventId, Date.now());
825
976
  pruneState();
826
977
  let scheduledNextRetry = false;
@@ -854,14 +1005,17 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
854
1005
  function parseSessionAddress(text) {
855
1006
  const name = ctx.getSessionName?.()?.trim();
856
1007
  if (!name) return { kind: "absent" };
857
- const own = new RegExp(`^${escapeRegExp(name)}:[ \\t]+(.+)$`, "s").exec(text.trim());
1008
+ const own = new RegExp(`^${escapeRegExp(name)}:[ \\t]+(.+)$`, "s").exec(
1009
+ text.trim()
1010
+ );
858
1011
  if (own) return { kind: "addressed", body: own[1] };
859
1012
  return { kind: "absent" };
860
1013
  }
861
1014
  async function handleInboundEventInner(event, retry) {
862
1015
  const matchesTarget = cfg.targetKind === "user" ? event.sender_id === cfg.targetId && (event.chatType === void 0 || event.chatType === "p2p") : event.chat_id === cfg.targetId;
863
1016
  if (!matchesTarget) return;
864
- if (cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id))) return;
1017
+ if (cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id)))
1018
+ return;
865
1019
  const messageId = event.message_id;
866
1020
  if (!messageId) return;
867
1021
  const releaseInvalidatedEvent = () => {
@@ -869,7 +1023,9 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
869
1023
  };
870
1024
  const sessionId = currentSessionId;
871
1025
  const epoch = inputEpoch;
872
- const scope = ctx.beginUserInput?.(() => !terminated && inputEpoch === epoch && currentSessionId === sessionId && isForwardingEnabled());
1026
+ const scope = ctx.beginUserInput?.(
1027
+ () => !terminated && inputEpoch === epoch && currentSessionId === sessionId && isForwardingEnabled()
1028
+ );
873
1029
  if (!scope) {
874
1030
  retry();
875
1031
  return;
@@ -886,10 +1042,46 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
886
1042
  return;
887
1043
  }
888
1044
  const address = parseSessionAddress(event.text);
889
- const resolution = address.kind === "addressed" ? { found: { messageId: "", threadId: meta.threadId ?? null, sessionId, sentAt: Date.now() } } : await resolveRouteForInbound(messageId, meta);
1045
+ const resolution = address.kind === "addressed" ? {
1046
+ found: {
1047
+ messageId: "",
1048
+ threadId: meta.threadId ?? null,
1049
+ sessionId,
1050
+ sentAt: Date.now()
1051
+ }
1052
+ } : await resolveRouteForInbound(messageId, meta);
890
1053
  if (!("found" in resolution)) {
891
- if (isTransient(resolution)) retry();
892
- else ctx.log(`im-forward: no route for ${messageId}; ignoring`);
1054
+ if (isTransient(resolution)) {
1055
+ retry();
1056
+ return;
1057
+ }
1058
+ if (routes.size === 0 && threadRoutes.size === 0 && !hasForwarded) {
1059
+ const firstSeenSession = event.event_id ? retrySessionIds.get(key(event.event_id)) : void 0;
1060
+ if (firstSeenSession !== void 0 && firstSeenSession !== sessionId) {
1061
+ ctx.log(`im-forward: cold-start retry crossed a session switch (${firstSeenSession} -> ${sessionId}); releasing for redelivery`);
1062
+ releaseInvalidatedEvent();
1063
+ return;
1064
+ }
1065
+ const bootstrapRoute = {
1066
+ messageId: "",
1067
+ threadId: meta.threadId ?? null,
1068
+ sessionId,
1069
+ sentAt: Date.now()
1070
+ };
1071
+ ctx.log(
1072
+ `im-forward: cold-start route bound to session ${sessionId} (first message in target conversation)`
1073
+ );
1074
+ await acceptRoutedMessage(
1075
+ bootstrapRoute,
1076
+ event,
1077
+ meta,
1078
+ scope,
1079
+ address,
1080
+ sessionId
1081
+ );
1082
+ return;
1083
+ }
1084
+ ctx.log(`im-forward: no route for ${messageId}; ignoring`);
893
1085
  return;
894
1086
  }
895
1087
  const route = resolution.found;
@@ -897,31 +1089,55 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
897
1089
  releaseInvalidatedEvent();
898
1090
  return;
899
1091
  }
900
- const imageKeys = event.images;
901
- const caption = address.kind === "addressed" ? address.body : event.text;
902
- if (!caption && !imageKeys.length) return;
903
- const submitText = `${IM_INPUT_PREFIX}
904
- ${caption || IM_INPUT_FALLBACK_CAPTION}`;
905
- const accepted = imageKeys.length ? await injectImageMessage(messageId, imageKeys, submitText, scope) : await scope.submit(submitText);
906
- const currentAfterSubmit = scope.isCurrent();
907
- if (!accepted || !currentAfterSubmit) {
908
- if (!accepted && !currentAfterSubmit) releaseInvalidatedEvent();
909
- if (currentAfterSubmit) {
910
- ctx.ui.notify("im-forward: message was not accepted; no input submitted.", "warning");
911
- await forwardMessage(`\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"}`, route.sessionId, ++forwardCounter, caption, messageId);
912
- }
913
- return;
914
- }
915
- replyAnchor.set(route.sessionId, { messageId, at: Date.now() });
916
- pendingInputs.push({ sessionId: route.sessionId, caption, messageId, threadId: route.threadId, at: Date.now() });
917
- pruneState();
918
- ctx.log(`im-forward: accepted ${messageId} into session ${route.sessionId} (${imageKeys.length} images)`);
919
- void acknowledgeMessage(messageId);
1092
+ await acceptRoutedMessage(route, event, meta, scope, address, sessionId);
920
1093
  } finally {
921
1094
  scopes.delete(scope);
922
1095
  scope.dispose();
923
1096
  }
924
1097
  }
1098
+ async function acceptRoutedMessage(route, event, meta, scope, address, sessionId) {
1099
+ const messageId = event.message_id;
1100
+ const releaseInvalidatedEvent = () => {
1101
+ if (event.event_id) seenEventIds.delete(key(event.event_id));
1102
+ };
1103
+ const imageKeys = event.images;
1104
+ const caption = address.kind === "addressed" ? address.body : event.text;
1105
+ if (!caption && !imageKeys.length) return;
1106
+ const submitText = `${IM_INPUT_PREFIX}
1107
+ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1108
+ const accepted = imageKeys.length ? await injectImageMessage(messageId, imageKeys, submitText, scope) : await scope.submit(submitText);
1109
+ const currentAfterSubmit = scope.isCurrent();
1110
+ if (!accepted || !currentAfterSubmit) {
1111
+ if (!accepted && !currentAfterSubmit) releaseInvalidatedEvent();
1112
+ if (currentAfterSubmit) {
1113
+ ctx.ui.notify(
1114
+ "im-forward: message was not accepted; no input submitted.",
1115
+ "warning"
1116
+ );
1117
+ await forwardMessage(
1118
+ `\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"}`,
1119
+ route.sessionId,
1120
+ ++forwardCounter,
1121
+ caption,
1122
+ messageId
1123
+ );
1124
+ }
1125
+ return;
1126
+ }
1127
+ replyAnchor.set(route.sessionId, { messageId, at: Date.now() });
1128
+ pendingInputs.push({
1129
+ sessionId: route.sessionId,
1130
+ caption,
1131
+ messageId,
1132
+ threadId: route.threadId,
1133
+ at: Date.now()
1134
+ });
1135
+ pruneState();
1136
+ ctx.log(
1137
+ `im-forward: accepted ${messageId} into session ${sessionId} (${imageKeys.length} images)`
1138
+ );
1139
+ void acknowledgeMessage(messageId);
1140
+ }
925
1141
  const retryAttempts = /* @__PURE__ */ new Map();
926
1142
  const retrySessionIds = /* @__PURE__ */ new Map();
927
1143
  function retryDepth(eventId) {
@@ -933,18 +1149,27 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
933
1149
  if (!eventId) return;
934
1150
  if (terminated || attempt > MAX_INBOUND_RETRIES) {
935
1151
  if (attempt > MAX_INBOUND_RETRIES) {
936
- ctx.log(`im-forward: giving up on event ${eventId} after ${MAX_INBOUND_RETRIES} retries`);
1152
+ ctx.log(
1153
+ `im-forward: giving up on event ${eventId} after ${MAX_INBOUND_RETRIES} retries`
1154
+ );
937
1155
  retryAttempts.delete(eventId);
938
1156
  const boundSession = retrySessionIds.get(eventId);
939
1157
  retrySessionIds.delete(eventId);
940
- void forwardMessage(`\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`, boundSession ?? currentSessionId ?? "", ++forwardCounter, void 0, event.message_id);
1158
+ void forwardMessage(
1159
+ `\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`,
1160
+ boundSession ?? currentSessionId ?? "",
1161
+ ++forwardCounter,
1162
+ void 0,
1163
+ event.message_id
1164
+ );
941
1165
  }
942
1166
  return;
943
1167
  }
944
1168
  const backoff = (cfg.retryBackoffMs ?? DEFAULT_INBOUND_RETRY_BACKOFF_MS) * 2 ** (attempt - 1);
945
1169
  if (retryTimers.has(eventId)) return;
946
1170
  retryAttempts.set(eventId, attempt);
947
- if (!retrySessionIds.has(eventId) && currentSessionId) retrySessionIds.set(eventId, currentSessionId);
1171
+ if (!retrySessionIds.has(eventId) && currentSessionId)
1172
+ retrySessionIds.set(eventId, currentSessionId);
948
1173
  const timer = setTimeout(() => {
949
1174
  retryTimers.delete(eventId);
950
1175
  inFlightRetries.add(eventId);
@@ -954,7 +1179,9 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
954
1179
  }, backoff);
955
1180
  timer.unref?.();
956
1181
  retryTimers.set(eventId, { attempt, timer, event });
957
- ctx.log(`im-forward: transient inbound failure; retrying ${eventId} in ${backoff}ms (attempt ${attempt}/${MAX_INBOUND_RETRIES})`);
1182
+ ctx.log(
1183
+ `im-forward: transient inbound failure; retrying ${eventId} in ${backoff}ms (attempt ${attempt}/${MAX_INBOUND_RETRIES})`
1184
+ );
958
1185
  }
959
1186
  ctx.__forceInboundRetriesForTest = () => {
960
1187
  for (const [eventId, entry] of retryTimers) {
@@ -976,7 +1203,10 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
976
1203
  downloads.push(await connection.downloadImage(messageId, image, index));
977
1204
  }
978
1205
  if (!scope.isCurrent()) return false;
979
- return await scope.submit(submitText, downloads.map((item) => item.file));
1206
+ return await scope.submit(
1207
+ submitText,
1208
+ downloads.map((item) => item.file)
1209
+ );
980
1210
  } catch {
981
1211
  ctx.log("im-forward: image preparation failed");
982
1212
  return false;
@@ -994,7 +1224,10 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
994
1224
  return providerCall("metadata", () => connection.metadata(messageId));
995
1225
  }
996
1226
  async function fetchThreadMessages(threadId) {
997
- return providerCall("thread lookup", () => connection.threadMessages(threadId));
1227
+ return providerCall(
1228
+ "thread lookup",
1229
+ () => connection.threadMessages(threadId)
1230
+ );
998
1231
  }
999
1232
  async function resolveRouteForInbound(messageId, meta) {
1000
1233
  if (meta.threadId) {
@@ -1061,7 +1294,12 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1061
1294
  restartTimer = void 0;
1062
1295
  restartDueAt = void 0;
1063
1296
  if (terminated || suspended || consumer || consumerRecovering) return;
1064
- const gen = { handle: null, installed: false, failed: false, retired: false };
1297
+ const gen = {
1298
+ handle: null,
1299
+ installed: false,
1300
+ failed: false,
1301
+ retired: false
1302
+ };
1065
1303
  generation = gen;
1066
1304
  consumerReady = false;
1067
1305
  updateFooterTag();
@@ -1072,7 +1310,10 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1072
1310
  consumer = null;
1073
1311
  consumerRecovering = false;
1074
1312
  if (terminated || suspended) return;
1075
- const backoff = Math.min(RESTART_BACKOFF_MIN_MS * 2 ** Math.min(consumerRestarts, 4), RESTART_BACKOFF_MAX_MS);
1313
+ const backoff = Math.min(
1314
+ RESTART_BACKOFF_MIN_MS * 2 ** Math.min(consumerRestarts, 4),
1315
+ RESTART_BACKOFF_MAX_MS
1316
+ );
1076
1317
  restartTimer = setTimeout(spawnConsumer, backoff);
1077
1318
  restartTimer.unref?.();
1078
1319
  restartDueAt = Date.now() + backoff;
@@ -1092,7 +1333,10 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1092
1333
  ctx.log(`im-forward: consumer exited (${consumerLastExit})`);
1093
1334
  if (!persistent || !notifiedPersistentFailure) {
1094
1335
  if (persistent) notifiedPersistentFailure = true;
1095
- ctx.ui.notify(`IM forwarding: ${cfg.provider} connection failed${safe ? `: ${safe}` : "; check provider configuration/authentication."}${persistent ? " Retrying in the background (see /tools/im-forward status)." : " Retrying."}`, persistent ? "error" : "warning");
1336
+ ctx.ui.notify(
1337
+ `IM forwarding: ${cfg.provider} connection failed${safe ? `: ${safe}` : "; check provider configuration/authentication."}${persistent ? " Retrying in the background (see /tools/im-forward status)." : " Retrying."}`,
1338
+ persistent ? "error" : "warning"
1339
+ );
1096
1340
  }
1097
1341
  recover();
1098
1342
  };
@@ -1107,7 +1351,8 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1107
1351
  void handleInboundEvent(event);
1108
1352
  },
1109
1353
  ready: () => {
1110
- if (terminated || gen.failed || gen.retired || generation !== gen) return;
1354
+ if (terminated || gen.failed || gen.retired || generation !== gen)
1355
+ return;
1111
1356
  clearTimeout(gen.startup);
1112
1357
  consumerReady = true;
1113
1358
  notifiedPersistentFailure = false;
@@ -1159,7 +1404,10 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1159
1404
  if (!suspended) return;
1160
1405
  suspended = false;
1161
1406
  if (consumer || consumerRecovering || restartTimer) return;
1162
- const delay2 = suspendedRestartInMs !== void 0 ? suspendedRestartInMs : Math.min(RESTART_BACKOFF_MIN_MS * 2 ** Math.min(consumerRestarts, 4), RESTART_BACKOFF_MAX_MS);
1407
+ const delay2 = suspendedRestartInMs !== void 0 ? suspendedRestartInMs : Math.min(
1408
+ RESTART_BACKOFF_MIN_MS * 2 ** Math.min(consumerRestarts, 4),
1409
+ RESTART_BACKOFF_MAX_MS
1410
+ );
1163
1411
  suspendedRestartInMs = void 0;
1164
1412
  scheduleRestart(delay2);
1165
1413
  };
@@ -1178,12 +1426,15 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1178
1426
  if (restartTimer) clearTimeout(restartTimer);
1179
1427
  if (generation) generation.retired = true;
1180
1428
  const results = await Promise.allSettled([
1181
- ...resources.map((scope) => Promise.resolve().then(() => scope.dispose())),
1429
+ ...resources.map(
1430
+ (scope) => Promise.resolve().then(() => scope.dispose())
1431
+ ),
1182
1432
  Promise.resolve().then(() => connection.dispose?.()),
1183
1433
  generation ? stopGeneration(generation) : Promise.resolve()
1184
1434
  ]);
1185
1435
  consumer = null;
1186
- if (results.some((result) => result.status === "rejected")) ctx.log(`im-forward: ${cfg.provider} resource cleanup failed`);
1436
+ if (results.some((result) => result.status === "rejected"))
1437
+ ctx.log(`im-forward: ${cfg.provider} resource cleanup failed`);
1187
1438
  });
1188
1439
  ctx.registerCommand({
1189
1440
  name: "im-forward",
@@ -1199,11 +1450,27 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1199
1450
  `- routes: ${routes.size} forwarded message(s) routable (${threadRoutes.size} thread(s), ${replyAnchor.size} anchor(s))`,
1200
1451
  `- current session: ${currentSessionId ?? "(none)"}`
1201
1452
  ];
1202
- if (!routes.size && !terminated && consumerReady) lines.push("- note: no forwarded message yet \u2014 IM replies are only accepted after the first answer is forwarded. Run any local turn to open the reply entry.");
1203
- if (lastSendError) lines.push(`- last send error: ${lastSendError} (at ${new Date(lastSendErrorAt).toISOString()})`);
1204
- if (anchorFallbacks) lines.push(`- anchor fallbacks to chat root: ${anchorFallbacks}`);
1205
- if (pendingInputs.length) lines.push(`- pending turn attributions: ${pendingInputs.length}`);
1206
- if (retryAttempts.size) lines.push(`- inbound retries pending: ${retryTimers.size} (attempts so far: ${Math.max(...retryAttempts.values())})`);
1453
+ if (!routes.size && !terminated && consumerReady)
1454
+ lines.push(
1455
+ // r18 P2: match the actual behavior — a NEVER-forwarded runtime now
1456
+ // bootstraps on the first authorized message in the target
1457
+ // conversation (r17); an EVER-forwarded runtime whose routes all
1458
+ // expired keeps classic routing (explicit '<session>: text'
1459
+ // addressing still works).
1460
+ hasForwarded ? "- note: all routes expired \u2014 replies to old forwards are dropped. Send a new local turn, or address explicitly with '<session name>: text'." : "- note: no forwarded message yet \u2014 the first authorized message in the bound conversation will open the session (cold-start)."
1461
+ );
1462
+ if (lastSendError)
1463
+ lines.push(
1464
+ `- last send error: ${lastSendError} (at ${new Date(lastSendErrorAt).toISOString()})`
1465
+ );
1466
+ if (anchorFallbacks)
1467
+ lines.push(`- anchor fallbacks to chat root: ${anchorFallbacks}`);
1468
+ if (pendingInputs.length)
1469
+ lines.push(`- pending turn attributions: ${pendingInputs.length}`);
1470
+ if (retryAttempts.size)
1471
+ lines.push(
1472
+ `- inbound retries pending: ${retryTimers.size} (attempts so far: ${Math.max(...retryAttempts.values())})`
1473
+ );
1207
1474
  commandCtx.ui.notify(lines.join("\n"), "info");
1208
1475
  }
1209
1476
  });
@@ -2322,7 +2589,9 @@ function imForward(ctx) {
2322
2589
  initializeImForward(ctx);
2323
2590
  }
2324
2591
  function initializeImForward(ctx, providers = implementedProviders) {
2325
- if (!ctx.hasUI) return;
2592
+ const caps = ctx.capabilities ?? { editorInjection: ctx.hasUI === true, interactiveUI: ctx.hasUI === true };
2593
+ if (!caps.editorInjection) return;
2594
+ const interactive = caps.interactiveUI;
2326
2595
  const dir = resolveConfigDir();
2327
2596
  let disposed = false;
2328
2597
  let session = null;
@@ -2493,59 +2762,63 @@ This does not remove the app credentials lark-cli itself stores; re-running setu
2493
2762
  commandCtx.ui.notify(error.message || "IM forwarding configuration could not be cleared.", "error");
2494
2763
  }
2495
2764
  }
2496
- ctx.registerShortcut("ctrl+r", { description: "Set up or toggle IM forwarding", handler: () => toggleNow(ctx) });
2497
- ctx.registerShortcut("alt+i", { description: "Set up or toggle IM forwarding (terminal Alt alias)", handler: () => toggleNow(ctx) });
2498
- ctx.registerCommand({ path: ["tools", "im-forward", "status"], description: "Show IM forwarding status", handler: async (commandCtx) => {
2499
- if (!disposed) showStatus(commandCtx);
2500
- } });
2501
- ctx.registerCommand({ path: ["tools", "im-forward", "switch-app"], description: "Rebind the configured platform to a different app/account", handler: async () => {
2502
- if (!disposed) await setup("switch-app");
2503
- } });
2504
- ctx.registerCommand({ path: ["tools", "im-forward", "setup"], description: "Run the IM forwarding setup wizard", handler: async () => {
2505
- if (!disposed) await setup();
2506
- } });
2507
- ctx.registerCommand({ path: ["tools", "im-forward", "toggle"], description: "Toggle IM forwarding on/off (same as Ctrl+R)", handler: async (commandCtx) => {
2508
- if (!disposed) await toggleNow(commandCtx);
2509
- } });
2510
- ctx.registerCommand({ path: ["tools", "im-forward", "clear"], description: "Remove IM forwarding configuration (with confirmation)", handler: async (commandCtx) => {
2511
- if (!disposed) await clearConfiguration(commandCtx);
2512
- } });
2513
- ctx.registerCommand({ name: "im-forward", path: ["tools", "im-forward"], description: "IM forwarding menu (status/setup/toggle/clear)", handler: async (commandCtx, args) => {
2514
- if (disposed) return;
2515
- const arg = args?.trim();
2516
- if (arg === "status") {
2517
- showStatus(commandCtx);
2518
- return;
2519
- }
2520
- if (arg === "setup") {
2521
- await setup();
2522
- return;
2523
- }
2524
- if (arg === "switch-app") {
2525
- await setup("switch-app");
2526
- return;
2527
- }
2528
- if (arg === "toggle") {
2529
- await toggleNow(commandCtx);
2530
- return;
2531
- }
2532
- if (arg === "clear") {
2533
- await clearConfiguration(commandCtx);
2534
- return;
2535
- }
2536
- if (arg) {
2537
- commandCtx.ui.notify("Usage: /tools/im-forward [status|setup|switch-app|toggle|clear]; bare /tools/im-forward opens the menu", "info");
2538
- return;
2539
- }
2540
- const options = toggle && activeConfig ? ["Status", "Setup\u2026", "Switch app\u2026", "Toggle forwarding on/off", "Clear configuration\u2026"] : hasConfigLayers(ctx.cwd, dir) ? ["Status", "Setup\u2026", "Switch app\u2026", "Clear configuration\u2026"] : ["Setup\u2026"];
2541
- const choice = await commandCtx.ui.select("IM forwarding", options);
2542
- if (disposed || !choice) return;
2543
- if (choice === "Status") showStatus(commandCtx);
2544
- else if (choice === "Setup\u2026") await setup();
2545
- else if (choice === "Switch app\u2026") await setup("switch-app");
2546
- else if (choice === "Toggle forwarding on/off") await toggleNow(commandCtx);
2547
- else if (choice === "Clear configuration\u2026") await clearConfiguration(commandCtx);
2548
- } });
2765
+ if (interactive) {
2766
+ ctx.registerShortcut("ctrl+r", { description: "Set up or toggle IM forwarding", handler: () => toggleNow(ctx) });
2767
+ ctx.registerShortcut("alt+i", { description: "Set up or toggle IM forwarding (terminal Alt alias)", handler: () => toggleNow(ctx) });
2768
+ }
2769
+ if (interactive) {
2770
+ ctx.registerCommand({ path: ["tools", "im-forward", "status"], description: "Show IM forwarding status", handler: async (commandCtx) => {
2771
+ if (!disposed) showStatus(commandCtx);
2772
+ } });
2773
+ ctx.registerCommand({ path: ["tools", "im-forward", "switch-app"], description: "Rebind the configured platform to a different app/account", handler: async () => {
2774
+ if (!disposed) await setup("switch-app");
2775
+ } });
2776
+ ctx.registerCommand({ path: ["tools", "im-forward", "setup"], description: "Run the IM forwarding setup wizard", handler: async () => {
2777
+ if (!disposed) await setup();
2778
+ } });
2779
+ ctx.registerCommand({ path: ["tools", "im-forward", "toggle"], description: "Toggle IM forwarding on/off (same as Ctrl+R)", handler: async (commandCtx) => {
2780
+ if (!disposed) await toggleNow(commandCtx);
2781
+ } });
2782
+ ctx.registerCommand({ path: ["tools", "im-forward", "clear"], description: "Remove IM forwarding configuration (with confirmation)", handler: async (commandCtx) => {
2783
+ if (!disposed) await clearConfiguration(commandCtx);
2784
+ } });
2785
+ ctx.registerCommand({ name: "im-forward", path: ["tools", "im-forward"], description: "IM forwarding menu (status/setup/toggle/clear)", handler: async (commandCtx, args) => {
2786
+ if (disposed) return;
2787
+ const arg = args?.trim();
2788
+ if (arg === "status") {
2789
+ showStatus(commandCtx);
2790
+ return;
2791
+ }
2792
+ if (arg === "setup") {
2793
+ await setup();
2794
+ return;
2795
+ }
2796
+ if (arg === "switch-app") {
2797
+ await setup("switch-app");
2798
+ return;
2799
+ }
2800
+ if (arg === "toggle") {
2801
+ await toggleNow(commandCtx);
2802
+ return;
2803
+ }
2804
+ if (arg === "clear") {
2805
+ await clearConfiguration(commandCtx);
2806
+ return;
2807
+ }
2808
+ if (arg) {
2809
+ commandCtx.ui.notify("Usage: /tools/im-forward [status|setup|switch-app|toggle|clear]; bare /tools/im-forward opens the menu", "info");
2810
+ return;
2811
+ }
2812
+ const options = toggle && activeConfig ? ["Status", "Setup\u2026", "Switch app\u2026", "Toggle forwarding on/off", "Clear configuration\u2026"] : hasConfigLayers(ctx.cwd, dir) ? ["Status", "Setup\u2026", "Switch app\u2026", "Clear configuration\u2026"] : ["Setup\u2026"];
2813
+ const choice = await commandCtx.ui.select("IM forwarding", options);
2814
+ if (disposed || !choice) return;
2815
+ if (choice === "Status") showStatus(commandCtx);
2816
+ else if (choice === "Setup\u2026") await setup();
2817
+ else if (choice === "Switch app\u2026") await setup("switch-app");
2818
+ else if (choice === "Toggle forwarding on/off") await toggleNow(commandCtx);
2819
+ else if (choice === "Clear configuration\u2026") await clearConfiguration(commandCtx);
2820
+ } });
2821
+ }
2549
2822
  ctx.registerCleanup?.(async () => {
2550
2823
  disposed = true;
2551
2824
  setupAbort?.abort();