@cydm/pie 4.10.2 → 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;
@@ -652,10 +703,418 @@ function resolveImForwardConfig(cwd, dir) {
652
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_...)"] };
653
704
  }
654
705
 
655
- // 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";
656
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";
657
1116
  import * as os2 from "node:os";
658
- 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";
659
1118
  function summarizeFailureReason(reason) {
660
1119
  if (!reason) return { summary: "", persistent: false };
661
1120
  const text = reason.toLowerCase();
@@ -690,10 +1149,10 @@ function ipcDiscoveryRoot() {
690
1149
  }
691
1150
  function liveManagerForBinding(binding) {
692
1151
  try {
693
- for (const file of fs2.readdirSync(ipcDiscoveryRoot())) {
1152
+ for (const file of fs3.readdirSync(ipcDiscoveryRoot())) {
694
1153
  if (!file.endsWith(".json")) continue;
695
1154
  try {
696
- const peer = JSON.parse(fs2.readFileSync(pathJoin(ipcDiscoveryRoot(), file), "utf8"));
1155
+ const peer = JSON.parse(fs3.readFileSync(pathJoin(ipcDiscoveryRoot(), file), "utf8"));
697
1156
  if (peer.pid === process.pid || peer.isManager !== true || peer.imBinding !== binding || !Number.isInteger(peer.pid) || !peer.pid || peer.pid <= 0) continue;
698
1157
  try {
699
1158
  process.kill(peer.pid, 0);
@@ -717,8 +1176,8 @@ async function applyPeerControlDirect(peerRef, control, payload, expected) {
717
1176
  let target;
718
1177
  try {
719
1178
  const dir = ipcDiscoveryRoot();
720
- for (const file of fs2.readdirSync(dir).filter((f) => f.endsWith(".json"))) {
721
- 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"));
722
1181
  if (!parsed.port || !parsed.secret || typeof parsed.pid !== "number" || !parsed.instanceId || typeof parsed.sessionId !== "string" || !parsed.sessionId) continue;
723
1182
  const match = parsed.instanceId === peerRef || parsed.instanceId.startsWith(peerRef) || parsed.displayName === peerRef;
724
1183
  if (!match) continue;
@@ -875,24 +1334,24 @@ _Estimate (bytes/4 heuristic) \u2014 same basis as the TUI's /debugs/context rep
875
1334
  }
876
1335
 
877
1336
  // builtin/extensions/im-forward/session-anchors.ts
878
- import * as fs4 from "node:fs";
879
- import * as path3 from "node:path";
1337
+ import * as fs5 from "node:fs";
1338
+ import * as path4 from "node:path";
880
1339
 
881
1340
  // builtin/extensions/im-forward/address-book.ts
882
- import * as fs3 from "node:fs";
1341
+ import * as fs4 from "node:fs";
883
1342
  import * as os3 from "node:os";
884
- import * as path2 from "node:path";
1343
+ import * as path3 from "node:path";
885
1344
  var MAX_ADDRESS_HEAD = 64;
886
1345
  function addressBookRoot() {
887
1346
  const raw = process.env.PIE_IPC_CONFIG_DIR;
888
1347
  if (raw !== void 0) {
889
1348
  if (raw.length > 0) {
890
- const expanded = raw === "~" ? os3.homedir() : raw.startsWith("~/") ? path2.join(os3.homedir(), raw.slice(2)) : raw;
891
- 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);
892
1351
  }
893
- return path2.resolve("");
1352
+ return path3.resolve("");
894
1353
  }
895
- return path2.resolve(resolveConfigDir());
1354
+ return path3.resolve(resolveConfigDir());
896
1355
  }
897
1356
  function pidAlive(pid) {
898
1357
  if (!Number.isInteger(pid) || pid <= 0) return true;
@@ -908,10 +1367,10 @@ function scanAddressBook() {
908
1367
  let complete = true;
909
1368
  let selfPublished;
910
1369
  let dirExists = false;
911
- const dir = path2.join(addressBookRoot(), "run", "ipc");
1370
+ const dir = path3.join(addressBookRoot(), "run", "ipc");
912
1371
  let entries;
913
1372
  try {
914
- entries = fs3.readdirSync(dir);
1373
+ entries = fs4.readdirSync(dir);
915
1374
  dirExists = true;
916
1375
  } catch (error) {
917
1376
  if (error.code === "ENOENT") return { names, complete: true, dirExists: false };
@@ -920,7 +1379,7 @@ function scanAddressBook() {
920
1379
  for (const [index, file] of entries.entries()) {
921
1380
  if (!file.endsWith(".json")) continue;
922
1381
  try {
923
- const status = JSON.parse(fs3.readFileSync(path2.join(dir, file), "utf8"));
1382
+ const status = JSON.parse(fs4.readFileSync(path3.join(dir, file), "utf8"));
924
1383
  dirExists = true;
925
1384
  const name = typeof status.sessionName === "string" ? status.sessionName.trim() : "";
926
1385
  const pid = typeof status.pid === "number" ? status.pid : void 0;
@@ -982,15 +1441,15 @@ function resolveAddress(text, ownLiveName, book) {
982
1441
 
983
1442
  // builtin/extensions/im-forward/session-anchors.ts
984
1443
  function anchorsDir() {
985
- return path3.join(addressBookRoot(), "im-forward", "anchors");
1444
+ return path4.join(addressBookRoot(), "im-forward", "anchors");
986
1445
  }
987
1446
  function anchorPath(sessionId) {
988
1447
  const safe = sessionId.replace(/[^a-zA-Z0-9._-]/g, "_");
989
- return path3.join(anchorsDir(), `${safe}.json`);
1448
+ return path4.join(anchorsDir(), `${safe}.json`);
990
1449
  }
991
1450
  function loadPersistedAnchor(sessionId, identity) {
992
1451
  try {
993
- const raw = fs4.readFileSync(anchorPath(sessionId), "utf8");
1452
+ const raw = fs5.readFileSync(anchorPath(sessionId), "utf8");
994
1453
  const parsed = JSON.parse(raw);
995
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
996
1455
  // anchor may live in ANY room — a group chat id differs from the
@@ -1020,8 +1479,8 @@ function savePersistedAnchor(sessionId, identity, anchor) {
1020
1479
  anchor
1021
1480
  };
1022
1481
  const target = anchorPath(sessionId);
1023
- fs4.mkdirSync(path3.dirname(target), { recursive: true });
1024
- fs4.writeFileSync(target, `${JSON.stringify(file)}
1482
+ fs5.mkdirSync(path4.dirname(target), { recursive: true });
1483
+ fs5.writeFileSync(target, `${JSON.stringify(file)}
1025
1484
  `, "utf8");
1026
1485
  } catch {
1027
1486
  }
@@ -1032,7 +1491,7 @@ var SAFE_APPLINK_HOST = /^[a-z0-9.-]+$/i;
1032
1491
  function resolveSessionThreadUrl(sessionId) {
1033
1492
  if (!sessionId) return void 0;
1034
1493
  try {
1035
- const raw = fs4.readFileSync(anchorPath(sessionId), "utf8");
1494
+ const raw = fs5.readFileSync(anchorPath(sessionId), "utf8");
1036
1495
  const parsed = JSON.parse(raw);
1037
1496
  if (parsed.provider !== "feishu" || !parsed.anchor) return void 0;
1038
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 : "";
@@ -1319,13 +1778,13 @@ function createRuntimeRoutes(ctx) {
1319
1778
  }
1320
1779
 
1321
1780
  // builtin/extensions/im-forward/event-hub.ts
1322
- import * as path4 from "node:path";
1781
+ import * as path5 from "node:path";
1323
1782
  function hubDir() {
1324
- return path4.join(addressBookRoot(), "im-forward");
1783
+ return path5.join(addressBookRoot(), "im-forward");
1325
1784
  }
1326
1785
  function lockPath(binding) {
1327
1786
  const safe = binding.replace(/[^a-zA-Z0-9._-]/g, "_");
1328
- return path4.join(hubDir(), `consumer-${safe}.lock`);
1787
+ return path5.join(hubDir(), `consumer-${safe}.lock`);
1329
1788
  }
1330
1789
  function readLock(binding) {
1331
1790
  return readOwnership(lockPath(binding), (v) => v.binding === binding);
@@ -1466,7 +1925,7 @@ function createConsumerLifecycle(ctx) {
1466
1925
  if (!ctx.isTerminated()) {
1467
1926
  restartTimer = setTimeout(() => {
1468
1927
  consumerSlotRetiring = false;
1469
- void spawn6();
1928
+ void spawn7();
1470
1929
  }, 15e3);
1471
1930
  restartTimer.unref?.();
1472
1931
  }
@@ -1489,10 +1948,10 @@ function createConsumerLifecycle(ctx) {
1489
1948
  const scheduleRestart = (delayMs) => {
1490
1949
  if (restartTimer) clearTimeout(restartTimer);
1491
1950
  restartDueAt = Date.now() + delayMs;
1492
- restartTimer = setTimeout(spawn6, delayMs);
1951
+ restartTimer = setTimeout(spawn7, delayMs);
1493
1952
  restartTimer.unref?.();
1494
1953
  };
1495
- async function spawn6() {
1954
+ async function spawn7() {
1496
1955
  restartTimer = void 0;
1497
1956
  restartDueAt = void 0;
1498
1957
  if (ctx.isTerminated() || suspended || consumerSlotRetiring || generation?.stopFailed || consumer || consumerRecovering) return;
@@ -1507,19 +1966,19 @@ function createConsumerLifecycle(ctx) {
1507
1966
  consumerStartupInFlight = false;
1508
1967
  }
1509
1968
  if (!key) {
1510
- restartTimer = setTimeout(spawn6, 15e3);
1969
+ restartTimer = setTimeout(spawn7, 15e3);
1511
1970
  restartTimer.unref?.();
1512
1971
  restartDueAt = Date.now() + 15e3;
1513
1972
  return;
1514
1973
  }
1515
1974
  if (!acquireClaimedSlot(key)) {
1516
- restartTimer = setTimeout(spawn6, 15e3);
1975
+ restartTimer = setTimeout(spawn7, 15e3);
1517
1976
  restartTimer.unref?.();
1518
1977
  restartDueAt = Date.now() + 15e3;
1519
1978
  return;
1520
1979
  }
1521
1980
  } else if (!acquireClaimedSlot(resolveBindingKeySync())) {
1522
- restartTimer = setTimeout(spawn6, 15e3);
1981
+ restartTimer = setTimeout(spawn7, 15e3);
1523
1982
  restartTimer.unref?.();
1524
1983
  restartDueAt = Date.now() + 15e3;
1525
1984
  return;
@@ -1544,7 +2003,7 @@ function createConsumerLifecycle(ctx) {
1544
2003
  RESTART_BACKOFF_MIN_MS * 2 ** Math.min(consumerRestarts, 4),
1545
2004
  RESTART_BACKOFF_MAX_MS
1546
2005
  );
1547
- restartTimer = setTimeout(spawn6, backoff);
2006
+ restartTimer = setTimeout(spawn7, backoff);
1548
2007
  restartTimer.unref?.();
1549
2008
  restartDueAt = Date.now() + backoff;
1550
2009
  });
@@ -1614,249 +2073,90 @@ function createConsumerLifecycle(ctx) {
1614
2073
  consumerLock = void 0;
1615
2074
  }
1616
2075
  consumer = null;
1617
- }
1618
- const suspend = async () => {
1619
- if (ctx.isTerminated() || suspended) return () => {
1620
- };
1621
- ctx.bumpInputEpoch();
1622
- suspended = true;
1623
- releaseImBinding?.();
1624
- releaseImBinding = void 0;
1625
- const gen = generation;
1626
- if (restartTimer) {
1627
- suspendedRestartInMs = restartDueAt !== void 0 ? Math.max(0, restartDueAt - Date.now()) : 0;
1628
- clearTimeout(restartTimer);
1629
- restartTimer = void 0;
1630
- restartDueAt = void 0;
1631
- }
1632
- consumer = null;
1633
- consumerRecovering = false;
1634
- consumerReady = false;
1635
- if (gen && !gen.retired) await stopGeneration(gen);
1636
- if (ctx.isTerminated()) return () => {
1637
- };
1638
- let resumed = false;
1639
- return () => {
1640
- if (resumed || ctx.isTerminated()) return;
1641
- resumed = true;
1642
- if (!suspended) return;
1643
- suspended = false;
1644
- if (consumer || consumerRecovering || restartTimer) return;
1645
- const delay2 = suspendedRestartInMs !== void 0 ? suspendedRestartInMs : Math.min(
1646
- RESTART_BACKOFF_MIN_MS * 2 ** Math.min(consumerRestarts, 4),
1647
- RESTART_BACKOFF_MAX_MS
1648
- );
1649
- suspendedRestartInMs = void 0;
1650
- scheduleRestart(delay2);
1651
- };
1652
- };
1653
- return {
1654
- bindingKey,
1655
- spawn: spawn6,
1656
- holdsSlot: () => !!consumerLock,
1657
- status: () => ({
1658
- consumerActive: !!consumer,
1659
- consumerReady,
1660
- consumerLastExit,
1661
- consumerRestarts,
1662
- terminated: ctx.isTerminated(),
1663
- pendingRestart: !!restartTimer,
1664
- suspended,
1665
- recovering: consumerRecovering
1666
- }),
1667
- terminate,
1668
- suspend,
1669
- stopGeneration
1670
- };
1671
- }
1672
-
1673
- // builtin/extensions/im-forward/panel.ts
1674
- import * as fs8 from "node:fs";
1675
- import * as os5 from "node:os";
1676
- import * as path9 from "node:path";
1677
- import { fileURLToPath } from "node:url";
1678
-
1679
- // builtin/extensions/im-forward/discovery.ts
1680
- import * as os4 from "node:os";
1681
- import * as path5 from "node:path";
1682
- function ipcDiscoveryRoot2() {
1683
- const home = os4.homedir() || process.env.HOME || process.env.USERPROFILE || "/tmp";
1684
- const override = process.env.PIE_IPC_CONFIG_DIR;
1685
- const agentDir = process.env.PIE_CODING_AGENT_DIR?.trim();
1686
- const raw = override !== void 0 ? override : agentDir || path5.join(home, ".pie");
1687
- const configDir = process.platform === "win32" ? raw : path5.resolve(raw === "~" ? home : raw.startsWith("~/") ? path5.join(home, raw.slice(2)) : raw);
1688
- return path5.join(configDir, "run", "ipc");
1689
- }
1690
-
1691
- // builtin/extensions/im-forward/panel-actions.ts
1692
- import { execFile, spawn as spawn3 } from "node:child_process";
1693
- import { randomBytes } from "node:crypto";
1694
- import { StringDecoder as StringDecoder3 } from "node:string_decoder";
1695
- import * as fs6 from "node:fs";
1696
- import * as path7 from "node:path";
1697
-
1698
- // builtin/extensions/im-forward/lark-cli.ts
1699
- import { spawn as spawn2 } from "node:child_process";
1700
- import { StringDecoder as StringDecoder2 } from "node:string_decoder";
1701
-
1702
- // builtin/extensions/im-forward/launch.ts
1703
- import { spawn } from "node:child_process";
1704
- import * as fs5 from "node:fs";
1705
- import * as path6 from "node:path";
1706
- import { StringDecoder } from "node:string_decoder";
1707
- function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
1708
- const windows = platform === "win32";
1709
- 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)));
1710
- for (const candidate of candidates) {
1711
- try {
1712
- if (!fs5.statSync(candidate).isFile()) continue;
1713
- const ext = path6.extname(candidate).toLowerCase();
1714
- if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
1715
- if (windows && ext === ".cmd") {
1716
- const dir = path6.dirname(candidate);
1717
- for (const root of [path6.join(dir, "node_modules", "@larksuite", "cli"), path6.resolve(dir, "..", "@larksuite", "cli")]) {
1718
- try {
1719
- const pkg = JSON.parse(fs5.readFileSync(path6.join(root, "package.json"), "utf8"));
1720
- const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
1721
- if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
1722
- const entry = path6.join(root, "scripts", "run.js");
1723
- if (fs5.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
1724
- } catch {
1725
- }
1726
- }
1727
- continue;
1728
- }
1729
- if (windows && ext !== ".exe") continue;
1730
- fs5.accessSync(candidate, fs5.constants.X_OK);
1731
- return { command: candidate, prefix: [] };
1732
- } catch {
1733
- }
1734
- }
1735
- return null;
1736
- }
1737
- var treeStops = /* @__PURE__ */ new WeakMap();
1738
- var hasExited = (child) => child.exitCode != null || child.signalCode != null;
1739
- function stopOwnedTree(child, signal) {
1740
- const existing = treeStops.get(child);
1741
- if (existing) return existing;
1742
- if (process.platform === "win32" && hasExited(child)) return Promise.resolve(false);
1743
- const pending = stopOwnedTreeInner(child, signal);
1744
- treeStops.set(child, pending);
1745
- void pending.finally(() => treeStops.delete(child));
1746
- return pending;
1747
- }
1748
- function stopOwnedTreeInner(child, signal) {
1749
- if (process.platform !== "win32" || !child.pid) {
1750
- try {
1751
- if (child.pid) process.kill(-child.pid, signal);
1752
- else child.kill(signal);
1753
- return Promise.resolve(true);
1754
- } catch {
1755
- try {
1756
- return Promise.resolve(child.kill(signal));
1757
- } catch {
1758
- return Promise.resolve(false);
1759
- }
1760
- }
1761
- }
1762
- return new Promise((resolve7) => {
1763
- let done = false;
1764
- let killer;
1765
- const finish = (ok) => {
1766
- if (done) return;
1767
- done = true;
1768
- clearTimeout(timer);
1769
- if (!ok && !hasExited(child)) {
1770
- try {
1771
- child.kill(signal);
1772
- } catch {
1773
- }
1774
- }
1775
- resolve7(ok);
1776
- };
1777
- const timer = setTimeout(() => {
1778
- try {
1779
- killer?.kill();
1780
- } catch {
1781
- }
1782
- finish(false);
1783
- }, 1500);
1784
- try {
1785
- const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
1786
- killer = spawn(path6.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
1787
- killer.on("error", () => finish(false));
1788
- killer.on("exit", (code) => finish(code === 0));
1789
- } catch {
1790
- finish(false);
1791
- }
1792
- });
1793
- }
1794
- function lineReader(onLine, max = 1024 * 1024) {
1795
- const decoder = new StringDecoder("utf8");
1796
- let pending = "";
1797
- let dropping = false;
1798
- const accept = (text) => {
1799
- for (const [i, part] of text.split("\n").entries()) {
1800
- if (i) {
1801
- if (!dropping) onLine(pending);
1802
- pending = "";
1803
- dropping = false;
1804
- }
1805
- if (!dropping) {
1806
- pending += part;
1807
- if (pending.length > max) {
1808
- pending = "";
1809
- dropping = true;
1810
- }
1811
- }
2076
+ }
2077
+ const suspend = async () => {
2078
+ if (ctx.isTerminated() || suspended) return () => {
2079
+ };
2080
+ ctx.bumpInputEpoch();
2081
+ suspended = true;
2082
+ releaseImBinding?.();
2083
+ releaseImBinding = void 0;
2084
+ const gen = generation;
2085
+ if (restartTimer) {
2086
+ suspendedRestartInMs = restartDueAt !== void 0 ? Math.max(0, restartDueAt - Date.now()) : 0;
2087
+ clearTimeout(restartTimer);
2088
+ restartTimer = void 0;
2089
+ restartDueAt = void 0;
1812
2090
  }
2091
+ consumer = null;
2092
+ consumerRecovering = false;
2093
+ consumerReady = false;
2094
+ if (gen && !gen.retired) await stopGeneration(gen);
2095
+ if (ctx.isTerminated()) return () => {
2096
+ };
2097
+ let resumed = false;
2098
+ return () => {
2099
+ if (resumed || ctx.isTerminated()) return;
2100
+ resumed = true;
2101
+ if (!suspended) return;
2102
+ suspended = false;
2103
+ if (consumer || consumerRecovering || restartTimer) return;
2104
+ const delay2 = suspendedRestartInMs !== void 0 ? suspendedRestartInMs : Math.min(
2105
+ RESTART_BACKOFF_MIN_MS * 2 ** Math.min(consumerRestarts, 4),
2106
+ RESTART_BACKOFF_MAX_MS
2107
+ );
2108
+ suspendedRestartInMs = void 0;
2109
+ scheduleRestart(delay2);
2110
+ };
1813
2111
  };
1814
- return { write: (chunk) => accept(decoder.write(chunk)), end() {
1815
- accept(decoder.end());
1816
- if (pending && !dropping) onLine(pending);
1817
- pending = "";
1818
- } };
1819
- }
1820
- var shutdowns = /* @__PURE__ */ new WeakMap();
1821
- function shutdownConsumer(child) {
1822
- const existing = shutdowns.get(child);
1823
- if (existing) return existing;
1824
- const pending = shutdownConsumerInner(child);
1825
- shutdowns.set(child, pending);
1826
- return pending;
1827
- }
1828
- async function shutdownConsumerInner(child) {
1829
- let closed = false;
1830
- const close = new Promise((resolve7) => child.once("close", () => {
1831
- closed = true;
1832
- resolve7();
1833
- }));
1834
- const wait = async (ms) => {
1835
- let timer;
1836
- await Promise.race([close, new Promise((resolve7) => {
1837
- timer = setTimeout(resolve7, ms);
1838
- })]);
1839
- 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
1840
2129
  };
1841
- try {
1842
- child.stdin?.end();
1843
- } catch {
1844
- }
1845
- await wait(500);
1846
- if (!closed) {
1847
- await stopOwnedTree(child, "SIGTERM");
1848
- await wait(500);
1849
- }
1850
- if (!closed) {
1851
- await stopOwnedTree(child, "SIGKILL");
1852
- await wait(500);
1853
- }
1854
- child.stdin?.destroy();
1855
- child.stdout?.destroy();
1856
- child.stderr?.destroy();
1857
2130
  }
1858
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
+
1859
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";
1860
2160
  async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
1861
2161
  return new Promise((resolve7) => {
1862
2162
  if (options.signal?.aborted) {
@@ -1867,7 +2167,7 @@ async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
1867
2167
  try {
1868
2168
  const spec = typeof binary === "string" ? resolveLaunchSpec(binary) ?? (options.spawn ? { command: binary, prefix: [] } : null) : binary;
1869
2169
  if (!spec) throw new Error("unsupported executable");
1870
- child = (options.spawn ?? spawn2)(spec.command, [...spec.prefix, ...args], {
2170
+ child = (options.spawn ?? spawn3)(spec.command, [...spec.prefix, ...args], {
1871
2171
  shell: false,
1872
2172
  windowsHide: true,
1873
2173
  stdio: [options.stdin ?? "ignore", "pipe", "pipe"],
@@ -2282,7 +2582,7 @@ async function fenceChild(childPid, marker) {
2282
2582
  return await new Promise((resolve7) => {
2283
2583
  let killer;
2284
2584
  try {
2285
- 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 });
2286
2586
  } catch {
2287
2587
  resolve7("unknown");
2288
2588
  return;
@@ -2611,7 +2911,7 @@ async function executeAction(req) {
2611
2911
  const { command, prefix } = interpreterFor(script);
2612
2912
  let child;
2613
2913
  try {
2614
- child = spawn3(command, prefix, {
2914
+ child = spawn4(command, prefix, {
2615
2915
  cwd,
2616
2916
  env: scriptEnv(req, launchId),
2617
2917
  detached: process.platform !== "win32",
@@ -2843,7 +3143,8 @@ function formatPeerModel(peer) {
2843
3143
  return "\u2014";
2844
3144
  }
2845
3145
  var SAFE_WORKER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;
2846
- var SAFE_MODEL_SEGMENT = /^[^/\s]+$/;
3146
+ var SAFE_PROVIDER_SEGMENT = /^[^/\s]+$/;
3147
+ var SAFE_MODEL_ID_SEGMENT = /^\S+$/;
2847
3148
  var OPAQUE_PEER_NAME = /^pie-[a-z0-9]{6,}$/i;
2848
3149
  function cleanSessionTitle(raw) {
2849
3150
  if (!raw) return void 0;
@@ -2884,7 +3185,7 @@ function parseCatalogFromRawDoc(raw) {
2884
3185
  const addEntry = (provider, id, name) => {
2885
3186
  const p = provider.trim();
2886
3187
  const m = id.trim();
2887
- 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;
2888
3189
  let group = groups.get(p);
2889
3190
  if (!group) {
2890
3191
  group = { provider: p, models: [] };
@@ -2946,15 +3247,20 @@ function isContainedRegularFile(rootDir, filePath) {
2946
3247
  }
2947
3248
  function readModelCatalog(opts = {}) {
2948
3249
  const configRoot = path8.dirname(path8.dirname(ipcDiscoveryRoot2()));
3250
+ const globalModelsPath = path8.join(configRoot, "models.json");
2949
3251
  if (opts.workerName && SAFE_WORKER_NAME.test(opts.workerName)) {
2950
3252
  const agentsDir = path8.join(configRoot, "pie-proc", "agents");
2951
3253
  const workerModelsPath = path8.join(agentsDir, opts.workerName, "models.json");
2952
3254
  if (isContainedRegularFile(agentsDir, workerModelsPath)) {
3255
+ syncInheritedWorkerModels(workerModelsPath, globalModelsPath, {
3256
+ allowedDestRoot: configRoot,
3257
+ allowedSrcRoot: configRoot
3258
+ });
2953
3259
  const workerCatalog = readCatalogFile(workerModelsPath);
2954
3260
  if (workerCatalog.length > 0) return workerCatalog;
2955
3261
  }
2956
3262
  }
2957
- return readCatalogFile(path8.join(configRoot, "models.json"));
3263
+ return readCatalogFile(globalModelsPath);
2958
3264
  }
2959
3265
  function canRemotelyQuitPeer(peer) {
2960
3266
  if (peer.isManager) return false;
@@ -4651,7 +4957,7 @@ async function deliverPeekDeniedAtGate(params) {
4651
4957
  const sendOpts = peekReplyTo ? { replyInThread: true } : void 0;
4652
4958
  const sent = await connection.sendCard(recipient, deniedSpec, `panel-peek-denied-${event.event_id}`, peekReplyTo, sendOpts);
4653
4959
  if (sent?.messageId && currentSessionId && isCurrent()) {
4654
- 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);
4655
4961
  }
4656
4962
  }
4657
4963
  async function runUpgradeConfirmActor(cols, log) {
@@ -5090,8 +5396,207 @@ function runCronPanelCommand(panelCmd, opts) {
5090
5396
  return { handled: false };
5091
5397
  }
5092
5398
 
5093
- // builtin/extensions/im-forward/runtime-panel.ts
5094
- 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
+ }
5095
5600
  function createPanelCardState(ctx) {
5096
5601
  const panelCardOwners = /* @__PURE__ */ new Map();
5097
5602
  const peekCards = /* @__PURE__ */ new Map();
@@ -5102,6 +5607,7 @@ function createPanelCardState(ctx) {
5102
5607
  const cardNavGens = /* @__PURE__ */ new Map();
5103
5608
  function rememberPanelCard(messageId, sessionId, chatId, thread) {
5104
5609
  if (!messageId) return;
5610
+ panelCardOwners.delete(messageId);
5105
5611
  panelCardOwners.set(messageId, {
5106
5612
  sessionId,
5107
5613
  epoch: ctx.getInputEpoch(),
@@ -5111,18 +5617,44 @@ function createPanelCardState(ctx) {
5111
5617
  ...thread?.workerScoped ? { workerScoped: true } : {},
5112
5618
  ...thread?.threadWorkerSessionId ? { threadWorkerSessionId: thread.threadWorkerSessionId } : {}
5113
5619
  });
5114
- if (panelCardOwners.size > 100) {
5115
- const oldest = [...panelCardOwners.keys()].slice(0, Math.ceil(panelCardOwners.size / 4));
5116
- 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
+ });
5117
5634
  }
5118
5635
  }
5119
5636
  const putBounded = (m, k, v) => {
5637
+ m.delete(k);
5120
5638
  m.set(k, v);
5121
5639
  if (m.size > 100) for (const old of [...m.keys()].slice(0, 25)) m.delete(old);
5122
5640
  };
5123
5641
  return {
5124
5642
  rememberPanelCard,
5125
- 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
+ },
5126
5658
  getPeekCard: (cardId) => peekCards.get(cardId),
5127
5659
  setPeekCard: (cardId, binding) => putBounded(peekCards, cardId, binding),
5128
5660
  clearPeekCard: (cardId) => {
@@ -5156,6 +5688,7 @@ function createPanelCardState(ctx) {
5156
5688
  getCardNav: (cardId) => cardNavGens.get(cardId) ?? 0,
5157
5689
  bumpCardNav: (cardId) => {
5158
5690
  const next = (cardNavGens.get(cardId) ?? 0) + 1;
5691
+ cardNavGens.delete(cardId);
5159
5692
  cardNavGens.set(cardId, next);
5160
5693
  if (cardNavGens.size > 200) for (const old of [...cardNavGens.keys()].slice(0, 50)) cardNavGens.delete(old);
5161
5694
  return next;
@@ -5169,6 +5702,9 @@ function createPanelCardState(ctx) {
5169
5702
  }
5170
5703
  };
5171
5704
  }
5705
+
5706
+ // builtin/extensions/im-forward/runtime-panel.ts
5707
+ import { resolve as pathResolve3 } from "node:path";
5172
5708
  function createPanelExecutor(ctx) {
5173
5709
  const peekAudienceAllowed = (event) => isPeekAudienceAllowed(ctx, event);
5174
5710
  const runPanelCommand = async (panelCmd, event, sessionId, isCurrent, opts) => {
@@ -5267,14 +5803,18 @@ function createPanelExecutor(ctx) {
5267
5803
  return;
5268
5804
  }
5269
5805
  if (!isCurrent() || ctx.cards.getCardNav(cardId) !== myNavGen) return;
5270
- 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`);
5271
5811
  }
5272
5812
  if (!isCurrent()) return;
5273
5813
  try {
5274
5814
  if (ctx.connection.sendCard) {
5275
5815
  const sent = await ctx.connection.sendCard(freshRecipient, normalizedSpec, key, sendReplyTo, sendOpts);
5276
5816
  if (isCurrent()) {
5277
- 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));
5278
5818
  applyIssuedCards(sent?.messageId, plannedWorker, plannedQuit, plannedCronStop);
5279
5819
  }
5280
5820
  ctx.log(sent?.messageId ? `im-forward: panel card sent (${panelCmd.cmd})` : `im-forward: panel card send failed (${panelCmd.cmd})`);
@@ -5441,7 +5981,7 @@ function createPanelExecutor(ctx) {
5441
5981
  await deliverPanelSpec(denied, `panel-peek-denied-${event.event_id}`, true);
5442
5982
  } else if (ctx.connection.sendCard) {
5443
5983
  const sent = await ctx.connection.sendCard(peekRecipient, denied, `panel-peek-denied-${event.event_id}`, sendReplyTo, sendOpts);
5444
- 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));
5445
5985
  }
5446
5986
  return;
5447
5987
  }
@@ -5454,7 +5994,13 @@ function createPanelExecutor(ctx) {
5454
5994
  if (existingPeek && existingPeek.chatId === event.chat_id && existingPeek.ownerSession === ctx.getCurrentSessionId() && existingPeek.epoch === ctx.getInputEpoch() && existingPeek.ref === ref && existingPeek.targetSession === issuedSession && issuedRef === ref) {
5455
5995
  return;
5456
5996
  }
5457
- 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
+ }
5458
6004
  return;
5459
6005
  }
5460
6006
  if (!isCurrent()) return;
@@ -5495,7 +6041,7 @@ function createPanelExecutor(ctx) {
5495
6041
  if (!ctx.connection.sendCard) return;
5496
6042
  const sent = await ctx.connection.sendCard(peekRecipient, progressSpec, `panel-peek-${event.event_id}`, sendReplyTo, sendOpts);
5497
6043
  if (!sent?.messageId || !isCurrent()) return;
5498
- 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));
5499
6045
  ctx.cards.setPeekCard(sent.messageId, binding);
5500
6046
  targetCardId = sent.messageId;
5501
6047
  }
@@ -5581,7 +6127,7 @@ ${receipt.ok ? "Compaction runs on the target host (LLM summary \u2014 may take
5581
6127
  try {
5582
6128
  if (ctx.connection.sendCard) {
5583
6129
  const sent = await ctx.connection.sendCard(freshRecipient, spec.columnsPerRow ? spec : { ...spec, columnsPerRow: cols }, key, sendReplyTo, sendOpts);
5584
- 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));
5585
6131
  return sent?.messageId;
5586
6132
  }
5587
6133
  return (await ctx.connection.send(freshRecipient, renderCardFallbackMarkdown(spec), key, sendReplyTo, sendOpts))?.messageId;
@@ -5868,11 +6414,11 @@ function createInboundRetryController(ctx) {
5868
6414
 
5869
6415
  // builtin/extensions/im-forward/event-dispatch.ts
5870
6416
  import * as net from "node:net";
5871
- import * as fs12 from "node:fs";
5872
- import * as path12 from "node:path";
5873
- 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";
5874
6420
  function discoveryDir() {
5875
- return path12.join(addressBookRoot(), "run", "ipc");
6421
+ return path13.join(addressBookRoot(), "run", "ipc");
5876
6422
  }
5877
6423
  function pidAlive5(pid) {
5878
6424
  if (!Number.isInteger(pid) || pid <= 0) return false;
@@ -5886,7 +6432,7 @@ function pidAlive5(pid) {
5886
6432
  function findOwnerInstance(sessionId) {
5887
6433
  let entries;
5888
6434
  try {
5889
- entries = fs12.readdirSync(discoveryDir());
6435
+ entries = fs13.readdirSync(discoveryDir());
5890
6436
  } catch {
5891
6437
  return void 0;
5892
6438
  }
@@ -5894,7 +6440,7 @@ function findOwnerInstance(sessionId) {
5894
6440
  for (const name of entries.slice(0, 256)) {
5895
6441
  if (!name.endsWith(".json")) continue;
5896
6442
  try {
5897
- const parsed = JSON.parse(fs12.readFileSync(path12.join(discoveryDir(), name), "utf8"));
6443
+ const parsed = JSON.parse(fs13.readFileSync(path13.join(discoveryDir(), name), "utf8"));
5898
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)) {
5899
6445
  candidates.push({ file: parsed, startedAt: typeof parsed.startedAt === "number" ? parsed.startedAt : 0 });
5900
6446
  }
@@ -5908,7 +6454,7 @@ function findOwnerInstance(sessionId) {
5908
6454
  function findNamedOwnerInstance(name, binding) {
5909
6455
  let entries;
5910
6456
  try {
5911
- entries = fs12.readdirSync(discoveryDir()).filter((entry) => entry.endsWith(".json"));
6457
+ entries = fs13.readdirSync(discoveryDir()).filter((entry) => entry.endsWith(".json"));
5912
6458
  } catch {
5913
6459
  return void 0;
5914
6460
  }
@@ -5916,7 +6462,7 @@ function findNamedOwnerInstance(name, binding) {
5916
6462
  const matches = [];
5917
6463
  for (const entry of entries) {
5918
6464
  try {
5919
- const peer = JSON.parse(fs12.readFileSync(path12.join(discoveryDir(), entry), "utf8"));
6465
+ const peer = JSON.parse(fs13.readFileSync(path13.join(discoveryDir(), entry), "utf8"));
5920
6466
  if (peer.sessionName?.trim() !== name || !pidAlive5(peer.pid)) continue;
5921
6467
  matches.push(peer);
5922
6468
  } catch {
@@ -5934,12 +6480,12 @@ async function dispatchEventToName(name, binding, eventText) {
5934
6480
  return await deliverOnce(owner.port, owner.secret, eventText, owner.sessionId, owner.instanceId) ? owner.instanceId : void 0;
5935
6481
  }
5936
6482
  var SYNTHETIC_SENDER = (() => {
5937
- const hex = randomUUID3().replace(/-/g, "");
6483
+ const hex = randomUUID4().replace(/-/g, "");
5938
6484
  return `pie-${hex.slice(0, 12)}`;
5939
6485
  })();
5940
6486
  function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
5941
6487
  return new Promise((resolve7) => {
5942
- const id = randomUUID3();
6488
+ const id = randomUUID4();
5943
6489
  const envelope = {
5944
6490
  v: IPC_PROTOCOL_VERSION,
5945
6491
  id,
@@ -6167,7 +6713,7 @@ function createInboundShell(ctx) {
6167
6713
 
6168
6714
  // builtin/extensions/im-forward/runtime.ts
6169
6715
  import * as crypto from "node:crypto";
6170
- import * as fs13 from "node:fs";
6716
+ import * as fs14 from "node:fs";
6171
6717
  import { basename } from "node:path";
6172
6718
  var ROUTE_TTL_MS2 = 24 * 60 * 60 * 1e3;
6173
6719
  var SEND_FAILURE_NOTIFY_THROTTLE_MS2 = 5 * 60 * 1e3;
@@ -6340,19 +6886,7 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
6340
6886
  const notifySendFailure = (error) => routeState.notifySendFailure(error);
6341
6887
  const registerRoute = (sent, sessionId) => routeState.registerRoute(sent, sessionId);
6342
6888
  function resolveOutboundAttribution(sessionId) {
6343
- const messages = ctx.getMessages?.() ?? [];
6344
- let lastUserText;
6345
- for (let i = messages.length - 1; i >= 0; i--) {
6346
- const message = messages[i];
6347
- if (!isRecord(message) || message.role !== "user") continue;
6348
- const joined = (typeof message.content === "string" ? message.content : Array.isArray(message.content) ? message.content.map(
6349
- (block) => isRecord(block) && typeof block.text === "string" ? block.text : ""
6350
- ).join("") : "").trim();
6351
- if (joined) {
6352
- lastUserText = joined;
6353
- break;
6354
- }
6355
- }
6889
+ const lastUserText = extractLastUserMessageText(ctx.getMessages?.() ?? []);
6356
6890
  if (lastUserText === void 0) return void 0;
6357
6891
  for (let j = 0; j < pendingInputs.length; j++) {
6358
6892
  const pending = pendingInputs[j];
@@ -6452,6 +6986,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
6452
6986
  const attribution = resolveOutboundAttribution(sessionId);
6453
6987
  const deliver = /* @__PURE__ */ new Map();
6454
6988
  if (!outboundRoleAllows(attribution, deliver)) return;
6989
+ const ipcQuote = !isManager && !attribution?.caption ? extractLastUserMessageText(ctx.getMessages?.() ?? []) : void 0;
6455
6990
  void forwardMessage(
6456
6991
  text,
6457
6992
  sessionId,
@@ -6459,7 +6994,9 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
6459
6994
  attribution?.caption,
6460
6995
  attribution?.replyTo,
6461
6996
  attribution,
6462
- deliver
6997
+ deliver,
6998
+ void 0,
6999
+ ipcQuote
6463
7000
  ).then((delivered) => {
6464
7001
  if (delivered === true && attribution?.replyTo && connection.react) {
6465
7002
  providerCall("react", () => connection.react(attribution.replyTo, "CheckMark")).catch(() => void 0);
@@ -6476,6 +7013,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
6476
7013
  const deliverTf = /* @__PURE__ */ new Map();
6477
7014
  if (!outboundRoleAllows(attribution, deliverTf)) return;
6478
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;
6479
7017
  void forwardMessage(
6480
7018
  `\u26A0\uFE0F Task failed: ${reason} (retries exhausted)
6481
7019
  ${recoveryHint}`,
@@ -6485,7 +7023,8 @@ ${recoveryHint}`,
6485
7023
  attribution?.replyTo,
6486
7024
  attribution,
6487
7025
  deliverTf,
6488
- true
7026
+ true,
7027
+ ipcQuoteTf
6489
7028
  ).catch(() => void 0);
6490
7029
  });
6491
7030
  ctx.on("turn:cancelled", (event) => {
@@ -6496,6 +7035,7 @@ ${recoveryHint}`,
6496
7035
  const attribution = resolveOutboundAttribution(sessionId);
6497
7036
  const deliverTc = /* @__PURE__ */ new Map();
6498
7037
  if (!outboundRoleAllows(attribution, deliverTc)) return;
7038
+ const ipcQuoteTc = !isManager && !attribution?.caption ? extractLastUserMessageText(ctx.getMessages?.() ?? []) : void 0;
6499
7039
  void forwardMessage(
6500
7040
  `\u26D4\uFE0F Task cancelled: ${event.reason}`,
6501
7041
  sessionId,
@@ -6504,20 +7044,21 @@ ${recoveryHint}`,
6504
7044
  attribution?.replyTo,
6505
7045
  attribution,
6506
7046
  deliverTc,
6507
- true
7047
+ true,
7048
+ ipcQuoteTc
6508
7049
  ).catch(() => void 0);
6509
7050
  });
6510
- async function forwardMessage(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice) {
7051
+ async function forwardMessage(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice, ipcInput) {
6511
7052
  let settled = false;
6512
7053
  try {
6513
7054
  return await forwardMessageInner(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice, () => {
6514
7055
  settled = true;
6515
- });
7056
+ }, ipcInput);
6516
7057
  } finally {
6517
7058
  if (!settled) settleDelivery(deliverRequests, false);
6518
7059
  }
6519
7060
  }
6520
- 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) {
6521
7062
  pruneState();
6522
7063
  const sessionName = ctx.getSessionDisplayName?.() ?? ctx.getSessionName?.();
6523
7064
  const composeMode = resolveSessionAnchor(sessionId).threadId ? "topic-reply" : "topic-root";
@@ -6526,7 +7067,8 @@ ${recoveryHint}`,
6526
7067
  sessionName,
6527
7068
  userInput,
6528
7069
  text,
6529
- composeMode
7070
+ composeMode,
7071
+ ipcInput
6530
7072
  );
6531
7073
  if (terminated || !isForwardingEnabled()) {
6532
7074
  settleDelivery(deliverRequests, false);
@@ -6719,18 +7261,18 @@ ${recoveryHint}`,
6719
7261
  const files = collectFileReferences(
6720
7262
  text,
6721
7263
  ctx.cwd,
6722
- (path17) => {
7264
+ (path18) => {
6723
7265
  try {
6724
- const stat = fs13.statSync(path17);
7266
+ const stat = fs14.statSync(path18);
6725
7267
  return { isFile: stat.isFile(), size: stat.size };
6726
7268
  } catch {
6727
7269
  return null;
6728
7270
  }
6729
7271
  },
6730
7272
  {
6731
- canonicalize: (path17) => {
7273
+ canonicalize: (path18) => {
6732
7274
  try {
6733
- return fs13.realpathSync(path17);
7275
+ return fs14.realpathSync(path18);
6734
7276
  } catch {
6735
7277
  return null;
6736
7278
  }
@@ -6844,7 +7386,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
6844
7386
  getCurrentSessionId: () => currentSessionId,
6845
7387
  getBindingKey: () => bindingKey()
6846
7388
  });
6847
- const panelCards = createPanelCardState({ getInputEpoch: () => inputEpoch });
7389
+ const panelCards = createPanelCardState({ getInputEpoch: () => inputEpoch, provider: cfg.provider });
6848
7390
  const rememberPanelCard = (messageId, sessionId, chatId, thread) => panelCards.rememberPanelCard(messageId, sessionId, chatId, thread);
6849
7391
  const panelExecutor = createPanelExecutor({
6850
7392
  log: (message) => ctx.log(message),
@@ -7122,6 +7664,27 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
7122
7664
  await runPanelCommand(panelCmd, event, sessionId, () => scope.isCurrent(), directScope ? { ...directScope, threadReplyTo: event.message_id } : void 0);
7123
7665
  return;
7124
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
+ }
7125
7688
  }
7126
7689
  const stripImagePlaceholders = (text) => text.replace(/!\[Image\]\(img_[A-Za-z0-9_-]+\)/g, "").replace(/\[Image:\s*img_[A-Za-z0-9_-]+\]/g, "").trim();
7127
7690
  const imagelessCaption = imageKeys.length ? stripImagePlaceholders(caption) : caption;
@@ -7439,7 +8002,7 @@ Enable forwarding and start the connection? No test message will be sent. Saving
7439
8002
  return resolveConfig(ctx.cwd, dir).config ?? void 0;
7440
8003
  }
7441
8004
  async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
7442
- const { spawn: spawn6 } = await import("node:child_process");
8005
+ const { spawn: spawn7 } = await import("node:child_process");
7443
8006
  const binary = binaryOverride ?? await settingsProbeBinary();
7444
8007
  if (!binary) return;
7445
8008
  await new Promise((resolve7) => {
@@ -7458,7 +8021,7 @@ async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
7458
8021
  done();
7459
8022
  }, 3500);
7460
8023
  timer.unref?.();
7461
- 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 });
7462
8025
  child.on("error", () => done());
7463
8026
  child.on("close", () => done());
7464
8027
  let out = "";
@@ -7479,19 +8042,19 @@ async function settingsProbeBinary() {
7479
8042
  try {
7480
8043
  const { spawnSync } = await import("node:child_process");
7481
8044
  const which = spawnSync(process.platform === "win32" ? "where" : "which", ["lark-cli"], { encoding: "utf8", timeout: 3e3, windowsHide: true });
7482
- const path17 = which.stdout?.split(/\r?\n/)[0]?.trim();
7483
- return path17 || void 0;
8045
+ const path18 = which.stdout?.split(/\r?\n/)[0]?.trim();
8046
+ return path18 || void 0;
7484
8047
  } catch {
7485
8048
  return void 0;
7486
8049
  }
7487
8050
  }
7488
8051
 
7489
8052
  // builtin/extensions/im-forward/providers/feishu/index.ts
7490
- import { spawn as spawn5 } from "node:child_process";
8053
+ import { spawn as spawn6 } from "node:child_process";
7491
8054
  import { createHash as createHash2 } from "node:crypto";
7492
- import * as fs15 from "node:fs";
8055
+ import * as fs16 from "node:fs";
7493
8056
  import * as os7 from "node:os";
7494
- import * as path16 from "node:path";
8057
+ import * as path17 from "node:path";
7495
8058
 
7496
8059
  // builtin/extensions/im-forward/providers/feishu/card.ts
7497
8060
  var COLOR_TEMPLATE = {
@@ -7638,17 +8201,17 @@ function extractImageKey(content) {
7638
8201
  }
7639
8202
 
7640
8203
  // builtin/extensions/im-forward/providers/feishu/setup.ts
7641
- import * as fs14 from "node:fs";
7642
- import * as path15 from "node:path";
8204
+ import * as fs15 from "node:fs";
8205
+ import * as path16 from "node:path";
7643
8206
 
7644
8207
  // builtin/extensions/im-forward/browser.ts
7645
- import { spawn as spawn4 } from "node:child_process";
7646
- import path13 from "node:path";
8208
+ import { spawn as spawn5 } from "node:child_process";
8209
+ import path14 from "node:path";
7647
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 }";
7648
8211
  function browserLaunch(platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
7649
8212
  if (platform === "win32") {
7650
8213
  if (!/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return;
7651
- 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 };
7652
8215
  }
7653
8216
  if (platform === "darwin") return { command: "/usr/bin/open", args: ["--"], stdin: false };
7654
8217
  if (platform === "linux") return { command: "/usr/bin/xdg-open", args: [], stdin: false };
@@ -7690,7 +8253,7 @@ async function openBrowser(url, signal, seam = {}) {
7690
8253
  const abort = () => stop();
7691
8254
  const timer = setTimeout(stop, seam.timeoutMs ?? 1e4);
7692
8255
  try {
7693
- 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"] });
7694
8257
  child.on("error", stop);
7695
8258
  child.on("close", (code) => {
7696
8259
  closed = true;
@@ -7707,24 +8270,24 @@ async function openBrowser(url, signal, seam = {}) {
7707
8270
  }
7708
8271
 
7709
8272
  // builtin/extensions/im-forward/existing-app-terminal.ts
7710
- import path14 from "node:path";
8273
+ import path15 from "node:path";
7711
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 }";
7712
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 }";
7713
8276
  function existingAppTerminal(binary, cwd, platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
7714
8277
  if (platform !== "win32" || !/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return null;
7715
8278
  const payload = Buffer.from(JSON.stringify({ command: binary.command, args: [...binary.prefix, "config", "init", "--brand", "feishu"], cwd }), "utf8").toString("base64");
7716
8279
  const script = existingAppOuterTemplate.replace("__PAYLOAD__", payload);
7717
- 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")] };
7718
8281
  }
7719
8282
 
7720
8283
  // builtin/extensions/im-forward/providers/feishu/setup.ts
7721
8284
  function findNpmCli() {
7722
- const dirs = [path15.dirname(process.execPath), ...(process.env.PATH ?? "").split(path15.delimiter)];
7723
- 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")]) {
7724
8287
  try {
7725
- const pkg = JSON.parse(fs14.readFileSync(path15.join(root, "package.json"), "utf8"));
7726
- const entry = path15.join(root, "bin", "npm-cli.js");
7727
- 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] };
7728
8291
  } catch {
7729
8292
  }
7730
8293
  }
@@ -8310,6 +8873,30 @@ function normalizeMenuEvent(line, fallbackChatId) {
8310
8873
  images: []
8311
8874
  };
8312
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
+ }
8313
8900
  function connect(binary, profile, targetKind = "chat", settings = { targetId: "" }) {
8314
8901
  const lifetime = new AbortController();
8315
8902
  const active = /* @__PURE__ */ new Set();
@@ -8319,9 +8906,28 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
8319
8906
  void pending.finally(() => active.delete(pending));
8320
8907
  return pending;
8321
8908
  };
8322
- const call = async (args) => {
8909
+ const callDetailed = async (args) => {
8323
8910
  const result = await native(binary, profile ? [...args, "--profile", profile] : args, 3e4, void 0, { signal: lifetime.signal });
8324
- 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
+ }
8325
8931
  };
8326
8932
  let canonicalAppIdCache = null;
8327
8933
  let canonicalResolved = false;
@@ -8380,10 +8986,37 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
8380
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;
8381
8987
  },
8382
8988
  // 4.3.10: patch an existing card in place (admin panels refresh without
8383
- // 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.
8384
8992
  async patch(messageId, spec) {
8385
- const data = await call(["im", "messages", "patch", "--as", "bot", "--params", JSON.stringify({ message_id: messageId }), "--data", JSON.stringify({ content: JSON.stringify(compileCard(spec)) })]);
8386
- 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;
8387
9020
  },
8388
9021
  async acknowledge(id) {
8389
9022
  await call(["im", "reactions", "create", "--as", "bot", "--params", JSON.stringify({ message_id: id }), "--data", JSON.stringify({ reaction_type: { emoji_type: "THUMBSUP" } })]);
@@ -8415,19 +9048,19 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
8415
9048
  return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
8416
9049
  },
8417
9050
  async downloadImage(messageId, image, index) {
8418
- const directory = fs15.mkdtempSync(path16.join(os7.tmpdir(), "pie-im-forward-"));
8419
- 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 });
8420
9053
  try {
8421
9054
  const name = `image-${index + 1}.png`;
8422
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 });
8423
9056
  if (result.error || !parseLarkCliEnvelope(result.stdout).ok) throw new Error("Image download failed");
8424
- let target = path16.join(directory, name);
8425
- 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");
8426
9059
  const detected = readImageFormat(target);
8427
9060
  if (detected.ext === ".bin") throw new Error("Unsupported image format");
8428
9061
  if (detected.ext !== ".png") {
8429
- const corrected = path16.join(directory, `image-${index + 1}${detected.ext}`);
8430
- fs15.renameSync(target, corrected);
9062
+ const corrected = path17.join(directory, `image-${index + 1}${detected.ext}`);
9063
+ fs16.renameSync(target, corrected);
8431
9064
  target = corrected;
8432
9065
  }
8433
9066
  return { file: { path: target, displayName: `feishu-image-${index + 1}${detected.ext}` }, cleanup };
@@ -8466,7 +9099,7 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
8466
9099
  optionalRespawnTimers.set(eventKey, timer);
8467
9100
  };
8468
9101
  const spawnConsume = (eventKey, map, required) => {
8469
- 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" });
8470
9103
  child2.stdin?.on("error", () => void 0);
8471
9104
  const output = lineReader((line) => {
8472
9105
  if (!closed) {
@@ -8607,18 +9240,18 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
8607
9240
  const appId = await canonicalAppIdNow();
8608
9241
  if (!appId) return void 0;
8609
9242
  const larkHome = process.env.PIE_LARK_CLI_HOME && process.env.PIE_LARK_CLI_HOME.trim() ? process.env.PIE_LARK_CLI_HOME : os7.homedir();
8610
- const logPath = path16.join(larkHome, ".lark-cli", "events", appId, "bus.log");
9243
+ const logPath = path17.join(larkHome, ".lark-cli", "events", appId, "bus.log");
8611
9244
  let tail;
8612
9245
  try {
8613
- const fd = fs15.openSync(logPath, "r");
9246
+ const fd = fs16.openSync(logPath, "r");
8614
9247
  try {
8615
- const size = fs15.fstatSync(fd).size;
9248
+ const size = fs16.fstatSync(fd).size;
8616
9249
  const start = Math.max(0, size - 64 * 1024);
8617
9250
  const buf = Buffer.alloc(size - start);
8618
- fs15.readSync(fd, buf, 0, buf.length, start);
9251
+ fs16.readSync(fd, buf, 0, buf.length, start);
8619
9252
  tail = buf.toString("utf8");
8620
9253
  } finally {
8621
- fs15.closeSync(fd);
9254
+ fs16.closeSync(fd);
8622
9255
  }
8623
9256
  } catch {
8624
9257
  return void 0;