@cydm/pie 2.7.19 → 2.8.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 (30) hide show
  1. package/README.md +6 -6
  2. package/dist/builtin/extensions/ask-user/README.md +117 -0
  3. package/dist/builtin/extensions/ask-user/index.js +3 -3
  4. package/dist/builtin/extensions/cron/index.js +166 -23
  5. package/dist/builtin/extensions/im-forward/README.md +297 -0
  6. package/dist/builtin/extensions/im-forward/index.js +319 -42
  7. package/dist/builtin/extensions/init/index.js +0 -6
  8. package/dist/builtin/extensions/mcp-adapter/README.md +27 -0
  9. package/dist/builtin/extensions/memory/index.js +323 -0
  10. package/dist/builtin/extensions/memory/package.json +18 -0
  11. package/dist/builtin/extensions/pie-ipc/README.md +21 -0
  12. package/dist/builtin/extensions/pie-ipc/index.js +16 -16
  13. package/dist/builtin/extensions/plan-mode/METHOD.md +70 -0
  14. package/dist/builtin/extensions/plan-mode/index.js +149 -82
  15. package/dist/builtin/extensions/subagent/README.md +315 -0
  16. package/dist/builtin/extensions/subagent/index.js +7 -5
  17. package/dist/builtin/extensions/todo/index.js +3 -3
  18. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +1 -1
  19. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  20. package/dist/builtin/skills/chrome-devtools-axi/{chunk-U75F4DPF.js → chunk-BNSAEVRT.js} +201 -77
  21. package/dist/builtin/skills/chrome-devtools-axi/{cli-4ITIR57L.js → cli-AO2ZTPRM.js} +57 -202
  22. package/dist/chunks/chunk-5353DEEC.js +130 -0
  23. package/dist/chunks/{chunk-2H2DD22Z.js → chunk-HGC25NYB.js} +1 -1
  24. package/dist/chunks/{chunk-X7UO6BA6.js → chunk-JNOFHHLZ.js} +156 -65
  25. package/dist/chunks/{chunk-UDCGB3LZ.js → chunk-LJXHECZ7.js} +12183 -10951
  26. package/dist/chunks/{chunk-TGCI5M6R.js → chunk-NEES4EBX.js} +19 -141
  27. package/dist/chunks/{src-GX4UBAYF.js → src-5XOKRS6F.js} +2 -2
  28. package/dist/chunks/{test-stream-AKIZNFCM.js → test-stream-5SDHKKDB.js} +1 -1
  29. package/dist/cli.js +127 -96
  30. package/package.json +2 -2
@@ -12,6 +12,7 @@ import * as os from "node:os";
12
12
  import { randomUUID } from "node:crypto";
13
13
 
14
14
  // builtin/extensions/im-forward/helpers.ts
15
+ import * as nodeCrypto from "node:crypto";
15
16
  var MAX_INPUT_HEADER_CHARS = 200;
16
17
  function isRecord(value) {
17
18
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -109,6 +110,222 @@ function truncateMarkdown(text, maxBytes = MAX_BODY_BYTES) {
109
110
  }
110
111
  return cut + suffix;
111
112
  }
113
+ function scanFenceLines(text) {
114
+ const lines = text.split("\n");
115
+ const stateAtLineStart = [];
116
+ const stateAtLineEnd = [];
117
+ const openedBy = [];
118
+ const closedBy = [];
119
+ let open = null;
120
+ for (const line of lines) {
121
+ stateAtLineStart.push(open);
122
+ let opened = null;
123
+ let closed = null;
124
+ if (!open) {
125
+ const m = /^( {0,3})(`{3,}|~{3,})(.*)$/.exec(line);
126
+ if (m && (m[2][0] === "~" || !m[3].includes("`"))) {
127
+ open = { delimiter: m[2], info: m[3].trim() };
128
+ opened = open;
129
+ }
130
+ } else {
131
+ const m = /^( {0,3})(`+|~+)[ \t]*$/.exec(line);
132
+ if (m && m[2][0] === open.delimiter[0] && m[2].length >= open.delimiter.length) {
133
+ closed = open;
134
+ open = null;
135
+ }
136
+ }
137
+ openedBy.push(opened);
138
+ closedBy.push(closed);
139
+ stateAtLineEnd.push(open);
140
+ }
141
+ return { stateAtLineStart, stateAtLineEnd, openedBy, closedBy, lines };
142
+ }
143
+ function chunkKey(base, index, tag = "part", digest = sha256Digest19) {
144
+ if (index === 0 && tag === "part" && base.length <= 50) return base;
145
+ const candidate = `${base}-${tag}${index + 1}`;
146
+ if (candidate.length <= 50) return candidate;
147
+ return `${base.slice(0, 30)}-${digest(`${tag}:${index}:${base}`)}`.slice(0, 50);
148
+ }
149
+ var sha256Digest19 = (input) => nodeCrypto.createHash("sha256").update(input).digest("hex").slice(0, 19);
150
+ function chunkMarkdown(text, maxBytes = MAX_BODY_BYTES) {
151
+ const MIN_FEASIBLE_BUDGET = 320;
152
+ if (maxBytes < MIN_FEASIBLE_BUDGET) return [[text], false];
153
+ if (utf16LengthBudget(text, MAX_BODY_UTF16_CHARS) === text && estimatePostRequestBytes(text) <= maxBytes) {
154
+ return [[text], false];
155
+ }
156
+ const scan = scanFenceLines(text);
157
+ const lines = scan.lines.slice();
158
+ const fits = (candidate) => candidate.length <= MAX_BODY_UTF16_CHARS && estimatePostRequestBytes(candidate) <= maxBytes;
159
+ const MAX_SYNTHETIC_INFO_CHARS = 32;
160
+ const closeMarker = (f) => f.delimiter;
161
+ const midLineCloseMarker = (f) => "\n" + f.delimiter;
162
+ const reopenMarker = (f) => f.delimiter + (f.info.length > MAX_SYNTHETIC_INFO_CHARS ? f.info.slice(0, MAX_SYNTHETIC_INFO_CHARS) : f.info) + "\n";
163
+ const chunks = [];
164
+ let lineIndex = 0;
165
+ let pendingPrefix = "";
166
+ while (lineIndex < lines.length) {
167
+ if (lines[lineIndex] === "" && lineIndex === lines.length - 1) {
168
+ lineIndex++;
169
+ continue;
170
+ }
171
+ const assemble = (endLine) => {
172
+ const separator = endLine < lines.length - 1 ? "\n" : "";
173
+ const body = pendingPrefix + lines.slice(lineIndex, endLine + 1).join("\n") + separator;
174
+ const fence = scan.stateAtLineEnd[endLine] ?? null;
175
+ const chunk = body + (fence ? body.endsWith("\n") || body === "" ? fence.delimiter : "\n" + fence.delimiter : "");
176
+ return fits(chunk) ? { chunk, fence, endLine } : null;
177
+ };
178
+ let lo = lineIndex, hi = lines.length - 1;
179
+ let best = null;
180
+ while (lo <= hi) {
181
+ const mid = lo + Math.ceil((hi - lo) / 2);
182
+ const built = assemble(mid);
183
+ if (built) {
184
+ best = built;
185
+ lo = mid + 1;
186
+ } else hi = mid - 1;
187
+ }
188
+ if (best) {
189
+ for (let j = best.endLine - 1; j > lineIndex + Math.floor((best.endLine - lineIndex) / 2); j--) {
190
+ if (lines[j + 1] === "" && scan.stateAtLineEnd[j] === null && !scan.openedBy[j]) {
191
+ const snapped = assemble(j);
192
+ if (snapped) best = snapped;
193
+ break;
194
+ }
195
+ }
196
+ chunks.push(best.chunk);
197
+ lineIndex = best.endLine + 1;
198
+ pendingPrefix = best.fence ? reopenMarker(best.fence) : "";
199
+ continue;
200
+ }
201
+ const firstLine = lines[lineIndex];
202
+ if (firstLine.length === 0) {
203
+ lineIndex++;
204
+ continue;
205
+ }
206
+ const pFence = scan.stateAtLineEnd[lineIndex] ?? null;
207
+ let plo = 1, phi = firstLine.length, pbest = 0;
208
+ while (plo <= phi) {
209
+ const mid = plo + Math.ceil((phi - plo) / 2);
210
+ const prefix = stripDanglingHighSurrogate(firstLine.slice(0, mid));
211
+ const chunk = pendingPrefix + prefix + (pFence ? midLineCloseMarker(pFence) : "");
212
+ if (fits(chunk)) {
213
+ pbest = prefix.length;
214
+ plo = mid + 1;
215
+ } else phi = mid - 1;
216
+ }
217
+ if (pbest > 0) {
218
+ chunks.push(pendingPrefix + stripDanglingHighSurrogate(firstLine.slice(0, pbest)) + (pFence ? midLineCloseMarker(pFence) : ""));
219
+ lines[lineIndex] = firstLine.slice(pbest);
220
+ pendingPrefix = pFence ? reopenMarker(pFence) : "";
221
+ continue;
222
+ }
223
+ const one = stripDanglingHighSurrogate(firstLine.slice(0, 2));
224
+ chunks.push(one.length > 0 ? one : firstLine.slice(0, 1));
225
+ lines[lineIndex] = firstLine.slice(one.length > 0 ? one.length : 1);
226
+ pendingPrefix = "";
227
+ }
228
+ return [chunks, chunks.length > 1];
229
+ }
230
+ var ATTACHABLE_EXTENSIONS = /* @__PURE__ */ new Set([
231
+ "ts",
232
+ "tsx",
233
+ "js",
234
+ "jsx",
235
+ "mjs",
236
+ "cjs",
237
+ "json",
238
+ "md",
239
+ "txt",
240
+ "log",
241
+ "py",
242
+ "cs",
243
+ "css",
244
+ "scss",
245
+ "html",
246
+ "xml",
247
+ "yaml",
248
+ "yml",
249
+ "toml",
250
+ "sh",
251
+ "sql",
252
+ "java",
253
+ "kt",
254
+ "swift",
255
+ "go",
256
+ "rs",
257
+ "rb",
258
+ "php",
259
+ "c",
260
+ "h",
261
+ "cpp",
262
+ "hpp"
263
+ ]);
264
+ var MAX_ATTACHMENT_BYTES = 2 * 1024 * 1024;
265
+ var MAX_ATTACHMENTS_PER_FORWARD = 5;
266
+ function collectFileReferences(text, cwd, fsStat, options) {
267
+ const maxFiles = options?.maxFiles ?? MAX_ATTACHMENTS_PER_FORWARD;
268
+ const maxBytes = options?.maxBytes ?? MAX_ATTACHMENT_BYTES;
269
+ const canonicalRoot = options?.canonicalize ? options.canonicalize(cwd) : cwd;
270
+ if (canonicalRoot === null) return [];
271
+ const rootPrefix = canonicalRoot.endsWith("/") ? canonicalRoot : canonicalRoot + "/";
272
+ const seen = /* @__PURE__ */ new Set();
273
+ const results = [];
274
+ const normalized = text.split("\n").map((line) => line.replace(/^(?: {0,3}> ?)+/, ""));
275
+ const scan = scanFenceLines(normalized.join("\n"));
276
+ let outside = "";
277
+ const indentColumns = (line) => {
278
+ let column = 0;
279
+ for (const ch of line) {
280
+ if (ch === " ") column += 1;
281
+ else if (ch === " ") column = 4 * Math.ceil((column + 1) / 4);
282
+ else break;
283
+ }
284
+ return column;
285
+ };
286
+ for (let i = 0; i < scan.lines.length; i++) {
287
+ const line = scan.lines[i];
288
+ const insideFence = scan.stateAtLineStart[i] !== null || scan.openedBy[i] !== null;
289
+ const indentedCode = indentColumns(line) >= 4;
290
+ if (!insideFence && !indentedCode) outside += line + "\n";
291
+ }
292
+ const candidates = [];
293
+ for (const match of outside.matchAll(/\[[^\]\n]*\]\(([^)\n]+)\)/g)) candidates.push(match[1]);
294
+ for (const match of outside.matchAll(/`([^`\n]+)`/g)) {
295
+ const code = match[1].trim();
296
+ if (code.includes("/") || /\.[a-z0-9]{1,8}$/i.test(code)) candidates.push(code);
297
+ }
298
+ for (const candidate of candidates) {
299
+ if (results.length >= maxFiles) break;
300
+ let path7 = candidate.trim();
301
+ if (!path7 || path7.startsWith("/") || path7.startsWith("~") || /^[a-z]+:/i.test(path7) || path7.includes("://")) continue;
302
+ const clean = path7.replace(/^\.\//, "").split("#")[0].split("?")[0];
303
+ if (clean.includes("..")) continue;
304
+ const extension = clean.split(".").pop().toLowerCase();
305
+ if (!extension || !ATTACHABLE_EXTENSIONS.has(extension)) continue;
306
+ const absolute = nodePathResolve(cwd, clean);
307
+ if (seen.has(absolute)) continue;
308
+ const stat = fsStat(absolute);
309
+ if (!stat || !stat.isFile || stat.size > maxBytes || stat.size === 0) continue;
310
+ const canonical = options?.canonicalize ? options.canonicalize(absolute) : absolute;
311
+ if (canonical === null) continue;
312
+ if (canonical !== canonicalRoot && !canonical.startsWith(rootPrefix)) continue;
313
+ if (seen.has(canonical)) continue;
314
+ seen.add(absolute);
315
+ seen.add(canonical);
316
+ results.push(absolute);
317
+ }
318
+ return results;
319
+ }
320
+ function nodePathResolve(cwd, relative) {
321
+ const normalized = relative.split("/").filter((part) => part.length > 0);
322
+ const base = cwd.replace(/\/$/, "").split("/");
323
+ for (const part of normalized) {
324
+ if (part === ".") continue;
325
+ base.push(part);
326
+ }
327
+ return base.join("/");
328
+ }
112
329
  function failureReason(message) {
113
330
  const detail = message.errorMessage?.trim();
114
331
  if (detail) {
@@ -292,6 +509,7 @@ function resolveImForwardConfig(cwd, dir) {
292
509
  }
293
510
 
294
511
  // builtin/extensions/im-forward/runtime.ts
512
+ import * as fs2 from "node:fs";
295
513
  var ROUTE_TTL_MS = 24 * 60 * 60 * 1e3;
296
514
  var MAX_ROUTES = 500;
297
515
  var MAX_SEEN_EVENTS = 1e3;
@@ -299,6 +517,8 @@ var REPLY_CHAIN_MAX_DEPTH = 5;
299
517
  var RESTART_BACKOFF_MIN_MS = 5e3;
300
518
  var RESTART_BACKOFF_MAX_MS = 6e4;
301
519
  var SEND_FAILURE_NOTIFY_THROTTLE_MS = 5 * 60 * 1e3;
520
+ var CHUNK_RETRY_DELAY_MS = 2e3;
521
+ var delay = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
302
522
  var MAX_INBOUND_RETRIES = 3;
303
523
  var DEFAULT_INBOUND_RETRY_BACKOFF_MS = 5e3;
304
524
  var MAX_PENDING_IM_INPUTS = 50;
@@ -306,7 +526,7 @@ var PENDING_IM_INPUT_TTL_MS = 60 * 60 * 1e3;
306
526
  function summarizeFailureReason(reason) {
307
527
  if (!reason) return { summary: "", persistent: false };
308
528
  const text = reason.toLowerCase();
309
- if (/another event bus|already connected/.test(text)) return { summary: "the app's event connection is occupied by another instance (possibly another machine); run /im-forward setup with another app/profile, or stop the other consumer", persistent: true };
529
+ if (/another event bus|already connected/.test(text)) return { summary: "the app's event connection is occupied by another instance (possibly another machine); run /tools/im-forward setup with another app/profile, or stop the other consumer", persistent: true };
310
530
  if (/no active profile|not configured/.test(text)) return { summary: "provider not configured", persistent: false };
311
531
  if (/auth|unauthorized|token|credential|login/.test(text)) return { summary: "authentication problem", persistent: false };
312
532
  if (/permission|forbidden|scope/.test(text)) return { summary: "permission problem", persistent: false };
@@ -512,26 +732,75 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
512
732
  pruneState();
513
733
  const sessionName = ctx.getSessionName?.();
514
734
  const composed = composeForwardBody(sessionId, sessionName, userInput, text);
515
- const body = truncateMarkdown(composed);
516
735
  if (terminated || !isForwardingEnabled()) return;
517
- const idempotencyKey = `pie-im-forward-${cfg.provider}-${sessionId}-${sequence}-${hashText(composed)}`;
736
+ const [chunks] = chunkMarkdown(composed);
737
+ const baseKey = `pie-im-forward-${cfg.provider}-${sessionId}-${sequence}-${hashText(composed)}`;
518
738
  let anchor = replyTo ?? replyAnchor.get(sessionId)?.messageId;
519
- let sent = await providerCall("send", () => connection.send(cfg.targetId, body, idempotencyKey, anchor));
739
+ const sendChunk = async (index) => {
740
+ const key2 = chunkKey(baseKey, index);
741
+ return providerCall("send", () => connection.send(cfg.targetId, chunks[index], key2, anchor));
742
+ };
743
+ let sent = await sendChunk(0);
520
744
  if (!sent && anchor && !terminated && isForwardingEnabled()) {
521
745
  if (replyAnchor.get(sessionId)?.messageId === anchor) replyAnchor.delete(sessionId);
522
746
  anchorFallbacks++;
523
- sent = await providerCall("send", () => connection.send(cfg.targetId, body, idempotencyKey));
747
+ anchor = void 0;
748
+ sent = await sendChunk(0);
524
749
  }
525
750
  if (!sent) {
526
751
  notifySendFailure(`${cfg.provider} send failed`);
527
752
  return;
528
753
  }
529
- const { messageId, threadId } = sent;
530
- const route = { messageId, threadId, sessionId, sentAt: Date.now() };
531
- routes.set(key(messageId), route);
532
- if (threadId) threadRoutes.set(key(threadId), route);
533
- ctx.log(`im-forward: forwarded session=${sessionId} as ${messageId}`);
534
- if (terminated || !isForwardingEnabled()) return;
754
+ registerRoute(sent, sessionId);
755
+ for (let index = 1; index < chunks.length; index++) {
756
+ if (terminated || !isForwardingEnabled()) return;
757
+ let next = await sendChunk(index);
758
+ if (!next && (terminated || !isForwardingEnabled())) return;
759
+ if (!next && !terminated && isForwardingEnabled()) {
760
+ await delay(CHUNK_RETRY_DELAY_MS);
761
+ if (terminated || !isForwardingEnabled()) return;
762
+ next = await sendChunk(index);
763
+ if (!next && (terminated || !isForwardingEnabled())) return;
764
+ }
765
+ if (!next) {
766
+ notifySendFailure(`${cfg.provider} send failed (part ${index + 1}/${chunks.length})`);
767
+ void providerCall("send notice", () => connection.send(cfg.targetId, `\u2026(\u7B2C ${index}/${chunks.length} \u6BB5\u4E4B\u540E\u7684\u5206\u6BB5\u53D1\u9001\u5931\u8D25\uFF0C\u5B8C\u6574\u5185\u5BB9\u89C1\u7EC8\u7AEF)`, chunkKey(baseKey, index, "fail"), anchor));
768
+ return;
769
+ }
770
+ registerRoute(next, sessionId);
771
+ }
772
+ if (connection.sendFile && !terminated && isForwardingEnabled()) {
773
+ const files = collectFileReferences(text, ctx.cwd, (path7) => {
774
+ try {
775
+ const stat = fs2.statSync(path7);
776
+ return { isFile: stat.isFile(), size: stat.size };
777
+ } catch {
778
+ return null;
779
+ }
780
+ }, { canonicalize: (path7) => {
781
+ try {
782
+ return fs2.realpathSync(path7);
783
+ } catch {
784
+ return null;
785
+ }
786
+ } });
787
+ for (const [index, file] of files.entries()) {
788
+ if (terminated || !isForwardingEnabled()) return;
789
+ const attachment = await providerCall("send file", () => connection.sendFile(cfg.targetId, file, chunkKey(baseKey, index, "file"), anchor));
790
+ if (attachment) {
791
+ registerRoute(attachment, sessionId);
792
+ ctx.log(`im-forward: attached ${file}`);
793
+ } else if (!terminated && isForwardingEnabled()) {
794
+ ctx.log(`im-forward: attachment upload failed: ${file}`);
795
+ }
796
+ }
797
+ }
798
+ }
799
+ function registerRoute(sent, sessionId) {
800
+ const route = { messageId: sent.messageId, threadId: sent.threadId, sessionId, sentAt: Date.now() };
801
+ routes.set(key(sent.messageId), route);
802
+ if (sent.threadId) threadRoutes.set(key(sent.threadId), route);
803
+ ctx.log(`im-forward: forwarded session=${sessionId} as ${sent.messageId}`);
535
804
  }
536
805
  ctx.on("session:changed", (event) => {
537
806
  inputEpoch++;
@@ -812,7 +1081,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
812
1081
  ctx.log(`im-forward: consumer exited (${consumerLastExit})`);
813
1082
  if (!persistent || !notifiedPersistentFailure) {
814
1083
  if (persistent) notifiedPersistentFailure = true;
815
- ctx.ui.notify(`IM forwarding: ${cfg.provider} connection failed${safe ? `: ${safe}` : "; check provider configuration/authentication."}${persistent ? " Retrying in the background (see /im-forward status)." : " Retrying."}`, persistent ? "error" : "warning");
1084
+ ctx.ui.notify(`IM forwarding: ${cfg.provider} connection failed${safe ? `: ${safe}` : "; check provider configuration/authentication."}${persistent ? " Retrying in the background (see /tools/im-forward status)." : " Retrying."}`, persistent ? "error" : "warning");
816
1085
  }
817
1086
  recover();
818
1087
  };
@@ -879,9 +1148,9 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
879
1148
  if (!suspended) return;
880
1149
  suspended = false;
881
1150
  if (consumer || consumerRecovering || restartTimer) return;
882
- const delay = suspendedRestartInMs !== void 0 ? suspendedRestartInMs : Math.min(RESTART_BACKOFF_MIN_MS * 2 ** Math.min(consumerRestarts, 4), RESTART_BACKOFF_MAX_MS);
1151
+ const delay2 = suspendedRestartInMs !== void 0 ? suspendedRestartInMs : Math.min(RESTART_BACKOFF_MIN_MS * 2 ** Math.min(consumerRestarts, 4), RESTART_BACKOFF_MAX_MS);
883
1152
  suspendedRestartInMs = void 0;
884
- scheduleRestart(delay);
1153
+ scheduleRestart(delay2);
885
1154
  };
886
1155
  };
887
1156
  updateFooterTag();
@@ -975,7 +1244,7 @@ Enable forwarding and start the connection? No test message will be sent. Saving
975
1244
 
976
1245
  // builtin/extensions/im-forward/providers/feishu/index.ts
977
1246
  import { spawn as spawn4 } from "node:child_process";
978
- import * as fs4 from "node:fs";
1247
+ import * as fs5 from "node:fs";
979
1248
  import * as os2 from "node:os";
980
1249
  import * as path6 from "node:path";
981
1250
 
@@ -985,7 +1254,7 @@ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
985
1254
 
986
1255
  // builtin/extensions/im-forward/launch.ts
987
1256
  import { spawn } from "node:child_process";
988
- import * as fs2 from "node:fs";
1257
+ import * as fs3 from "node:fs";
989
1258
  import * as path2 from "node:path";
990
1259
  import { StringDecoder } from "node:string_decoder";
991
1260
  function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
@@ -993,25 +1262,25 @@ function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.pla
993
1262
  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)));
994
1263
  for (const candidate of candidates) {
995
1264
  try {
996
- if (!fs2.statSync(candidate).isFile()) continue;
1265
+ if (!fs3.statSync(candidate).isFile()) continue;
997
1266
  const ext = path2.extname(candidate).toLowerCase();
998
1267
  if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
999
1268
  if (windows && ext === ".cmd") {
1000
1269
  const dir = path2.dirname(candidate);
1001
1270
  for (const root of [path2.join(dir, "node_modules", "@larksuite", "cli"), path2.resolve(dir, "..", "@larksuite", "cli")]) {
1002
1271
  try {
1003
- const pkg = JSON.parse(fs2.readFileSync(path2.join(root, "package.json"), "utf8"));
1272
+ const pkg = JSON.parse(fs3.readFileSync(path2.join(root, "package.json"), "utf8"));
1004
1273
  const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
1005
1274
  if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
1006
1275
  const entry = path2.join(root, "scripts", "run.js");
1007
- if (fs2.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
1276
+ if (fs3.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
1008
1277
  } catch {
1009
1278
  }
1010
1279
  }
1011
1280
  continue;
1012
1281
  }
1013
1282
  if (windows && ext !== ".exe") continue;
1014
- fs2.accessSync(candidate, fs2.constants.X_OK);
1283
+ fs3.accessSync(candidate, fs3.constants.X_OK);
1015
1284
  return { command: candidate, prefix: [] };
1016
1285
  } catch {
1017
1286
  }
@@ -1312,7 +1581,7 @@ function extractImageKey(content) {
1312
1581
  }
1313
1582
 
1314
1583
  // builtin/extensions/im-forward/providers/feishu/setup.ts
1315
- import * as fs3 from "node:fs";
1584
+ import * as fs4 from "node:fs";
1316
1585
  import * as path5 from "node:path";
1317
1586
 
1318
1587
  // builtin/extensions/im-forward/browser.ts
@@ -1396,9 +1665,9 @@ function findNpmCli() {
1396
1665
  const dirs = [path5.dirname(process.execPath), ...(process.env.PATH ?? "").split(path5.delimiter)];
1397
1666
  for (const dir of dirs) for (const root of [path5.join(dir, "node_modules", "npm"), path5.resolve(dir, "..", "lib", "node_modules", "npm")]) {
1398
1667
  try {
1399
- const pkg = JSON.parse(fs3.readFileSync(path5.join(root, "package.json"), "utf8"));
1668
+ const pkg = JSON.parse(fs4.readFileSync(path5.join(root, "package.json"), "utf8"));
1400
1669
  const entry = path5.join(root, "bin", "npm-cli.js");
1401
- if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs3.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
1670
+ if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs4.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
1402
1671
  } catch {
1403
1672
  }
1404
1673
  }
@@ -1925,6 +2194,11 @@ function connect(binary, profile, targetKind = "chat") {
1925
2194
  const data = await call(replyTo ? ["im", "+messages-reply", "--as", "bot", "--message-id", replyTo, "--markdown", text, "--idempotency-key", key] : ["im", "+messages-send", "--as", "bot", ...recipient, "--markdown", text, "--idempotency-key", key]);
1926
2195
  return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null } : null;
1927
2196
  },
2197
+ async sendFile(target, file, key, replyTo) {
2198
+ const recipient = targetKind === "user" ? ["--user-id", target] : ["--chat-id", target];
2199
+ const data = await call(replyTo ? ["im", "+messages-reply", "--as", "bot", "--message-id", replyTo, "--file", file, "--idempotency-key", key] : ["im", "+messages-send", "--as", "bot", ...recipient, "--file", file, "--idempotency-key", key]);
2200
+ return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null } : null;
2201
+ },
1928
2202
  async acknowledge(id) {
1929
2203
  await call(["im", "reactions", "create", "--as", "bot", "--params", JSON.stringify({ message_id: id }), "--data", JSON.stringify({ reaction_type: { emoji_type: "THUMBSUP" } })]);
1930
2204
  },
@@ -1938,19 +2212,19 @@ function connect(binary, profile, targetKind = "chat") {
1938
2212
  return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
1939
2213
  },
1940
2214
  async downloadImage(messageId, image, index) {
1941
- const directory = fs4.mkdtempSync(path6.join(os2.tmpdir(), "pie-im-forward-"));
1942
- const cleanup = () => fs4.rmSync(directory, { recursive: true, force: true });
2215
+ const directory = fs5.mkdtempSync(path6.join(os2.tmpdir(), "pie-im-forward-"));
2216
+ const cleanup = () => fs5.rmSync(directory, { recursive: true, force: true });
1943
2217
  try {
1944
2218
  const name = `image-${index + 1}.png`;
1945
2219
  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 });
1946
2220
  if (result.error || !parseLarkCliEnvelope(result.stdout).ok) throw new Error("Image download failed");
1947
2221
  let target = path6.join(directory, name);
1948
- if (fs4.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
2222
+ if (fs5.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
1949
2223
  const detected = readImageFormat(target);
1950
2224
  if (detected.ext === ".bin") throw new Error("Unsupported image format");
1951
2225
  if (detected.ext !== ".png") {
1952
2226
  const corrected = path6.join(directory, `image-${index + 1}${detected.ext}`);
1953
- fs4.renameSync(target, corrected);
2227
+ fs5.renameSync(target, corrected);
1954
2228
  target = corrected;
1955
2229
  }
1956
2230
  return { file: { path: target, displayName: `feishu-image-${index + 1}${detected.ext}` }, cleanup };
@@ -2066,7 +2340,7 @@ function initializeImForward(ctx, providers = implementedProviders) {
2066
2340
  ctx.ui.setStatus?.("im-forward", "[IM!]");
2067
2341
  if (!warnedMismatch) {
2068
2342
  warnedMismatch = true;
2069
- ctx.ui.notify("IM forwarding configuration changed or cannot be read. Forwarding is paused; run /im-forward setup.", "warning");
2343
+ ctx.ui.notify("IM forwarding configuration changed or cannot be read. Forwarding is paused; run /tools/im-forward setup.", "warning");
2070
2344
  }
2071
2345
  return null;
2072
2346
  }
@@ -2076,20 +2350,20 @@ function initializeImForward(ctx, providers = implementedProviders) {
2076
2350
  if (disposed) return;
2077
2351
  const provider = providers.find((item) => item.id === config.provider);
2078
2352
  if (!provider) {
2079
- ctx.ui.notify(`IM forwarding: unsupported provider "${config.provider}". Run /im-forward setup.`, "error");
2353
+ ctx.ui.notify(`IM forwarding: unsupported provider "${config.provider}". Run /tools/im-forward setup.`, "error");
2080
2354
  ctx.ui.setStatus?.("im-forward", "[IM!]");
2081
2355
  return;
2082
2356
  }
2083
2357
  try {
2084
2358
  const settings = provider.resolve(config.settings);
2085
2359
  if (!settings) {
2086
- ctx.ui.notify(`IM forwarding: ${provider.label} target/settings are incomplete. Use Ctrl+R or /im-forward setup.`, "warning");
2360
+ ctx.ui.notify(`IM forwarding: ${provider.label} target/settings are incomplete. Use Ctrl+R or /tools/im-forward setup.`, "warning");
2087
2361
  ctx.ui.setStatus?.("im-forward", "[IM!]");
2088
2362
  return;
2089
2363
  }
2090
2364
  const connection = provider.connect(settings, ctx.cwd);
2091
2365
  if (!connection) {
2092
- ctx.ui.notify(`IM forwarding: ${provider.label} connection could not be prepared. Use Ctrl+R or /im-forward setup to check provider dependencies and configuration.`, "warning");
2366
+ ctx.ui.notify(`IM forwarding: ${provider.label} connection could not be prepared. Use Ctrl+R or /tools/im-forward setup to check provider dependencies and configuration.`, "warning");
2093
2367
  ctx.ui.setStatus?.("im-forward", "[IM!]");
2094
2368
  return;
2095
2369
  }
@@ -2160,7 +2434,7 @@ function initializeImForward(ctx, providers = implementedProviders) {
2160
2434
  const latest = resolveConfig(ctx.cwd, dir);
2161
2435
  if (latest.problems.length || !latest.config) {
2162
2436
  ctx.ui.setStatus?.("im-forward", "[IM!]");
2163
- ctx.ui.notify("IM forwarding configuration cannot be read; run /im-forward setup.", "error");
2437
+ ctx.ui.notify("IM forwarding configuration cannot be read; run /tools/im-forward setup.", "error");
2164
2438
  } else activate(latest.config);
2165
2439
  }
2166
2440
  } catch {
@@ -2180,7 +2454,7 @@ function initializeImForward(ctx, providers = implementedProviders) {
2180
2454
  }
2181
2455
  const latest = resolveConfig(ctx.cwd, dir);
2182
2456
  if (!latest.config || latest.problems.length || configurationIdentity(latest.config) !== configurationIdentity(activeConfig)) {
2183
- commandCtx.ui.notify("IM forwarding configuration changed. Run /im-forward setup before forwarding.", "warning");
2457
+ commandCtx.ui.notify("IM forwarding configuration changed. Run /tools/im-forward setup before forwarding.", "warning");
2184
2458
  ctx.ui.setStatus?.("im-forward", "[IM!]");
2185
2459
  return;
2186
2460
  }
@@ -2188,7 +2462,7 @@ function initializeImForward(ctx, providers = implementedProviders) {
2188
2462
  }
2189
2463
  function showStatus(commandCtx) {
2190
2464
  if (status) status(commandCtx);
2191
- else commandCtx.ui.notify("IM forwarding is not configured or unavailable. Use Ctrl+R or /im-forward setup.", "info");
2465
+ else commandCtx.ui.notify("IM forwarding is not configured or unavailable. Use Ctrl+R or /tools/im-forward setup.", "info");
2192
2466
  }
2193
2467
  async function clearConfiguration(commandCtx) {
2194
2468
  setupAbort?.abort();
@@ -2202,7 +2476,7 @@ This does not remove the app credentials lark-cli itself stores; re-running setu
2202
2476
  return;
2203
2477
  }
2204
2478
  await retire();
2205
- commandCtx.ui.notify("IM forwarding configuration cleared. Use /im-forward setup to configure again.", "info");
2479
+ commandCtx.ui.notify("IM forwarding configuration cleared. Use /tools/im-forward setup to configure again.", "info");
2206
2480
  } catch (error) {
2207
2481
  ctx.ui.setStatus?.("im-forward", "[IM!]");
2208
2482
  commandCtx.ui.notify(error.message || "IM forwarding configuration could not be cleared.", "error");
@@ -2210,22 +2484,22 @@ This does not remove the app credentials lark-cli itself stores; re-running setu
2210
2484
  }
2211
2485
  ctx.registerShortcut("ctrl+r", { description: "Set up or toggle IM forwarding", handler: () => toggleNow(ctx) });
2212
2486
  ctx.registerShortcut("alt+i", { description: "Set up or toggle IM forwarding (terminal Alt alias)", handler: () => toggleNow(ctx) });
2213
- ctx.registerCommand({ path: ["im-forward", "status"], description: "Show IM forwarding status", handler: async (commandCtx) => {
2487
+ ctx.registerCommand({ path: ["tools", "im-forward", "status"], description: "Show IM forwarding status", handler: async (commandCtx) => {
2214
2488
  if (!disposed) showStatus(commandCtx);
2215
2489
  } });
2216
- ctx.registerCommand({ path: ["im-forward", "switch-app"], description: "Rebind the configured platform to a different app/account", handler: async () => {
2490
+ ctx.registerCommand({ path: ["tools", "im-forward", "switch-app"], description: "Rebind the configured platform to a different app/account", handler: async () => {
2217
2491
  if (!disposed) await setup("switch-app");
2218
2492
  } });
2219
- ctx.registerCommand({ path: ["im-forward", "setup"], description: "Run the IM forwarding setup wizard", handler: async () => {
2493
+ ctx.registerCommand({ path: ["tools", "im-forward", "setup"], description: "Run the IM forwarding setup wizard", handler: async () => {
2220
2494
  if (!disposed) await setup();
2221
2495
  } });
2222
- ctx.registerCommand({ path: ["im-forward", "toggle"], description: "Toggle IM forwarding on/off (same as Ctrl+R)", handler: async (commandCtx) => {
2496
+ ctx.registerCommand({ path: ["tools", "im-forward", "toggle"], description: "Toggle IM forwarding on/off (same as Ctrl+R)", handler: async (commandCtx) => {
2223
2497
  if (!disposed) await toggleNow(commandCtx);
2224
2498
  } });
2225
- ctx.registerCommand({ path: ["im-forward", "clear"], description: "Remove IM forwarding configuration (with confirmation)", handler: async (commandCtx) => {
2499
+ ctx.registerCommand({ path: ["tools", "im-forward", "clear"], description: "Remove IM forwarding configuration (with confirmation)", handler: async (commandCtx) => {
2226
2500
  if (!disposed) await clearConfiguration(commandCtx);
2227
2501
  } });
2228
- ctx.registerCommand({ name: "im-forward", path: ["im-forward"], description: "IM forwarding menu (status/setup/toggle/clear)", handler: async (commandCtx, args) => {
2502
+ ctx.registerCommand({ name: "im-forward", path: ["tools", "im-forward"], description: "IM forwarding menu (status/setup/toggle/clear)", handler: async (commandCtx, args) => {
2229
2503
  if (disposed) return;
2230
2504
  const arg = args?.trim();
2231
2505
  if (arg === "status") {
@@ -2249,7 +2523,7 @@ This does not remove the app credentials lark-cli itself stores; re-running setu
2249
2523
  return;
2250
2524
  }
2251
2525
  if (arg) {
2252
- commandCtx.ui.notify("Usage: /im-forward [status|setup|switch-app|toggle|clear]; bare /im-forward opens the menu", "info");
2526
+ commandCtx.ui.notify("Usage: /tools/im-forward [status|setup|switch-app|toggle|clear]; bare /tools/im-forward opens the menu", "info");
2253
2527
  return;
2254
2528
  }
2255
2529
  const options = toggle && activeConfig ? ["Status", "Setup\u2026", "Switch app\u2026", "Toggle forwarding on/off", "Clear configuration\u2026"] : hasConfigLayers(ctx.cwd, dir) ? ["Status", "Setup\u2026", "Switch app\u2026", "Clear configuration\u2026"] : ["Setup\u2026"];
@@ -2275,6 +2549,9 @@ This does not remove the app credentials lark-cli itself stores; re-running setu
2275
2549
  }
2276
2550
  export {
2277
2551
  assistantForwardText,
2552
+ chunkKey,
2553
+ chunkMarkdown,
2554
+ collectFileReferences,
2278
2555
  composeForwardBody,
2279
2556
  imForward as default,
2280
2557
  detectImageMime,
@@ -125,12 +125,6 @@ async function initExtension(ctx) {
125
125
  description: "Research the project and create or update the root AGENTS.md index",
126
126
  handler
127
127
  });
128
- ctx.registerCommand({
129
- path: ["init"],
130
- hidden: true,
131
- description: "Research the project and create or update the root AGENTS.md index",
132
- handler
133
- });
134
128
  ctx.log("Init extension ready");
135
129
  }
136
130
  export {
@@ -0,0 +1,27 @@
1
+ # MCP Adapter Extension for Pie
2
+
3
+ Builtin MCP (Model Context Protocol) adapter: one `mcp` proxy tool instead of N
4
+ tool definitions, lazy stdio/HTTP server startup, trust-gated project configs,
5
+ and a per-server sharded metadata cache (`<configDir>/mcp-metadata/<server>.json`)
6
+ so `search` works without live connections.
7
+
8
+ ## Design Decisions
9
+
10
+ ### Package placement
11
+
12
+ mcp-adapter is a CLI product-level capability by design and stays in
13
+ `products/cli/builtin/extensions/mcp-adapter/`; it is deliberately not moved to
14
+ `@pie/agent-framework` or `@pie/shared-headless-capabilities`.
15
+
16
+ The config/trust layer (`src/config.ts`, `src/trust.ts` — zero CLI dependencies)
17
+ is the extraction candidate if a second host (e.g. Unity) ever needs MCP
18
+ support. Decided 2026-10-04: at that time the Unity host had no near-term MCP
19
+ plans, so no extraction was done.
20
+
21
+ ### Static tool catalogs
22
+
23
+ The adapter does not subscribe to MCP `tools/list_changed` notifications
24
+ (decided 2026-10-04). A server's tool list is snapshotted when it connects;
25
+ tools a server adds or removes while running only become visible after `/reload`
26
+ reconnects and re-lists. No notification subscription and no lazy re-query is
27
+ planned for this — the `mcp` proxy tool description carries the same hint.