@cydm/pie 4.10.0 → 4.10.2
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/dist/builtin/extensions/im-forward/index.js +172 -53
- package/dist/builtin/extensions/mcp-adapter/index.js +216 -7
- package/dist/builtin/extensions/pie-proc/index.js +176 -146
- package/dist/chunks/chunk-BB7ETSJK.js +463 -0
- package/dist/chunks/chunk-Z2RT3P4F.js +251 -0
- package/dist/chunks/manager-allow-SF5ROGDM.js +21 -0
- package/dist/chunks/{manager-cli-Y6HM3MHA.js → manager-cli-BXI4UFTJ.js} +12 -55
- package/dist/chunks/{manager-upgrade-LSTOHBUV.js → manager-upgrade-XPFXKO7A.js} +64 -39
- package/dist/cli.js +295 -36
- package/package.json +1 -1
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
isWindowsServiceManager,
|
|
4
|
+
launchWindowsServiceUpgradeActor,
|
|
5
|
+
resolveAbsoluteActorEnv
|
|
6
|
+
} from "../../../chunks/chunk-BB7ETSJK.js";
|
|
2
7
|
import {
|
|
3
8
|
DISPATCH_PREFIX,
|
|
4
9
|
IPC_PROTOCOL_VERSION,
|
|
@@ -570,6 +575,40 @@ function writeConfig(cwd, dir, update, expected) {
|
|
|
570
575
|
function hasConfigLayers(cwd, dir) {
|
|
571
576
|
return configPaths(cwd, dir).some((file) => fs.existsSync(file));
|
|
572
577
|
}
|
|
578
|
+
function findInvalidConfigLayers(cwd, dir) {
|
|
579
|
+
const invalid = [];
|
|
580
|
+
for (const file of configPaths(cwd, dir)) {
|
|
581
|
+
if (!fs.existsSync(file)) continue;
|
|
582
|
+
let text;
|
|
583
|
+
try {
|
|
584
|
+
text = fs.readFileSync(file, "utf8");
|
|
585
|
+
} catch {
|
|
586
|
+
continue;
|
|
587
|
+
}
|
|
588
|
+
try {
|
|
589
|
+
const value = JSON.parse(text);
|
|
590
|
+
if (!isRecord(value)) invalid.push(file);
|
|
591
|
+
} catch {
|
|
592
|
+
invalid.push(file);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return invalid;
|
|
596
|
+
}
|
|
597
|
+
function backupInvalidConfigLayers(cwd, dir, expectedSnapshot) {
|
|
598
|
+
if (expectedSnapshot !== void 0 && configSnapshot(cwd, dir) !== expectedSnapshot) {
|
|
599
|
+
throw new Error("IM configuration changed before backup. Please retry.");
|
|
600
|
+
}
|
|
601
|
+
const invalid = findInvalidConfigLayers(cwd, dir);
|
|
602
|
+
const stamp = `${Date.now()}-${randomUUID().slice(0, 6)}`;
|
|
603
|
+
const moved = [];
|
|
604
|
+
for (const file of invalid) {
|
|
605
|
+
const backup = `${file}.corrupt-${stamp}`;
|
|
606
|
+
fs.renameSync(file, backup);
|
|
607
|
+
moved.push({ from: file, to: backup });
|
|
608
|
+
}
|
|
609
|
+
if (moved.length) invalidateConfigCache();
|
|
610
|
+
return moved;
|
|
611
|
+
}
|
|
573
612
|
async function clearImConfig(cwd, dir, confirm) {
|
|
574
613
|
const files = configPaths(cwd, dir).filter((file) => fs.existsSync(file));
|
|
575
614
|
if (!files.length) return false;
|
|
@@ -3561,7 +3600,7 @@ ${a.runs} \u6B21 \xB7 \u6700\u8FD1 ${cleanInline2(a.lastRunBy ?? "\u2014", 20)}
|
|
|
3561
3600
|
last,
|
|
3562
3601
|
``,
|
|
3563
3602
|
"Upgrade = `npm install -g @cydm/pie@latest` + restart the manager resident (IM pauses ~15s). Idle workers are recycled; busy ones keep running. Desktop TUI sessions keep their code until you restart them.",
|
|
3564
|
-
"
|
|
3603
|
+
"Requires allowUsers membership when configured (or bound chat / owner DM under default panelAccess)."
|
|
3565
3604
|
].join("\n"),
|
|
3566
3605
|
actions: [
|
|
3567
3606
|
{ id: "panel.upgrade.confirm", label: "\u2B06\uFE0F Install latest + restart", style: "primary", requireAllowUsers: true },
|
|
@@ -3583,6 +3622,7 @@ ${a.runs} \u6B21 \xB7 \u6700\u8FD1 ${cleanInline2(a.lastRunBy ?? "\u2014", 20)}
|
|
|
3583
3622
|
|
|
3584
3623
|
// builtin/extensions/im-forward/runtime-panel-lifecycle.ts
|
|
3585
3624
|
import * as fs11 from "node:fs";
|
|
3625
|
+
import * as os6 from "node:os";
|
|
3586
3626
|
import { dirname as pathDirname, join as join13, resolve as pathResolve2 } from "node:path";
|
|
3587
3627
|
import { spawn as spawnProcess } from "node:child_process";
|
|
3588
3628
|
|
|
@@ -4522,6 +4562,32 @@ function isPeekAudienceAllowed(ctx, event) {
|
|
|
4522
4562
|
if (event.chatType !== "group") return !ctx.allowUsers || isAllowedUser();
|
|
4523
4563
|
return true;
|
|
4524
4564
|
}
|
|
4565
|
+
function evaluateUpgradeConfirmAuth(ctx, event) {
|
|
4566
|
+
const hasAllowUsers = Array.isArray(ctx.allowUsers) && ctx.allowUsers.length > 0;
|
|
4567
|
+
if (hasAllowUsers) {
|
|
4568
|
+
return event.sender_id && ctx.allowUsers.includes(event.sender_id) ? { allowed: true } : { allowed: false, reason: "not-in-allowUsers" };
|
|
4569
|
+
}
|
|
4570
|
+
if (ctx.panelAccess === "allowUsers") {
|
|
4571
|
+
return { allowed: false, reason: "panelAccess-allowUsers-unconfigured" };
|
|
4572
|
+
}
|
|
4573
|
+
if (ctx.targetKind === "user") {
|
|
4574
|
+
return ctx.targetId && event.sender_id && event.sender_id === ctx.targetId ? { allowed: true } : { allowed: false, reason: "not-in-allowUsers" };
|
|
4575
|
+
}
|
|
4576
|
+
if (ctx.targetId && event.chat_id === ctx.targetId) {
|
|
4577
|
+
return { allowed: true };
|
|
4578
|
+
}
|
|
4579
|
+
return { allowed: false, reason: "unbound-chat" };
|
|
4580
|
+
}
|
|
4581
|
+
function formatUpgradeAuthRefusal(reason, senderId) {
|
|
4582
|
+
const idSpan = senderId ? `\`${cleanCodeSpan(senderId, 64)}\`` : void 0;
|
|
4583
|
+
if (reason === "panelAccess-allowUsers-unconfigured") {
|
|
4584
|
+
return idSpan ? `\u26D4\uFE0F Upgrading pie requires admin rights (panelAccess=allowUsers, but allowUsers is empty). Add ${idSpan} to allowUsers in im-forward.json.` : "\u26D4\uFE0F Upgrading pie requires admin rights (panelAccess=allowUsers, but allowUsers is empty).";
|
|
4585
|
+
}
|
|
4586
|
+
if (reason === "unbound-chat") {
|
|
4587
|
+
return idSpan ? `\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers) outside the bound chat. Use /panel in the bound chat, or add ${idSpan} to allowUsers.` : "\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers) outside the bound chat.";
|
|
4588
|
+
}
|
|
4589
|
+
return idSpan ? `\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers). Your ID: ${idSpan}` : "\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers).";
|
|
4590
|
+
}
|
|
4525
4591
|
function buildPeekCardSpec(targetRef, targetSession, isManagerTarget, cols, receipt, inThread = false) {
|
|
4526
4592
|
const meta = parsePeekMeta(receipt);
|
|
4527
4593
|
const actions = [
|
|
@@ -4596,48 +4662,62 @@ async function runUpgradeConfirmActor(cols, log) {
|
|
|
4596
4662
|
const entry = process.argv[1] ? pathResolve2(process.argv[1]) : "";
|
|
4597
4663
|
if (!entry) throw new Error("cannot resolve the pie entry point");
|
|
4598
4664
|
const configRoot = pathDirname(pathDirname(ipcDiscoveryRoot()));
|
|
4599
|
-
const
|
|
4600
|
-
|
|
4601
|
-
|
|
4602
|
-
|
|
4603
|
-
|
|
4604
|
-
|
|
4605
|
-
|
|
4606
|
-
|
|
4607
|
-
|
|
4608
|
-
|
|
4609
|
-
detached: true,
|
|
4610
|
-
stdio: out !== void 0 ? ["ignore", out, out] : "ignore",
|
|
4611
|
-
windowsHide: true,
|
|
4612
|
-
env: process.env
|
|
4613
|
-
});
|
|
4614
|
-
const spawnOutcome = await new Promise((resolve7) => {
|
|
4615
|
-
let settled = false;
|
|
4616
|
-
const settle = (v) => {
|
|
4617
|
-
if (!settled) {
|
|
4618
|
-
settled = true;
|
|
4619
|
-
resolve7(v);
|
|
4620
|
-
}
|
|
4621
|
-
};
|
|
4622
|
-
child.once("spawn", () => settle("spawned"));
|
|
4623
|
-
child.once("error", (error) => {
|
|
4624
|
-
log(`im-forward: upgrade actor spawn error: ${error instanceof Error ? error.message : String(error)}`);
|
|
4625
|
-
settle("error");
|
|
4665
|
+
const managerDir = join13(configRoot, "manager");
|
|
4666
|
+
const logFile = join13(managerDir, "upgrade-actor.log");
|
|
4667
|
+
const actorEnv = resolveAbsoluteActorEnv(process.env);
|
|
4668
|
+
if (process.platform === "win32" && isWindowsServiceManager(configRoot)) {
|
|
4669
|
+
const launched = launchWindowsServiceUpgradeActor({
|
|
4670
|
+
managerDir,
|
|
4671
|
+
nodePath: process.execPath,
|
|
4672
|
+
entry,
|
|
4673
|
+
logFile,
|
|
4674
|
+
env: actorEnv
|
|
4626
4675
|
});
|
|
4627
|
-
|
|
4628
|
-
|
|
4629
|
-
|
|
4630
|
-
|
|
4676
|
+
actorOk = launched.ok;
|
|
4677
|
+
actorDetail = launched.detail;
|
|
4678
|
+
} else {
|
|
4679
|
+
let out;
|
|
4631
4680
|
try {
|
|
4632
|
-
fs11.
|
|
4681
|
+
fs11.mkdirSync(managerDir, { recursive: true });
|
|
4682
|
+
out = fs11.openSync(logFile, "a");
|
|
4633
4683
|
} catch {
|
|
4684
|
+
out = void 0;
|
|
4685
|
+
}
|
|
4686
|
+
const child = spawnProcess(process.execPath, [entry, "manager", "upgrade"], {
|
|
4687
|
+
cwd: os6.tmpdir(),
|
|
4688
|
+
detached: true,
|
|
4689
|
+
stdio: out !== void 0 ? ["ignore", out, out] : "ignore",
|
|
4690
|
+
windowsHide: true,
|
|
4691
|
+
env: actorEnv
|
|
4692
|
+
});
|
|
4693
|
+
const spawnOutcome = await new Promise((resolve7) => {
|
|
4694
|
+
let settled = false;
|
|
4695
|
+
const settle = (v) => {
|
|
4696
|
+
if (!settled) {
|
|
4697
|
+
settled = true;
|
|
4698
|
+
resolve7(v);
|
|
4699
|
+
}
|
|
4700
|
+
};
|
|
4701
|
+
child.once("spawn", () => settle("spawned"));
|
|
4702
|
+
child.once("error", (error) => {
|
|
4703
|
+
log(`im-forward: upgrade actor spawn error: ${error instanceof Error ? error.message : String(error)}`);
|
|
4704
|
+
settle("error");
|
|
4705
|
+
});
|
|
4706
|
+
setTimeout(() => settle("timeout"), 3e3).unref?.();
|
|
4707
|
+
});
|
|
4708
|
+
child.unref();
|
|
4709
|
+
if (out !== void 0) {
|
|
4710
|
+
try {
|
|
4711
|
+
fs11.closeSync(out);
|
|
4712
|
+
} catch {
|
|
4713
|
+
}
|
|
4714
|
+
}
|
|
4715
|
+
if (spawnOutcome === "error") {
|
|
4716
|
+
actorDetail = "the actor process failed to spawn (see the manager log)";
|
|
4717
|
+
} else {
|
|
4718
|
+
actorOk = true;
|
|
4719
|
+
actorDetail = `actor pid ${child.pid}${spawnOutcome === "timeout" ? " (spawn unconfirmed \u2014 will report via /panel)" : ""} \xB7 log ${logFile}`;
|
|
4634
4720
|
}
|
|
4635
|
-
}
|
|
4636
|
-
if (spawnOutcome === "error") {
|
|
4637
|
-
actorDetail = "the actor process failed to spawn (see the manager log)";
|
|
4638
|
-
} else {
|
|
4639
|
-
actorOk = true;
|
|
4640
|
-
actorDetail = `actor pid ${child.pid}${spawnOutcome === "timeout" ? " (spawn unconfirmed \u2014 will report via /panel)" : ""} \xB7 log ${logFile}`;
|
|
4641
4721
|
}
|
|
4642
4722
|
} catch (error) {
|
|
4643
4723
|
actorDetail = error instanceof Error ? error.message : String(error);
|
|
@@ -5225,7 +5305,7 @@ function createPanelExecutor(ctx) {
|
|
|
5225
5305
|
return;
|
|
5226
5306
|
}
|
|
5227
5307
|
const effectiveCmd = threadScopeCheck.rewrittenCmd ?? panelCmd;
|
|
5228
|
-
if (panelCmd.restricted && ctx.allowUsers && (!event.sender_id || !ctx.allowUsers.includes(event.sender_id))) {
|
|
5308
|
+
if (panelCmd.restricted && panelCmd.cmd !== "panel.upgrade.confirm" && ctx.allowUsers && (!event.sender_id || !ctx.allowUsers.includes(event.sender_id))) {
|
|
5229
5309
|
ctx.log(`im-forward: restricted panel action ${panelCmd.cmd} refused for ${event.sender_id ?? "unknown"} (not in allowUsers)`);
|
|
5230
5310
|
try {
|
|
5231
5311
|
await ctx.connection.send(freshRecipient, "\u26D4\uFE0F This action requires admin rights (allowUsers).", `panel-refused-${event.event_id}`, sendReplyTo, sendOpts);
|
|
@@ -5477,10 +5557,11 @@ ${receipt.ok ? "Compaction runs on the target host (LLM summary \u2014 may take
|
|
|
5477
5557
|
return;
|
|
5478
5558
|
}
|
|
5479
5559
|
if (panelCmd.cmd === "panel.upgrade.confirm") {
|
|
5480
|
-
|
|
5481
|
-
|
|
5560
|
+
const auth = evaluateUpgradeConfirmAuth(ctx, event);
|
|
5561
|
+
if (!auth.allowed) {
|
|
5562
|
+
ctx.log(`im-forward: panel.upgrade.confirm refused for ${event.sender_id ?? "unknown"} (execution-sink gate: ${auth.reason})`);
|
|
5482
5563
|
try {
|
|
5483
|
-
await ctx.connection.send(freshRecipient,
|
|
5564
|
+
await ctx.connection.send(freshRecipient, formatUpgradeAuthRefusal(auth.reason, event.sender_id), `panel-refused-${event.event_id}`, sendReplyTo, sendOpts);
|
|
5484
5565
|
} catch {
|
|
5485
5566
|
}
|
|
5486
5567
|
return;
|
|
@@ -7280,13 +7361,45 @@ ${imagelessCaption || (imageKeys.length ? IM_INPUT_FALLBACK_CAPTION : "") || cap
|
|
|
7280
7361
|
|
|
7281
7362
|
// builtin/extensions/im-forward/onboarding.ts
|
|
7282
7363
|
async function runSetup(ctx, dir, providers, signal, isCurrent = () => !signal.aborted, intent = "first-run", suspendEventConsumer) {
|
|
7283
|
-
const
|
|
7364
|
+
const options = { signal, timeout: 12e4 };
|
|
7365
|
+
let initial = resolveConfig(ctx.cwd, dir);
|
|
7284
7366
|
if (initial.problems.length) {
|
|
7285
|
-
ctx.
|
|
7286
|
-
|
|
7367
|
+
const invalidFiles = findInvalidConfigLayers(ctx.cwd, dir);
|
|
7368
|
+
if (invalidFiles.length > 0 && typeof ctx.ui.confirm === "function") {
|
|
7369
|
+
let preBackupSnapshot;
|
|
7370
|
+
try {
|
|
7371
|
+
preBackupSnapshot = configSnapshot(ctx.cwd, dir);
|
|
7372
|
+
} catch (error) {
|
|
7373
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
7374
|
+
return;
|
|
7375
|
+
}
|
|
7376
|
+
const recover = await ctx.ui.confirm(
|
|
7377
|
+
"Repair invalid IM configuration?",
|
|
7378
|
+
`${initial.problems.join("\n")}
|
|
7379
|
+
|
|
7380
|
+
Back up invalid file(s) (*.corrupt-*) and continue setup?
|
|
7381
|
+
${invalidFiles.join("\n")}`,
|
|
7382
|
+
options
|
|
7383
|
+
);
|
|
7384
|
+
if (!isCurrent() || !recover) {
|
|
7385
|
+
ctx.ui.notify(initial.problems.join("\n"), "error");
|
|
7386
|
+
return;
|
|
7387
|
+
}
|
|
7388
|
+
try {
|
|
7389
|
+
const moved = backupInvalidConfigLayers(ctx.cwd, dir, preBackupSnapshot);
|
|
7390
|
+
ctx.ui.notify(`Backed up invalid IM config: ${moved.map((m) => m.to).join(", ")}`, "info");
|
|
7391
|
+
} catch (error) {
|
|
7392
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
7393
|
+
return;
|
|
7394
|
+
}
|
|
7395
|
+
initial = resolveConfig(ctx.cwd, dir);
|
|
7396
|
+
}
|
|
7397
|
+
if (initial.problems.length) {
|
|
7398
|
+
ctx.ui.notify(initial.problems.join("\n"), "error");
|
|
7399
|
+
return;
|
|
7400
|
+
}
|
|
7287
7401
|
}
|
|
7288
7402
|
const snapshot = configSnapshot(ctx.cwd, dir);
|
|
7289
|
-
const options = { signal, timeout: 12e4 };
|
|
7290
7403
|
if (!providers.length || !isCurrent()) return;
|
|
7291
7404
|
let selected;
|
|
7292
7405
|
if (intent === "switch-app" && initial.config) {
|
|
@@ -7377,7 +7490,7 @@ async function settingsProbeBinary() {
|
|
|
7377
7490
|
import { spawn as spawn5 } from "node:child_process";
|
|
7378
7491
|
import { createHash as createHash2 } from "node:crypto";
|
|
7379
7492
|
import * as fs15 from "node:fs";
|
|
7380
|
-
import * as
|
|
7493
|
+
import * as os7 from "node:os";
|
|
7381
7494
|
import * as path16 from "node:path";
|
|
7382
7495
|
|
|
7383
7496
|
// builtin/extensions/im-forward/providers/feishu/card.ts
|
|
@@ -7931,8 +8044,8 @@ ${progressLabel}` : "");
|
|
|
7931
8044
|
if (!await bindNewApp()) return;
|
|
7932
8045
|
} else profileName = singleProfile.name;
|
|
7933
8046
|
} else if (profiles && profiles.length > 1) {
|
|
7934
|
-
const
|
|
7935
|
-
if (!
|
|
8047
|
+
const previousProfile2 = profiles.find((item) => item.name === profileName);
|
|
8048
|
+
if (!previousProfile2) profileName = void 0;
|
|
7936
8049
|
const items = ["Use the CLI's active app (no per-machine profile)", ...profiles.map(describe), connectDifferent, "Cancel"];
|
|
7937
8050
|
const choice = await ui.select("IM forwarding setup \u2014 Feishu app (per machine)", items, options);
|
|
7938
8051
|
if (!current() || !choice || choice === "Cancel") return;
|
|
@@ -8090,7 +8203,13 @@ ${detect.error ?? ""}`);
|
|
|
8090
8203
|
}
|
|
8091
8204
|
if (!current() || !target) return;
|
|
8092
8205
|
const boundAppId = profiles?.find((item) => item.name === profileName)?.appId ?? (profileName ? void 0 : profiles?.find((item) => item.active)?.appId);
|
|
8093
|
-
|
|
8206
|
+
const previousAppId = typeof previous?.larkCliAppId === "string" && previous.larkCliAppId.trim() ? previous.larkCliAppId.trim() : void 0;
|
|
8207
|
+
const previousProfile = typeof previous?.larkCliProfile === "string" && previous.larkCliProfile.trim() ? previous.larkCliProfile.trim() : void 0;
|
|
8208
|
+
const appChanged = Boolean(
|
|
8209
|
+
boundAppId && previousAppId && boundAppId !== previousAppId || profileName && previousProfile && profileName !== previousProfile
|
|
8210
|
+
);
|
|
8211
|
+
const inheritedAllowUsers = appChanged ? null : previous?.allowUsers ?? null;
|
|
8212
|
+
return { ...previous ?? {}, ...target.openId ? { openId: target.openId, chatId: null } : { chatId: target.chatId, openId: null }, larkCli: executable ?? null, larkCliProfile: profileName ?? null, larkCliAppId: boundAppId ?? null, allowUsers: target.allowUsers ?? inheritedAllowUsers };
|
|
8094
8213
|
}
|
|
8095
8214
|
|
|
8096
8215
|
// builtin/extensions/im-forward/providers/feishu/index.ts
|
|
@@ -8296,7 +8415,7 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
|
|
|
8296
8415
|
return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
|
|
8297
8416
|
},
|
|
8298
8417
|
async downloadImage(messageId, image, index) {
|
|
8299
|
-
const directory = fs15.mkdtempSync(path16.join(
|
|
8418
|
+
const directory = fs15.mkdtempSync(path16.join(os7.tmpdir(), "pie-im-forward-"));
|
|
8300
8419
|
const cleanup = () => fs15.rmSync(directory, { recursive: true, force: true });
|
|
8301
8420
|
try {
|
|
8302
8421
|
const name = `image-${index + 1}.png`;
|
|
@@ -8487,7 +8606,7 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
|
|
|
8487
8606
|
async consumeBusHealth() {
|
|
8488
8607
|
const appId = await canonicalAppIdNow();
|
|
8489
8608
|
if (!appId) return void 0;
|
|
8490
|
-
const larkHome = process.env.PIE_LARK_CLI_HOME && process.env.PIE_LARK_CLI_HOME.trim() ? process.env.PIE_LARK_CLI_HOME :
|
|
8609
|
+
const larkHome = process.env.PIE_LARK_CLI_HOME && process.env.PIE_LARK_CLI_HOME.trim() ? process.env.PIE_LARK_CLI_HOME : os7.homedir();
|
|
8491
8610
|
const logPath = path16.join(larkHome, ".lark-cli", "events", appId, "bus.log");
|
|
8492
8611
|
let tail;
|
|
8493
8612
|
try {
|
|
@@ -507,6 +507,7 @@ var require_cross_spawn = __commonJS({
|
|
|
507
507
|
});
|
|
508
508
|
|
|
509
509
|
// builtin/extensions/mcp-adapter/index.ts
|
|
510
|
+
import { randomBytes } from "node:crypto";
|
|
510
511
|
import * as path4 from "node:path";
|
|
511
512
|
import * as os2 from "node:os";
|
|
512
513
|
import * as fs4 from "node:fs";
|
|
@@ -20181,8 +20182,8 @@ async function random(size) {
|
|
|
20181
20182
|
const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
|
|
20182
20183
|
let result = "";
|
|
20183
20184
|
while (result.length < size) {
|
|
20184
|
-
const
|
|
20185
|
-
for (const randomByte of
|
|
20185
|
+
const randomBytes2 = await getRandomValues(size - result.length);
|
|
20186
|
+
for (const randomByte of randomBytes2) {
|
|
20186
20187
|
if (randomByte < evenDistCutoff) {
|
|
20187
20188
|
result += mask[randomByte % mask.length];
|
|
20188
20189
|
}
|
|
@@ -25570,6 +25571,71 @@ function resolveConfigDir() {
|
|
|
25570
25571
|
}
|
|
25571
25572
|
return path4.join(os2.homedir(), ".pie");
|
|
25572
25573
|
}
|
|
25574
|
+
function tokenizeCommandArgs(input) {
|
|
25575
|
+
const tokens = [];
|
|
25576
|
+
let current = "";
|
|
25577
|
+
let quote = null;
|
|
25578
|
+
let inToken = false;
|
|
25579
|
+
for (let i = 0; i < input.length; i += 1) {
|
|
25580
|
+
const ch = input[i];
|
|
25581
|
+
if (quote) {
|
|
25582
|
+
if (ch === quote) {
|
|
25583
|
+
quote = null;
|
|
25584
|
+
} else if (ch === "\\" && quote === '"' && i + 1 < input.length && (input[i + 1] === '"' || input[i + 1] === "\\")) {
|
|
25585
|
+
current += input[++i];
|
|
25586
|
+
} else {
|
|
25587
|
+
current += ch;
|
|
25588
|
+
}
|
|
25589
|
+
continue;
|
|
25590
|
+
}
|
|
25591
|
+
if (ch === "'" || ch === '"') {
|
|
25592
|
+
quote = ch;
|
|
25593
|
+
inToken = true;
|
|
25594
|
+
continue;
|
|
25595
|
+
}
|
|
25596
|
+
if (/\s/.test(ch)) {
|
|
25597
|
+
if (inToken) {
|
|
25598
|
+
tokens.push(current);
|
|
25599
|
+
current = "";
|
|
25600
|
+
inToken = false;
|
|
25601
|
+
}
|
|
25602
|
+
continue;
|
|
25603
|
+
}
|
|
25604
|
+
current += ch;
|
|
25605
|
+
inToken = true;
|
|
25606
|
+
}
|
|
25607
|
+
if (inToken) tokens.push(current);
|
|
25608
|
+
return tokens;
|
|
25609
|
+
}
|
|
25610
|
+
function writeFileAtomic(filePath, content) {
|
|
25611
|
+
fs4.mkdirSync(path4.dirname(filePath), { recursive: true });
|
|
25612
|
+
const tmp = path4.join(path4.dirname(filePath), `.mcp-${process.pid}-${randomBytes(4).toString("hex")}.tmp`);
|
|
25613
|
+
try {
|
|
25614
|
+
fs4.writeFileSync(tmp, content, "utf8");
|
|
25615
|
+
fs4.renameSync(tmp, filePath);
|
|
25616
|
+
} finally {
|
|
25617
|
+
try {
|
|
25618
|
+
fs4.rmSync(tmp, { force: true });
|
|
25619
|
+
} catch {
|
|
25620
|
+
}
|
|
25621
|
+
}
|
|
25622
|
+
}
|
|
25623
|
+
function rollbackIfUnchanged(filePath, expectedWritten, priorRaw) {
|
|
25624
|
+
try {
|
|
25625
|
+
const current = fs4.existsSync(filePath) ? fs4.readFileSync(filePath, "utf8") : null;
|
|
25626
|
+
if (current !== expectedWritten) {
|
|
25627
|
+
return { ok: false, detail: "file was modified concurrently; skipped rollback" };
|
|
25628
|
+
}
|
|
25629
|
+
if (priorRaw === null) {
|
|
25630
|
+
fs4.rmSync(filePath, { force: true });
|
|
25631
|
+
} else {
|
|
25632
|
+
writeFileAtomic(filePath, priorRaw);
|
|
25633
|
+
}
|
|
25634
|
+
return { ok: true };
|
|
25635
|
+
} catch (error2) {
|
|
25636
|
+
return { ok: false, detail: error2 instanceof Error ? error2.message : String(error2) };
|
|
25637
|
+
}
|
|
25638
|
+
}
|
|
25573
25639
|
function formatServerForTrustPrompt(definition) {
|
|
25574
25640
|
const lines = [
|
|
25575
25641
|
`MCP server "${definition.name}" (from ${definition.sourcePath}) wants to start.`,
|
|
@@ -25681,9 +25747,152 @@ function mcpAdapter(ctx) {
|
|
|
25681
25747
|
}
|
|
25682
25748
|
ctx.registerCommand({
|
|
25683
25749
|
name: "mcp",
|
|
25684
|
-
description: "MCP adapter: status (default), enable/disable <server>",
|
|
25750
|
+
description: "MCP adapter: status (default), add, remove, enable/disable <server>",
|
|
25685
25751
|
handler: async (commandCtx, args) => {
|
|
25686
|
-
const
|
|
25752
|
+
const rawTokens = tokenizeCommandArgs(args ?? "");
|
|
25753
|
+
const [sub, target] = rawTokens;
|
|
25754
|
+
if (sub === "add") {
|
|
25755
|
+
let scope;
|
|
25756
|
+
let idx = 1;
|
|
25757
|
+
while (idx < rawTokens.length) {
|
|
25758
|
+
const tok = rawTokens[idx];
|
|
25759
|
+
if (tok === "--") {
|
|
25760
|
+
idx += 1;
|
|
25761
|
+
break;
|
|
25762
|
+
}
|
|
25763
|
+
if (tok === "--global" || tok === "--user") {
|
|
25764
|
+
if (scope === "project") {
|
|
25765
|
+
commandCtx.ui.notify("Choose one scope: --project or --global.", "warning");
|
|
25766
|
+
return;
|
|
25767
|
+
}
|
|
25768
|
+
scope = "global";
|
|
25769
|
+
idx += 1;
|
|
25770
|
+
continue;
|
|
25771
|
+
}
|
|
25772
|
+
if (tok === "--project") {
|
|
25773
|
+
if (scope === "global") {
|
|
25774
|
+
commandCtx.ui.notify("Choose one scope: --project or --global.", "warning");
|
|
25775
|
+
return;
|
|
25776
|
+
}
|
|
25777
|
+
scope = "project";
|
|
25778
|
+
idx += 1;
|
|
25779
|
+
continue;
|
|
25780
|
+
}
|
|
25781
|
+
break;
|
|
25782
|
+
}
|
|
25783
|
+
const rest = rawTokens.slice(idx);
|
|
25784
|
+
const isGlobal = scope === "global";
|
|
25785
|
+
let name = rest[0];
|
|
25786
|
+
let targetSpec = rest[1];
|
|
25787
|
+
let serverArgs = rest.slice(2);
|
|
25788
|
+
if ((!name || !targetSpec) && commandCtx.hasUI) {
|
|
25789
|
+
if (!name) name = (await commandCtx.ui.input("MCP server name", "e.g. chrome-devtools"))?.trim();
|
|
25790
|
+
if (!name) return;
|
|
25791
|
+
if (!targetSpec) {
|
|
25792
|
+
targetSpec = (await commandCtx.ui.input("Command or HTTP URL", "e.g. npx or https://mcp.example.com/sse"))?.trim();
|
|
25793
|
+
}
|
|
25794
|
+
if (!targetSpec) return;
|
|
25795
|
+
if (!/^https?:\/\//i.test(targetSpec) && serverArgs.length === 0) {
|
|
25796
|
+
const rawArgs = (await commandCtx.ui.input("Arguments (optional, quotes supported)", "e.g. -y chrome-devtools-mcp@latest"))?.trim();
|
|
25797
|
+
if (rawArgs) serverArgs = tokenizeCommandArgs(rawArgs);
|
|
25798
|
+
}
|
|
25799
|
+
}
|
|
25800
|
+
if (!name || !targetSpec) {
|
|
25801
|
+
commandCtx.ui.notify("Usage: /mcp add [--global|--project] <name> <url|command> [args...]", "warning");
|
|
25802
|
+
return;
|
|
25803
|
+
}
|
|
25804
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name)) {
|
|
25805
|
+
commandCtx.ui.notify(`Invalid MCP server name "${name}" (use letters, digits, ., _, -).`, "warning");
|
|
25806
|
+
return;
|
|
25807
|
+
}
|
|
25808
|
+
const filePath = isGlobal ? path4.join(configDir, "mcp-adapter.json") : path4.join(ctx.cwd, ".mcp.json");
|
|
25809
|
+
let priorRaw = null;
|
|
25810
|
+
let doc = {};
|
|
25811
|
+
if (fs4.existsSync(filePath)) {
|
|
25812
|
+
priorRaw = fs4.readFileSync(filePath, "utf8");
|
|
25813
|
+
try {
|
|
25814
|
+
const parsed = JSON.parse(priorRaw);
|
|
25815
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
25816
|
+
throw new Error("top-level JSON must be an object");
|
|
25817
|
+
}
|
|
25818
|
+
doc = { ...parsed };
|
|
25819
|
+
} catch (error2) {
|
|
25820
|
+
commandCtx.ui.notify(
|
|
25821
|
+
`Cannot update ${filePath}: invalid JSON (${error2 instanceof Error ? error2.message : String(error2)}). Fix or back up that file first.`,
|
|
25822
|
+
"error"
|
|
25823
|
+
);
|
|
25824
|
+
return;
|
|
25825
|
+
}
|
|
25826
|
+
}
|
|
25827
|
+
const existingServers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? { ...doc.mcpServers } : {};
|
|
25828
|
+
const entry = /^https?:\/\//i.test(targetSpec) ? { url: targetSpec } : { command: targetSpec, ...serverArgs.length > 0 ? { args: serverArgs } : {} };
|
|
25829
|
+
existingServers[name] = entry;
|
|
25830
|
+
doc.mcpServers = existingServers;
|
|
25831
|
+
const nextContent = `${JSON.stringify(doc, null, 2)}
|
|
25832
|
+
`;
|
|
25833
|
+
writeFileAtomic(filePath, nextContent);
|
|
25834
|
+
const reload = await reloadManager();
|
|
25835
|
+
if (!reload.ok) {
|
|
25836
|
+
const rb = rollbackIfUnchanged(filePath, nextContent, priorRaw);
|
|
25837
|
+
commandCtx.ui.notify(
|
|
25838
|
+
`MCP server "${name}" NOT added: config reload failed (${reload.error}); ${rb.ok ? `rolled back ${filePath}` : `rollback failed (${rb.detail})`}.`,
|
|
25839
|
+
"error"
|
|
25840
|
+
);
|
|
25841
|
+
return;
|
|
25842
|
+
}
|
|
25843
|
+
commandCtx.ui.notify(`MCP server "${name}" added (${isGlobal ? "global" : "project"}: ${filePath}).`, "info");
|
|
25844
|
+
return;
|
|
25845
|
+
}
|
|
25846
|
+
if (sub === "remove") {
|
|
25847
|
+
const hasGlobal = rawTokens.includes("--global") || rawTokens.includes("--user");
|
|
25848
|
+
const hasProject = rawTokens.includes("--project");
|
|
25849
|
+
if (hasGlobal && hasProject) {
|
|
25850
|
+
commandCtx.ui.notify("Choose one scope: --project or --global.", "warning");
|
|
25851
|
+
return;
|
|
25852
|
+
}
|
|
25853
|
+
const isGlobal = hasGlobal;
|
|
25854
|
+
const serverName = rawTokens.slice(1).find((t) => !t.startsWith("-"));
|
|
25855
|
+
if (!serverName) {
|
|
25856
|
+
commandCtx.ui.notify("Usage: /mcp remove <server> [--global]", "warning");
|
|
25857
|
+
return;
|
|
25858
|
+
}
|
|
25859
|
+
const filePath = isGlobal ? path4.join(configDir, "mcp-adapter.json") : path4.join(ctx.cwd, ".mcp.json");
|
|
25860
|
+
if (!fs4.existsSync(filePath)) {
|
|
25861
|
+
commandCtx.ui.notify(`No MCP config file at ${filePath}.`, "warning");
|
|
25862
|
+
return;
|
|
25863
|
+
}
|
|
25864
|
+
const priorRaw = fs4.readFileSync(filePath, "utf8");
|
|
25865
|
+
let doc;
|
|
25866
|
+
try {
|
|
25867
|
+
const parsed = JSON.parse(priorRaw);
|
|
25868
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("top-level JSON must be an object");
|
|
25869
|
+
doc = { ...parsed };
|
|
25870
|
+
} catch (error2) {
|
|
25871
|
+
commandCtx.ui.notify(`Cannot update ${filePath}: invalid JSON (${error2 instanceof Error ? error2.message : String(error2)}).`, "error");
|
|
25872
|
+
return;
|
|
25873
|
+
}
|
|
25874
|
+
const servers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? { ...doc.mcpServers } : {};
|
|
25875
|
+
if (!(serverName in servers)) {
|
|
25876
|
+
commandCtx.ui.notify(`MCP server "${serverName}" is not defined in ${filePath}.`, "warning");
|
|
25877
|
+
return;
|
|
25878
|
+
}
|
|
25879
|
+
delete servers[serverName];
|
|
25880
|
+
doc.mcpServers = servers;
|
|
25881
|
+
const nextContent = `${JSON.stringify(doc, null, 2)}
|
|
25882
|
+
`;
|
|
25883
|
+
writeFileAtomic(filePath, nextContent);
|
|
25884
|
+
const reload = await reloadManager();
|
|
25885
|
+
if (!reload.ok) {
|
|
25886
|
+
const rb = rollbackIfUnchanged(filePath, nextContent, priorRaw);
|
|
25887
|
+
commandCtx.ui.notify(
|
|
25888
|
+
`MCP server "${serverName}" NOT removed: config reload failed (${reload.error}); ${rb.ok ? "rolled back" : `rollback failed (${rb.detail})`}.`,
|
|
25889
|
+
"error"
|
|
25890
|
+
);
|
|
25891
|
+
return;
|
|
25892
|
+
}
|
|
25893
|
+
commandCtx.ui.notify(`MCP server "${serverName}" removed from ${filePath}.`, "info");
|
|
25894
|
+
return;
|
|
25895
|
+
}
|
|
25687
25896
|
if (sub === "enable" || sub === "disable") {
|
|
25688
25897
|
if (!target) {
|
|
25689
25898
|
commandCtx.ui.notify(`Usage: /mcp ${sub} <server>`, "warning");
|
|
@@ -25731,14 +25940,14 @@ function mcpAdapter(ctx) {
|
|
|
25731
25940
|
return;
|
|
25732
25941
|
}
|
|
25733
25942
|
if (sub !== void 0 && sub !== "" && sub !== "status" && sub !== "list") {
|
|
25734
|
-
commandCtx.ui.notify(`Unknown /mcp subcommand "${sub}". Usage: /mcp [status|list|enable <server>|disable <server>]`, "warning");
|
|
25943
|
+
commandCtx.ui.notify(`Unknown /mcp subcommand "${sub}". Usage: /mcp [status|list|add <name> <url|command> [args...] [--global]|remove <server> [--global]|enable <server>|disable <server>]`, "warning");
|
|
25735
25944
|
return;
|
|
25736
25945
|
}
|
|
25737
25946
|
const definitions = manager.listDefinitions();
|
|
25738
25947
|
const lines = ["MCP adapter"];
|
|
25739
25948
|
if (definitions.length === 0) {
|
|
25740
|
-
lines.push("No MCP servers configured.", "", "
|
|
25741
|
-
lines.push(
|
|
25949
|
+
lines.push("No MCP servers configured.", "", "Run `/mcp add <name> <url|command> [args...] [--global]` (or `/mcp add` interactively) to register one.");
|
|
25950
|
+
lines.push("Config files: .mcp.json (project) or ~/.pie/mcp-adapter.json (global).");
|
|
25742
25951
|
} else {
|
|
25743
25952
|
for (const definition of definitions) {
|
|
25744
25953
|
const trustLabel = trustStore.isTrusted(commandCtx.cwd, definition) ? "trusted" : "needs approval";
|