@cydm/pie 4.10.1 → 4.11.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.
@@ -14,8 +14,9 @@ import {
14
14
  registerTurnImDriver
15
15
  } from "../../../chunks/chunk-OU33ROFD.js";
16
16
  import {
17
- currentWorkerLifecycleBridge
18
- } from "../../../chunks/chunk-6WKBQZWM.js";
17
+ currentWorkerLifecycleBridge,
18
+ syncInheritedWorkerModels
19
+ } from "../../../chunks/chunk-EWPPGYBU.js";
19
20
  import {
20
21
  readProcessCommandLine
21
22
  } from "../../../chunks/chunk-7RJXKN7N.js";
@@ -30,7 +31,7 @@ import {
30
31
  } from "../../../chunks/chunk-ZPJ3BNQB.js";
31
32
  import {
32
33
  loadResolvedModelsConfig
33
- } from "../../../chunks/chunk-FC5AN5QP.js";
34
+ } from "../../../chunks/chunk-B5GKDXVG.js";
34
35
  import "../../../chunks/chunk-CBDQJMUI.js";
35
36
  import "../../../chunks/chunk-G2K4GY6N.js";
36
37
  import {
@@ -51,9 +52,20 @@ import { randomUUID } from "node:crypto";
51
52
  // builtin/extensions/im-forward/helpers.ts
52
53
  import * as nodeCrypto from "node:crypto";
53
54
  var MAX_INPUT_HEADER_CHARS = 200;
55
+ var MAX_IPC_INPUT_HEADER_CHARS = 600;
56
+ var MAX_IPC_INPUT_HEADER_LINES = 8;
54
57
  function isRecord(value) {
55
58
  return typeof value === "object" && value !== null && !Array.isArray(value);
56
59
  }
60
+ function extractLastUserMessageText(messages) {
61
+ for (let i = messages.length - 1; i >= 0; i--) {
62
+ const message = messages[i];
63
+ if (!isRecord(message) || message.role !== "user") continue;
64
+ 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();
65
+ if (joined) return joined;
66
+ }
67
+ return void 0;
68
+ }
57
69
  function assistantForwardText(message) {
58
70
  if (message?.role !== "assistant" || !Array.isArray(message.content)) return "";
59
71
  let text = "";
@@ -66,29 +78,68 @@ function assistantForwardText(message) {
66
78
  if (hasToolCalls) return "";
67
79
  return text.trim();
68
80
  }
81
+ var MAX_DERIVED_IPC_LABEL_CHARS = 40;
69
82
  function sessionLabel(sessionId, sessionName) {
70
- if (sessionName && sessionName.trim()) return sessionName.trim();
83
+ const raw = sessionName?.trim();
84
+ if (raw && raw.startsWith("[pie-ipc]")) {
85
+ const envName = process.env.PIE_IPC_DISPLAY_NAME?.trim();
86
+ if (envName) return envName;
87
+ const unwrapped = raw.replace(/^\[pie-ipc\][^\n]*?says:\s*(?:\r?\n)?/, "").trim();
88
+ if (unwrapped !== raw && unwrapped) {
89
+ const firstLine = unwrapped.split(/\r?\n/, 1)[0].replace(/\s+/g, " ").trim();
90
+ if (firstLine && !firstLine.startsWith("[ipc-done]")) {
91
+ return clipEscapedMarkdown(escapeMarkdownInline(firstLine), MAX_DERIVED_IPC_LABEL_CHARS);
92
+ }
93
+ }
94
+ return sessionId.length > 8 ? sessionId.slice(0, 8) : sessionId;
95
+ }
96
+ if (raw) return raw;
71
97
  return sessionId.length > 8 ? sessionId.slice(0, 8) : sessionId;
72
98
  }
73
99
  function escapeMarkdownInline(text) {
74
100
  return text.replace(/\\/g, "\\\\").replace(/`/g, "\\`");
75
101
  }
102
+ function clipEscapedMarkdown(escaped, maxChars) {
103
+ if (escaped.length <= maxChars) return escaped;
104
+ let clipped = stripDanglingHighSurrogate(escaped.slice(0, maxChars));
105
+ if (/(?:^|[^\\])(?:\\\\)*\\$/.test(clipped)) clipped = clipped.slice(0, -1);
106
+ return `${clipped}\u2026`;
107
+ }
76
108
  function inputHeaderLine(userInput) {
77
109
  if (!userInput) return null;
78
110
  const collapsed = userInput.replace(/\s+/g, " ").trim();
79
111
  if (!collapsed) return null;
80
- let escaped = escapeMarkdownInline(collapsed);
81
- if (escaped.length > MAX_INPUT_HEADER_CHARS) {
82
- let clipped = stripDanglingHighSurrogate(escaped.slice(0, MAX_INPUT_HEADER_CHARS));
83
- if (/(?:^|[^\\])(?:\\\\)*\\$/.test(clipped)) clipped = clipped.slice(0, -1);
84
- escaped = clipped + "\u2026";
85
- }
86
- return `> [UserInput] ${escaped}`;
87
- }
88
- function composeForwardBody(sessionId, sessionName, userInput, text, mode = "topic-root") {
112
+ return `> [UserInput] ${clipEscapedMarkdown(escapeMarkdownInline(collapsed), MAX_INPUT_HEADER_CHARS)}`;
113
+ }
114
+ function formatIpcInputHeader(rawUserText) {
115
+ if (!rawUserText) return null;
116
+ const match = /^\[pie-ipc\][^\n]*?peer\s+"([^"\n]+)"\s+says:\s*(?:\r?\n)?([\s\S]*)$/.exec(rawUserText.trim());
117
+ if (!match) return null;
118
+ const fromPeer = escapeMarkdownInline(match[1].replace(/\s+/g, " ").trim() || "peer");
119
+ let body = match[2].replace(/\r\n/g, "\n").trim();
120
+ let tag = `IPC \xB7 ${fromPeer}`;
121
+ const doneMatch = /^\[ipc-done\]\s+requestId=\S+(?:\s+outcome=(\S+))?[^\n]*(?:\n([\s\S]*))?$/.exec(body);
122
+ if (doneMatch) {
123
+ const outcome = doneMatch[1];
124
+ tag = outcome && outcome !== "done" ? `IPC \u5B8C\u6210 (${outcome}) \xB7 ${fromPeer}` : `IPC \u5B8C\u6210 \xB7 ${fromPeer}`;
125
+ body = (doneMatch[2] ?? "").trim();
126
+ }
127
+ if (!body) return `> [${tag}]`;
128
+ const rawLines = body.split("\n").map((l) => l.trimEnd()).filter((l, idx, arr) => l.length > 0 || idx > 0 && idx < arr.length - 1 && arr[idx - 1].length > 0);
129
+ const clippedByLines = rawLines.length > MAX_IPC_INPUT_HEADER_LINES;
130
+ const visibleLines = rawLines.slice(0, MAX_IPC_INPUT_HEADER_LINES);
131
+ const joined = visibleLines.join("\n");
132
+ const escaped = clipEscapedMarkdown(escapeMarkdownInline(joined), MAX_IPC_INPUT_HEADER_CHARS);
133
+ const outLines = escaped.split("\n");
134
+ if (clippedByLines && !outLines[outLines.length - 1].endsWith("\u2026")) {
135
+ outLines[outLines.length - 1] = `${outLines[outLines.length - 1]}\u2026`;
136
+ }
137
+ return outLines.map((line, idx) => idx === 0 ? `> [${tag}] ${line}` : `> ${line}`).join("\n");
138
+ }
139
+ function composeForwardBody(sessionId, sessionName, userInput, text, mode = "topic-root", ipcInput) {
89
140
  const lines = [];
90
141
  lines.push(`**[Pie] \xB7 ${sessionLabel(sessionId, sessionName)}**`);
91
- const input = inputHeaderLine(userInput);
142
+ const input = inputHeaderLine(userInput) ?? formatIpcInputHeader(ipcInput);
92
143
  if (input) lines.push(input);
93
144
  if (lines.length > 0) lines.push("");
94
145
  lines.push(text);
@@ -385,9 +436,9 @@ function collectFileReferences(text, cwd, fsStat, options) {
385
436
  }
386
437
  for (const candidate of candidates) {
387
438
  if (results.length >= maxFiles) break;
388
- let path17 = candidate.trim();
389
- if (!path17 || path17.startsWith("/") || path17.startsWith("~") || /^[a-z]+:/i.test(path17) || path17.includes("://")) continue;
390
- const clean = path17.replace(/^\.\//, "").split("#")[0].split("?")[0];
439
+ let path18 = candidate.trim();
440
+ if (!path18 || path18.startsWith("/") || path18.startsWith("~") || /^[a-z]+:/i.test(path18) || path18.includes("://")) continue;
441
+ const clean = path18.replace(/^\.\//, "").split("#")[0].split("?")[0];
391
442
  if (clean.includes("..")) continue;
392
443
  const extension = clean.split(".").pop().toLowerCase();
393
444
  if (!extension || !ATTACHABLE_EXTENSIONS.has(extension)) continue;
@@ -575,6 +626,40 @@ function writeConfig(cwd, dir, update, expected) {
575
626
  function hasConfigLayers(cwd, dir) {
576
627
  return configPaths(cwd, dir).some((file) => fs.existsSync(file));
577
628
  }
629
+ function findInvalidConfigLayers(cwd, dir) {
630
+ const invalid = [];
631
+ for (const file of configPaths(cwd, dir)) {
632
+ if (!fs.existsSync(file)) continue;
633
+ let text;
634
+ try {
635
+ text = fs.readFileSync(file, "utf8");
636
+ } catch {
637
+ continue;
638
+ }
639
+ try {
640
+ const value = JSON.parse(text);
641
+ if (!isRecord(value)) invalid.push(file);
642
+ } catch {
643
+ invalid.push(file);
644
+ }
645
+ }
646
+ return invalid;
647
+ }
648
+ function backupInvalidConfigLayers(cwd, dir, expectedSnapshot) {
649
+ if (expectedSnapshot !== void 0 && configSnapshot(cwd, dir) !== expectedSnapshot) {
650
+ throw new Error("IM configuration changed before backup. Please retry.");
651
+ }
652
+ const invalid = findInvalidConfigLayers(cwd, dir);
653
+ const stamp = `${Date.now()}-${randomUUID().slice(0, 6)}`;
654
+ const moved = [];
655
+ for (const file of invalid) {
656
+ const backup = `${file}.corrupt-${stamp}`;
657
+ fs.renameSync(file, backup);
658
+ moved.push({ from: file, to: backup });
659
+ }
660
+ if (moved.length) invalidateConfigCache();
661
+ return moved;
662
+ }
578
663
  async function clearImConfig(cwd, dir, confirm) {
579
664
  const files = configPaths(cwd, dir).filter((file) => fs.existsSync(file));
580
665
  if (!files.length) return false;
@@ -618,10 +703,418 @@ function resolveImForwardConfig(cwd, dir) {
618
703
  return { config: { enabled: cfg.enabled, chatId, allowUsers: allowUsers?.length ? allowUsers : void 0, larkCli: typeof raw.larkCli === "string" && raw.larkCli.trim() ? raw.larkCli.trim() : void 0, retryBackoffMs: cfg.retryBackoffMs }, problems: chatId.startsWith("oc_") ? [] : ["im-forward: chatId does not look like a chat id (oc_...)"] };
619
704
  }
620
705
 
621
- // builtin/extensions/im-forward/runtime-core.ts
706
+ // builtin/extensions/im-forward/runtime-direct-cmd.ts
707
+ import { spawn as spawn2 } from "node:child_process";
708
+
709
+ // builtin/extensions/im-forward/launch.ts
710
+ import { spawn } from "node:child_process";
622
711
  import * as fs2 from "node:fs";
712
+ import * as path2 from "node:path";
713
+ import { StringDecoder } from "node:string_decoder";
714
+ function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
715
+ const windows = platform === "win32";
716
+ const candidates = explicit ? [path2.resolve(cwd, explicit)] : (env.PATH ?? "").split(windows ? ";" : ":").filter(Boolean).flatMap((dir) => (windows ? ["lark-cli.exe", "lark-cli.cmd"] : ["lark-cli"]).map((name) => path2.resolve(cwd, dir, name)));
717
+ for (const candidate of candidates) {
718
+ try {
719
+ if (!fs2.statSync(candidate).isFile()) continue;
720
+ const ext = path2.extname(candidate).toLowerCase();
721
+ if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
722
+ if (windows && ext === ".cmd") {
723
+ const dir = path2.dirname(candidate);
724
+ for (const root of [path2.join(dir, "node_modules", "@larksuite", "cli"), path2.resolve(dir, "..", "@larksuite", "cli")]) {
725
+ try {
726
+ const pkg = JSON.parse(fs2.readFileSync(path2.join(root, "package.json"), "utf8"));
727
+ const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
728
+ if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
729
+ const entry = path2.join(root, "scripts", "run.js");
730
+ if (fs2.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
731
+ } catch {
732
+ }
733
+ }
734
+ continue;
735
+ }
736
+ if (windows && ext !== ".exe") continue;
737
+ fs2.accessSync(candidate, fs2.constants.X_OK);
738
+ return { command: candidate, prefix: [] };
739
+ } catch {
740
+ }
741
+ }
742
+ return null;
743
+ }
744
+ var treeStops = /* @__PURE__ */ new WeakMap();
745
+ var hasExited = (child) => child.exitCode != null || child.signalCode != null;
746
+ function stopOwnedTree(child, signal) {
747
+ const existing = treeStops.get(child);
748
+ if (existing) return existing;
749
+ if (process.platform === "win32" && hasExited(child)) return Promise.resolve(false);
750
+ const pending = stopOwnedTreeInner(child, signal);
751
+ treeStops.set(child, pending);
752
+ void pending.finally(() => treeStops.delete(child));
753
+ return pending;
754
+ }
755
+ function stopOwnedTreeInner(child, signal) {
756
+ if (process.platform !== "win32" || !child.pid) {
757
+ try {
758
+ if (child.pid) process.kill(-child.pid, signal);
759
+ else child.kill(signal);
760
+ return Promise.resolve(true);
761
+ } catch {
762
+ try {
763
+ return Promise.resolve(child.kill(signal));
764
+ } catch {
765
+ return Promise.resolve(false);
766
+ }
767
+ }
768
+ }
769
+ return new Promise((resolve7) => {
770
+ let done = false;
771
+ let killer;
772
+ const finish = (ok) => {
773
+ if (done) return;
774
+ done = true;
775
+ clearTimeout(timer);
776
+ if (!ok && !hasExited(child)) {
777
+ try {
778
+ child.kill(signal);
779
+ } catch {
780
+ }
781
+ }
782
+ resolve7(ok);
783
+ };
784
+ const timer = setTimeout(() => {
785
+ try {
786
+ killer?.kill();
787
+ } catch {
788
+ }
789
+ finish(false);
790
+ }, 1500);
791
+ try {
792
+ const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
793
+ killer = spawn(path2.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
794
+ killer.on("error", () => finish(false));
795
+ killer.on("exit", (code) => finish(code === 0));
796
+ } catch {
797
+ finish(false);
798
+ }
799
+ });
800
+ }
801
+ function lineReader(onLine, max = 1024 * 1024) {
802
+ const decoder = new StringDecoder("utf8");
803
+ let pending = "";
804
+ let dropping = false;
805
+ const accept = (text) => {
806
+ for (const [i, part] of text.split("\n").entries()) {
807
+ if (i) {
808
+ if (!dropping) onLine(pending);
809
+ pending = "";
810
+ dropping = false;
811
+ }
812
+ if (!dropping) {
813
+ pending += part;
814
+ if (pending.length > max) {
815
+ pending = "";
816
+ dropping = true;
817
+ }
818
+ }
819
+ }
820
+ };
821
+ return { write: (chunk) => accept(decoder.write(chunk)), end() {
822
+ accept(decoder.end());
823
+ if (pending && !dropping) onLine(pending);
824
+ pending = "";
825
+ } };
826
+ }
827
+ var shutdowns = /* @__PURE__ */ new WeakMap();
828
+ function shutdownConsumer(child) {
829
+ const existing = shutdowns.get(child);
830
+ if (existing) return existing;
831
+ const pending = shutdownConsumerInner(child);
832
+ shutdowns.set(child, pending);
833
+ return pending;
834
+ }
835
+ async function shutdownConsumerInner(child) {
836
+ let closed = false;
837
+ const close = new Promise((resolve7) => child.once("close", () => {
838
+ closed = true;
839
+ resolve7();
840
+ }));
841
+ const wait = async (ms) => {
842
+ let timer;
843
+ await Promise.race([close, new Promise((resolve7) => {
844
+ timer = setTimeout(resolve7, ms);
845
+ })]);
846
+ clearTimeout(timer);
847
+ };
848
+ try {
849
+ child.stdin?.end();
850
+ } catch {
851
+ }
852
+ await wait(500);
853
+ if (!closed) {
854
+ await stopOwnedTree(child, "SIGTERM");
855
+ await wait(500);
856
+ }
857
+ if (!closed) {
858
+ await stopOwnedTree(child, "SIGKILL");
859
+ await wait(500);
860
+ }
861
+ child.stdin?.destroy();
862
+ child.stdout?.destroy();
863
+ child.stderr?.destroy();
864
+ }
865
+
866
+ // builtin/extensions/im-forward/runtime-direct-cmd.ts
867
+ var DIRECT_IM_CMD_TIMEOUT_MS = 3e4;
868
+ var MAX_CAPTURE_HEAD_BYTES = 16 * 1024;
869
+ var MAX_CAPTURE_TAIL_BYTES = 16 * 1024;
870
+ var MAX_RENDER_BYTES = 6 * 1024;
871
+ var MAX_RENDER_LINES = 120;
872
+ function parseDirectImCommand(caption) {
873
+ const trimmed = caption.trim();
874
+ if (!trimmed.startsWith("!!")) return void 0;
875
+ const command = trimmed.slice(2).trim();
876
+ return command.length > 0 ? command : void 0;
877
+ }
878
+ function evaluateDirectImCmdAuth(ctx, event) {
879
+ const hasAllowUsers = Array.isArray(ctx.allowUsers) && ctx.allowUsers.length > 0;
880
+ if (hasAllowUsers) {
881
+ return event.sender_id && ctx.allowUsers.includes(event.sender_id) ? { allowed: true } : { allowed: false, reason: "not-in-allowUsers" };
882
+ }
883
+ if (ctx.panelAccess === "allowUsers") {
884
+ return { allowed: false, reason: "panelAccess-allowUsers-unconfigured" };
885
+ }
886
+ if (event.chatType === "group") {
887
+ return { allowed: false, reason: "group-requires-allowUsers" };
888
+ }
889
+ if (ctx.targetKind === "user") {
890
+ return ctx.targetId && event.sender_id && event.sender_id === ctx.targetId ? { allowed: true } : { allowed: false, reason: "not-in-allowUsers" };
891
+ }
892
+ if (ctx.targetId && event.chat_id === ctx.targetId) {
893
+ return { allowed: true };
894
+ }
895
+ return { allowed: false, reason: "unbound-chat" };
896
+ }
897
+ function formatDirectImCmdAuthRefusal(reason, senderId) {
898
+ const idSpan = senderId ? `\`${cleanCodeSpan(senderId, 64)}\`` : void 0;
899
+ if (reason === "group-requires-allowUsers") {
900
+ return idSpan ? `\u26D4\uFE0F Running \`!!\` shell commands in a group chat requires \`allowUsers\` configuration. Add ${idSpan} via \`pie im config\` or \`im-forward.json\`.` : "\u26D4\uFE0F Running `!!` shell commands in a group chat requires `allowUsers` configuration.";
901
+ }
902
+ if (reason === "panelAccess-allowUsers-unconfigured") {
903
+ return idSpan ? `\u26D4\uFE0F Running \`!!\` shell commands requires admin rights (panelAccess=allowUsers, but allowUsers is empty). Add ${idSpan} to allowUsers.` : "\u26D4\uFE0F Running `!!` shell commands requires admin rights (panelAccess=allowUsers, but allowUsers is empty).";
904
+ }
905
+ if (reason === "unbound-chat") {
906
+ return idSpan ? `\u26D4\uFE0F Running \`!!\` shell commands outside the bound chat requires \`allowUsers\` membership. Add ${idSpan} to allowUsers.` : "\u26D4\uFE0F Running `!!` shell commands outside the bound chat requires `allowUsers` membership.";
907
+ }
908
+ return idSpan ? `\u26D4\uFE0F Running \`!!\` shell commands requires admin rights (allowUsers). Your ID: ${idSpan}` : "\u26D4\uFE0F Running `!!` shell commands requires admin rights (allowUsers).";
909
+ }
910
+ function buildDirectShellSpec(command, platform = process.platform) {
911
+ if (platform === "win32") {
912
+ return {
913
+ file: "powershell.exe",
914
+ args: ["-NoProfile", "-NonInteractive", "-Command", command],
915
+ prompt: "PS>"
916
+ };
917
+ }
918
+ return { file: "bash", args: ["-lc", command], prompt: "$" };
919
+ }
920
+ function takeUtf8Prefix(text, maxBytes) {
921
+ const buf = Buffer.from(text, "utf8");
922
+ if (buf.length <= maxBytes) return text;
923
+ return buf.subarray(0, maxBytes).toString("utf8").replace(/\uFFFD+$/g, "");
924
+ }
925
+ function takeUtf8Suffix(text, maxBytes) {
926
+ const buf = Buffer.from(text, "utf8");
927
+ if (buf.length <= maxBytes) return text;
928
+ return buf.subarray(Math.max(0, buf.length - maxBytes)).toString("utf8").replace(/^\uFFFD+/g, "");
929
+ }
930
+ function boundCommandOutput(raw) {
931
+ const normalized = raw.replace(/\r\n/g, "\n").trimEnd();
932
+ if (!normalized) return { text: "", truncated: false };
933
+ const lines = normalized.split("\n");
934
+ let text = normalized;
935
+ let truncated = false;
936
+ if (lines.length > MAX_RENDER_LINES) {
937
+ const headCount = Math.floor(MAX_RENDER_LINES / 2);
938
+ const tailCount = MAX_RENDER_LINES - headCount;
939
+ const omitted = lines.length - headCount - tailCount;
940
+ text = [...lines.slice(0, headCount), `\u2026 (${omitted} lines omitted) \u2026`, ...lines.slice(-tailCount)].join("\n");
941
+ truncated = true;
942
+ }
943
+ if (Buffer.byteLength(text, "utf8") > MAX_RENDER_BYTES) {
944
+ const half = Math.floor(MAX_RENDER_BYTES / 2) - 32;
945
+ text = `${takeUtf8Prefix(text, half)}
946
+ \u2026 (output truncated) \u2026
947
+ ${takeUtf8Suffix(text, half)}`;
948
+ truncated = true;
949
+ }
950
+ return { text, truncated };
951
+ }
952
+ function chooseFence(content) {
953
+ let fence = "```";
954
+ while (content.includes(fence)) fence += "`";
955
+ return fence;
956
+ }
957
+ async function executeDirectImCommand(command, opts) {
958
+ const started = Date.now();
959
+ const platform = opts.platform ?? process.platform;
960
+ const spec = buildDirectShellSpec(command, platform);
961
+ if (/^cwd$/i.test(command.trim())) {
962
+ return {
963
+ ok: true,
964
+ exitCode: 0,
965
+ timedOut: false,
966
+ durationMs: Date.now() - started,
967
+ prompt: spec.prompt,
968
+ output: opts.cwd,
969
+ truncated: false
970
+ };
971
+ }
972
+ const timeoutMs = opts.timeoutMs ?? DIRECT_IM_CMD_TIMEOUT_MS;
973
+ const { PIE_DEFAULT_PROVIDER: _p, PIE_DEFAULT_MODEL: _m, PIE_MANAGER_BOOTSTRAP: _b, PIE_PROC_CURATED_NAME: _c, ...cleanEnv } = process.env;
974
+ return new Promise((resolve7) => {
975
+ let head = "";
976
+ let tail = "";
977
+ let totalBytes = 0;
978
+ let overflowed = false;
979
+ const append = (chunk) => {
980
+ if (!chunk) return;
981
+ totalBytes += Buffer.byteLength(chunk, "utf8");
982
+ if (!overflowed) {
983
+ const next = head + chunk;
984
+ if (Buffer.byteLength(next, "utf8") <= MAX_CAPTURE_HEAD_BYTES + MAX_CAPTURE_TAIL_BYTES) {
985
+ head = next;
986
+ return;
987
+ }
988
+ overflowed = true;
989
+ head = takeUtf8Prefix(next, MAX_CAPTURE_HEAD_BYTES);
990
+ tail = takeUtf8Suffix(next, MAX_CAPTURE_TAIL_BYTES);
991
+ return;
992
+ }
993
+ tail = takeUtf8Suffix(tail + chunk, MAX_CAPTURE_TAIL_BYTES);
994
+ };
995
+ let child;
996
+ try {
997
+ child = spawn2(spec.file, spec.args, {
998
+ cwd: opts.cwd,
999
+ env: cleanEnv,
1000
+ stdio: ["ignore", "pipe", "pipe"],
1001
+ shell: false,
1002
+ windowsHide: true,
1003
+ detached: platform !== "win32"
1004
+ });
1005
+ } catch (error) {
1006
+ resolve7({
1007
+ ok: false,
1008
+ exitCode: null,
1009
+ timedOut: false,
1010
+ durationMs: Date.now() - started,
1011
+ prompt: spec.prompt,
1012
+ output: error instanceof Error ? error.message : String(error),
1013
+ truncated: false
1014
+ });
1015
+ return;
1016
+ }
1017
+ let settled = false;
1018
+ let timedOut = false;
1019
+ let killTimer;
1020
+ let closeTimer;
1021
+ const finish = (exitCode) => {
1022
+ if (settled) return;
1023
+ settled = true;
1024
+ clearTimeout(timeoutTimer);
1025
+ clearTimeout(killTimer);
1026
+ clearTimeout(closeTimer);
1027
+ opts.signal?.removeEventListener("abort", onAbort);
1028
+ const raw = overflowed ? `${head}
1029
+ \u2026 (middle output omitted) \u2026
1030
+ ${tail}` : head;
1031
+ const bounded = boundCommandOutput(raw);
1032
+ resolve7({
1033
+ ok: !timedOut && exitCode === 0,
1034
+ exitCode,
1035
+ timedOut,
1036
+ durationMs: Date.now() - started,
1037
+ prompt: spec.prompt,
1038
+ output: bounded.text,
1039
+ truncated: bounded.truncated || overflowed
1040
+ });
1041
+ };
1042
+ const terminateTree = () => {
1043
+ void stopOwnedTree(child, "SIGTERM").catch(() => void 0);
1044
+ killTimer = setTimeout(() => {
1045
+ void stopOwnedTree(child, "SIGKILL").catch(() => void 0);
1046
+ closeTimer = setTimeout(() => finish(null), 1e3);
1047
+ closeTimer.unref?.();
1048
+ }, 1e3);
1049
+ killTimer.unref?.();
1050
+ };
1051
+ const onAbort = () => terminateTree();
1052
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
1053
+ if (opts.signal?.aborted) {
1054
+ terminateTree();
1055
+ }
1056
+ const timeoutTimer = setTimeout(() => {
1057
+ timedOut = true;
1058
+ terminateTree();
1059
+ }, timeoutMs);
1060
+ timeoutTimer.unref?.();
1061
+ child.stdout?.on("data", (chunk) => append(chunk.toString("utf8")));
1062
+ child.stderr?.on("data", (chunk) => append(chunk.toString("utf8")));
1063
+ child.on("error", (error) => {
1064
+ append(error.message);
1065
+ finish(null);
1066
+ });
1067
+ child.on("close", (code) => finish(code));
1068
+ });
1069
+ }
1070
+ function formatDirectImCmdReply(command, cwd, result) {
1071
+ const icon = result.timedOut ? "\u23F1\uFE0F" : result.ok ? "\u2705" : "\u274C";
1072
+ const duration = `${(result.durationMs / 1e3).toFixed(result.durationMs < 1e3 ? 2 : 1)}s`;
1073
+ const status = result.timedOut ? `timed out (>${Math.round(DIRECT_IM_CMD_TIMEOUT_MS / 1e3)}s)` : `exit ${result.exitCode ?? "error"}`;
1074
+ const header = `${icon} \`${cleanCodeSpan(`${result.prompt} ${command}`, 120)}\`
1075
+ \`cwd:\` \`${cleanCodeSpan(cwd, 120)}\` \xB7 ${status} \xB7 ${duration}`;
1076
+ if (!result.output) {
1077
+ return `${header}
1078
+
1079
+ _(no output)_`;
1080
+ }
1081
+ const fence = chooseFence(result.output);
1082
+ return `${header}
1083
+
1084
+ ${fence}
1085
+ ${result.output}
1086
+ ${fence}`;
1087
+ }
1088
+ function redactDirectImCmdForAudit(command) {
1089
+ return command.replace(/(https?:\/\/[^/\s:@]+):[^@\s/]+@/gi, "$1:[REDACTED]@").replace(/\b(Bearer|Basic|Token)\s+[A-Za-z0-9._~+/=-]{4,}/gi, "$1 [REDACTED]").replace(/((?:authorization|x-api-key|api-key|x-auth-token)\s*[:=]\s*["']?)(?:Bearer\s+|Basic\s+)?[^\s"';,&]+/gi, "$1[REDACTED]").replace(/([?&](?:access_token|refresh_token|id_token|token|api[_-]?key|apikey|key|secret|sig|signature|password|passwd|pwd|auth|x-amz-signature|x-amz-security-token)=)[^&\s"']+/gi, "$1[REDACTED]").replace(/\b([A-Za-z_][A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|APIKEY|AUTH|COOKIE|CREDENTIAL|PRIVATE_KEY|ACCESS_KEY))\s*=\s*(?:"[^"]*"|'[^']*'|[^\s;&|]+)/gi, "$1=[REDACTED]").replace(/(--?(?:token|api[-_]?key|secret|password|passwd|auth|bearer|cookie|private[-_]?key|access[-_]?key)(?:=|\s+))(?:"[^"]*"|'[^']*'|[^\s;&|]+)/gi, "$1[REDACTED]");
1090
+ }
1091
+ function directImCmdAuditSummary(event, command, result) {
1092
+ return `im-forward: !! cmd by ${event.sender_id ?? "unknown"} in ${event.chat_id} (${result.timedOut ? "timeout" : `exit=${String(result.exitCode)}`}, ${result.durationMs}ms): ${cleanCodeSpan(redactDirectImCmdForAudit(command), 80)}`;
1093
+ }
1094
+ async function runDirectImCommandMessage(params) {
1095
+ const auth = evaluateDirectImCmdAuth(params.authCtx, params.event);
1096
+ if (!auth.allowed) {
1097
+ params.log(`im-forward: !! cmd refused for ${params.event.sender_id ?? "unknown"} (${auth.reason})`);
1098
+ await params.reply(formatDirectImCmdAuthRefusal(auth.reason, params.event.sender_id)).catch(() => void 0);
1099
+ return;
1100
+ }
1101
+ void params.acknowledge();
1102
+ const abort = new AbortController();
1103
+ params.registerAbort(abort);
1104
+ try {
1105
+ const res = await executeDirectImCommand(params.command, { cwd: params.cwd, signal: abort.signal });
1106
+ params.log(directImCmdAuditSummary(params.event, params.command, res));
1107
+ const delivered = await params.reply(formatDirectImCmdReply(params.command, params.cwd, res));
1108
+ if (delivered === true) void params.reactDone();
1109
+ } finally {
1110
+ params.unregisterAbort(abort);
1111
+ }
1112
+ }
1113
+
1114
+ // builtin/extensions/im-forward/runtime-core.ts
1115
+ import * as fs3 from "node:fs";
623
1116
  import * as os2 from "node:os";
624
- import { join as pathJoin, resolve as pathResolve, join as join2 } from "node:path";
1117
+ import { join as pathJoin, resolve as pathResolve, join as join3 } from "node:path";
625
1118
  function summarizeFailureReason(reason) {
626
1119
  if (!reason) return { summary: "", persistent: false };
627
1120
  const text = reason.toLowerCase();
@@ -656,10 +1149,10 @@ function ipcDiscoveryRoot() {
656
1149
  }
657
1150
  function liveManagerForBinding(binding) {
658
1151
  try {
659
- for (const file of fs2.readdirSync(ipcDiscoveryRoot())) {
1152
+ for (const file of fs3.readdirSync(ipcDiscoveryRoot())) {
660
1153
  if (!file.endsWith(".json")) continue;
661
1154
  try {
662
- const peer = JSON.parse(fs2.readFileSync(pathJoin(ipcDiscoveryRoot(), file), "utf8"));
1155
+ const peer = JSON.parse(fs3.readFileSync(pathJoin(ipcDiscoveryRoot(), file), "utf8"));
663
1156
  if (peer.pid === process.pid || peer.isManager !== true || peer.imBinding !== binding || !Number.isInteger(peer.pid) || !peer.pid || peer.pid <= 0) continue;
664
1157
  try {
665
1158
  process.kill(peer.pid, 0);
@@ -683,8 +1176,8 @@ async function applyPeerControlDirect(peerRef, control, payload, expected) {
683
1176
  let target;
684
1177
  try {
685
1178
  const dir = ipcDiscoveryRoot();
686
- for (const file of fs2.readdirSync(dir).filter((f) => f.endsWith(".json"))) {
687
- const parsed = JSON.parse(fs2.readFileSync(join2(dir, file), "utf8"));
1179
+ for (const file of fs3.readdirSync(dir).filter((f) => f.endsWith(".json"))) {
1180
+ const parsed = JSON.parse(fs3.readFileSync(join3(dir, file), "utf8"));
688
1181
  if (!parsed.port || !parsed.secret || typeof parsed.pid !== "number" || !parsed.instanceId || typeof parsed.sessionId !== "string" || !parsed.sessionId) continue;
689
1182
  const match = parsed.instanceId === peerRef || parsed.instanceId.startsWith(peerRef) || parsed.displayName === peerRef;
690
1183
  if (!match) continue;
@@ -841,24 +1334,24 @@ _Estimate (bytes/4 heuristic) \u2014 same basis as the TUI's /debugs/context rep
841
1334
  }
842
1335
 
843
1336
  // builtin/extensions/im-forward/session-anchors.ts
844
- import * as fs4 from "node:fs";
845
- import * as path3 from "node:path";
1337
+ import * as fs5 from "node:fs";
1338
+ import * as path4 from "node:path";
846
1339
 
847
1340
  // builtin/extensions/im-forward/address-book.ts
848
- import * as fs3 from "node:fs";
1341
+ import * as fs4 from "node:fs";
849
1342
  import * as os3 from "node:os";
850
- import * as path2 from "node:path";
1343
+ import * as path3 from "node:path";
851
1344
  var MAX_ADDRESS_HEAD = 64;
852
1345
  function addressBookRoot() {
853
1346
  const raw = process.env.PIE_IPC_CONFIG_DIR;
854
1347
  if (raw !== void 0) {
855
1348
  if (raw.length > 0) {
856
- const expanded = raw === "~" ? os3.homedir() : raw.startsWith("~/") ? path2.join(os3.homedir(), raw.slice(2)) : raw;
857
- return path2.resolve(expanded);
1349
+ const expanded = raw === "~" ? os3.homedir() : raw.startsWith("~/") ? path3.join(os3.homedir(), raw.slice(2)) : raw;
1350
+ return path3.resolve(expanded);
858
1351
  }
859
- return path2.resolve("");
1352
+ return path3.resolve("");
860
1353
  }
861
- return path2.resolve(resolveConfigDir());
1354
+ return path3.resolve(resolveConfigDir());
862
1355
  }
863
1356
  function pidAlive(pid) {
864
1357
  if (!Number.isInteger(pid) || pid <= 0) return true;
@@ -874,10 +1367,10 @@ function scanAddressBook() {
874
1367
  let complete = true;
875
1368
  let selfPublished;
876
1369
  let dirExists = false;
877
- const dir = path2.join(addressBookRoot(), "run", "ipc");
1370
+ const dir = path3.join(addressBookRoot(), "run", "ipc");
878
1371
  let entries;
879
1372
  try {
880
- entries = fs3.readdirSync(dir);
1373
+ entries = fs4.readdirSync(dir);
881
1374
  dirExists = true;
882
1375
  } catch (error) {
883
1376
  if (error.code === "ENOENT") return { names, complete: true, dirExists: false };
@@ -886,7 +1379,7 @@ function scanAddressBook() {
886
1379
  for (const [index, file] of entries.entries()) {
887
1380
  if (!file.endsWith(".json")) continue;
888
1381
  try {
889
- const status = JSON.parse(fs3.readFileSync(path2.join(dir, file), "utf8"));
1382
+ const status = JSON.parse(fs4.readFileSync(path3.join(dir, file), "utf8"));
890
1383
  dirExists = true;
891
1384
  const name = typeof status.sessionName === "string" ? status.sessionName.trim() : "";
892
1385
  const pid = typeof status.pid === "number" ? status.pid : void 0;
@@ -948,15 +1441,15 @@ function resolveAddress(text, ownLiveName, book) {
948
1441
 
949
1442
  // builtin/extensions/im-forward/session-anchors.ts
950
1443
  function anchorsDir() {
951
- return path3.join(addressBookRoot(), "im-forward", "anchors");
1444
+ return path4.join(addressBookRoot(), "im-forward", "anchors");
952
1445
  }
953
1446
  function anchorPath(sessionId) {
954
1447
  const safe = sessionId.replace(/[^a-zA-Z0-9._-]/g, "_");
955
- return path3.join(anchorsDir(), `${safe}.json`);
1448
+ return path4.join(anchorsDir(), `${safe}.json`);
956
1449
  }
957
1450
  function loadPersistedAnchor(sessionId, identity) {
958
1451
  try {
959
- const raw = fs4.readFileSync(anchorPath(sessionId), "utf8");
1452
+ const raw = fs5.readFileSync(anchorPath(sessionId), "utf8");
960
1453
  const parsed = JSON.parse(raw);
961
1454
  if (typeof parsed.anchor?.messageId === "string" && parsed.anchor.messageId && typeof parsed.anchor.at === "number" && parsed.provider === identity.provider && // v2 group-home (11-12): the home is the APP'S WHOLE PRESENCE, so an
962
1455
  // anchor may live in ANY room — a group chat id differs from the
@@ -986,8 +1479,8 @@ function savePersistedAnchor(sessionId, identity, anchor) {
986
1479
  anchor
987
1480
  };
988
1481
  const target = anchorPath(sessionId);
989
- fs4.mkdirSync(path3.dirname(target), { recursive: true });
990
- fs4.writeFileSync(target, `${JSON.stringify(file)}
1482
+ fs5.mkdirSync(path4.dirname(target), { recursive: true });
1483
+ fs5.writeFileSync(target, `${JSON.stringify(file)}
991
1484
  `, "utf8");
992
1485
  } catch {
993
1486
  }
@@ -998,7 +1491,7 @@ var SAFE_APPLINK_HOST = /^[a-z0-9.-]+$/i;
998
1491
  function resolveSessionThreadUrl(sessionId) {
999
1492
  if (!sessionId) return void 0;
1000
1493
  try {
1001
- const raw = fs4.readFileSync(anchorPath(sessionId), "utf8");
1494
+ const raw = fs5.readFileSync(anchorPath(sessionId), "utf8");
1002
1495
  const parsed = JSON.parse(raw);
1003
1496
  if (parsed.provider !== "feishu" || !parsed.anchor) return void 0;
1004
1497
  const rawChat = typeof parsed.anchor.chatId === "string" && parsed.anchor.chatId ? parsed.anchor.chatId : typeof parsed.anchor.home === "string" && parsed.anchor.home ? parsed.anchor.home : "";
@@ -1285,13 +1778,13 @@ function createRuntimeRoutes(ctx) {
1285
1778
  }
1286
1779
 
1287
1780
  // builtin/extensions/im-forward/event-hub.ts
1288
- import * as path4 from "node:path";
1781
+ import * as path5 from "node:path";
1289
1782
  function hubDir() {
1290
- return path4.join(addressBookRoot(), "im-forward");
1783
+ return path5.join(addressBookRoot(), "im-forward");
1291
1784
  }
1292
1785
  function lockPath(binding) {
1293
1786
  const safe = binding.replace(/[^a-zA-Z0-9._-]/g, "_");
1294
- return path4.join(hubDir(), `consumer-${safe}.lock`);
1787
+ return path5.join(hubDir(), `consumer-${safe}.lock`);
1295
1788
  }
1296
1789
  function readLock(binding) {
1297
1790
  return readOwnership(lockPath(binding), (v) => v.binding === binding);
@@ -1432,7 +1925,7 @@ function createConsumerLifecycle(ctx) {
1432
1925
  if (!ctx.isTerminated()) {
1433
1926
  restartTimer = setTimeout(() => {
1434
1927
  consumerSlotRetiring = false;
1435
- void spawn6();
1928
+ void spawn7();
1436
1929
  }, 15e3);
1437
1930
  restartTimer.unref?.();
1438
1931
  }
@@ -1455,10 +1948,10 @@ function createConsumerLifecycle(ctx) {
1455
1948
  const scheduleRestart = (delayMs) => {
1456
1949
  if (restartTimer) clearTimeout(restartTimer);
1457
1950
  restartDueAt = Date.now() + delayMs;
1458
- restartTimer = setTimeout(spawn6, delayMs);
1951
+ restartTimer = setTimeout(spawn7, delayMs);
1459
1952
  restartTimer.unref?.();
1460
1953
  };
1461
- async function spawn6() {
1954
+ async function spawn7() {
1462
1955
  restartTimer = void 0;
1463
1956
  restartDueAt = void 0;
1464
1957
  if (ctx.isTerminated() || suspended || consumerSlotRetiring || generation?.stopFailed || consumer || consumerRecovering) return;
@@ -1473,19 +1966,19 @@ function createConsumerLifecycle(ctx) {
1473
1966
  consumerStartupInFlight = false;
1474
1967
  }
1475
1968
  if (!key) {
1476
- restartTimer = setTimeout(spawn6, 15e3);
1969
+ restartTimer = setTimeout(spawn7, 15e3);
1477
1970
  restartTimer.unref?.();
1478
1971
  restartDueAt = Date.now() + 15e3;
1479
1972
  return;
1480
1973
  }
1481
1974
  if (!acquireClaimedSlot(key)) {
1482
- restartTimer = setTimeout(spawn6, 15e3);
1975
+ restartTimer = setTimeout(spawn7, 15e3);
1483
1976
  restartTimer.unref?.();
1484
1977
  restartDueAt = Date.now() + 15e3;
1485
1978
  return;
1486
1979
  }
1487
1980
  } else if (!acquireClaimedSlot(resolveBindingKeySync())) {
1488
- restartTimer = setTimeout(spawn6, 15e3);
1981
+ restartTimer = setTimeout(spawn7, 15e3);
1489
1982
  restartTimer.unref?.();
1490
1983
  restartDueAt = Date.now() + 15e3;
1491
1984
  return;
@@ -1510,7 +2003,7 @@ function createConsumerLifecycle(ctx) {
1510
2003
  RESTART_BACKOFF_MIN_MS * 2 ** Math.min(consumerRestarts, 4),
1511
2004
  RESTART_BACKOFF_MAX_MS
1512
2005
  );
1513
- restartTimer = setTimeout(spawn6, backoff);
2006
+ restartTimer = setTimeout(spawn7, backoff);
1514
2007
  restartTimer.unref?.();
1515
2008
  restartDueAt = Date.now() + backoff;
1516
2009
  });
@@ -1611,218 +2104,59 @@ function createConsumerLifecycle(ctx) {
1611
2104
  const delay2 = suspendedRestartInMs !== void 0 ? suspendedRestartInMs : Math.min(
1612
2105
  RESTART_BACKOFF_MIN_MS * 2 ** Math.min(consumerRestarts, 4),
1613
2106
  RESTART_BACKOFF_MAX_MS
1614
- );
1615
- suspendedRestartInMs = void 0;
1616
- scheduleRestart(delay2);
1617
- };
1618
- };
1619
- return {
1620
- bindingKey,
1621
- spawn: spawn6,
1622
- holdsSlot: () => !!consumerLock,
1623
- status: () => ({
1624
- consumerActive: !!consumer,
1625
- consumerReady,
1626
- consumerLastExit,
1627
- consumerRestarts,
1628
- terminated: ctx.isTerminated(),
1629
- pendingRestart: !!restartTimer,
1630
- suspended,
1631
- recovering: consumerRecovering
1632
- }),
1633
- terminate,
1634
- suspend,
1635
- stopGeneration
1636
- };
1637
- }
1638
-
1639
- // builtin/extensions/im-forward/panel.ts
1640
- import * as fs8 from "node:fs";
1641
- import * as os5 from "node:os";
1642
- import * as path9 from "node:path";
1643
- import { fileURLToPath } from "node:url";
1644
-
1645
- // builtin/extensions/im-forward/discovery.ts
1646
- import * as os4 from "node:os";
1647
- import * as path5 from "node:path";
1648
- function ipcDiscoveryRoot2() {
1649
- const home = os4.homedir() || process.env.HOME || process.env.USERPROFILE || "/tmp";
1650
- const override = process.env.PIE_IPC_CONFIG_DIR;
1651
- const agentDir = process.env.PIE_CODING_AGENT_DIR?.trim();
1652
- const raw = override !== void 0 ? override : agentDir || path5.join(home, ".pie");
1653
- const configDir = process.platform === "win32" ? raw : path5.resolve(raw === "~" ? home : raw.startsWith("~/") ? path5.join(home, raw.slice(2)) : raw);
1654
- return path5.join(configDir, "run", "ipc");
1655
- }
1656
-
1657
- // builtin/extensions/im-forward/panel-actions.ts
1658
- import { execFile, spawn as spawn3 } from "node:child_process";
1659
- import { randomBytes } from "node:crypto";
1660
- import { StringDecoder as StringDecoder3 } from "node:string_decoder";
1661
- import * as fs6 from "node:fs";
1662
- import * as path7 from "node:path";
1663
-
1664
- // builtin/extensions/im-forward/lark-cli.ts
1665
- import { spawn as spawn2 } from "node:child_process";
1666
- import { StringDecoder as StringDecoder2 } from "node:string_decoder";
1667
-
1668
- // builtin/extensions/im-forward/launch.ts
1669
- import { spawn } from "node:child_process";
1670
- import * as fs5 from "node:fs";
1671
- import * as path6 from "node:path";
1672
- import { StringDecoder } from "node:string_decoder";
1673
- function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
1674
- const windows = platform === "win32";
1675
- const candidates = explicit ? [path6.resolve(cwd, explicit)] : (env.PATH ?? "").split(windows ? ";" : ":").filter(Boolean).flatMap((dir) => (windows ? ["lark-cli.exe", "lark-cli.cmd"] : ["lark-cli"]).map((name) => path6.resolve(cwd, dir, name)));
1676
- for (const candidate of candidates) {
1677
- try {
1678
- if (!fs5.statSync(candidate).isFile()) continue;
1679
- const ext = path6.extname(candidate).toLowerCase();
1680
- if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
1681
- if (windows && ext === ".cmd") {
1682
- const dir = path6.dirname(candidate);
1683
- for (const root of [path6.join(dir, "node_modules", "@larksuite", "cli"), path6.resolve(dir, "..", "@larksuite", "cli")]) {
1684
- try {
1685
- const pkg = JSON.parse(fs5.readFileSync(path6.join(root, "package.json"), "utf8"));
1686
- const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
1687
- if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
1688
- const entry = path6.join(root, "scripts", "run.js");
1689
- if (fs5.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
1690
- } catch {
1691
- }
1692
- }
1693
- continue;
1694
- }
1695
- if (windows && ext !== ".exe") continue;
1696
- fs5.accessSync(candidate, fs5.constants.X_OK);
1697
- return { command: candidate, prefix: [] };
1698
- } catch {
1699
- }
1700
- }
1701
- return null;
1702
- }
1703
- var treeStops = /* @__PURE__ */ new WeakMap();
1704
- var hasExited = (child) => child.exitCode != null || child.signalCode != null;
1705
- function stopOwnedTree(child, signal) {
1706
- const existing = treeStops.get(child);
1707
- if (existing) return existing;
1708
- if (process.platform === "win32" && hasExited(child)) return Promise.resolve(false);
1709
- const pending = stopOwnedTreeInner(child, signal);
1710
- treeStops.set(child, pending);
1711
- void pending.finally(() => treeStops.delete(child));
1712
- return pending;
1713
- }
1714
- function stopOwnedTreeInner(child, signal) {
1715
- if (process.platform !== "win32" || !child.pid) {
1716
- try {
1717
- if (child.pid) process.kill(-child.pid, signal);
1718
- else child.kill(signal);
1719
- return Promise.resolve(true);
1720
- } catch {
1721
- try {
1722
- return Promise.resolve(child.kill(signal));
1723
- } catch {
1724
- return Promise.resolve(false);
1725
- }
1726
- }
1727
- }
1728
- return new Promise((resolve7) => {
1729
- let done = false;
1730
- let killer;
1731
- const finish = (ok) => {
1732
- if (done) return;
1733
- done = true;
1734
- clearTimeout(timer);
1735
- if (!ok && !hasExited(child)) {
1736
- try {
1737
- child.kill(signal);
1738
- } catch {
1739
- }
1740
- }
1741
- resolve7(ok);
1742
- };
1743
- const timer = setTimeout(() => {
1744
- try {
1745
- killer?.kill();
1746
- } catch {
1747
- }
1748
- finish(false);
1749
- }, 1500);
1750
- try {
1751
- const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
1752
- killer = spawn(path6.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
1753
- killer.on("error", () => finish(false));
1754
- killer.on("exit", (code) => finish(code === 0));
1755
- } catch {
1756
- finish(false);
1757
- }
1758
- });
1759
- }
1760
- function lineReader(onLine, max = 1024 * 1024) {
1761
- const decoder = new StringDecoder("utf8");
1762
- let pending = "";
1763
- let dropping = false;
1764
- const accept = (text) => {
1765
- for (const [i, part] of text.split("\n").entries()) {
1766
- if (i) {
1767
- if (!dropping) onLine(pending);
1768
- pending = "";
1769
- dropping = false;
1770
- }
1771
- if (!dropping) {
1772
- pending += part;
1773
- if (pending.length > max) {
1774
- pending = "";
1775
- dropping = true;
1776
- }
1777
- }
1778
- }
2107
+ );
2108
+ suspendedRestartInMs = void 0;
2109
+ scheduleRestart(delay2);
2110
+ };
1779
2111
  };
1780
- return { write: (chunk) => accept(decoder.write(chunk)), end() {
1781
- accept(decoder.end());
1782
- if (pending && !dropping) onLine(pending);
1783
- pending = "";
1784
- } };
1785
- }
1786
- var shutdowns = /* @__PURE__ */ new WeakMap();
1787
- function shutdownConsumer(child) {
1788
- const existing = shutdowns.get(child);
1789
- if (existing) return existing;
1790
- const pending = shutdownConsumerInner(child);
1791
- shutdowns.set(child, pending);
1792
- return pending;
1793
- }
1794
- async function shutdownConsumerInner(child) {
1795
- let closed = false;
1796
- const close = new Promise((resolve7) => child.once("close", () => {
1797
- closed = true;
1798
- resolve7();
1799
- }));
1800
- const wait = async (ms) => {
1801
- let timer;
1802
- await Promise.race([close, new Promise((resolve7) => {
1803
- timer = setTimeout(resolve7, ms);
1804
- })]);
1805
- clearTimeout(timer);
2112
+ return {
2113
+ bindingKey,
2114
+ spawn: spawn7,
2115
+ holdsSlot: () => !!consumerLock,
2116
+ status: () => ({
2117
+ consumerActive: !!consumer,
2118
+ consumerReady,
2119
+ consumerLastExit,
2120
+ consumerRestarts,
2121
+ terminated: ctx.isTerminated(),
2122
+ pendingRestart: !!restartTimer,
2123
+ suspended,
2124
+ recovering: consumerRecovering
2125
+ }),
2126
+ terminate,
2127
+ suspend,
2128
+ stopGeneration
1806
2129
  };
1807
- try {
1808
- child.stdin?.end();
1809
- } catch {
1810
- }
1811
- await wait(500);
1812
- if (!closed) {
1813
- await stopOwnedTree(child, "SIGTERM");
1814
- await wait(500);
1815
- }
1816
- if (!closed) {
1817
- await stopOwnedTree(child, "SIGKILL");
1818
- await wait(500);
1819
- }
1820
- child.stdin?.destroy();
1821
- child.stdout?.destroy();
1822
- child.stderr?.destroy();
1823
2130
  }
1824
2131
 
2132
+ // builtin/extensions/im-forward/panel.ts
2133
+ import * as fs8 from "node:fs";
2134
+ import * as os5 from "node:os";
2135
+ import * as path9 from "node:path";
2136
+ import { fileURLToPath } from "node:url";
2137
+
2138
+ // builtin/extensions/im-forward/discovery.ts
2139
+ import * as os4 from "node:os";
2140
+ import * as path6 from "node:path";
2141
+ function ipcDiscoveryRoot2() {
2142
+ const home = os4.homedir() || process.env.HOME || process.env.USERPROFILE || "/tmp";
2143
+ const override = process.env.PIE_IPC_CONFIG_DIR;
2144
+ const agentDir = process.env.PIE_CODING_AGENT_DIR?.trim();
2145
+ const raw = override !== void 0 ? override : agentDir || path6.join(home, ".pie");
2146
+ const configDir = process.platform === "win32" ? raw : path6.resolve(raw === "~" ? home : raw.startsWith("~/") ? path6.join(home, raw.slice(2)) : raw);
2147
+ return path6.join(configDir, "run", "ipc");
2148
+ }
2149
+
2150
+ // builtin/extensions/im-forward/panel-actions.ts
2151
+ import { execFile, spawn as spawn4 } from "node:child_process";
2152
+ import { randomBytes } from "node:crypto";
2153
+ import { StringDecoder as StringDecoder3 } from "node:string_decoder";
2154
+ import * as fs6 from "node:fs";
2155
+ import * as path7 from "node:path";
2156
+
1825
2157
  // builtin/extensions/im-forward/lark-cli.ts
2158
+ import { spawn as spawn3 } from "node:child_process";
2159
+ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
1826
2160
  async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
1827
2161
  return new Promise((resolve7) => {
1828
2162
  if (options.signal?.aborted) {
@@ -1833,7 +2167,7 @@ async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
1833
2167
  try {
1834
2168
  const spec = typeof binary === "string" ? resolveLaunchSpec(binary) ?? (options.spawn ? { command: binary, prefix: [] } : null) : binary;
1835
2169
  if (!spec) throw new Error("unsupported executable");
1836
- child = (options.spawn ?? spawn2)(spec.command, [...spec.prefix, ...args], {
2170
+ child = (options.spawn ?? spawn3)(spec.command, [...spec.prefix, ...args], {
1837
2171
  shell: false,
1838
2172
  windowsHide: true,
1839
2173
  stdio: [options.stdin ?? "ignore", "pipe", "pipe"],
@@ -2248,7 +2582,7 @@ async function fenceChild(childPid, marker) {
2248
2582
  return await new Promise((resolve7) => {
2249
2583
  let killer;
2250
2584
  try {
2251
- killer = spawn3("taskkill", ["/T", "/F", "/PID", String(childPid)], { stdio: "ignore", windowsHide: true });
2585
+ killer = spawn4("taskkill", ["/T", "/F", "/PID", String(childPid)], { stdio: "ignore", windowsHide: true });
2252
2586
  } catch {
2253
2587
  resolve7("unknown");
2254
2588
  return;
@@ -2577,7 +2911,7 @@ async function executeAction(req) {
2577
2911
  const { command, prefix } = interpreterFor(script);
2578
2912
  let child;
2579
2913
  try {
2580
- child = spawn3(command, prefix, {
2914
+ child = spawn4(command, prefix, {
2581
2915
  cwd,
2582
2916
  env: scriptEnv(req, launchId),
2583
2917
  detached: process.platform !== "win32",
@@ -2809,7 +3143,8 @@ function formatPeerModel(peer) {
2809
3143
  return "\u2014";
2810
3144
  }
2811
3145
  var SAFE_WORKER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;
2812
- var SAFE_MODEL_SEGMENT = /^[^/\s]+$/;
3146
+ var SAFE_PROVIDER_SEGMENT = /^[^/\s]+$/;
3147
+ var SAFE_MODEL_ID_SEGMENT = /^\S+$/;
2813
3148
  var OPAQUE_PEER_NAME = /^pie-[a-z0-9]{6,}$/i;
2814
3149
  function cleanSessionTitle(raw) {
2815
3150
  if (!raw) return void 0;
@@ -2850,7 +3185,7 @@ function parseCatalogFromRawDoc(raw) {
2850
3185
  const addEntry = (provider, id, name) => {
2851
3186
  const p = provider.trim();
2852
3187
  const m = id.trim();
2853
- if (!SAFE_MODEL_SEGMENT.test(p) || !SAFE_MODEL_SEGMENT.test(m)) return;
3188
+ if (!SAFE_PROVIDER_SEGMENT.test(p) || !SAFE_MODEL_ID_SEGMENT.test(m)) return;
2854
3189
  let group = groups.get(p);
2855
3190
  if (!group) {
2856
3191
  group = { provider: p, models: [] };
@@ -2912,15 +3247,20 @@ function isContainedRegularFile(rootDir, filePath) {
2912
3247
  }
2913
3248
  function readModelCatalog(opts = {}) {
2914
3249
  const configRoot = path8.dirname(path8.dirname(ipcDiscoveryRoot2()));
3250
+ const globalModelsPath = path8.join(configRoot, "models.json");
2915
3251
  if (opts.workerName && SAFE_WORKER_NAME.test(opts.workerName)) {
2916
3252
  const agentsDir = path8.join(configRoot, "pie-proc", "agents");
2917
3253
  const workerModelsPath = path8.join(agentsDir, opts.workerName, "models.json");
2918
3254
  if (isContainedRegularFile(agentsDir, workerModelsPath)) {
3255
+ syncInheritedWorkerModels(workerModelsPath, globalModelsPath, {
3256
+ allowedDestRoot: configRoot,
3257
+ allowedSrcRoot: configRoot
3258
+ });
2919
3259
  const workerCatalog = readCatalogFile(workerModelsPath);
2920
3260
  if (workerCatalog.length > 0) return workerCatalog;
2921
3261
  }
2922
3262
  }
2923
- return readCatalogFile(path8.join(configRoot, "models.json"));
3263
+ return readCatalogFile(globalModelsPath);
2924
3264
  }
2925
3265
  function canRemotelyQuitPeer(peer) {
2926
3266
  if (peer.isManager) return false;
@@ -3566,7 +3906,7 @@ ${a.runs} \u6B21 \xB7 \u6700\u8FD1 ${cleanInline2(a.lastRunBy ?? "\u2014", 20)}
3566
3906
  last,
3567
3907
  ``,
3568
3908
  "Upgrade = `npm install -g @cydm/pie@latest` + restart the manager resident (IM pauses ~15s). Idle workers are recycled; busy ones keep running. Desktop TUI sessions keep their code until you restart them.",
3569
- "The confirm button requires allowUsers membership."
3909
+ "Requires allowUsers membership when configured (or bound chat / owner DM under default panelAccess)."
3570
3910
  ].join("\n"),
3571
3911
  actions: [
3572
3912
  { id: "panel.upgrade.confirm", label: "\u2B06\uFE0F Install latest + restart", style: "primary", requireAllowUsers: true },
@@ -4528,6 +4868,32 @@ function isPeekAudienceAllowed(ctx, event) {
4528
4868
  if (event.chatType !== "group") return !ctx.allowUsers || isAllowedUser();
4529
4869
  return true;
4530
4870
  }
4871
+ function evaluateUpgradeConfirmAuth(ctx, event) {
4872
+ const hasAllowUsers = Array.isArray(ctx.allowUsers) && ctx.allowUsers.length > 0;
4873
+ if (hasAllowUsers) {
4874
+ return event.sender_id && ctx.allowUsers.includes(event.sender_id) ? { allowed: true } : { allowed: false, reason: "not-in-allowUsers" };
4875
+ }
4876
+ if (ctx.panelAccess === "allowUsers") {
4877
+ return { allowed: false, reason: "panelAccess-allowUsers-unconfigured" };
4878
+ }
4879
+ if (ctx.targetKind === "user") {
4880
+ return ctx.targetId && event.sender_id && event.sender_id === ctx.targetId ? { allowed: true } : { allowed: false, reason: "not-in-allowUsers" };
4881
+ }
4882
+ if (ctx.targetId && event.chat_id === ctx.targetId) {
4883
+ return { allowed: true };
4884
+ }
4885
+ return { allowed: false, reason: "unbound-chat" };
4886
+ }
4887
+ function formatUpgradeAuthRefusal(reason, senderId) {
4888
+ const idSpan = senderId ? `\`${cleanCodeSpan(senderId, 64)}\`` : void 0;
4889
+ if (reason === "panelAccess-allowUsers-unconfigured") {
4890
+ return idSpan ? `\u26D4\uFE0F Upgrading pie requires admin rights (panelAccess=allowUsers, but allowUsers is empty). Add ${idSpan} to allowUsers in im-forward.json.` : "\u26D4\uFE0F Upgrading pie requires admin rights (panelAccess=allowUsers, but allowUsers is empty).";
4891
+ }
4892
+ if (reason === "unbound-chat") {
4893
+ return idSpan ? `\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers) outside the bound chat. Use /panel in the bound chat, or add ${idSpan} to allowUsers.` : "\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers) outside the bound chat.";
4894
+ }
4895
+ return idSpan ? `\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers). Your ID: ${idSpan}` : "\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers).";
4896
+ }
4531
4897
  function buildPeekCardSpec(targetRef, targetSession, isManagerTarget, cols, receipt, inThread = false) {
4532
4898
  const meta = parsePeekMeta(receipt);
4533
4899
  const actions = [
@@ -4591,7 +4957,7 @@ async function deliverPeekDeniedAtGate(params) {
4591
4957
  const sendOpts = peekReplyTo ? { replyInThread: true } : void 0;
4592
4958
  const sent = await connection.sendCard(recipient, deniedSpec, `panel-peek-denied-${event.event_id}`, peekReplyTo, sendOpts);
4593
4959
  if (sent?.messageId && currentSessionId && isCurrent()) {
4594
- params.rememberPanelCard(sent.messageId, currentSessionId, event.chat_id, owner?.replyInThread || owner?.workerScoped ? { ...owner.replyInThread ? { replyTo: sent.messageId, replyInThread: true } : {}, ...owner.workerScoped ? { workerScoped: true } : {}, threadWorkerSessionId: owner.threadWorkerSessionId } : void 0);
4960
+ params.rememberPanelCard(sent.messageId, currentSessionId, sent.chatId ?? event.chat_id, owner?.replyInThread || owner?.workerScoped ? { ...owner.replyInThread ? { replyTo: sent.messageId, replyInThread: true } : {}, ...owner.workerScoped ? { workerScoped: true } : {}, threadWorkerSessionId: owner.threadWorkerSessionId } : void 0);
4595
4961
  }
4596
4962
  }
4597
4963
  async function runUpgradeConfirmActor(cols, log) {
@@ -5030,8 +5396,207 @@ function runCronPanelCommand(panelCmd, opts) {
5030
5396
  return { handled: false };
5031
5397
  }
5032
5398
 
5033
- // builtin/extensions/im-forward/runtime-panel.ts
5034
- import { resolve as pathResolve3 } from "node:path";
5399
+ // builtin/extensions/im-forward/panel-card-store.ts
5400
+ import * as fs12 from "node:fs";
5401
+ import * as path12 from "node:path";
5402
+ import { randomUUID as randomUUID3 } from "node:crypto";
5403
+ var MAX_PERSISTED_PANEL_CARDS = 100;
5404
+ var PANEL_CARD_TTL_MS = 14 * 24 * 60 * 60 * 1e3;
5405
+ function storePath() {
5406
+ return path12.join(addressBookRoot(), "im-forward", "panel-cards.json");
5407
+ }
5408
+ function makeKey(provider, messageId) {
5409
+ return `${provider}\0${messageId}`;
5410
+ }
5411
+ var readCache;
5412
+ function fileStamp(file) {
5413
+ try {
5414
+ const st = fs12.lstatSync(file);
5415
+ if (st.isSymbolicLink() || !st.isFile()) return "unsafe";
5416
+ return `${st.ino}:${st.mtimeMs}:${st.ctimeMs}:${st.size}`;
5417
+ } catch {
5418
+ return "-";
5419
+ }
5420
+ }
5421
+ function parseEntry(raw) {
5422
+ if (!isRecord(raw)) return void 0;
5423
+ if (typeof raw.messageId !== "string" || !raw.messageId) return void 0;
5424
+ if (typeof raw.provider !== "string" || !raw.provider) return void 0;
5425
+ if (typeof raw.sessionId !== "string" || !raw.sessionId) return void 0;
5426
+ if (typeof raw.chatId !== "string" || !raw.chatId) return void 0;
5427
+ if (typeof raw.updatedAt !== "number" || !Number.isFinite(raw.updatedAt)) return void 0;
5428
+ return {
5429
+ messageId: raw.messageId,
5430
+ provider: raw.provider,
5431
+ sessionId: raw.sessionId,
5432
+ chatId: raw.chatId,
5433
+ updatedAt: raw.updatedAt,
5434
+ ...typeof raw.replyTo === "string" && raw.replyTo ? { replyTo: raw.replyTo } : {},
5435
+ ...raw.replyInThread === true ? { replyInThread: true } : {},
5436
+ ...raw.workerScoped === true ? { workerScoped: true } : {},
5437
+ ...typeof raw.threadWorkerSessionId === "string" && raw.threadWorkerSessionId ? { threadWorkerSessionId: raw.threadWorkerSessionId } : {}
5438
+ };
5439
+ }
5440
+ function readStoreMap(file) {
5441
+ const stamp = fileStamp(file);
5442
+ if (stamp === "unsafe") return /* @__PURE__ */ new Map();
5443
+ if (readCache && readCache.file === file && readCache.stamp === stamp) {
5444
+ return readCache.map;
5445
+ }
5446
+ const map = /* @__PURE__ */ new Map();
5447
+ try {
5448
+ const text = fs12.readFileSync(file, "utf8");
5449
+ const parsed = JSON.parse(text);
5450
+ if (isRecord(parsed) && Array.isArray(parsed.entries)) {
5451
+ for (const item of parsed.entries) {
5452
+ const entry = parseEntry(item);
5453
+ if (!entry) continue;
5454
+ const k = makeKey(entry.provider, entry.messageId);
5455
+ map.delete(k);
5456
+ map.set(k, entry);
5457
+ }
5458
+ }
5459
+ } catch {
5460
+ }
5461
+ readCache = { file, stamp, map };
5462
+ return map;
5463
+ }
5464
+ function loadPersistedPanelCard(provider, messageId, now = Date.now()) {
5465
+ if (!provider || !messageId) return void 0;
5466
+ const file = storePath();
5467
+ const map = readStoreMap(file);
5468
+ const found = map.get(makeKey(provider, messageId));
5469
+ if (!found) return void 0;
5470
+ if (now - found.updatedAt > PANEL_CARD_TTL_MS) return void 0;
5471
+ const { messageId: _ignored, ...record } = found;
5472
+ return record;
5473
+ }
5474
+ var LOCK_STALE_MS = 5e3;
5475
+ var LOCK_MAX_ATTEMPTS = 12;
5476
+ var LOCK_WAIT_MS = 10;
5477
+ var LOCK_SLEEP_BUF = new Int32Array(new SharedArrayBuffer(4));
5478
+ function sleepSyncMs(ms) {
5479
+ try {
5480
+ Atomics.wait(LOCK_SLEEP_BUF, 0, 0, ms);
5481
+ } catch {
5482
+ const end = Date.now() + ms;
5483
+ while (Date.now() < end) {
5484
+ }
5485
+ }
5486
+ }
5487
+ function isPidAlive(pid) {
5488
+ if (!Number.isInteger(pid) || pid <= 0) return false;
5489
+ try {
5490
+ process.kill(pid, 0);
5491
+ return true;
5492
+ } catch (error) {
5493
+ return error?.code === "EPERM";
5494
+ }
5495
+ }
5496
+ function acquireStoreLock(lockPath2) {
5497
+ try {
5498
+ if (fs12.existsSync(lockPath2) && fs12.lstatSync(lockPath2).isSymbolicLink()) return void 0;
5499
+ } catch {
5500
+ }
5501
+ for (let attempt = 0; attempt < LOCK_MAX_ATTEMPTS; attempt++) {
5502
+ try {
5503
+ const fd = fs12.openSync(lockPath2, "wx", 384);
5504
+ try {
5505
+ fs12.writeFileSync(fd, `${process.pid}
5506
+ `, "utf8");
5507
+ } finally {
5508
+ fs12.closeSync(fd);
5509
+ }
5510
+ return () => {
5511
+ try {
5512
+ fs12.unlinkSync(lockPath2);
5513
+ } catch {
5514
+ }
5515
+ };
5516
+ } catch (error) {
5517
+ if (error?.code !== "EEXIST") return void 0;
5518
+ let reclaimed = false;
5519
+ try {
5520
+ const st = fs12.lstatSync(lockPath2);
5521
+ if (st.isSymbolicLink() || !st.isFile()) return void 0;
5522
+ const ageMs = Date.now() - st.mtimeMs;
5523
+ let ownerDead = false;
5524
+ try {
5525
+ const pid = Number.parseInt(fs12.readFileSync(lockPath2, "utf8").trim(), 10);
5526
+ if (Number.isInteger(pid) && pid > 0 && !isPidAlive(pid)) ownerDead = true;
5527
+ } catch {
5528
+ }
5529
+ if (ownerDead || ageMs > LOCK_STALE_MS) {
5530
+ fs12.unlinkSync(lockPath2);
5531
+ reclaimed = true;
5532
+ }
5533
+ } catch (e) {
5534
+ if (e?.code === "ENOENT") reclaimed = true;
5535
+ }
5536
+ if (reclaimed) continue;
5537
+ sleepSyncMs(LOCK_WAIT_MS);
5538
+ }
5539
+ }
5540
+ return void 0;
5541
+ }
5542
+ function savePersistedPanelCard(provider, messageId, entry, now = Date.now()) {
5543
+ if (!provider || !messageId || !entry.sessionId || !entry.chatId) return;
5544
+ const file = storePath();
5545
+ let tmp;
5546
+ let releaseLock;
5547
+ try {
5548
+ const dir = path12.dirname(file);
5549
+ if (fs12.existsSync(dir) && fs12.lstatSync(dir).isSymbolicLink()) return;
5550
+ if (fs12.existsSync(file) && fs12.lstatSync(file).isSymbolicLink()) return;
5551
+ fs12.mkdirSync(dir, { recursive: true, mode: 448 });
5552
+ releaseLock = acquireStoreLock(path12.join(dir, ".panel-cards.lock"));
5553
+ if (!releaseLock) return;
5554
+ readCache = void 0;
5555
+ const map = readStoreMap(file);
5556
+ for (const [k, existing] of map) {
5557
+ if (now - existing.updatedAt > PANEL_CARD_TTL_MS) map.delete(k);
5558
+ }
5559
+ const key = makeKey(provider, messageId);
5560
+ map.delete(key);
5561
+ map.set(key, {
5562
+ messageId,
5563
+ provider,
5564
+ sessionId: entry.sessionId,
5565
+ chatId: entry.chatId,
5566
+ updatedAt: now,
5567
+ ...entry.replyTo ? { replyTo: entry.replyTo } : {},
5568
+ ...entry.replyInThread ? { replyInThread: true } : {},
5569
+ ...entry.workerScoped ? { workerScoped: true } : {},
5570
+ ...entry.threadWorkerSessionId ? { threadWorkerSessionId: entry.threadWorkerSessionId } : {}
5571
+ });
5572
+ while (map.size > MAX_PERSISTED_PANEL_CARDS) {
5573
+ const oldest = map.keys().next().value;
5574
+ if (oldest === void 0) break;
5575
+ map.delete(oldest);
5576
+ }
5577
+ const payload = { version: 1, entries: [...map.values()] };
5578
+ tmp = path12.join(dir, `.panel-cards-${process.pid}-${randomUUID3()}.tmp`);
5579
+ const fd = fs12.openSync(tmp, "wx", 384);
5580
+ try {
5581
+ fs12.writeFileSync(fd, `${JSON.stringify(payload)}
5582
+ `);
5583
+ } finally {
5584
+ fs12.closeSync(fd);
5585
+ }
5586
+ fs12.renameSync(tmp, file);
5587
+ tmp = void 0;
5588
+ readCache = { file, stamp: fileStamp(file), map };
5589
+ } catch {
5590
+ if (tmp) {
5591
+ try {
5592
+ fs12.rmSync(tmp, { force: true });
5593
+ } catch {
5594
+ }
5595
+ }
5596
+ } finally {
5597
+ releaseLock?.();
5598
+ }
5599
+ }
5035
5600
  function createPanelCardState(ctx) {
5036
5601
  const panelCardOwners = /* @__PURE__ */ new Map();
5037
5602
  const peekCards = /* @__PURE__ */ new Map();
@@ -5042,6 +5607,7 @@ function createPanelCardState(ctx) {
5042
5607
  const cardNavGens = /* @__PURE__ */ new Map();
5043
5608
  function rememberPanelCard(messageId, sessionId, chatId, thread) {
5044
5609
  if (!messageId) return;
5610
+ panelCardOwners.delete(messageId);
5045
5611
  panelCardOwners.set(messageId, {
5046
5612
  sessionId,
5047
5613
  epoch: ctx.getInputEpoch(),
@@ -5051,18 +5617,44 @@ function createPanelCardState(ctx) {
5051
5617
  ...thread?.workerScoped ? { workerScoped: true } : {},
5052
5618
  ...thread?.threadWorkerSessionId ? { threadWorkerSessionId: thread.threadWorkerSessionId } : {}
5053
5619
  });
5054
- if (panelCardOwners.size > 100) {
5055
- const oldest = [...panelCardOwners.keys()].slice(0, Math.ceil(panelCardOwners.size / 4));
5056
- for (const k of oldest) panelCardOwners.delete(k);
5620
+ while (panelCardOwners.size > MAX_PERSISTED_PANEL_CARDS) {
5621
+ const oldest = panelCardOwners.keys().next().value;
5622
+ if (oldest === void 0) break;
5623
+ panelCardOwners.delete(oldest);
5624
+ }
5625
+ if (ctx.provider) {
5626
+ savePersistedPanelCard(ctx.provider, messageId, {
5627
+ sessionId,
5628
+ chatId,
5629
+ ...thread?.replyTo ? { replyTo: thread.replyTo } : {},
5630
+ ...thread?.replyInThread ? { replyInThread: true } : {},
5631
+ ...thread?.workerScoped ? { workerScoped: true } : {},
5632
+ ...thread?.threadWorkerSessionId ? { threadWorkerSessionId: thread.threadWorkerSessionId } : {}
5633
+ });
5057
5634
  }
5058
5635
  }
5059
5636
  const putBounded = (m, k, v) => {
5637
+ m.delete(k);
5060
5638
  m.set(k, v);
5061
5639
  if (m.size > 100) for (const old of [...m.keys()].slice(0, 25)) m.delete(old);
5062
5640
  };
5063
5641
  return {
5064
5642
  rememberPanelCard,
5065
- getPanelCardOwner: (messageId) => panelCardOwners.get(messageId),
5643
+ getPanelCardOwner: (messageId) => {
5644
+ if (panelCardOwners.has(messageId)) return panelCardOwners.get(messageId);
5645
+ if (!ctx.provider) return void 0;
5646
+ const persisted = loadPersistedPanelCard(ctx.provider, messageId);
5647
+ if (!persisted) return void 0;
5648
+ return {
5649
+ sessionId: persisted.sessionId,
5650
+ epoch: ctx.getInputEpoch(),
5651
+ chatId: persisted.chatId,
5652
+ ...persisted.replyTo ? { replyTo: persisted.replyTo } : {},
5653
+ ...persisted.replyInThread ? { replyInThread: true } : {},
5654
+ ...persisted.workerScoped ? { workerScoped: true } : {},
5655
+ ...persisted.threadWorkerSessionId ? { threadWorkerSessionId: persisted.threadWorkerSessionId } : {}
5656
+ };
5657
+ },
5066
5658
  getPeekCard: (cardId) => peekCards.get(cardId),
5067
5659
  setPeekCard: (cardId, binding) => putBounded(peekCards, cardId, binding),
5068
5660
  clearPeekCard: (cardId) => {
@@ -5096,6 +5688,7 @@ function createPanelCardState(ctx) {
5096
5688
  getCardNav: (cardId) => cardNavGens.get(cardId) ?? 0,
5097
5689
  bumpCardNav: (cardId) => {
5098
5690
  const next = (cardNavGens.get(cardId) ?? 0) + 1;
5691
+ cardNavGens.delete(cardId);
5099
5692
  cardNavGens.set(cardId, next);
5100
5693
  if (cardNavGens.size > 200) for (const old of [...cardNavGens.keys()].slice(0, 50)) cardNavGens.delete(old);
5101
5694
  return next;
@@ -5109,6 +5702,9 @@ function createPanelCardState(ctx) {
5109
5702
  }
5110
5703
  };
5111
5704
  }
5705
+
5706
+ // builtin/extensions/im-forward/runtime-panel.ts
5707
+ import { resolve as pathResolve3 } from "node:path";
5112
5708
  function createPanelExecutor(ctx) {
5113
5709
  const peekAudienceAllowed = (event) => isPeekAudienceAllowed(ctx, event);
5114
5710
  const runPanelCommand = async (panelCmd, event, sessionId, isCurrent, opts) => {
@@ -5207,14 +5803,18 @@ function createPanelExecutor(ctx) {
5207
5803
  return;
5208
5804
  }
5209
5805
  if (!isCurrent() || ctx.cards.getCardNav(cardId) !== myNavGen) return;
5210
- ctx.log("im-forward: panel patch failed; falling back to a fresh card");
5806
+ const patchErr = ctx.connection.consumeLastPatchError?.(cardId);
5807
+ ctx.log(patchErr ? `im-forward: panel patch failed (${patchErr}); falling back to a fresh card` : "im-forward: panel patch failed; falling back to a fresh card");
5808
+ } else if (patchInPlace && event.text?.startsWith("/card ")) {
5809
+ const skipReason = !ctx.connection.patch ? "no-patch-support" : !event.message_id ? "no-message-id" : !ownedOrigin ? "no-owner" : ownedOrigin.chatId !== event.chat_id ? "chat-mismatch" : ownedOrigin.sessionId !== sessionId ? "session-mismatch" : "epoch-mismatch";
5810
+ ctx.log(`im-forward: panel patch skipped (${panelCmd.cmd}, reason=${skipReason}); sending fresh card`);
5211
5811
  }
5212
5812
  if (!isCurrent()) return;
5213
5813
  try {
5214
5814
  if (ctx.connection.sendCard) {
5215
5815
  const sent = await ctx.connection.sendCard(freshRecipient, normalizedSpec, key, sendReplyTo, sendOpts);
5216
5816
  if (isCurrent()) {
5217
- ctx.cards.rememberPanelCard(sent?.messageId, sessionId, event.chat_id, threadMetaFor(sent?.messageId, keepWorkerSession));
5817
+ ctx.cards.rememberPanelCard(sent?.messageId, sessionId, sent?.chatId ?? event.chat_id, threadMetaFor(sent?.messageId, keepWorkerSession));
5218
5818
  applyIssuedCards(sent?.messageId, plannedWorker, plannedQuit, plannedCronStop);
5219
5819
  }
5220
5820
  ctx.log(sent?.messageId ? `im-forward: panel card sent (${panelCmd.cmd})` : `im-forward: panel card send failed (${panelCmd.cmd})`);
@@ -5245,7 +5845,7 @@ function createPanelExecutor(ctx) {
5245
5845
  return;
5246
5846
  }
5247
5847
  const effectiveCmd = threadScopeCheck.rewrittenCmd ?? panelCmd;
5248
- if (panelCmd.restricted && ctx.allowUsers && (!event.sender_id || !ctx.allowUsers.includes(event.sender_id))) {
5848
+ if (panelCmd.restricted && panelCmd.cmd !== "panel.upgrade.confirm" && ctx.allowUsers && (!event.sender_id || !ctx.allowUsers.includes(event.sender_id))) {
5249
5849
  ctx.log(`im-forward: restricted panel action ${panelCmd.cmd} refused for ${event.sender_id ?? "unknown"} (not in allowUsers)`);
5250
5850
  try {
5251
5851
  await ctx.connection.send(freshRecipient, "\u26D4\uFE0F This action requires admin rights (allowUsers).", `panel-refused-${event.event_id}`, sendReplyTo, sendOpts);
@@ -5381,7 +5981,7 @@ function createPanelExecutor(ctx) {
5381
5981
  await deliverPanelSpec(denied, `panel-peek-denied-${event.event_id}`, true);
5382
5982
  } else if (ctx.connection.sendCard) {
5383
5983
  const sent = await ctx.connection.sendCard(peekRecipient, denied, `panel-peek-denied-${event.event_id}`, sendReplyTo, sendOpts);
5384
- if (isCurrent()) ctx.cards.rememberPanelCard(sent?.messageId, sessionId, event.chat_id, threadMetaFor(sent?.messageId));
5984
+ if (isCurrent()) ctx.cards.rememberPanelCard(sent?.messageId, sessionId, sent?.chatId ?? event.chat_id, threadMetaFor(sent?.messageId));
5385
5985
  }
5386
5986
  return;
5387
5987
  }
@@ -5394,7 +5994,13 @@ function createPanelExecutor(ctx) {
5394
5994
  if (existingPeek && existingPeek.chatId === event.chat_id && existingPeek.ownerSession === ctx.getCurrentSessionId() && existingPeek.epoch === ctx.getInputEpoch() && existingPeek.ref === ref && existingPeek.targetSession === issuedSession && issuedRef === ref) {
5395
5995
  return;
5396
5996
  }
5397
- if (ctx.connection.sendCard) await ctx.connection.sendCard(peekRecipient, { title: "Peek refused", color: "red", columnsPerRow: cols, body: "Missing or forged worker/session binding. Reopen the worker from /panel.", actions: panelHomeAction(hideHome, threadWorkerSessionId) }, `panel-peek-refused-${event.event_id}`, sendReplyTo, sendOpts);
5997
+ const refused = { title: "Peek refused", color: "red", columnsPerRow: cols, body: "Missing or forged worker/session binding. Reopen the worker from /panel.", actions: panelHomeAction(hideHome, threadWorkerSessionId) };
5998
+ if (canPatchOrigin && event.message_id && ctx.connection.patch) {
5999
+ await deliverPanelSpec(refused, `panel-peek-refused-${event.event_id}`, true);
6000
+ } else if (ctx.connection.sendCard) {
6001
+ const sent = await ctx.connection.sendCard(peekRecipient, refused, `panel-peek-refused-${event.event_id}`, sendReplyTo, sendOpts);
6002
+ if (isCurrent()) ctx.cards.rememberPanelCard(sent?.messageId, sessionId, sent?.chatId ?? event.chat_id, threadMetaFor(sent?.messageId));
6003
+ }
5398
6004
  return;
5399
6005
  }
5400
6006
  if (!isCurrent()) return;
@@ -5435,7 +6041,7 @@ function createPanelExecutor(ctx) {
5435
6041
  if (!ctx.connection.sendCard) return;
5436
6042
  const sent = await ctx.connection.sendCard(peekRecipient, progressSpec, `panel-peek-${event.event_id}`, sendReplyTo, sendOpts);
5437
6043
  if (!sent?.messageId || !isCurrent()) return;
5438
- ctx.cards.rememberPanelCard(sent.messageId, sessionId, event.chat_id, threadMetaFor(sent.messageId));
6044
+ ctx.cards.rememberPanelCard(sent.messageId, sessionId, sent.chatId ?? event.chat_id, threadMetaFor(sent.messageId));
5439
6045
  ctx.cards.setPeekCard(sent.messageId, binding);
5440
6046
  targetCardId = sent.messageId;
5441
6047
  }
@@ -5497,10 +6103,11 @@ ${receipt.ok ? "Compaction runs on the target host (LLM summary \u2014 may take
5497
6103
  return;
5498
6104
  }
5499
6105
  if (panelCmd.cmd === "panel.upgrade.confirm") {
5500
- if (!ctx.allowUsers || !event.sender_id || !ctx.allowUsers.includes(event.sender_id)) {
5501
- ctx.log(`im-forward: panel.upgrade.confirm refused for ${event.sender_id ?? "unknown"} (execution-sink gate: allowUsers membership required)`);
6106
+ const auth = evaluateUpgradeConfirmAuth(ctx, event);
6107
+ if (!auth.allowed) {
6108
+ ctx.log(`im-forward: panel.upgrade.confirm refused for ${event.sender_id ?? "unknown"} (execution-sink gate: ${auth.reason})`);
5502
6109
  try {
5503
- await ctx.connection.send(freshRecipient, "\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers).", `panel-refused-${event.event_id}`, sendReplyTo, sendOpts);
6110
+ await ctx.connection.send(freshRecipient, formatUpgradeAuthRefusal(auth.reason, event.sender_id), `panel-refused-${event.event_id}`, sendReplyTo, sendOpts);
5504
6111
  } catch {
5505
6112
  }
5506
6113
  return;
@@ -5520,7 +6127,7 @@ ${receipt.ok ? "Compaction runs on the target host (LLM summary \u2014 may take
5520
6127
  try {
5521
6128
  if (ctx.connection.sendCard) {
5522
6129
  const sent = await ctx.connection.sendCard(freshRecipient, spec.columnsPerRow ? spec : { ...spec, columnsPerRow: cols }, key, sendReplyTo, sendOpts);
5523
- if (guard()) ctx.cards.rememberPanelCard(sent?.messageId, sessionId, event.chat_id, threadMetaFor(sent?.messageId));
6130
+ if (guard()) ctx.cards.rememberPanelCard(sent?.messageId, sessionId, sent?.chatId ?? event.chat_id, threadMetaFor(sent?.messageId));
5524
6131
  return sent?.messageId;
5525
6132
  }
5526
6133
  return (await ctx.connection.send(freshRecipient, renderCardFallbackMarkdown(spec), key, sendReplyTo, sendOpts))?.messageId;
@@ -5807,11 +6414,11 @@ function createInboundRetryController(ctx) {
5807
6414
 
5808
6415
  // builtin/extensions/im-forward/event-dispatch.ts
5809
6416
  import * as net from "node:net";
5810
- import * as fs12 from "node:fs";
5811
- import * as path12 from "node:path";
5812
- import { createHmac, randomUUID as randomUUID3 } from "node:crypto";
6417
+ import * as fs13 from "node:fs";
6418
+ import * as path13 from "node:path";
6419
+ import { createHmac, randomUUID as randomUUID4 } from "node:crypto";
5813
6420
  function discoveryDir() {
5814
- return path12.join(addressBookRoot(), "run", "ipc");
6421
+ return path13.join(addressBookRoot(), "run", "ipc");
5815
6422
  }
5816
6423
  function pidAlive5(pid) {
5817
6424
  if (!Number.isInteger(pid) || pid <= 0) return false;
@@ -5825,7 +6432,7 @@ function pidAlive5(pid) {
5825
6432
  function findOwnerInstance(sessionId) {
5826
6433
  let entries;
5827
6434
  try {
5828
- entries = fs12.readdirSync(discoveryDir());
6435
+ entries = fs13.readdirSync(discoveryDir());
5829
6436
  } catch {
5830
6437
  return void 0;
5831
6438
  }
@@ -5833,7 +6440,7 @@ function findOwnerInstance(sessionId) {
5833
6440
  for (const name of entries.slice(0, 256)) {
5834
6441
  if (!name.endsWith(".json")) continue;
5835
6442
  try {
5836
- const parsed = JSON.parse(fs12.readFileSync(path12.join(discoveryDir(), name), "utf8"));
6443
+ const parsed = JSON.parse(fs13.readFileSync(path13.join(discoveryDir(), name), "utf8"));
5837
6444
  if (parsed.instanceId === name.slice(0, -".json".length) && parsed.sessionId === sessionId && parsed.port && typeof parsed.secret === "string" && parsed.protocol === IPC_PROTOCOL_VERSION && pidAlive5(parsed.pid ?? 0)) {
5838
6445
  candidates.push({ file: parsed, startedAt: typeof parsed.startedAt === "number" ? parsed.startedAt : 0 });
5839
6446
  }
@@ -5847,7 +6454,7 @@ function findOwnerInstance(sessionId) {
5847
6454
  function findNamedOwnerInstance(name, binding) {
5848
6455
  let entries;
5849
6456
  try {
5850
- entries = fs12.readdirSync(discoveryDir()).filter((entry) => entry.endsWith(".json"));
6457
+ entries = fs13.readdirSync(discoveryDir()).filter((entry) => entry.endsWith(".json"));
5851
6458
  } catch {
5852
6459
  return void 0;
5853
6460
  }
@@ -5855,7 +6462,7 @@ function findNamedOwnerInstance(name, binding) {
5855
6462
  const matches = [];
5856
6463
  for (const entry of entries) {
5857
6464
  try {
5858
- const peer = JSON.parse(fs12.readFileSync(path12.join(discoveryDir(), entry), "utf8"));
6465
+ const peer = JSON.parse(fs13.readFileSync(path13.join(discoveryDir(), entry), "utf8"));
5859
6466
  if (peer.sessionName?.trim() !== name || !pidAlive5(peer.pid)) continue;
5860
6467
  matches.push(peer);
5861
6468
  } catch {
@@ -5873,12 +6480,12 @@ async function dispatchEventToName(name, binding, eventText) {
5873
6480
  return await deliverOnce(owner.port, owner.secret, eventText, owner.sessionId, owner.instanceId) ? owner.instanceId : void 0;
5874
6481
  }
5875
6482
  var SYNTHETIC_SENDER = (() => {
5876
- const hex = randomUUID3().replace(/-/g, "");
6483
+ const hex = randomUUID4().replace(/-/g, "");
5877
6484
  return `pie-${hex.slice(0, 12)}`;
5878
6485
  })();
5879
6486
  function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
5880
6487
  return new Promise((resolve7) => {
5881
- const id = randomUUID3();
6488
+ const id = randomUUID4();
5882
6489
  const envelope = {
5883
6490
  v: IPC_PROTOCOL_VERSION,
5884
6491
  id,
@@ -6106,7 +6713,7 @@ function createInboundShell(ctx) {
6106
6713
 
6107
6714
  // builtin/extensions/im-forward/runtime.ts
6108
6715
  import * as crypto from "node:crypto";
6109
- import * as fs13 from "node:fs";
6716
+ import * as fs14 from "node:fs";
6110
6717
  import { basename } from "node:path";
6111
6718
  var ROUTE_TTL_MS2 = 24 * 60 * 60 * 1e3;
6112
6719
  var SEND_FAILURE_NOTIFY_THROTTLE_MS2 = 5 * 60 * 1e3;
@@ -6279,19 +6886,7 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
6279
6886
  const notifySendFailure = (error) => routeState.notifySendFailure(error);
6280
6887
  const registerRoute = (sent, sessionId) => routeState.registerRoute(sent, sessionId);
6281
6888
  function resolveOutboundAttribution(sessionId) {
6282
- const messages = ctx.getMessages?.() ?? [];
6283
- let lastUserText;
6284
- for (let i = messages.length - 1; i >= 0; i--) {
6285
- const message = messages[i];
6286
- if (!isRecord(message) || message.role !== "user") continue;
6287
- const joined = (typeof message.content === "string" ? message.content : Array.isArray(message.content) ? message.content.map(
6288
- (block) => isRecord(block) && typeof block.text === "string" ? block.text : ""
6289
- ).join("") : "").trim();
6290
- if (joined) {
6291
- lastUserText = joined;
6292
- break;
6293
- }
6294
- }
6889
+ const lastUserText = extractLastUserMessageText(ctx.getMessages?.() ?? []);
6295
6890
  if (lastUserText === void 0) return void 0;
6296
6891
  for (let j = 0; j < pendingInputs.length; j++) {
6297
6892
  const pending = pendingInputs[j];
@@ -6391,6 +6986,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
6391
6986
  const attribution = resolveOutboundAttribution(sessionId);
6392
6987
  const deliver = /* @__PURE__ */ new Map();
6393
6988
  if (!outboundRoleAllows(attribution, deliver)) return;
6989
+ const ipcQuote = !isManager && !attribution?.caption ? extractLastUserMessageText(ctx.getMessages?.() ?? []) : void 0;
6394
6990
  void forwardMessage(
6395
6991
  text,
6396
6992
  sessionId,
@@ -6398,7 +6994,9 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
6398
6994
  attribution?.caption,
6399
6995
  attribution?.replyTo,
6400
6996
  attribution,
6401
- deliver
6997
+ deliver,
6998
+ void 0,
6999
+ ipcQuote
6402
7000
  ).then((delivered) => {
6403
7001
  if (delivered === true && attribution?.replyTo && connection.react) {
6404
7002
  providerCall("react", () => connection.react(attribution.replyTo, "CheckMark")).catch(() => void 0);
@@ -6415,6 +7013,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
6415
7013
  const deliverTf = /* @__PURE__ */ new Map();
6416
7014
  if (!outboundRoleAllows(attribution, deliverTf)) return;
6417
7015
  const recoveryHint = `Your input is still in the session \u2014 reply "redo the last one" to answer from it again without resending the original request.`;
7016
+ const ipcQuoteTf = !isManager && !attribution?.caption ? extractLastUserMessageText(ctx.getMessages?.() ?? []) : void 0;
6418
7017
  void forwardMessage(
6419
7018
  `\u26A0\uFE0F Task failed: ${reason} (retries exhausted)
6420
7019
  ${recoveryHint}`,
@@ -6424,7 +7023,8 @@ ${recoveryHint}`,
6424
7023
  attribution?.replyTo,
6425
7024
  attribution,
6426
7025
  deliverTf,
6427
- true
7026
+ true,
7027
+ ipcQuoteTf
6428
7028
  ).catch(() => void 0);
6429
7029
  });
6430
7030
  ctx.on("turn:cancelled", (event) => {
@@ -6435,6 +7035,7 @@ ${recoveryHint}`,
6435
7035
  const attribution = resolveOutboundAttribution(sessionId);
6436
7036
  const deliverTc = /* @__PURE__ */ new Map();
6437
7037
  if (!outboundRoleAllows(attribution, deliverTc)) return;
7038
+ const ipcQuoteTc = !isManager && !attribution?.caption ? extractLastUserMessageText(ctx.getMessages?.() ?? []) : void 0;
6438
7039
  void forwardMessage(
6439
7040
  `\u26D4\uFE0F Task cancelled: ${event.reason}`,
6440
7041
  sessionId,
@@ -6443,20 +7044,21 @@ ${recoveryHint}`,
6443
7044
  attribution?.replyTo,
6444
7045
  attribution,
6445
7046
  deliverTc,
6446
- true
7047
+ true,
7048
+ ipcQuoteTc
6447
7049
  ).catch(() => void 0);
6448
7050
  });
6449
- async function forwardMessage(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice) {
7051
+ async function forwardMessage(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice, ipcInput) {
6450
7052
  let settled = false;
6451
7053
  try {
6452
7054
  return await forwardMessageInner(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice, () => {
6453
7055
  settled = true;
6454
- });
7056
+ }, ipcInput);
6455
7057
  } finally {
6456
7058
  if (!settled) settleDelivery(deliverRequests, false);
6457
7059
  }
6458
7060
  }
6459
- async function forwardMessageInner(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice, markSettled) {
7061
+ async function forwardMessageInner(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice, markSettled, ipcInput) {
6460
7062
  pruneState();
6461
7063
  const sessionName = ctx.getSessionDisplayName?.() ?? ctx.getSessionName?.();
6462
7064
  const composeMode = resolveSessionAnchor(sessionId).threadId ? "topic-reply" : "topic-root";
@@ -6465,7 +7067,8 @@ ${recoveryHint}`,
6465
7067
  sessionName,
6466
7068
  userInput,
6467
7069
  text,
6468
- composeMode
7070
+ composeMode,
7071
+ ipcInput
6469
7072
  );
6470
7073
  if (terminated || !isForwardingEnabled()) {
6471
7074
  settleDelivery(deliverRequests, false);
@@ -6658,18 +7261,18 @@ ${recoveryHint}`,
6658
7261
  const files = collectFileReferences(
6659
7262
  text,
6660
7263
  ctx.cwd,
6661
- (path17) => {
7264
+ (path18) => {
6662
7265
  try {
6663
- const stat = fs13.statSync(path17);
7266
+ const stat = fs14.statSync(path18);
6664
7267
  return { isFile: stat.isFile(), size: stat.size };
6665
7268
  } catch {
6666
7269
  return null;
6667
7270
  }
6668
7271
  },
6669
7272
  {
6670
- canonicalize: (path17) => {
7273
+ canonicalize: (path18) => {
6671
7274
  try {
6672
- return fs13.realpathSync(path17);
7275
+ return fs14.realpathSync(path18);
6673
7276
  } catch {
6674
7277
  return null;
6675
7278
  }
@@ -6783,7 +7386,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
6783
7386
  getCurrentSessionId: () => currentSessionId,
6784
7387
  getBindingKey: () => bindingKey()
6785
7388
  });
6786
- const panelCards = createPanelCardState({ getInputEpoch: () => inputEpoch });
7389
+ const panelCards = createPanelCardState({ getInputEpoch: () => inputEpoch, provider: cfg.provider });
6787
7390
  const rememberPanelCard = (messageId, sessionId, chatId, thread) => panelCards.rememberPanelCard(messageId, sessionId, chatId, thread);
6788
7391
  const panelExecutor = createPanelExecutor({
6789
7392
  log: (message) => ctx.log(message),
@@ -7061,6 +7664,27 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
7061
7664
  await runPanelCommand(panelCmd, event, sessionId, () => scope.isCurrent(), directScope ? { ...directScope, threadReplyTo: event.message_id } : void 0);
7062
7665
  return;
7063
7666
  }
7667
+ const directShellCmd = parseDirectImCommand(caption);
7668
+ if (directShellCmd) {
7669
+ await runDirectImCommandMessage({
7670
+ command: directShellCmd,
7671
+ event,
7672
+ messageId,
7673
+ cwd: ctx.cwd,
7674
+ authCtx: { targetKind: cfg.targetKind, targetId: cfg.targetId, allowUsers: cfg.allowUsers, panelAccess: cfg.panelAccess },
7675
+ log: (m) => ctx.log(m),
7676
+ acknowledge: () => acknowledgeMessage(messageId),
7677
+ reactDone: () => connection.react ? providerCall("react", () => connection.react(messageId, "CheckMark")).then(() => void 0) : Promise.resolve(),
7678
+ reply: (body) => forwardMessage(body, sessionId, ++forwardCounter, void 0, messageId, void 0, void 0, true),
7679
+ registerAbort: (c) => {
7680
+ panelActionControllers.add(c);
7681
+ },
7682
+ unregisterAbort: (c) => {
7683
+ panelActionControllers.delete(c);
7684
+ }
7685
+ });
7686
+ return;
7687
+ }
7064
7688
  }
7065
7689
  const stripImagePlaceholders = (text) => text.replace(/!\[Image\]\(img_[A-Za-z0-9_-]+\)/g, "").replace(/\[Image:\s*img_[A-Za-z0-9_-]+\]/g, "").trim();
7066
7690
  const imagelessCaption = imageKeys.length ? stripImagePlaceholders(caption) : caption;
@@ -7300,13 +7924,45 @@ ${imagelessCaption || (imageKeys.length ? IM_INPUT_FALLBACK_CAPTION : "") || cap
7300
7924
 
7301
7925
  // builtin/extensions/im-forward/onboarding.ts
7302
7926
  async function runSetup(ctx, dir, providers, signal, isCurrent = () => !signal.aborted, intent = "first-run", suspendEventConsumer) {
7303
- const initial = resolveConfig(ctx.cwd, dir);
7927
+ const options = { signal, timeout: 12e4 };
7928
+ let initial = resolveConfig(ctx.cwd, dir);
7304
7929
  if (initial.problems.length) {
7305
- ctx.ui.notify(initial.problems.join("\n"), "error");
7306
- return;
7930
+ const invalidFiles = findInvalidConfigLayers(ctx.cwd, dir);
7931
+ if (invalidFiles.length > 0 && typeof ctx.ui.confirm === "function") {
7932
+ let preBackupSnapshot;
7933
+ try {
7934
+ preBackupSnapshot = configSnapshot(ctx.cwd, dir);
7935
+ } catch (error) {
7936
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
7937
+ return;
7938
+ }
7939
+ const recover = await ctx.ui.confirm(
7940
+ "Repair invalid IM configuration?",
7941
+ `${initial.problems.join("\n")}
7942
+
7943
+ Back up invalid file(s) (*.corrupt-*) and continue setup?
7944
+ ${invalidFiles.join("\n")}`,
7945
+ options
7946
+ );
7947
+ if (!isCurrent() || !recover) {
7948
+ ctx.ui.notify(initial.problems.join("\n"), "error");
7949
+ return;
7950
+ }
7951
+ try {
7952
+ const moved = backupInvalidConfigLayers(ctx.cwd, dir, preBackupSnapshot);
7953
+ ctx.ui.notify(`Backed up invalid IM config: ${moved.map((m) => m.to).join(", ")}`, "info");
7954
+ } catch (error) {
7955
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
7956
+ return;
7957
+ }
7958
+ initial = resolveConfig(ctx.cwd, dir);
7959
+ }
7960
+ if (initial.problems.length) {
7961
+ ctx.ui.notify(initial.problems.join("\n"), "error");
7962
+ return;
7963
+ }
7307
7964
  }
7308
7965
  const snapshot = configSnapshot(ctx.cwd, dir);
7309
- const options = { signal, timeout: 12e4 };
7310
7966
  if (!providers.length || !isCurrent()) return;
7311
7967
  let selected;
7312
7968
  if (intent === "switch-app" && initial.config) {
@@ -7346,7 +8002,7 @@ Enable forwarding and start the connection? No test message will be sent. Saving
7346
8002
  return resolveConfig(ctx.cwd, dir).config ?? void 0;
7347
8003
  }
7348
8004
  async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
7349
- const { spawn: spawn6 } = await import("node:child_process");
8005
+ const { spawn: spawn7 } = await import("node:child_process");
7350
8006
  const binary = binaryOverride ?? await settingsProbeBinary();
7351
8007
  if (!binary) return;
7352
8008
  await new Promise((resolve7) => {
@@ -7365,7 +8021,7 @@ async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
7365
8021
  done();
7366
8022
  }, 3500);
7367
8023
  timer.unref?.();
7368
- const child = spawn6(binary, ["event", "consume", "card.action.trigger", "--as", "bot", ...profile ? ["--profile", profile] : []], { cwd, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
8024
+ const child = spawn7(binary, ["event", "consume", "card.action.trigger", "--as", "bot", ...profile ? ["--profile", profile] : []], { cwd, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
7369
8025
  child.on("error", () => done());
7370
8026
  child.on("close", () => done());
7371
8027
  let out = "";
@@ -7386,19 +8042,19 @@ async function settingsProbeBinary() {
7386
8042
  try {
7387
8043
  const { spawnSync } = await import("node:child_process");
7388
8044
  const which = spawnSync(process.platform === "win32" ? "where" : "which", ["lark-cli"], { encoding: "utf8", timeout: 3e3, windowsHide: true });
7389
- const path17 = which.stdout?.split(/\r?\n/)[0]?.trim();
7390
- return path17 || void 0;
8045
+ const path18 = which.stdout?.split(/\r?\n/)[0]?.trim();
8046
+ return path18 || void 0;
7391
8047
  } catch {
7392
8048
  return void 0;
7393
8049
  }
7394
8050
  }
7395
8051
 
7396
8052
  // builtin/extensions/im-forward/providers/feishu/index.ts
7397
- import { spawn as spawn5 } from "node:child_process";
8053
+ import { spawn as spawn6 } from "node:child_process";
7398
8054
  import { createHash as createHash2 } from "node:crypto";
7399
- import * as fs15 from "node:fs";
8055
+ import * as fs16 from "node:fs";
7400
8056
  import * as os7 from "node:os";
7401
- import * as path16 from "node:path";
8057
+ import * as path17 from "node:path";
7402
8058
 
7403
8059
  // builtin/extensions/im-forward/providers/feishu/card.ts
7404
8060
  var COLOR_TEMPLATE = {
@@ -7545,17 +8201,17 @@ function extractImageKey(content) {
7545
8201
  }
7546
8202
 
7547
8203
  // builtin/extensions/im-forward/providers/feishu/setup.ts
7548
- import * as fs14 from "node:fs";
7549
- import * as path15 from "node:path";
8204
+ import * as fs15 from "node:fs";
8205
+ import * as path16 from "node:path";
7550
8206
 
7551
8207
  // builtin/extensions/im-forward/browser.ts
7552
- import { spawn as spawn4 } from "node:child_process";
7553
- import path13 from "node:path";
8208
+ import { spawn as spawn5 } from "node:child_process";
8209
+ import path14 from "node:path";
7554
8210
  var browserScript = "$ErrorActionPreference = 'Stop'; try { $reader = [System.IO.StreamReader]::new([Console]::OpenStandardInput(), [System.Text.Encoding]::UTF8); $url = $reader.ReadToEnd(); Start-Process -FilePath $url; exit 0 } catch { exit 1 }";
7555
8211
  function browserLaunch(platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
7556
8212
  if (platform === "win32") {
7557
8213
  if (!/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return;
7558
- return { command: path13.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(browserScript, "utf16le").toString("base64")], stdin: true };
8214
+ return { command: path14.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(browserScript, "utf16le").toString("base64")], stdin: true };
7559
8215
  }
7560
8216
  if (platform === "darwin") return { command: "/usr/bin/open", args: ["--"], stdin: false };
7561
8217
  if (platform === "linux") return { command: "/usr/bin/xdg-open", args: [], stdin: false };
@@ -7597,7 +8253,7 @@ async function openBrowser(url, signal, seam = {}) {
7597
8253
  const abort = () => stop();
7598
8254
  const timer = setTimeout(stop, seam.timeoutMs ?? 1e4);
7599
8255
  try {
7600
- child = (seam.spawn ?? spawn4)(spec.command, spec.stdin ? spec.args : [...spec.args, url], { shell: false, windowsHide: true, detached: process.platform !== "win32", stdio: [spec.stdin ? "pipe" : "ignore", "ignore", "ignore"] });
8256
+ child = (seam.spawn ?? spawn5)(spec.command, spec.stdin ? spec.args : [...spec.args, url], { shell: false, windowsHide: true, detached: process.platform !== "win32", stdio: [spec.stdin ? "pipe" : "ignore", "ignore", "ignore"] });
7601
8257
  child.on("error", stop);
7602
8258
  child.on("close", (code) => {
7603
8259
  closed = true;
@@ -7614,24 +8270,24 @@ async function openBrowser(url, signal, seam = {}) {
7614
8270
  }
7615
8271
 
7616
8272
  // builtin/extensions/im-forward/existing-app-terminal.ts
7617
- import path14 from "node:path";
8273
+ import path15 from "node:path";
7618
8274
  var existingAppInnerScript = "$ErrorActionPreference = 'Stop'; try { $payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PAYLOAD__')) | ConvertFrom-Json; Set-Location -LiteralPath $payload.cwd; & $payload.command @($payload.args); $code = $LASTEXITCODE; if ($null -eq $code) { exit 1 }; exit $code } catch { Write-Host 'Official setup failed. Close this window and retry from Pie.'; exit 1 }";
7619
8275
  var existingAppOuterTemplate = "$ErrorActionPreference = 'Stop'; try { $inner = '" + existingAppInnerScript.replaceAll("'", "''") + "'; $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($inner)); $child = Start-Process -FilePath (Join-Path $PSHOME 'powershell.exe') -WindowStyle Normal -Wait -PassThru -ArgumentList @('-NoLogo', '-NoProfile', '-EncodedCommand', $encoded); exit $child.ExitCode } catch { exit 1 }";
7620
8276
  function existingAppTerminal(binary, cwd, platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
7621
8277
  if (platform !== "win32" || !/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return null;
7622
8278
  const payload = Buffer.from(JSON.stringify({ command: binary.command, args: [...binary.prefix, "config", "init", "--brand", "feishu"], cwd }), "utf8").toString("base64");
7623
8279
  const script = existingAppOuterTemplate.replace("__PAYLOAD__", payload);
7624
- return { command: path14.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), prefix: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
8280
+ return { command: path15.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), prefix: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
7625
8281
  }
7626
8282
 
7627
8283
  // builtin/extensions/im-forward/providers/feishu/setup.ts
7628
8284
  function findNpmCli() {
7629
- const dirs = [path15.dirname(process.execPath), ...(process.env.PATH ?? "").split(path15.delimiter)];
7630
- for (const dir of dirs) for (const root of [path15.join(dir, "node_modules", "npm"), path15.resolve(dir, "..", "lib", "node_modules", "npm")]) {
8285
+ const dirs = [path16.dirname(process.execPath), ...(process.env.PATH ?? "").split(path16.delimiter)];
8286
+ for (const dir of dirs) for (const root of [path16.join(dir, "node_modules", "npm"), path16.resolve(dir, "..", "lib", "node_modules", "npm")]) {
7631
8287
  try {
7632
- const pkg = JSON.parse(fs14.readFileSync(path15.join(root, "package.json"), "utf8"));
7633
- const entry = path15.join(root, "bin", "npm-cli.js");
7634
- if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs14.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
8288
+ const pkg = JSON.parse(fs15.readFileSync(path16.join(root, "package.json"), "utf8"));
8289
+ const entry = path16.join(root, "bin", "npm-cli.js");
8290
+ if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs15.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
7635
8291
  } catch {
7636
8292
  }
7637
8293
  }
@@ -7951,8 +8607,8 @@ ${progressLabel}` : "");
7951
8607
  if (!await bindNewApp()) return;
7952
8608
  } else profileName = singleProfile.name;
7953
8609
  } else if (profiles && profiles.length > 1) {
7954
- const previousProfile = profiles.find((item) => item.name === profileName);
7955
- if (!previousProfile) profileName = void 0;
8610
+ const previousProfile2 = profiles.find((item) => item.name === profileName);
8611
+ if (!previousProfile2) profileName = void 0;
7956
8612
  const items = ["Use the CLI's active app (no per-machine profile)", ...profiles.map(describe), connectDifferent, "Cancel"];
7957
8613
  const choice = await ui.select("IM forwarding setup \u2014 Feishu app (per machine)", items, options);
7958
8614
  if (!current() || !choice || choice === "Cancel") return;
@@ -8110,7 +8766,13 @@ ${detect.error ?? ""}`);
8110
8766
  }
8111
8767
  if (!current() || !target) return;
8112
8768
  const boundAppId = profiles?.find((item) => item.name === profileName)?.appId ?? (profileName ? void 0 : profiles?.find((item) => item.active)?.appId);
8113
- return { ...previous ?? {}, ...target.openId ? { openId: target.openId, chatId: null } : { chatId: target.chatId, openId: null }, larkCli: executable ?? null, larkCliProfile: profileName ?? null, larkCliAppId: boundAppId ?? null, allowUsers: target.allowUsers ?? previous?.allowUsers ?? null };
8769
+ const previousAppId = typeof previous?.larkCliAppId === "string" && previous.larkCliAppId.trim() ? previous.larkCliAppId.trim() : void 0;
8770
+ const previousProfile = typeof previous?.larkCliProfile === "string" && previous.larkCliProfile.trim() ? previous.larkCliProfile.trim() : void 0;
8771
+ const appChanged = Boolean(
8772
+ boundAppId && previousAppId && boundAppId !== previousAppId || profileName && previousProfile && profileName !== previousProfile
8773
+ );
8774
+ const inheritedAllowUsers = appChanged ? null : previous?.allowUsers ?? null;
8775
+ return { ...previous ?? {}, ...target.openId ? { openId: target.openId, chatId: null } : { chatId: target.chatId, openId: null }, larkCli: executable ?? null, larkCliProfile: profileName ?? null, larkCliAppId: boundAppId ?? null, allowUsers: target.allowUsers ?? inheritedAllowUsers };
8114
8776
  }
8115
8777
 
8116
8778
  // builtin/extensions/im-forward/providers/feishu/index.ts
@@ -8211,6 +8873,30 @@ function normalizeMenuEvent(line, fallbackChatId) {
8211
8873
  images: []
8212
8874
  };
8213
8875
  }
8876
+ var PATCH_RETRY_DELAYS_MS = [300, 900];
8877
+ var PERMANENT_PATCH_ERROR_PATTERN = /\b(?:230001|230002|230011|230013|230027|230072|230073|230099|200621|200340|200341)\b|recalled|deleted|message not found|card not found|14 day|invalid_argument|permission|unauthorized|cancelled|update_multi/i;
8878
+ function isPermanentFeishuPatchError(reason) {
8879
+ return Boolean(reason && PERMANENT_PATCH_ERROR_PATTERN.test(reason));
8880
+ }
8881
+ function sanitizePatchError(raw) {
8882
+ const single = raw.replace(/[\r\n\t]+/g, " ").replace(/\bbearer\s+\S+/gi, "Bearer [redacted]").replace(/(?:token|secret|authorization|app_secret|api_key)\s*[:=]\s*\S+/gi, "[redacted]").replace(/\s+/g, " ").trim();
8883
+ return single.length <= 180 ? single : `${single.slice(0, 179)}\u2026`;
8884
+ }
8885
+ function sleepAbortable(ms, signal) {
8886
+ if (signal.aborted) return Promise.resolve(false);
8887
+ return new Promise((resolve7) => {
8888
+ const onAbort = () => {
8889
+ clearTimeout(timer);
8890
+ resolve7(false);
8891
+ };
8892
+ const timer = setTimeout(() => {
8893
+ signal.removeEventListener("abort", onAbort);
8894
+ resolve7(true);
8895
+ }, ms);
8896
+ timer.unref?.();
8897
+ signal.addEventListener("abort", onAbort, { once: true });
8898
+ });
8899
+ }
8214
8900
  function connect(binary, profile, targetKind = "chat", settings = { targetId: "" }) {
8215
8901
  const lifetime = new AbortController();
8216
8902
  const active = /* @__PURE__ */ new Set();
@@ -8220,9 +8906,28 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
8220
8906
  void pending.finally(() => active.delete(pending));
8221
8907
  return pending;
8222
8908
  };
8223
- const call = async (args) => {
8909
+ const callDetailed = async (args) => {
8224
8910
  const result = await native(binary, profile ? [...args, "--profile", profile] : args, 3e4, void 0, { signal: lifetime.signal });
8225
- return result.error ? void 0 : parseLarkCliEnvelope(result.stdout).data;
8911
+ if (result.error) {
8912
+ const env2 = result.stdout.trim() ? parseLarkCliEnvelope(result.stdout) : void 0;
8913
+ return { ok: false, error: env2?.errorText ? `${result.error} (${env2.errorText})` : result.error };
8914
+ }
8915
+ const env = parseLarkCliEnvelope(result.stdout);
8916
+ if (env.ok && env.data) return { ok: true, data: env.data };
8917
+ return { ok: false, error: env.errorText ?? "empty lark-cli response" };
8918
+ };
8919
+ const call = async (args) => {
8920
+ const res = await callDetailed(args);
8921
+ return res.ok ? res.data : void 0;
8922
+ };
8923
+ const lastPatchErrors = /* @__PURE__ */ new Map();
8924
+ const recordPatchError = (messageId, reason) => {
8925
+ lastPatchErrors.delete(messageId);
8926
+ lastPatchErrors.set(messageId, sanitizePatchError(reason));
8927
+ if (lastPatchErrors.size > 50) {
8928
+ const oldest = lastPatchErrors.keys().next().value;
8929
+ if (oldest !== void 0) lastPatchErrors.delete(oldest);
8930
+ }
8226
8931
  };
8227
8932
  let canonicalAppIdCache = null;
8228
8933
  let canonicalResolved = false;
@@ -8281,10 +8986,37 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
8281
8986
  return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null, ...typeof data.chat_id === "string" && data.chat_id ? { chatId: data.chat_id } : {} } : null;
8282
8987
  },
8283
8988
  // 4.3.10: patch an existing card in place (admin panels refresh without
8284
- // re-sending). Feishu bound: the message must be <14 days old.
8989
+ // re-sending). Feishu bound: the message must be <14 days old. Transient
8990
+ // errors (rate limit, network/CLI hiccup) retry briefly before failing so
8991
+ // a single blip does not spawn a duplicate card.
8285
8992
  async patch(messageId, spec) {
8286
- const data = await call(["im", "messages", "patch", "--as", "bot", "--params", JSON.stringify({ message_id: messageId }), "--data", JSON.stringify({ content: JSON.stringify(compileCard(spec)) })]);
8287
- return Boolean(data);
8993
+ const args = ["im", "messages", "patch", "--as", "bot", "--params", JSON.stringify({ message_id: messageId }), "--data", JSON.stringify({ content: JSON.stringify(compileCard(spec)) })];
8994
+ const maxAttempts = PATCH_RETRY_DELAYS_MS.length + 1;
8995
+ let lastError = "unknown patch error";
8996
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
8997
+ const res = await callDetailed(args);
8998
+ if (res.ok) {
8999
+ lastPatchErrors.delete(messageId);
9000
+ return true;
9001
+ }
9002
+ lastError = res.error;
9003
+ if (attempt >= maxAttempts || isPermanentFeishuPatchError(lastError) || lifetime.signal.aborted) {
9004
+ recordPatchError(messageId, attempt > 1 ? `attempt ${attempt}/${maxAttempts}: ${lastError}` : lastError);
9005
+ return false;
9006
+ }
9007
+ const okToContinue = await sleepAbortable(PATCH_RETRY_DELAYS_MS[attempt - 1], lifetime.signal);
9008
+ if (!okToContinue) {
9009
+ recordPatchError(messageId, `cancelled after attempt ${attempt}/${maxAttempts}: ${lastError}`);
9010
+ return false;
9011
+ }
9012
+ }
9013
+ recordPatchError(messageId, lastError);
9014
+ return false;
9015
+ },
9016
+ consumeLastPatchError(messageId) {
9017
+ const detail = lastPatchErrors.get(messageId);
9018
+ lastPatchErrors.delete(messageId);
9019
+ return detail;
8288
9020
  },
8289
9021
  async acknowledge(id) {
8290
9022
  await call(["im", "reactions", "create", "--as", "bot", "--params", JSON.stringify({ message_id: id }), "--data", JSON.stringify({ reaction_type: { emoji_type: "THUMBSUP" } })]);
@@ -8316,19 +9048,19 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
8316
9048
  return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
8317
9049
  },
8318
9050
  async downloadImage(messageId, image, index) {
8319
- const directory = fs15.mkdtempSync(path16.join(os7.tmpdir(), "pie-im-forward-"));
8320
- const cleanup = () => fs15.rmSync(directory, { recursive: true, force: true });
9051
+ const directory = fs16.mkdtempSync(path17.join(os7.tmpdir(), "pie-im-forward-"));
9052
+ const cleanup = () => fs16.rmSync(directory, { recursive: true, force: true });
8321
9053
  try {
8322
9054
  const name = `image-${index + 1}.png`;
8323
9055
  const result = await native(binary, profile ? ["im", "+messages-resources-download", "--as", "bot", "--message-id", messageId, "--file-key", image, "--type", "image", "--output", name, "--profile", profile] : ["im", "+messages-resources-download", "--as", "bot", "--message-id", messageId, "--file-key", image, "--type", "image", "--output", name], 3e4, directory, { signal: lifetime.signal });
8324
9056
  if (result.error || !parseLarkCliEnvelope(result.stdout).ok) throw new Error("Image download failed");
8325
- let target = path16.join(directory, name);
8326
- if (fs15.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
9057
+ let target = path17.join(directory, name);
9058
+ if (fs16.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
8327
9059
  const detected = readImageFormat(target);
8328
9060
  if (detected.ext === ".bin") throw new Error("Unsupported image format");
8329
9061
  if (detected.ext !== ".png") {
8330
- const corrected = path16.join(directory, `image-${index + 1}${detected.ext}`);
8331
- fs15.renameSync(target, corrected);
9062
+ const corrected = path17.join(directory, `image-${index + 1}${detected.ext}`);
9063
+ fs16.renameSync(target, corrected);
8332
9064
  target = corrected;
8333
9065
  }
8334
9066
  return { file: { path: target, displayName: `feishu-image-${index + 1}${detected.ext}` }, cleanup };
@@ -8367,7 +9099,7 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
8367
9099
  optionalRespawnTimers.set(eventKey, timer);
8368
9100
  };
8369
9101
  const spawnConsume = (eventKey, map, required) => {
8370
- const child2 = spawn5(binary.command, [...binary.prefix, "event", "consume", eventKey, "--as", "bot", ...profile ? ["--profile", profile] : []], { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, detached: process.platform !== "win32" });
9102
+ const child2 = spawn6(binary.command, [...binary.prefix, "event", "consume", eventKey, "--as", "bot", ...profile ? ["--profile", profile] : []], { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, detached: process.platform !== "win32" });
8371
9103
  child2.stdin?.on("error", () => void 0);
8372
9104
  const output = lineReader((line) => {
8373
9105
  if (!closed) {
@@ -8508,18 +9240,18 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
8508
9240
  const appId = await canonicalAppIdNow();
8509
9241
  if (!appId) return void 0;
8510
9242
  const larkHome = process.env.PIE_LARK_CLI_HOME && process.env.PIE_LARK_CLI_HOME.trim() ? process.env.PIE_LARK_CLI_HOME : os7.homedir();
8511
- const logPath = path16.join(larkHome, ".lark-cli", "events", appId, "bus.log");
9243
+ const logPath = path17.join(larkHome, ".lark-cli", "events", appId, "bus.log");
8512
9244
  let tail;
8513
9245
  try {
8514
- const fd = fs15.openSync(logPath, "r");
9246
+ const fd = fs16.openSync(logPath, "r");
8515
9247
  try {
8516
- const size = fs15.fstatSync(fd).size;
9248
+ const size = fs16.fstatSync(fd).size;
8517
9249
  const start = Math.max(0, size - 64 * 1024);
8518
9250
  const buf = Buffer.alloc(size - start);
8519
- fs15.readSync(fd, buf, 0, buf.length, start);
9251
+ fs16.readSync(fd, buf, 0, buf.length, start);
8520
9252
  tail = buf.toString("utf8");
8521
9253
  } finally {
8522
- fs15.closeSync(fd);
9254
+ fs16.closeSync(fd);
8523
9255
  }
8524
9256
  } catch {
8525
9257
  return void 0;