@cydm/pie 4.10.1 → 4.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 randomBytes = await getRandomValues(size - result.length);
20185
- for (const randomByte of randomBytes) {
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 [sub, target] = (args ?? "").trim().split(/\s+/).filter(Boolean);
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.", "", "Add one to .mcp.json (project) or ~/.config/mcp/mcp.json (global), e.g.:");
25741
- lines.push('{ "mcpServers": { "chrome-devtools": { "command": "npx", "args": ["-y", "chrome-devtools-mcp@1.10.1"] } } }');
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";
@@ -3,7 +3,7 @@ import {
3
3
  distillWorkerLogPath,
4
4
  readDistillWorkerLog,
5
5
  spawnDistillWorker
6
- } from "../../../chunks/chunk-XMTRKMBG.js";
6
+ } from "../../../chunks/chunk-L7XXKNZW.js";
7
7
  import {
8
8
  DEFAULT_MEMORY_INJECTION_BUDGET,
9
9
  MemoryStore,