@cydm/pie 4.12.2 → 4.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +1 -1
  2. package/dist/builtin/extensions/cron/index.js +177 -28
  3. package/dist/builtin/extensions/im-forward/index.js +472 -53
  4. package/dist/builtin/extensions/memory/index.js +8 -8
  5. package/dist/builtin/extensions/pie-proc/index.js +7 -7
  6. package/dist/builtin/extensions/plan-mode/index.js +1 -1
  7. package/dist/builtin/extensions/subagent/index.js +5 -5
  8. package/dist/builtin/extensions/todo/index.js +1 -1
  9. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +1 -1
  10. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  11. package/dist/builtin/skills/chrome-devtools-axi/{chunk-NL3FSRAW.js → chunk-D2OVVTF6.js} +32 -4
  12. package/dist/builtin/skills/chrome-devtools-axi/{cli-QAJYAXI4.js → cli-DJ36OIQ4.js} +1 -1
  13. package/dist/chunks/{chunk-QSXBPTOA.js → chunk-3CJLYX5J.js} +4 -4
  14. package/dist/chunks/{chunk-W37NAT3N.js → chunk-5MCIBDAM.js} +5 -5
  15. package/dist/chunks/{chunk-WTBLV6F5.js → chunk-5PCLBIOO.js} +23 -9
  16. package/dist/chunks/{chunk-KW46ND3S.js → chunk-AKC7NMP4.js} +126 -15
  17. package/dist/chunks/{chunk-26ILLZKQ.js → chunk-NOSNHMA2.js} +1 -1
  18. package/dist/chunks/{host-image-fallback-NXY36VO2.js → host-image-fallback-MZK633DK.js} +1 -1
  19. package/dist/chunks/{memory-git-C3S276QJ.js → memory-git-Q3UBYOJ4.js} +2 -2
  20. package/dist/chunks/{read-file-understanding-ZCBNCQHG.js → read-file-understanding-KCJMSOS7.js} +3 -3
  21. package/dist/chunks/{src-7CU7OTQS.js → src-QI47K3W3.js} +1 -1
  22. package/dist/cli.js +48 -48
  23. package/package.json +2 -2
@@ -24,6 +24,15 @@ import {
24
24
  detectImageMime,
25
25
  readImageFormat
26
26
  } from "../../../chunks/chunk-F7EBZTZO.js";
27
+ import {
28
+ acquireDistillLock,
29
+ readDistillWorkerLog,
30
+ spawnDistillAutoWorker,
31
+ spawnWikiGcWorker
32
+ } from "../../../chunks/chunk-5PCLBIOO.js";
33
+ import {
34
+ readCuratedMemoryGitLog
35
+ } from "../../../chunks/chunk-NOSNHMA2.js";
27
36
  import {
28
37
  liveSessionHolder
29
38
  } from "../../../chunks/chunk-Q5PSWX3B.js";
@@ -35,7 +44,17 @@ import {
35
44
  import {
36
45
  loadResolvedModelsConfig
37
46
  } from "../../../chunks/chunk-IZ4DYCJ7.js";
38
- import "../../../chunks/chunk-CBDQJMUI.js";
47
+ import {
48
+ getConfigDir
49
+ } from "../../../chunks/chunk-CBDQJMUI.js";
50
+ import {
51
+ DEFAULT_WIKI_LIMITS,
52
+ WikiStore,
53
+ estimateWikiTokens,
54
+ todayKey
55
+ } from "../../../chunks/chunk-AKC7NMP4.js";
56
+ import "../../../chunks/chunk-SXBX2P5R.js";
57
+ import "../../../chunks/chunk-BQWHLYYZ.js";
39
58
  import "../../../chunks/chunk-G2K4GY6N.js";
40
59
  import {
41
60
  cronActiveCount,
@@ -440,9 +459,9 @@ function collectFileReferences(text, cwd, fsStat, options) {
440
459
  }
441
460
  for (const candidate of candidates) {
442
461
  if (results.length >= maxFiles) break;
443
- let path20 = candidate.trim();
444
- if (!path20 || path20.startsWith("/") || path20.startsWith("~") || /^[a-z]+:/i.test(path20) || path20.includes("://")) continue;
445
- const clean = path20.replace(/^\.\//, "").split("#")[0].split("?")[0];
462
+ let path21 = candidate.trim();
463
+ if (!path21 || path21.startsWith("/") || path21.startsWith("~") || /^[a-z]+:/i.test(path21) || path21.includes("://")) continue;
464
+ const clean = path21.replace(/^\.\//, "").split("#")[0].split("?")[0];
446
465
  if (clean.includes("..")) continue;
447
466
  const extension = clean.split(".").pop().toLowerCase();
448
467
  if (!extension || !ATTACHABLE_EXTENSIONS.has(extension)) continue;
@@ -1020,8 +1039,22 @@ async function executeDirectImCommand(command, opts) {
1020
1039
  }
1021
1040
  let settled = false;
1022
1041
  let timedOut = false;
1042
+ let terminating = false;
1043
+ let childClosed = false;
1044
+ let closedExitCode = null;
1023
1045
  let killTimer;
1024
1046
  let closeTimer;
1047
+ const killGraceMs = opts.killGraceMs ?? 1e3;
1048
+ const isPosixProcessGroupAlive = () => {
1049
+ if (platform === "win32" || !child.pid) return false;
1050
+ try {
1051
+ process.kill(-child.pid, 0);
1052
+ return true;
1053
+ } catch (err) {
1054
+ const code = err?.code;
1055
+ return code !== "ESRCH";
1056
+ }
1057
+ };
1025
1058
  const finish = (exitCode) => {
1026
1059
  if (settled) return;
1027
1060
  settled = true;
@@ -1044,12 +1077,19 @@ ${tail}` : head;
1044
1077
  });
1045
1078
  };
1046
1079
  const terminateTree = () => {
1080
+ if (terminating || settled) return;
1081
+ terminating = true;
1047
1082
  void stopOwnedTree(child, "SIGTERM").catch(() => void 0);
1048
1083
  killTimer = setTimeout(() => {
1049
- void stopOwnedTree(child, "SIGKILL").catch(() => void 0);
1050
- closeTimer = setTimeout(() => finish(null), 1e3);
1051
- closeTimer.unref?.();
1052
- }, 1e3);
1084
+ void stopOwnedTree(child, "SIGKILL").catch(() => void 0).finally(() => {
1085
+ if (childClosed) {
1086
+ finish(closedExitCode);
1087
+ return;
1088
+ }
1089
+ closeTimer = setTimeout(() => finish(null), 1e3);
1090
+ closeTimer.unref?.();
1091
+ });
1092
+ }, killGraceMs);
1053
1093
  killTimer.unref?.();
1054
1094
  };
1055
1095
  const onAbort = () => terminateTree();
@@ -1068,7 +1108,14 @@ ${tail}` : head;
1068
1108
  append(error.message);
1069
1109
  finish(null);
1070
1110
  });
1071
- child.on("close", (code) => finish(code));
1111
+ child.on("close", (code) => {
1112
+ childClosed = true;
1113
+ closedExitCode = code;
1114
+ if (terminating && isPosixProcessGroupAlive()) {
1115
+ return;
1116
+ }
1117
+ finish(code);
1118
+ });
1072
1119
  });
1073
1120
  }
1074
1121
  function formatDirectImCmdReply(command, cwd, result) {
@@ -1090,7 +1137,7 @@ ${result.output}
1090
1137
  ${fence}`;
1091
1138
  }
1092
1139
  function redactDirectImCmdForAudit(command) {
1093
- 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]");
1140
+ 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]");
1094
1141
  }
1095
1142
  function directImCmdAuditSummary(event, command, result) {
1096
1143
  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)}`;
@@ -2788,6 +2835,11 @@ function boundIdempotencyKey(key) {
2788
2835
  if (key.length <= 50) return key;
2789
2836
  return `k-${createHash2("sha256").update(key).digest("hex").slice(0, 48)}`;
2790
2837
  }
2838
+ function classifyFeishuChatMode(mode) {
2839
+ if (mode === "group" || mode === "topic") return "group";
2840
+ if (mode === "p2p") return "p2p";
2841
+ return void 0;
2842
+ }
2791
2843
  function normalizeEvent(line, botOpenId) {
2792
2844
  let raw;
2793
2845
  try {
@@ -3197,8 +3249,7 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
3197
3249
  if (chatTypeCache.has(chatId)) return chatTypeCache.get(chatId);
3198
3250
  try {
3199
3251
  const data = await call(["im", "chats", "get", "--as", "bot", "--params", JSON.stringify({ chat_id: chatId })]);
3200
- const mode = typeof data?.chat_mode === "string" ? data.chat_mode : void 0;
3201
- const type = mode === "group" ? "group" : mode === "p2p" ? "p2p" : void 0;
3252
+ const type = classifyFeishuChatMode(data?.chat_mode);
3202
3253
  if (type) chatTypeCache.set(chatId, type);
3203
3254
  return type;
3204
3255
  } catch {
@@ -5864,7 +5915,7 @@ function parsePanelCommand(text) {
5864
5915
  cmd = next?.[1] ?? "";
5865
5916
  rest = next?.[2] ?? "";
5866
5917
  }
5867
- if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.home" && cmd !== "panel.archive" && cmd !== "panel.models" && cmd !== "panel.context" && cmd !== "panel.compact" && cmd !== "panel.cron" && cmd !== "panel.upgrade" && cmd !== "panel.upgrade.confirm" && cmd !== "panel.help" && cmd !== "panel.actions" && cmd !== "panel.worker.offline" && cmd !== "\u9762\u677F") {
5918
+ if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.home" && cmd !== "panel.archive" && cmd !== "panel.models" && cmd !== "panel.context" && cmd !== "panel.compact" && cmd !== "panel.cron" && cmd !== "panel.memory" && cmd !== "panel.memory.view" && cmd !== "panel.memory.logs" && cmd !== "panel.memory.dream" && cmd !== "panel.memory.gc" && cmd !== "panel.upgrade" && cmd !== "panel.upgrade.confirm" && cmd !== "panel.help" && cmd !== "panel.actions" && cmd !== "panel.worker.offline" && cmd !== "\u9762\u677F") {
5868
5919
  if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd) && !/^panel\.thinking\.[A-Za-z0-9-]+\.(?:off|minimal|low|medium|high|xhigh|max)$/.test(cmd) && !/^panel\.(context|compact)\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.peek(?:\.refresh)?\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.archive\.view\.[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/.test(cmd) && !/^panel\.worker(?:\.(?:models|cron))?\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.cron\.(?:pause|resume|stop(?:\.confirm)?)\.[A-Za-z0-9-]{8,64}$/.test(cmd) && !/^panel\.stop\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.quit(?:\.(?:confirm|force))?\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.resume\.[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/.test(cmd) && !/^panel\.action\.[a-z0-9][a-z0-9-]{0,31}$/.test(cmd)) return void 0;
5869
5920
  }
5870
5921
  const leadingFlag = /^--restricted(?:\s+|$)/.exec(rest);
@@ -6008,7 +6059,7 @@ ${meta}`, actions: rowActions };
6008
6059
  { id: "panel.archive", label: "\u{1F4DA} \u5F52\u6863" },
6009
6060
  ...!managerPeer ? [{ id: "panel.models", label: "\u{1F39A} Model" }] : [],
6010
6061
  { id: "panel.context", label: "\u{1F4CA} Context" },
6011
- { id: "panel.compact", label: "\u{1F9F9} Compact" },
6062
+ { id: "panel.memory", label: "\u{1F9E0} Memory" },
6012
6063
  { id: "panel.cron", label: cronLabel },
6013
6064
  { id: "panel.upgrade", label: "\u2B06\uFE0F Upgrade" },
6014
6065
  { id: "panel.help", label: "\u2753 Help" }
@@ -6104,31 +6155,31 @@ function executePanelCommand(input) {
6104
6155
  };
6105
6156
  }
6106
6157
  if (input.cmd === "panel.context" || input.cmd === "panel.compact") {
6107
- const isCompact = input.cmd === "panel.compact";
6158
+ const isCompactOnly = input.cmd === "panel.compact";
6108
6159
  const peers = scanPeers().filter((p) => p.sessionControls);
6109
- const PAGE_SIZE2 = 10;
6160
+ const PAGE_SIZE2 = isCompactOnly ? 10 : 7;
6110
6161
  const totalPages = Math.max(1, Math.ceil(peers.length / PAGE_SIZE2));
6111
6162
  const page = Math.min(Math.max(1, parsePage(input.payload)), totalPages);
6112
6163
  const slice = peers.slice((page - 1) * PAGE_SIZE2, page * PAGE_SIZE2);
6113
6164
  const items = slice.map((p) => ({
6114
6165
  text: `${formatPeerSessionLabel(p)}
6115
6166
  \`${cleanCodeSpan(formatPeerModel(p), 44)}\` \xB7 ${formatPeerState(p.state, p.currentTool)}`,
6116
- actions: [{
6117
- id: `${input.cmd}.${p.instanceId}`,
6118
- label: isCompact ? "\u{1F9F9} Compact" : "\u{1F4CA} \u67E5\u770B"
6119
- }]
6167
+ actions: isCompactOnly ? [{ id: `panel.compact.${p.instanceId}`, label: "\u{1F9F9} Compact" }] : [
6168
+ { id: `panel.context.${p.instanceId}`, label: "\u{1F4CA} \u67E5\u770B" },
6169
+ { id: `panel.compact.${p.instanceId}`, label: "\u{1F9F9} \u538B\u7F29" }
6170
+ ]
6120
6171
  }));
6121
6172
  const nav = [];
6122
6173
  if (page > 1) nav.push({ id: input.cmd, label: `\u25C0\uFE0F \u7B2C ${page - 1} \u9875`, payload: { page: page - 1 } });
6123
6174
  if (page < totalPages) nav.push({ id: input.cmd, label: `\u7B2C ${page + 1} \u9875 \u25B6\uFE0F`, payload: { page: page + 1 } });
6124
6175
  return { spec: {
6125
- title: isCompact ? "Compact Context" : "Context Report",
6126
- subtitle: `${peers.length} session(s)${totalPages > 1 ? ` \xB7 p${page}/${totalPages}` : ""} \xB7 ${isCompact ? "\u624B\u52A8\u538B\u7F29\u4E0A\u4E0B\u6587\u5386\u53F2" : "\u67E5\u770B\u4F1A\u8BDD\u4E0A\u4E0B\u6587\u5360\u7528\u4F30\u7B97"}`,
6176
+ title: isCompactOnly ? "Compact Context" : "Context & Compact",
6177
+ subtitle: `${peers.length} session(s)${totalPages > 1 ? ` \xB7 p${page}/${totalPages}` : ""} \xB7 ${isCompactOnly ? "\u624B\u52A8\u538B\u7F29\u4E0A\u4E0B\u6587\u5386\u53F2" : "\u67E5\u770B\u4E0A\u4E0B\u6587\u4F30\u7B97\u6216\u624B\u52A8\u538B\u7F29\u5386\u53F2"}`,
6127
6178
  color: "violet",
6128
6179
  columnsPerRow: cols,
6129
6180
  body: peers.length === 0 ? "_\u5F53\u524D\u6682\u65E0\u652F\u6301\u8BE5\u63A7\u5236\u7684\u5728\u7EBF\u4F1A\u8BDD_" : "",
6130
6181
  ...items.length > 0 ? { items } : {},
6131
- footer: isCompact ? "\u538B\u7F29\u4F1A\u5C06\u65E7\u5386\u53F2\u603B\u7ED3\u4E3A checkpoint \u5E76\u4FDD\u7559\u5C3E\u90E8\uFF08\u4E0E /sessions/compact \u76F8\u540C\uFF09\uFF1B\u4F1A\u8BDD\u5FD9\u788C\u65F6\u4F1A\u62D2\u7EDD\uFF0C\u8BF7\u7A7A\u95F2\u65F6\u91CD\u8BD5\u3002" : "\u70B9\u51FB\u884C\u5185\u6309\u94AE\u67E5\u8BE2\u76EE\u6807\u4F1A\u8BDD\u7684\u5B9E\u65F6\u4E0A\u4E0B\u6587\u4F30\u7B97\uFF08\u4E0E TUI /debugs/context \u4E00\u81F4\uFF0Czero LLM\uFF09\u3002",
6182
+ footer: isCompactOnly ? "\u538B\u7F29\u4F1A\u5C06\u65E7\u5386\u53F2\u603B\u7ED3\u4E3A checkpoint \u5E76\u4FDD\u7559\u5C3E\u90E8\uFF08\u4E0E /sessions/compact \u76F8\u540C\uFF09\uFF1B\u4F1A\u8BDD\u5FD9\u788C\u65F6\u4F1A\u62D2\u7EDD\uFF0C\u8BF7\u7A7A\u95F2\u65F6\u91CD\u8BD5\u3002" : "\u300C\u{1F4CA} \u67E5\u770B\u300D\u67E5\u8BE2\u5B9E\u65F6\u4E0A\u4E0B\u6587\u5360\u7528\uFF08zero LLM\uFF09\uFF1B\u300C\u{1F9F9} \u538B\u7F29\u300D\u603B\u7ED3\u65E7\u5386\u53F2\u5E76\u4FDD\u7559\u5C3E\u90E8\uFF08\u4F1A\u8BDD\u7A7A\u95F2\u65F6\u53EF\u6267\u884C\uFF09\u3002",
6132
6183
  actions: [...nav, { id: "panel.home", label: "\u21A9\uFE0F \u603B\u9762\u677F" }]
6133
6184
  }, patchOrigin: patchInPlace };
6134
6185
  }
@@ -6223,7 +6274,7 @@ ${a.runs} \u6B21 \xB7 \u6700\u8FD1 ${cleanInline2(a.lastRunBy ?? "\u2014", 20)}
6223
6274
  return { spec: {
6224
6275
  title: "Panel Commands",
6225
6276
  columnsPerRow: cols,
6226
- body: "`/panel` summons the status panel (inside a worker thread, opens that worker's dedicated panel in-thread). Controls: \u{1F504} Refresh, \u{1F4DA} \u5F52\u6863 (browse recent historical sessions across directories, inspect offline summaries, and one-click Resume workers), \u{1F39A} Model & Thinking, \u{1F4CA} Context, \u{1F9F9} Compact, \u23F0 Cron (list / pause / resume / stop scheduled jobs; create new jobs in chat), \u23F9 Stop (abort current turn), \u{1F6AA} Quit (graceful shutdown / force kill), \u267B\uFE0F Resume (when offline), \u{1F440} Peek (live snapshot). Navigation updates the card in place.",
6277
+ body: "`/panel` summons the status panel (inside a worker thread, opens that worker's dedicated panel in-thread). Controls: \u{1F504} Refresh, \u{1F4DA} \u5F52\u6863 (browse recent historical sessions across directories, inspect offline summaries, and one-click Resume workers), \u{1F39A} Model & Thinking, \u{1F4CA} Context (inspect context usage & one-tap Compact), \u{1F9E0} Memory (Wiki status, curated page preview, distill/GC triggers, and logs), \u23F0 Cron (list / pause / resume / stop scheduled jobs; create new jobs in chat), \u23F9 Stop (abort current turn), \u{1F6AA} Quit (graceful shutdown / force kill), \u267B\uFE0F Resume (when offline), \u{1F440} Peek (live snapshot). Navigation updates the card in place.",
6227
6278
  actions: [{ id: "panel.home", label: "\u21A9\uFE0F \u603B\u9762\u677F" }]
6228
6279
  }, patchOrigin: patchInPlace };
6229
6280
  }
@@ -7102,6 +7153,11 @@ var THREAD_FORBIDDEN_GLOBAL_CMDS = /* @__PURE__ */ new Set([
7102
7153
  "panel.context",
7103
7154
  "panel.compact",
7104
7155
  "panel.cron",
7156
+ "panel.memory",
7157
+ "panel.memory.view",
7158
+ "panel.memory.logs",
7159
+ "panel.memory.dream",
7160
+ "panel.memory.gc",
7105
7161
  "panel.upgrade",
7106
7162
  "panel.upgrade.confirm",
7107
7163
  "panel.actions",
@@ -8127,14 +8183,349 @@ function runCronPanelCommand(panelCmd, opts) {
8127
8183
  return { handled: false };
8128
8184
  }
8129
8185
 
8130
- // builtin/extensions/im-forward/panel-card-store.ts
8186
+ // builtin/extensions/im-forward/panel-memory.ts
8131
8187
  import * as fs16 from "node:fs";
8132
8188
  import * as path19 from "node:path";
8189
+ var MEMORY_PAGE_SIZE = 6;
8190
+ var PAGE_PREVIEW_CHAR_BUDGET = 2600;
8191
+ var LOG_LINE_LIMIT = 15;
8192
+ var GIT_LOG_LIMIT = 6;
8193
+ var USER_PAGE_KEY = "USER.md";
8194
+ function resolveMemoryRoot(override) {
8195
+ return override ?? path19.join(getConfigDir(), "memory");
8196
+ }
8197
+ function parsePage2(payload, field = "page") {
8198
+ if (!isRecord(payload)) return 1;
8199
+ const raw = payload[field];
8200
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 1) return 1;
8201
+ return Math.floor(raw);
8202
+ }
8203
+ function formatDateTime(ts) {
8204
+ if (typeof ts !== "number" || !Number.isFinite(ts) || ts <= 0) return "\u5C1A\u672A\u8FD0\u884C";
8205
+ const d = new Date(ts);
8206
+ const mm = String(d.getMonth() + 1).padStart(2, "0");
8207
+ const dd = String(d.getDate()).padStart(2, "0");
8208
+ const hh = String(d.getHours()).padStart(2, "0");
8209
+ const mi = String(d.getMinutes()).padStart(2, "0");
8210
+ return `${mm}-${dd} ${hh}:${mi}`;
8211
+ }
8212
+ function sanitizeFenceContent(text, maxChars = 1600) {
8213
+ const clipped = text.length > maxChars ? `${text.slice(0, maxChars)}
8214
+ \u2026(truncated)` : text;
8215
+ return clipped.replace(/```/g, "'''").replace(/</g, "\u2039").replace(/>/g, "\u203A");
8216
+ }
8217
+ function readRegularUserMd(memoryRoot) {
8218
+ try {
8219
+ const target = path19.join(memoryRoot, USER_PAGE_KEY);
8220
+ const st = fs16.lstatSync(target);
8221
+ if (!st.isFile() || st.isSymbolicLink() || st.size > 512e3) return null;
8222
+ const content = fs16.readFileSync(target, "utf8");
8223
+ return content.trim().length > 0 ? content : null;
8224
+ } catch {
8225
+ return null;
8226
+ }
8227
+ }
8228
+ function collectMissingRecentDates(wiki, days = 7) {
8229
+ const today = todayKey(Date.now());
8230
+ const missing = [];
8231
+ for (let offset = days; offset >= 1; offset -= 1) {
8232
+ const probe = /* @__PURE__ */ new Date();
8233
+ probe.setDate(probe.getDate() - offset);
8234
+ const date = todayKey(probe.getTime());
8235
+ if (date === today) continue;
8236
+ if (!wiki.hasDreamedDate(date)) missing.push(date);
8237
+ }
8238
+ return missing;
8239
+ }
8240
+ function enumerateCuratedPages(memoryRoot, wiki) {
8241
+ const entries = [];
8242
+ const userContent = readRegularUserMd(memoryRoot);
8243
+ if (userContent !== null) {
8244
+ entries.push({
8245
+ key: USER_PAGE_KEY,
8246
+ label: "\u{1F464} USER.md\uFF08\u7528\u6237\u753B\u50CF\u4E0E\u504F\u597D\uFF09",
8247
+ category: "user",
8248
+ tokens: estimateWikiTokens(userContent)
8249
+ });
8250
+ }
8251
+ for (const rel of wiki.listActivePages()) {
8252
+ const content = wiki.readPage(rel) ?? "";
8253
+ const icon = rel === "index.md" ? "\u{1F5C2}" : rel === "active-threads.md" ? "\u{1F9F5}" : rel.startsWith("projects/") ? "\u{1F4C1}" : "\u{1F4C4}";
8254
+ entries.push({
8255
+ key: `wiki/${rel}`,
8256
+ label: `${icon} wiki/${rel}`,
8257
+ category: "active",
8258
+ tokens: estimateWikiTokens(content)
8259
+ });
8260
+ }
8261
+ for (const rel of wiki.listArchivedPages()) {
8262
+ const content = wiki.readPage(rel) ?? "";
8263
+ entries.push({
8264
+ key: `wiki/${rel}`,
8265
+ label: `\u{1F4E6} wiki/${rel}\uFF08\u5F52\u6863\uFF09`,
8266
+ category: "archived",
8267
+ tokens: estimateWikiTokens(content)
8268
+ });
8269
+ }
8270
+ return entries;
8271
+ }
8272
+ function readAllowlistedPage(memoryRoot, wiki, pageKey) {
8273
+ const entries = enumerateCuratedPages(memoryRoot, wiki);
8274
+ const entry = entries.find((item) => item.key === pageKey);
8275
+ if (!entry) return void 0;
8276
+ const content = entry.key === USER_PAGE_KEY ? readRegularUserMd(memoryRoot) : wiki.readPage(entry.key.slice("wiki/".length));
8277
+ if (content === null) return void 0;
8278
+ return { entry, content };
8279
+ }
8280
+ function summarizeMemoryCron() {
8281
+ try {
8282
+ const bridge = currentCronPanelBridge();
8283
+ if (!bridge) return "\u672A\u63A5\u5165 Cron \u6865\u63A5";
8284
+ const job = bridge.listJobs().jobs.find((j) => j.isProcess && j.managedBy === "memory");
8285
+ if (!job) return "\u672A\u542F\u7528\uFF08\u53EF\u7528 `pie memory schedule on` \u5F00\u542F\uFF09";
8286
+ if (job.state === "running") return "\u{1F7E1} \u8FD0\u884C\u4E2D";
8287
+ if (job.state === "blocked") {
8288
+ const detail = job.error ? `\uFF08${cleanCodeSpan(job.error, 80)}\uFF09` : "";
8289
+ return `\u{1F534} \u5DF2\u963B\u585E${detail}`;
8290
+ }
8291
+ if (!job.enabled) return "\u23F8 \u5DF2\u6682\u505C";
8292
+ const nextText = job.next !== null ? formatDateTime(job.next) : "\u2014";
8293
+ if (job.error && job.error.startsWith("degraded")) {
8294
+ return `\u{1F7E0} \u9000\u907F\u91CD\u8BD5\u4E2D \xB7 \u4E0B\u6B21 ${nextText}`;
8295
+ }
8296
+ return `\u{1F7E2} \u6B63\u5E38\uFF08\`${cleanCodeSpan(job.schedule.text, 24)}\` \xB7 \u4E0B\u6B21 ${nextText}\uFF09`;
8297
+ } catch {
8298
+ return "\u72B6\u6001\u4E0D\u53EF\u8BFB";
8299
+ }
8300
+ }
8301
+ function composeMemoryCard(opts) {
8302
+ const cols = opts.inThread ? 2 : 3;
8303
+ const memoryRoot = resolveMemoryRoot(opts.memoryRoot);
8304
+ const wiki = new WikiStore(memoryRoot);
8305
+ const exists = wiki.exists();
8306
+ const activePages = wiki.listActivePages();
8307
+ const archivedPages = wiki.listArchivedPages();
8308
+ const meta = wiki.readMeta();
8309
+ const indexTokens = estimateWikiTokens(wiki.readPage("index.md") ?? "");
8310
+ const missingDates = collectMissingRecentDates(wiki, 7);
8311
+ const allEntries = enumerateCuratedPages(memoryRoot, wiki);
8312
+ const totalPages = Math.max(1, Math.ceil(allEntries.length / MEMORY_PAGE_SIZE));
8313
+ const page = Math.min(Math.max(1, opts.page ?? 1), totalPages);
8314
+ const slice = allEntries.slice((page - 1) * MEMORY_PAGE_SIZE, page * MEMORY_PAGE_SIZE);
8315
+ const items = slice.map((entry) => ({
8316
+ text: `**${sanitizeLiteralMarkdown(entry.label)}**
8317
+ \u7EA6 ${entry.tokens} tokens`,
8318
+ actions: [{
8319
+ id: "panel.memory.view",
8320
+ label: "\u{1F4D6} \u67E5\u770B",
8321
+ payload: { pageKey: entry.key, returnPage: page }
8322
+ }]
8323
+ }));
8324
+ const missingLine = missingDates.length === 0 ? "\u8FD1 7 \u5929\u5DF2\u5B8C\u6574\u8986\u76D6 \u2705" : `\u8FD1 7 \u5929\u7F3A\u65E5 ${missingDates.length} \u5929\uFF08${missingDates.slice(-4).map((d) => d.slice(5)).join(", ")}${missingDates.length > 4 ? "\u2026" : ""}\uFF09`;
8325
+ const lastFailLine = meta.lastDreamError ? `- **\u6700\u8FD1\u5931\u8D25**\uFF1A\`${cleanCodeSpan(meta.lastDreamError, 100)}\`${meta.lastDreamFailedDate ? ` (${meta.lastDreamFailedDate})` : ""}` : void 0;
8326
+ const bodyLines = [
8327
+ ...opts.banner ? [opts.banner, ""] : [],
8328
+ `- **Wiki**\uFF1A${exists ? `\u6D3B\u8DC3 ${activePages.length}/${DEFAULT_WIKI_LIMITS.maxActivePages} \u9875 \xB7 \u5F52\u6863 ${archivedPages.length} \u9875` : "\u5C1A\u672A\u521D\u59CB\u5316\uFF08\u9996\u6B21\u84B8\u998F\u81EA\u52A8\u521B\u5EFA\uFF09"} \xB7 index \u7EA6 ${indexTokens}/${DEFAULT_WIKI_LIMITS.maxIndexTokens} tokens`,
8329
+ `- **Dream**\uFF1A\u4E0A\u6B21 ${formatDateTime(meta.lastDreamAt)} \xB7 ${missingLine}`,
8330
+ ...lastFailLine ? [lastFailLine] : [],
8331
+ `- **GC**\uFF1A\u4E0A\u6B21 ${formatDateTime(meta.lastGcAt)} \xB7 **\u5B9A\u65F6\u4EFB\u52A1**\uFF1A${summarizeMemoryCron()}`,
8332
+ ...allEntries.length === 0 ? ["", "_\u5F53\u524D\u6682\u65E0\u53EF\u6D4F\u89C8\u7684\u8BB0\u5FC6\u9875\u9762\u3002_"] : []
8333
+ ];
8334
+ const nav = [];
8335
+ if (page > 1) nav.push({ id: "panel.memory", label: `\u25C0\uFE0F \u7B2C ${page - 1} \u9875`, payload: { page: page - 1 } });
8336
+ if (page < totalPages) nav.push({ id: "panel.memory", label: `\u7B2C ${page + 1} \u9875 \u25B6\uFE0F`, payload: { page: page + 1 } });
8337
+ const defaultColor = meta.lastDreamError ? "red" : "violet";
8338
+ return {
8339
+ title: "\u{1F9E0} Memory \xB7 Wiki & Dreaming",
8340
+ subtitle: `${activePages.length} active \xB7 ${archivedPages.length} archived${totalPages > 1 ? ` \xB7 p${page}/${totalPages}` : ""} \xB7 zero LLM`,
8341
+ color: opts.bannerColor ?? defaultColor,
8342
+ columnsPerRow: cols,
8343
+ body: bodyLines.join("\n"),
8344
+ ...items.length > 0 ? { items } : {},
8345
+ footer: "\u70B9\u51FB\u884C\u5185\u300C\u{1F4D6} \u67E5\u770B\u300D\u9884\u89C8\u9875\u9762\uFF1B\u300C\u{1F319} \u7ACB\u5373\u84B8\u998F\u300D\u4E0E\u300C\u{1F9F9} \u89E6\u53D1 GC\u300D\u5747\u5728\u540E\u53F0\u72EC\u7ACB\u8FD0\u884C\uFF0C\u4E0D\u5360\u7528\u5F53\u524D\u4F1A\u8BDD\u3002",
8346
+ actions: [
8347
+ ...nav,
8348
+ { id: "panel.memory.dream", label: "\u{1F319} \u7ACB\u5373\u84B8\u998F", style: "primary" },
8349
+ { id: "panel.memory.gc", label: "\u{1F9F9} \u89E6\u53D1 GC" },
8350
+ { id: "panel.memory.logs", label: "\u{1F4DC} \u84B8\u998F\u65E5\u5FD7" },
8351
+ { id: "panel.memory", label: "\u{1F504} Refresh", payload: { page } },
8352
+ { id: "panel.home", label: "\u21A9\uFE0F \u603B\u9762\u677F" }
8353
+ ]
8354
+ };
8355
+ }
8356
+ function composeMemoryPageCard(opts) {
8357
+ const cols = opts.inThread ? 2 : 3;
8358
+ const returnPage = Math.max(1, opts.returnPage ?? 1);
8359
+ const memoryRoot = resolveMemoryRoot(opts.memoryRoot);
8360
+ const wiki = new WikiStore(memoryRoot);
8361
+ const found = readAllowlistedPage(memoryRoot, wiki, opts.pageKey);
8362
+ if (!found) {
8363
+ return {
8364
+ title: "\u26A0\uFE0F \u9875\u9762\u4E0D\u53EF\u7528",
8365
+ color: "grey",
8366
+ columnsPerRow: cols,
8367
+ body: `\u672A\u627E\u5230\u6216\u65E0\u6743\u8BBF\u95EE\u9875\u9762 \`${cleanCodeSpan(opts.pageKey, 80)}\`\u3002\u8BF7\u8FD4\u56DE Memory \u5217\u8868\u91CD\u65B0\u9009\u62E9\u3002`,
8368
+ actions: [
8369
+ { id: "panel.memory", label: "\u21A9\uFE0F \u8FD4\u56DE Memory", payload: { page: returnPage } },
8370
+ { id: "panel.home", label: "\u{1F4CB} \u603B\u9762\u677F" }
8371
+ ]
8372
+ };
8373
+ }
8374
+ const preview = truncateMarkdown(found.content.trim() || "_(\u7A7A\u9875\u9762)_", PAGE_PREVIEW_CHAR_BUDGET);
8375
+ return {
8376
+ title: `\u{1F4D6} ${cleanCodeSpan(found.entry.key, 48)}`,
8377
+ subtitle: `\u7EA6 ${found.entry.tokens} tokens \xB7 ${found.content.length} chars \xB7 \u53EA\u8BFB\u9884\u89C8`,
8378
+ color: "blue",
8379
+ columnsPerRow: cols,
8380
+ body: preview,
8381
+ footer: "\u5982\u9700\u4FEE\u6539\u6216\u5220\u9664\u8BB0\u5FC6\uFF0C\u76F4\u63A5\u5728\u5BF9\u8BDD\u4E2D\u544A\u8BC9 Manager \u5373\u53EF\u3002",
8382
+ actions: [
8383
+ { id: "panel.memory.view", label: "\u{1F504} Refresh", payload: { pageKey: found.entry.key, returnPage } },
8384
+ { id: "panel.memory", label: "\u21A9\uFE0F \u8FD4\u56DE Memory", payload: { page: returnPage } },
8385
+ { id: "panel.home", label: "\u{1F4CB} \u603B\u9762\u677F" }
8386
+ ]
8387
+ };
8388
+ }
8389
+ function composeMemoryLogsCard(opts) {
8390
+ const cols = opts.inThread ? 2 : 3;
8391
+ const memoryRoot = resolveMemoryRoot(opts.memoryRoot);
8392
+ const workerLines = (opts.hooks?.readWorkerLog ?? readDistillWorkerLog)(memoryRoot, LOG_LINE_LIMIT);
8393
+ const gitLines = (opts.hooks?.readGitLog ?? readCuratedMemoryGitLog)(memoryRoot, GIT_LOG_LIMIT);
8394
+ const workerSection = workerLines.length > 0 ? `**distill-worker.log\uFF08\u6700\u8FD1 ${workerLines.length} \u884C\uFF09**
8395
+ \`\`\`
8396
+ ${sanitizeFenceContent(workerLines.join("\n"), 1500)}
8397
+ \`\`\`` : "**distill-worker.log**\uFF1A_\u6682\u65E0\u8BB0\u5F55_";
8398
+ const gitSection = gitLines.length > 0 ? `**Curated Git \u53D8\u66F4\uFF08\u6700\u8FD1\uFF09**
8399
+ \`\`\`
8400
+ ${sanitizeFenceContent(gitLines.join("\n"), 900)}
8401
+ \`\`\`` : "**Curated Git \u53D8\u66F4**\uFF1A_\u6682\u65E0\u63D0\u4EA4_";
8402
+ return {
8403
+ title: "\u{1F4DC} Memory \u84B8\u998F\u65E5\u5FD7",
8404
+ subtitle: "worker \u65E5\u5FD7 + curated git \u5386\u53F2 \xB7 zero LLM",
8405
+ color: "blue",
8406
+ columnsPerRow: cols,
8407
+ body: `${workerSection}
8408
+
8409
+ ${gitSection}`,
8410
+ actions: [
8411
+ { id: "panel.memory.dream", label: "\u{1F319} \u7ACB\u5373\u84B8\u998F", style: "primary" },
8412
+ { id: "panel.memory.logs", label: "\u{1F504} Refresh" },
8413
+ { id: "panel.memory", label: "\u21A9\uFE0F \u8FD4\u56DE Memory" },
8414
+ { id: "panel.home", label: "\u{1F4CB} \u603B\u9762\u677F" }
8415
+ ]
8416
+ };
8417
+ }
8418
+ function defaultProbeLockFree(memoryRoot) {
8419
+ try {
8420
+ const release = acquireDistillLock(memoryRoot);
8421
+ if (!release) return false;
8422
+ release();
8423
+ return true;
8424
+ } catch {
8425
+ return true;
8426
+ }
8427
+ }
8428
+ function runMemoryPanelCommand(panelCmd, opts) {
8429
+ const isMemoryCmd = panelCmd.cmd === "panel.memory" || panelCmd.cmd === "panel.memory.view" || panelCmd.cmd === "panel.memory.logs" || panelCmd.cmd === "panel.memory.dream" || panelCmd.cmd === "panel.memory.gc";
8430
+ if (!isMemoryCmd) return { handled: false };
8431
+ const cols = opts.inThread ? 2 : 3;
8432
+ if (!opts.canReadSensitive) {
8433
+ return {
8434
+ handled: true,
8435
+ keyPrefix: "panel-memory-denied",
8436
+ spec: {
8437
+ title: "\u{1F9E0} Memory \u4E0D\u53EF\u7528",
8438
+ color: "red",
8439
+ columnsPerRow: cols,
8440
+ body: "\u26D4\uFE0F Memory \u9762\u677F\u4EC5\u9650\u5DF2\u6388\u6743\u7684\u5BF9\u8BDD\u6216\u7BA1\u7406\u5458\u79C1\u804A\u67E5\u770B\u3002",
8441
+ actions: [{ id: "panel.home", label: "\u21A9\uFE0F \u603B\u9762\u677F" }]
8442
+ }
8443
+ };
8444
+ }
8445
+ const memoryRoot = resolveMemoryRoot(opts.memoryRoot);
8446
+ const page = parsePage2(panelCmd.payload, "page");
8447
+ if (panelCmd.cmd === "panel.memory") {
8448
+ return {
8449
+ handled: true,
8450
+ keyPrefix: "panel-memory",
8451
+ spec: composeMemoryCard({ memoryRoot, inThread: opts.inThread, page })
8452
+ };
8453
+ }
8454
+ if (panelCmd.cmd === "panel.memory.view") {
8455
+ const pageKey = isRecord(panelCmd.payload) && typeof panelCmd.payload.pageKey === "string" ? panelCmd.payload.pageKey.trim() : "";
8456
+ const returnPage = parsePage2(panelCmd.payload, "returnPage");
8457
+ return {
8458
+ handled: true,
8459
+ keyPrefix: "panel-memory-view",
8460
+ spec: composeMemoryPageCard({ memoryRoot, pageKey, returnPage, inThread: opts.inThread })
8461
+ };
8462
+ }
8463
+ if (panelCmd.cmd === "panel.memory.logs") {
8464
+ return {
8465
+ handled: true,
8466
+ keyPrefix: "panel-memory-logs",
8467
+ spec: composeMemoryLogsCard({ memoryRoot, inThread: opts.inThread, hooks: opts.hooks })
8468
+ };
8469
+ }
8470
+ if (!opts.canMutate) {
8471
+ return {
8472
+ handled: true,
8473
+ refusedText: "\u26D4\uFE0F \u89E6\u53D1 Memory \u84B8\u998F\u6216 GC \u9700\u8981\u7BA1\u7406\u5458\u6743\u9650\uFF08panelAccess=allowUsers\uFF09\u3002"
8474
+ };
8475
+ }
8476
+ const probeLockFree = opts.hooks?.probeLockFree ?? defaultProbeLockFree;
8477
+ if (!probeLockFree(memoryRoot)) {
8478
+ return {
8479
+ handled: true,
8480
+ keyPrefix: "panel-memory-busy",
8481
+ spec: composeMemoryCard({
8482
+ memoryRoot,
8483
+ inThread: opts.inThread,
8484
+ page,
8485
+ banner: "\u23F3 **\u5DF2\u6709 Memory \u540E\u53F0\u4EFB\u52A1\u6B63\u5728\u8FD0\u884C**\uFF08\u6301\u6709 `distill.lock`\uFF09\uFF0C\u8BF7\u7A0D\u5019\u70B9\u300C\u{1F4DC} \u84B8\u998F\u65E5\u5FD7\u300D\u67E5\u770B\u8FDB\u5EA6\u3002",
8486
+ bannerColor: "grey"
8487
+ })
8488
+ };
8489
+ }
8490
+ if (panelCmd.cmd === "panel.memory.dream") {
8491
+ const spawnDream = opts.hooks?.spawnDream ?? spawnDistillAutoWorker;
8492
+ const sessionsDir = process.env.PIE_SESSIONS_DIR?.trim() || void 0;
8493
+ const ok2 = spawnDream(memoryRoot, sessionsDir);
8494
+ return {
8495
+ handled: true,
8496
+ keyPrefix: "panel-memory-dream",
8497
+ spec: composeMemoryCard({
8498
+ memoryRoot,
8499
+ inThread: opts.inThread,
8500
+ page,
8501
+ banner: ok2 ? "\u{1F319} **\u5DF2\u5728\u540E\u53F0\u542F\u52A8\u8865\u84B8\u998F (`--auto`)**\uFF0C\u5B8C\u6210\u540E\u81EA\u52A8\u66F4\u65B0 Wiki \u4E0E Git\uFF08\u70B9\u300C\u{1F4DC} \u84B8\u998F\u65E5\u5FD7\u300D\u67E5\u770B\u5B9E\u65F6\u8FDB\u5EA6\uFF09\u3002" : "\u274C **\u540E\u53F0\u84B8\u998F\u8FDB\u7A0B\u542F\u52A8\u5931\u8D25**\uFF0C\u8BF7\u70B9\u300C\u{1F4DC} \u84B8\u998F\u65E5\u5FD7\u300D\u6392\u67E5\u539F\u56E0\u3002",
8502
+ bannerColor: ok2 ? "green" : "red"
8503
+ })
8504
+ };
8505
+ }
8506
+ const spawnGc = opts.hooks?.spawnGc ?? spawnWikiGcWorker;
8507
+ const ok = spawnGc(memoryRoot);
8508
+ return {
8509
+ handled: true,
8510
+ keyPrefix: "panel-memory-gc",
8511
+ spec: composeMemoryCard({
8512
+ memoryRoot,
8513
+ inThread: opts.inThread,
8514
+ page,
8515
+ banner: ok ? "\u{1F9F9} **\u5DF2\u5728\u540E\u53F0\u542F\u52A8 Wiki GC**\uFF08\u5F52\u6863\u4E0D\u6D3B\u8DC3\u9879\u76EE\u3001\u6E05\u7406\u8FC7\u671F\u951A\u70B9\u3001\u538B\u7F29\u8D85\u9884\u7B97\u9875\u9762\uFF09\uFF0C\u70B9\u300C\u{1F4DC} \u84B8\u998F\u65E5\u5FD7\u300D\u67E5\u770B\u8FDB\u5EA6\u3002" : "\u274C **\u540E\u53F0 Wiki GC \u542F\u52A8\u5931\u8D25**\uFF0C\u8BF7\u70B9\u300C\u{1F4DC} \u84B8\u998F\u65E5\u5FD7\u300D\u6392\u67E5\u539F\u56E0\u3002",
8516
+ bannerColor: ok ? "green" : "red"
8517
+ })
8518
+ };
8519
+ }
8520
+
8521
+ // builtin/extensions/im-forward/panel-card-store.ts
8522
+ import * as fs17 from "node:fs";
8523
+ import * as path20 from "node:path";
8133
8524
  import { randomUUID as randomUUID4 } from "node:crypto";
8134
8525
  var MAX_PERSISTED_PANEL_CARDS = 100;
8135
8526
  var PANEL_CARD_TTL_MS = 14 * 24 * 60 * 60 * 1e3;
8136
8527
  function storePath() {
8137
- return path19.join(addressBookRoot(), "im-forward", "panel-cards.json");
8528
+ return path20.join(addressBookRoot(), "im-forward", "panel-cards.json");
8138
8529
  }
8139
8530
  function makeKey(provider, messageId) {
8140
8531
  return `${provider}\0${messageId}`;
@@ -8142,7 +8533,7 @@ function makeKey(provider, messageId) {
8142
8533
  var readCache;
8143
8534
  function fileStamp(file) {
8144
8535
  try {
8145
- const st = fs16.lstatSync(file);
8536
+ const st = fs17.lstatSync(file);
8146
8537
  if (st.isSymbolicLink() || !st.isFile()) return "unsafe";
8147
8538
  return `${st.ino}:${st.mtimeMs}:${st.ctimeMs}:${st.size}`;
8148
8539
  } catch {
@@ -8176,7 +8567,7 @@ function readStoreMap(file) {
8176
8567
  }
8177
8568
  const map = /* @__PURE__ */ new Map();
8178
8569
  try {
8179
- const text = fs16.readFileSync(file, "utf8");
8570
+ const text = fs17.readFileSync(file, "utf8");
8180
8571
  const parsed = JSON.parse(text);
8181
8572
  if (isRecord(parsed) && Array.isArray(parsed.entries)) {
8182
8573
  for (const item of parsed.entries) {
@@ -8226,21 +8617,21 @@ function isPidAlive(pid) {
8226
8617
  }
8227
8618
  function acquireStoreLock(lockPath2) {
8228
8619
  try {
8229
- if (fs16.existsSync(lockPath2) && fs16.lstatSync(lockPath2).isSymbolicLink()) return void 0;
8620
+ if (fs17.existsSync(lockPath2) && fs17.lstatSync(lockPath2).isSymbolicLink()) return void 0;
8230
8621
  } catch {
8231
8622
  }
8232
8623
  for (let attempt = 0; attempt < LOCK_MAX_ATTEMPTS; attempt++) {
8233
8624
  try {
8234
- const fd = fs16.openSync(lockPath2, "wx", 384);
8625
+ const fd = fs17.openSync(lockPath2, "wx", 384);
8235
8626
  try {
8236
- fs16.writeFileSync(fd, `${process.pid}
8627
+ fs17.writeFileSync(fd, `${process.pid}
8237
8628
  `, "utf8");
8238
8629
  } finally {
8239
- fs16.closeSync(fd);
8630
+ fs17.closeSync(fd);
8240
8631
  }
8241
8632
  return () => {
8242
8633
  try {
8243
- fs16.unlinkSync(lockPath2);
8634
+ fs17.unlinkSync(lockPath2);
8244
8635
  } catch {
8245
8636
  }
8246
8637
  };
@@ -8248,17 +8639,17 @@ function acquireStoreLock(lockPath2) {
8248
8639
  if (error?.code !== "EEXIST") return void 0;
8249
8640
  let reclaimed = false;
8250
8641
  try {
8251
- const st = fs16.lstatSync(lockPath2);
8642
+ const st = fs17.lstatSync(lockPath2);
8252
8643
  if (st.isSymbolicLink() || !st.isFile()) return void 0;
8253
8644
  const ageMs = Date.now() - st.mtimeMs;
8254
8645
  let ownerDead = false;
8255
8646
  try {
8256
- const pid = Number.parseInt(fs16.readFileSync(lockPath2, "utf8").trim(), 10);
8647
+ const pid = Number.parseInt(fs17.readFileSync(lockPath2, "utf8").trim(), 10);
8257
8648
  if (Number.isInteger(pid) && pid > 0 && !isPidAlive(pid)) ownerDead = true;
8258
8649
  } catch {
8259
8650
  }
8260
8651
  if (ownerDead || ageMs > LOCK_STALE_MS) {
8261
- fs16.unlinkSync(lockPath2);
8652
+ fs17.unlinkSync(lockPath2);
8262
8653
  reclaimed = true;
8263
8654
  }
8264
8655
  } catch (e) {
@@ -8276,11 +8667,11 @@ function savePersistedPanelCard(provider, messageId, entry, now = Date.now()) {
8276
8667
  let tmp;
8277
8668
  let releaseLock;
8278
8669
  try {
8279
- const dir = path19.dirname(file);
8280
- if (fs16.existsSync(dir) && fs16.lstatSync(dir).isSymbolicLink()) return;
8281
- if (fs16.existsSync(file) && fs16.lstatSync(file).isSymbolicLink()) return;
8282
- fs16.mkdirSync(dir, { recursive: true, mode: 448 });
8283
- releaseLock = acquireStoreLock(path19.join(dir, ".panel-cards.lock"));
8670
+ const dir = path20.dirname(file);
8671
+ if (fs17.existsSync(dir) && fs17.lstatSync(dir).isSymbolicLink()) return;
8672
+ if (fs17.existsSync(file) && fs17.lstatSync(file).isSymbolicLink()) return;
8673
+ fs17.mkdirSync(dir, { recursive: true, mode: 448 });
8674
+ releaseLock = acquireStoreLock(path20.join(dir, ".panel-cards.lock"));
8284
8675
  if (!releaseLock) return;
8285
8676
  readCache = void 0;
8286
8677
  const map = readStoreMap(file);
@@ -8306,21 +8697,21 @@ function savePersistedPanelCard(provider, messageId, entry, now = Date.now()) {
8306
8697
  map.delete(oldest);
8307
8698
  }
8308
8699
  const payload = { version: 1, entries: [...map.values()] };
8309
- tmp = path19.join(dir, `.panel-cards-${process.pid}-${randomUUID4()}.tmp`);
8310
- const fd = fs16.openSync(tmp, "wx", 384);
8700
+ tmp = path20.join(dir, `.panel-cards-${process.pid}-${randomUUID4()}.tmp`);
8701
+ const fd = fs17.openSync(tmp, "wx", 384);
8311
8702
  try {
8312
- fs16.writeFileSync(fd, `${JSON.stringify(payload)}
8703
+ fs17.writeFileSync(fd, `${JSON.stringify(payload)}
8313
8704
  `);
8314
8705
  } finally {
8315
- fs16.closeSync(fd);
8706
+ fs17.closeSync(fd);
8316
8707
  }
8317
- fs16.renameSync(tmp, file);
8708
+ fs17.renameSync(tmp, file);
8318
8709
  tmp = void 0;
8319
8710
  readCache = { file, stamp: fileStamp(file), map };
8320
8711
  } catch {
8321
8712
  if (tmp) {
8322
8713
  try {
8323
- fs16.rmSync(tmp, { force: true });
8714
+ fs17.rmSync(tmp, { force: true });
8324
8715
  } catch {
8325
8716
  }
8326
8717
  }
@@ -8668,6 +9059,23 @@ function createPanelExecutor(ctx) {
8668
9059
  await deliverPanelSpec(archiveResult.spec, `${archiveResult.keyPrefix}-${event.event_id}`, true);
8669
9060
  return;
8670
9061
  }
9062
+ const memoryResult = runMemoryPanelCommand(effectiveCmd, {
9063
+ inThread,
9064
+ canReadSensitive: peekAudienceAllowed(event),
9065
+ canMutate: canMutatePanel()
9066
+ });
9067
+ if (memoryResult.handled) {
9068
+ if (memoryResult.refusedText !== void 0) {
9069
+ ctx.log(`im-forward: ${panelCmd.cmd} refused for ${event.sender_id ?? "unknown"} (panelAccess=allowUsers)`);
9070
+ try {
9071
+ await ctx.connection.send(freshRecipient, memoryResult.refusedText, `panel-refused-${event.event_id}`, sendReplyTo, sendOpts);
9072
+ } catch {
9073
+ }
9074
+ return;
9075
+ }
9076
+ await deliverPanelSpec(memoryResult.spec, `${memoryResult.keyPrefix}-${event.event_id}`, true);
9077
+ return;
9078
+ }
8671
9079
  const verifiedCronStop = issuedCronStopForGuard && issuedCronStopForGuard.chatId === event.chat_id && issuedCronStopForGuard.ownerSession === ctx.getCurrentSessionId() && issuedCronStopForGuard.epoch === ctx.getInputEpoch() ? { jobId: issuedCronStopForGuard.jobId, sessionId: issuedCronStopForGuard.sessionId, ...issuedCronStopForGuard.storeKey ? { storeKey: issuedCronStopForGuard.storeKey } : {} } : void 0;
8672
9080
  const cronResult = runCronPanelCommand(effectiveCmd, {
8673
9081
  inThread,
@@ -8828,7 +9236,14 @@ function createPanelExecutor(ctx) {
8828
9236
  title: "Context Report",
8829
9237
  columnsPerRow: cols,
8830
9238
  body: renderContextReceipt(contextAction[1], receipt),
8831
- actions: workerScoped ? [{ id: `panel.worker.${contextAction[1]}`, label: "\u21A9\uFE0F Back to worker" }] : payloadFromWorker ? [{ id: `panel.worker.${payloadFromWorker}`, label: "\u21A9\uFE0F Back to worker" }, ...homeOpt] : hideHome ? panelHomeAction(true, threadWorkerSessionId, contextAction[1]) : [{ id: "panel.context", label: "\u21A9\uFE0F Back to context list" }, { id: "panel.home", label: "\u{1F4CB} \u603B\u9762\u677F" }]
9239
+ actions: [
9240
+ {
9241
+ id: `panel.compact.${contextAction[1]}`,
9242
+ label: "\u{1F9F9} \u538B\u7F29",
9243
+ ...workerScoped || payloadFromWorker ? { payload: { from: "worker", peer: workerScoped ? contextAction[1] : payloadFromWorker } } : {}
9244
+ },
9245
+ ...workerScoped ? [{ id: `panel.worker.${contextAction[1]}`, label: "\u21A9\uFE0F Back to worker" }] : payloadFromWorker ? [{ id: `panel.worker.${payloadFromWorker}`, label: "\u21A9\uFE0F Back to worker" }, ...homeOpt] : hideHome ? panelHomeAction(true, threadWorkerSessionId, contextAction[1]) : [{ id: "panel.context", label: "\u21A9\uFE0F Back to context list" }, { id: "panel.home", label: "\u{1F4CB} \u603B\u9762\u677F" }]
9246
+ ]
8832
9247
  };
8833
9248
  await deliverPanelSpec(spec, `panel-context-${event.event_id}`, true, navGen);
8834
9249
  return;
@@ -9337,7 +9752,7 @@ function createInboundShell(ctx) {
9337
9752
 
9338
9753
  // builtin/extensions/im-forward/runtime.ts
9339
9754
  import * as crypto from "node:crypto";
9340
- import * as fs17 from "node:fs";
9755
+ import * as fs18 from "node:fs";
9341
9756
  import { basename } from "node:path";
9342
9757
  var ROUTE_TTL_MS2 = 24 * 60 * 60 * 1e3;
9343
9758
  var SEND_FAILURE_NOTIFY_THROTTLE_MS2 = 5 * 60 * 1e3;
@@ -9839,18 +10254,18 @@ ${recoveryHint}`,
9839
10254
  const files = collectFileReferences(
9840
10255
  text,
9841
10256
  ctx.cwd,
9842
- (path20) => {
10257
+ (path21) => {
9843
10258
  try {
9844
- const stat = fs17.statSync(path20);
10259
+ const stat = fs18.statSync(path21);
9845
10260
  return { isFile: stat.isFile(), size: stat.size };
9846
10261
  } catch {
9847
10262
  return null;
9848
10263
  }
9849
10264
  },
9850
10265
  {
9851
- canonicalize: (path20) => {
10266
+ canonicalize: (path21) => {
9852
10267
  try {
9853
- return fs17.realpathSync(path20);
10268
+ return fs18.realpathSync(path21);
9854
10269
  } catch {
9855
10270
  return null;
9856
10271
  }
@@ -10011,6 +10426,10 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
10011
10426
  const peekAudienceAllowed = panelExecutor.peekAudienceAllowed;
10012
10427
  async function handleInboundEventInner(event, retry) {
10013
10428
  let nonBoundGroup = false;
10429
+ if (event.isCardAction === true && event.chatType !== "group" && event.chatType !== "p2p") {
10430
+ ctx.log(`im-forward: card action refused (unclassified chatType=${String(event.chatType)})`);
10431
+ return;
10432
+ }
10014
10433
  const isGroup = event.chatType === "group";
10015
10434
  if (isGroup) {
10016
10435
  nonBoundGroup = cfg.targetKind === "chat" && !!cfg.targetId && event.chat_id !== cfg.targetId;