@cydm/pie 2.7.20 → 2.8.1
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.
- package/README.md +18 -0
- package/dist/builtin/extensions/ask-user/README.md +117 -0
- package/dist/builtin/extensions/ask-user/index.js +4 -3
- package/dist/builtin/extensions/cron/index.js +299 -39
- package/dist/builtin/extensions/im-forward/README.md +297 -0
- package/dist/builtin/extensions/im-forward/index.js +315 -27
- package/dist/builtin/extensions/mcp-adapter/README.md +27 -0
- package/dist/builtin/extensions/memory/index.js +515 -0
- package/dist/builtin/extensions/memory/package.json +19 -0
- package/dist/builtin/extensions/pie-ipc/README.md +21 -0
- package/dist/builtin/extensions/plan-mode/METHOD.md +70 -0
- package/dist/builtin/extensions/plan-mode/index.js +150 -82
- package/dist/builtin/extensions/subagent/README.md +315 -0
- package/dist/builtin/extensions/subagent/index.js +8 -5
- package/dist/builtin/extensions/todo/index.js +4 -3
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +1 -1
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
- package/dist/builtin/skills/chrome-devtools-axi/{chunk-U75F4DPF.js → chunk-BNSAEVRT.js} +201 -77
- package/dist/builtin/skills/chrome-devtools-axi/{cli-4ITIR57L.js → cli-AO2ZTPRM.js} +57 -202
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +6 -1
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +6 -1
- package/dist/chunks/auth-storage-3EGM3VTK.js +13 -0
- package/dist/chunks/{chunk-X7UO6BA6.js → chunk-3BC5KGDQ.js} +451 -162
- package/dist/chunks/chunk-3NHP7HK5.js +298 -0
- package/dist/chunks/chunk-6DNYGVZP.js +278 -0
- package/dist/chunks/{chunk-TGCI5M6R.js → chunk-GDIYSMTS.js} +22 -142
- package/dist/chunks/{chunk-2H2DD22Z.js → chunk-GH4VW2OT.js} +1 -1
- package/dist/chunks/chunk-ILUHTKF3.js +149 -0
- package/dist/chunks/{chunk-UDCGB3LZ.js → chunk-PK72LVWQ.js} +11841 -16501
- package/dist/chunks/chunk-RSL7E4R7.js +9634 -0
- package/dist/chunks/chunk-YRR6C43W.js +1740 -0
- package/dist/chunks/config-74AUVDLT.js +46 -0
- package/dist/chunks/model-registry-LI5THXV4.js +17 -0
- package/dist/chunks/src-66XSMIAM.js +134 -0
- package/dist/chunks/src-BPSQMSSC.js +431 -0
- package/dist/chunks/src-OPPYTPWG.js +285 -0
- package/dist/chunks/{src-GX4UBAYF.js → src-YG5M2H44.js} +2 -2
- package/dist/chunks/{test-stream-AKIZNFCM.js → test-stream-JBWXKOQA.js} +1 -1
- package/dist/cli.js +986 -2292
- package/package.json +3 -3
|
@@ -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;
|
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
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++;
|
|
@@ -579,6 +848,16 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
579
848
|
terminalCleanup();
|
|
580
849
|
}
|
|
581
850
|
}
|
|
851
|
+
function escapeRegExp(text) {
|
|
852
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
853
|
+
}
|
|
854
|
+
function parseSessionAddress(text) {
|
|
855
|
+
const name = ctx.getSessionName?.()?.trim();
|
|
856
|
+
if (!name) return { kind: "absent" };
|
|
857
|
+
const own = new RegExp(`^${escapeRegExp(name)}:[ \\t]+(.+)$`, "s").exec(text.trim());
|
|
858
|
+
if (own) return { kind: "addressed", body: own[1] };
|
|
859
|
+
return { kind: "absent" };
|
|
860
|
+
}
|
|
582
861
|
async function handleInboundEventInner(event, retry) {
|
|
583
862
|
const matchesTarget = cfg.targetKind === "user" ? event.sender_id === cfg.targetId && (event.chatType === void 0 || event.chatType === "p2p") : event.chat_id === cfg.targetId;
|
|
584
863
|
if (!matchesTarget) return;
|
|
@@ -606,7 +885,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
606
885
|
releaseInvalidatedEvent();
|
|
607
886
|
return;
|
|
608
887
|
}
|
|
609
|
-
const
|
|
888
|
+
const address = parseSessionAddress(event.text);
|
|
889
|
+
const resolution = address.kind === "addressed" ? { found: { messageId: "", threadId: meta.threadId ?? null, sessionId, sentAt: Date.now() } } : await resolveRouteForInbound(messageId, meta);
|
|
610
890
|
if (!("found" in resolution)) {
|
|
611
891
|
if (isTransient(resolution)) retry();
|
|
612
892
|
else ctx.log(`im-forward: no route for ${messageId}; ignoring`);
|
|
@@ -618,7 +898,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
618
898
|
return;
|
|
619
899
|
}
|
|
620
900
|
const imageKeys = event.images;
|
|
621
|
-
const caption = event.text;
|
|
901
|
+
const caption = address.kind === "addressed" ? address.body : event.text;
|
|
622
902
|
if (!caption && !imageKeys.length) return;
|
|
623
903
|
const submitText = `${IM_INPUT_PREFIX}
|
|
624
904
|
${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
@@ -879,9 +1159,9 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
879
1159
|
if (!suspended) return;
|
|
880
1160
|
suspended = false;
|
|
881
1161
|
if (consumer || consumerRecovering || restartTimer) return;
|
|
882
|
-
const
|
|
1162
|
+
const delay2 = suspendedRestartInMs !== void 0 ? suspendedRestartInMs : Math.min(RESTART_BACKOFF_MIN_MS * 2 ** Math.min(consumerRestarts, 4), RESTART_BACKOFF_MAX_MS);
|
|
883
1163
|
suspendedRestartInMs = void 0;
|
|
884
|
-
scheduleRestart(
|
|
1164
|
+
scheduleRestart(delay2);
|
|
885
1165
|
};
|
|
886
1166
|
};
|
|
887
1167
|
updateFooterTag();
|
|
@@ -975,7 +1255,7 @@ Enable forwarding and start the connection? No test message will be sent. Saving
|
|
|
975
1255
|
|
|
976
1256
|
// builtin/extensions/im-forward/providers/feishu/index.ts
|
|
977
1257
|
import { spawn as spawn4 } from "node:child_process";
|
|
978
|
-
import * as
|
|
1258
|
+
import * as fs5 from "node:fs";
|
|
979
1259
|
import * as os2 from "node:os";
|
|
980
1260
|
import * as path6 from "node:path";
|
|
981
1261
|
|
|
@@ -985,7 +1265,7 @@ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
|
|
|
985
1265
|
|
|
986
1266
|
// builtin/extensions/im-forward/launch.ts
|
|
987
1267
|
import { spawn } from "node:child_process";
|
|
988
|
-
import * as
|
|
1268
|
+
import * as fs3 from "node:fs";
|
|
989
1269
|
import * as path2 from "node:path";
|
|
990
1270
|
import { StringDecoder } from "node:string_decoder";
|
|
991
1271
|
function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
|
|
@@ -993,25 +1273,25 @@ function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.pla
|
|
|
993
1273
|
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
1274
|
for (const candidate of candidates) {
|
|
995
1275
|
try {
|
|
996
|
-
if (!
|
|
1276
|
+
if (!fs3.statSync(candidate).isFile()) continue;
|
|
997
1277
|
const ext = path2.extname(candidate).toLowerCase();
|
|
998
1278
|
if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
|
|
999
1279
|
if (windows && ext === ".cmd") {
|
|
1000
1280
|
const dir = path2.dirname(candidate);
|
|
1001
1281
|
for (const root of [path2.join(dir, "node_modules", "@larksuite", "cli"), path2.resolve(dir, "..", "@larksuite", "cli")]) {
|
|
1002
1282
|
try {
|
|
1003
|
-
const pkg = JSON.parse(
|
|
1283
|
+
const pkg = JSON.parse(fs3.readFileSync(path2.join(root, "package.json"), "utf8"));
|
|
1004
1284
|
const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
|
|
1005
1285
|
if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
|
|
1006
1286
|
const entry = path2.join(root, "scripts", "run.js");
|
|
1007
|
-
if (
|
|
1287
|
+
if (fs3.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
|
|
1008
1288
|
} catch {
|
|
1009
1289
|
}
|
|
1010
1290
|
}
|
|
1011
1291
|
continue;
|
|
1012
1292
|
}
|
|
1013
1293
|
if (windows && ext !== ".exe") continue;
|
|
1014
|
-
|
|
1294
|
+
fs3.accessSync(candidate, fs3.constants.X_OK);
|
|
1015
1295
|
return { command: candidate, prefix: [] };
|
|
1016
1296
|
} catch {
|
|
1017
1297
|
}
|
|
@@ -1312,7 +1592,7 @@ function extractImageKey(content) {
|
|
|
1312
1592
|
}
|
|
1313
1593
|
|
|
1314
1594
|
// builtin/extensions/im-forward/providers/feishu/setup.ts
|
|
1315
|
-
import * as
|
|
1595
|
+
import * as fs4 from "node:fs";
|
|
1316
1596
|
import * as path5 from "node:path";
|
|
1317
1597
|
|
|
1318
1598
|
// builtin/extensions/im-forward/browser.ts
|
|
@@ -1396,9 +1676,9 @@ function findNpmCli() {
|
|
|
1396
1676
|
const dirs = [path5.dirname(process.execPath), ...(process.env.PATH ?? "").split(path5.delimiter)];
|
|
1397
1677
|
for (const dir of dirs) for (const root of [path5.join(dir, "node_modules", "npm"), path5.resolve(dir, "..", "lib", "node_modules", "npm")]) {
|
|
1398
1678
|
try {
|
|
1399
|
-
const pkg = JSON.parse(
|
|
1679
|
+
const pkg = JSON.parse(fs4.readFileSync(path5.join(root, "package.json"), "utf8"));
|
|
1400
1680
|
const entry = path5.join(root, "bin", "npm-cli.js");
|
|
1401
|
-
if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" &&
|
|
1681
|
+
if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs4.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
|
|
1402
1682
|
} catch {
|
|
1403
1683
|
}
|
|
1404
1684
|
}
|
|
@@ -1925,6 +2205,11 @@ function connect(binary, profile, targetKind = "chat") {
|
|
|
1925
2205
|
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
2206
|
return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null } : null;
|
|
1927
2207
|
},
|
|
2208
|
+
async sendFile(target, file, key, replyTo) {
|
|
2209
|
+
const recipient = targetKind === "user" ? ["--user-id", target] : ["--chat-id", target];
|
|
2210
|
+
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]);
|
|
2211
|
+
return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null } : null;
|
|
2212
|
+
},
|
|
1928
2213
|
async acknowledge(id) {
|
|
1929
2214
|
await call(["im", "reactions", "create", "--as", "bot", "--params", JSON.stringify({ message_id: id }), "--data", JSON.stringify({ reaction_type: { emoji_type: "THUMBSUP" } })]);
|
|
1930
2215
|
},
|
|
@@ -1938,19 +2223,19 @@ function connect(binary, profile, targetKind = "chat") {
|
|
|
1938
2223
|
return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
|
|
1939
2224
|
},
|
|
1940
2225
|
async downloadImage(messageId, image, index) {
|
|
1941
|
-
const directory =
|
|
1942
|
-
const cleanup = () =>
|
|
2226
|
+
const directory = fs5.mkdtempSync(path6.join(os2.tmpdir(), "pie-im-forward-"));
|
|
2227
|
+
const cleanup = () => fs5.rmSync(directory, { recursive: true, force: true });
|
|
1943
2228
|
try {
|
|
1944
2229
|
const name = `image-${index + 1}.png`;
|
|
1945
2230
|
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
2231
|
if (result.error || !parseLarkCliEnvelope(result.stdout).ok) throw new Error("Image download failed");
|
|
1947
2232
|
let target = path6.join(directory, name);
|
|
1948
|
-
if (
|
|
2233
|
+
if (fs5.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
|
|
1949
2234
|
const detected = readImageFormat(target);
|
|
1950
2235
|
if (detected.ext === ".bin") throw new Error("Unsupported image format");
|
|
1951
2236
|
if (detected.ext !== ".png") {
|
|
1952
2237
|
const corrected = path6.join(directory, `image-${index + 1}${detected.ext}`);
|
|
1953
|
-
|
|
2238
|
+
fs5.renameSync(target, corrected);
|
|
1954
2239
|
target = corrected;
|
|
1955
2240
|
}
|
|
1956
2241
|
return { file: { path: target, displayName: `feishu-image-${index + 1}${detected.ext}` }, cleanup };
|
|
@@ -2275,6 +2560,9 @@ This does not remove the app credentials lark-cli itself stores; re-running setu
|
|
|
2275
2560
|
}
|
|
2276
2561
|
export {
|
|
2277
2562
|
assistantForwardText,
|
|
2563
|
+
chunkKey,
|
|
2564
|
+
chunkMarkdown,
|
|
2565
|
+
collectFileReferences,
|
|
2278
2566
|
composeForwardBody,
|
|
2279
2567
|
imForward as default,
|
|
2280
2568
|
detectImageMime,
|
|
@@ -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.
|