multicorn-shield 1.10.0 → 1.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.
@@ -1,15 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import { createHash } from 'crypto';
3
- import { readFile, mkdir, writeFile, copyFile, chmod, unlink } from 'fs/promises';
4
- import { dirname, resolve, join, basename, sep } from 'path';
3
+ import { readFile, mkdir, writeFile, copyFile, chmod, rename, rm, unlink } from 'fs/promises';
4
+ import { dirname, resolve, basename, join, sep } from 'path';
5
5
  import { homedir } from 'os';
6
- import { spawn } from 'child_process';
7
- import { readFileSync, existsSync, statSync } from 'fs';
6
+ import { spawn, spawnSync } from 'child_process';
7
+ import { existsSync, readFileSync, mkdirSync, openSync, realpathSync, unlinkSync, writeFileSync, statSync, readdirSync } from 'fs';
8
8
  import { fileURLToPath } from 'url';
9
9
  import { createRequire } from 'module';
10
10
  import { createInterface } from 'readline';
11
11
  import { parse, stringify } from 'yaml';
12
12
  import 'stream';
13
+ import { createConnection } from 'net';
13
14
 
14
15
  var __defProp = Object.defineProperty;
15
16
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -235,6 +236,7 @@ async function fetchGrantedScopes(agentId, apiKey, baseUrl) {
235
236
  if (perm.revoked_at !== null) continue;
236
237
  if (perm.read) scopes.push({ service: perm.service, permissionLevel: "read" });
237
238
  if (perm.write) scopes.push({ service: perm.service, permissionLevel: "write" });
239
+ if (perm.delete === true) scopes.push({ service: perm.service, permissionLevel: "delete" });
238
240
  if (perm.execute) scopes.push({ service: perm.service, permissionLevel: "execute" });
239
241
  }
240
242
  return scopes;
@@ -324,7 +326,7 @@ function detectScopeHints() {
324
326
  return [];
325
327
  }
326
328
  function sleep(ms) {
327
- return new Promise((resolve2) => setTimeout(resolve2, ms));
329
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
328
330
  }
329
331
  function isApiSuccessResponse(value) {
330
332
  if (typeof value !== "object" || value === null) return false;
@@ -1878,6 +1880,17 @@ async function warnIfApiKeyFileNotGitignored(workspaceRoot, relativePosixPath) {
1878
1880
  style.yellow("\u26A0") + " Config contains your API key. Add " + style.cyan(norm) + " to .gitignore to avoid committing credentials.\n"
1879
1881
  );
1880
1882
  }
1883
+ async function writeFileAtomic(filePath, body) {
1884
+ await mkdir(dirname(filePath), { recursive: true });
1885
+ const tmp = `${filePath}.${String(process.pid)}.${String(Date.now())}.tmp`;
1886
+ try {
1887
+ await writeFile(tmp, body, SECRET_JSON_FILE_OPTIONS);
1888
+ await rename(tmp, filePath);
1889
+ } catch (e) {
1890
+ await rm(tmp, { force: true }).catch(() => void 0);
1891
+ throw e;
1892
+ }
1893
+ }
1881
1894
  async function mergeTopLevelKeyedJsonFile(filePath, topLevelKey, shortName, entry, options) {
1882
1895
  let root = {};
1883
1896
  try {
@@ -1902,21 +1915,25 @@ async function mergeTopLevelKeyedJsonFile(filePath, topLevelKey, shortName, entr
1902
1915
  }
1903
1916
  }
1904
1917
  const bucketRaw = root[topLevelKey];
1905
- const bucket = typeof bucketRaw === "object" && bucketRaw !== null && !Array.isArray(bucketRaw) ? { ...bucketRaw } : {};
1906
- if (options.onExisting === "skip" && bucket[shortName] !== void 0) {
1918
+ const existingBucket = typeof bucketRaw === "object" && bucketRaw !== null && !Array.isArray(bucketRaw) ? bucketRaw : {};
1919
+ if (options.onExisting === "skip" && existingBucket[shortName] !== void 0) {
1907
1920
  return "unchanged";
1908
1921
  }
1922
+ const staleKeys = new Set((options.removeKeys ?? []).filter((k) => k !== shortName));
1923
+ const bucket = Object.fromEntries(
1924
+ Object.entries(existingBucket).filter(([k]) => !staleKeys.has(k))
1925
+ );
1909
1926
  bucket[shortName] = entry;
1910
1927
  root[topLevelKey] = bucket;
1911
- await mkdir(dirname(filePath), { recursive: true });
1912
- await writeFile(filePath, JSON.stringify(root, null, 2) + "\n", SECRET_JSON_FILE_OPTIONS);
1928
+ await writeFileAtomic(filePath, JSON.stringify(root, null, 2) + "\n");
1913
1929
  writeMcpAddedLine(shortName, filePath);
1914
1930
  return "ok";
1915
1931
  }
1916
- async function mergeMcpServersObjectStyle(filePath, shortName, entry) {
1932
+ async function mergeMcpServersObjectStyle(filePath, shortName, entry, removeKeys) {
1917
1933
  const result = await mergeTopLevelKeyedJsonFile(filePath, "mcpServers", shortName, entry, {
1918
1934
  stripJsonComments: false,
1919
- onExisting: "overwrite"
1935
+ onExisting: "overwrite",
1936
+ removeKeys
1920
1937
  });
1921
1938
  return result === "parse-error" ? "parse-error" : "ok";
1922
1939
  }
@@ -2651,8 +2668,8 @@ async function runInit(explicitBaseUrl, options) {
2651
2668
  process.exit(1);
2652
2669
  }
2653
2670
  const rl = createInterface({ input: process.stdin, output: process.stderr });
2654
- const ask = (question) => new Promise((resolve2) => {
2655
- rl.question(question, resolve2);
2671
+ const ask = (question) => new Promise((resolve3) => {
2672
+ rl.question(question, resolve3);
2656
2673
  });
2657
2674
  process.stderr.write("\n" + BANNER + "\n");
2658
2675
  process.stderr.write(style.dim("Agent governance for the AI era") + "\n\n");
@@ -3682,7 +3699,254 @@ You have ${String(agentsForPlatform.length)} agent(s) connected for ${selectedLa
3682
3699
  }
3683
3700
  return lastConfig;
3684
3701
  }
3685
- var SECRET_JSON_FILE_OPTIONS, style, BANNER, NativePluginPrerequisiteMissingError, CONFIG_DIR, CONFIG_PATH, OPENCLAW_CONFIG_PATH, ANSI_PATTERN, UPSTREAM_AUTH_KNOWN_SCHEME_WITH_PAYLOAD, OPENCLAW_MIN_VERSION, INIT_WIZARD_PLATFORM_REGISTRY, INIT_WIZARD_MENU_SECTIONS, INIT_WIZARD_SELECTION_MAX, INIT_EXISTING_AGENTS_PLATFORM_ACTIONS, PLATFORM_BY_SELECTION, HOSTED_PROXY_PLATFORMS_WITH_URL_KEY, OPENCODE_CONFIG_SCHEMA_URL, DEFAULT_SHIELD_API_BASE_URL;
3702
+ function clientDisplayName(client) {
3703
+ return CLIENT_DISPLAY_NAMES[client];
3704
+ }
3705
+ function clientReloadInstruction(client) {
3706
+ return CLIENT_RELOAD_INSTRUCTIONS[client];
3707
+ }
3708
+ function clientConfigPath(client, workspacePath) {
3709
+ switch (client) {
3710
+ case "cursor":
3711
+ return getCursorMcpJsonPath();
3712
+ case "cline":
3713
+ return getClineMcpSettingsPath();
3714
+ case "windsurf":
3715
+ return getWindsurfMcpConfigPath();
3716
+ case "claude":
3717
+ return getClaudeDesktopConfigPath();
3718
+ case "goose":
3719
+ return join(homedir(), ".config", "goose", "config.yaml");
3720
+ case "gemini":
3721
+ return join(homedir(), ".gemini", "settings.json");
3722
+ case "codex":
3723
+ return join(homedir(), ".codex", "config.toml");
3724
+ case "copilot":
3725
+ return join(workspacePath ?? ".", ".vscode", "mcp.json");
3726
+ case "continue":
3727
+ return join(workspacePath ?? ".", ".continue", "mcpServers");
3728
+ case "kilo":
3729
+ return join(workspacePath ?? ".", ".kilo", "kilo.jsonc");
3730
+ case "opencode":
3731
+ return join(workspacePath ?? ".", "opencode.json");
3732
+ }
3733
+ }
3734
+ function detectInstalledClients() {
3735
+ const found = [];
3736
+ const homeClients = [
3737
+ "cursor",
3738
+ "cline",
3739
+ "windsurf",
3740
+ "claude",
3741
+ "goose",
3742
+ "gemini",
3743
+ "codex"
3744
+ ];
3745
+ for (const client of homeClients) {
3746
+ const p = clientConfigPath(client);
3747
+ if (existsSync(p)) {
3748
+ found.push(client);
3749
+ } else {
3750
+ const dir = dirname(p);
3751
+ if (existsSync(dir)) {
3752
+ found.push(client);
3753
+ }
3754
+ }
3755
+ }
3756
+ return found;
3757
+ }
3758
+ async function writeLocalMcpEntry(client, agentName, localProxyUrl, apiKey, workspacePath) {
3759
+ const filePath = clientConfigPath(client, workspacePath);
3760
+ const entryKey = agentName;
3761
+ const legacyKeys = [`${agentName}-files`];
3762
+ if (apiKey.trim().length === 0) {
3763
+ process.stderr.write(
3764
+ style.yellow("\u26A0") + ` Refusing to write MCP config for "${agentName}": missing API key. Left the config file unchanged.
3765
+ `
3766
+ );
3767
+ return null;
3768
+ }
3769
+ const authHeader = `Bearer ${apiKey}`;
3770
+ const url = shouldEmbedKeyInHostedProxyUrl(CODING_CLIENT_TO_PLATFORM[client]) ? hostedProxyUrlWithKeyParam(localProxyUrl, apiKey) : localProxyUrl;
3771
+ switch (client) {
3772
+ case "cursor":
3773
+ return await mergeMcpServersObjectStyle(
3774
+ filePath,
3775
+ entryKey,
3776
+ {
3777
+ url,
3778
+ headers: { Authorization: authHeader }
3779
+ },
3780
+ legacyKeys
3781
+ ) === "ok" ? filePath : null;
3782
+ case "cline":
3783
+ return await mergeMcpServersObjectStyle(
3784
+ filePath,
3785
+ entryKey,
3786
+ {
3787
+ url
3788
+ },
3789
+ legacyKeys
3790
+ ) === "ok" ? filePath : null;
3791
+ case "windsurf":
3792
+ return await mergeMcpServersObjectStyle(
3793
+ filePath,
3794
+ entryKey,
3795
+ {
3796
+ serverUrl: url,
3797
+ headers: { Authorization: authHeader }
3798
+ },
3799
+ legacyKeys
3800
+ ) === "ok" ? filePath : null;
3801
+ case "claude":
3802
+ return await mergeMcpServersObjectStyle(
3803
+ filePath,
3804
+ entryKey,
3805
+ {
3806
+ url,
3807
+ headers: { Authorization: authHeader }
3808
+ },
3809
+ legacyKeys
3810
+ ) === "ok" ? filePath : null;
3811
+ case "gemini": {
3812
+ return await mergeMcpServersObjectStyle(
3813
+ filePath,
3814
+ entryKey,
3815
+ {
3816
+ httpUrl: url,
3817
+ headers: { Authorization: authHeader }
3818
+ },
3819
+ legacyKeys
3820
+ ) === "ok" ? filePath : null;
3821
+ }
3822
+ case "copilot": {
3823
+ const result = await mergeTopLevelKeyedJsonFile(
3824
+ filePath,
3825
+ "servers",
3826
+ entryKey,
3827
+ { type: "http", url, headers: { Authorization: authHeader } },
3828
+ { stripJsonComments: false, onExisting: "overwrite", removeKeys: legacyKeys }
3829
+ );
3830
+ return result === "ok" ? filePath : null;
3831
+ }
3832
+ case "goose": {
3833
+ const goosePath = filePath;
3834
+ let content = "";
3835
+ try {
3836
+ content = await readFile(goosePath, "utf8");
3837
+ } catch (e) {
3838
+ if (isErrnoException(e) && e.code === "ENOENT") {
3839
+ content = "";
3840
+ } else {
3841
+ return null;
3842
+ }
3843
+ }
3844
+ let root;
3845
+ try {
3846
+ const data = content.trim().length === 0 ? {} : parse(content);
3847
+ if (data === null || typeof data !== "object" || Array.isArray(data)) return null;
3848
+ root = data;
3849
+ } catch {
3850
+ return null;
3851
+ }
3852
+ const extensionsRaw = root["extensions"];
3853
+ let extensions;
3854
+ if (isYamlPlainObject(extensionsRaw)) {
3855
+ extensions = { ...extensionsRaw };
3856
+ } else if (extensionsRaw === void 0) {
3857
+ extensions = {};
3858
+ } else {
3859
+ return null;
3860
+ }
3861
+ extensions[entryKey] = {
3862
+ enabled: true,
3863
+ type: "streamable_http",
3864
+ name: entryKey,
3865
+ description: "",
3866
+ uri: url,
3867
+ envs: {},
3868
+ env_keys: [],
3869
+ headers: { Authorization: authHeader },
3870
+ timeout: 300,
3871
+ socket: null,
3872
+ bundled: null,
3873
+ available_tools: []
3874
+ };
3875
+ root["extensions"] = extensions;
3876
+ const out = stringify(root, { indent: 2, lineWidth: 0 });
3877
+ const body = out.endsWith("\n") ? out : `${out}
3878
+ `;
3879
+ await mkdir(dirname(goosePath), { recursive: true });
3880
+ await writeFile(goosePath, body, SECRET_JSON_FILE_OPTIONS);
3881
+ return goosePath;
3882
+ }
3883
+ case "codex": {
3884
+ const codexPath = filePath;
3885
+ let existing = "";
3886
+ try {
3887
+ existing = await readFile(codexPath, "utf8");
3888
+ } catch (e) {
3889
+ if (isErrnoException(e) && e.code === "ENOENT") {
3890
+ existing = "";
3891
+ } else {
3892
+ return null;
3893
+ }
3894
+ }
3895
+ const sectionHeader = `[mcp_servers.${entryKey}]`;
3896
+ const sectionBlock = `${sectionHeader}
3897
+ type = "http"
3898
+ url = "${url}"
3899
+
3900
+ [mcp_servers.${entryKey}.http_headers]
3901
+ Authorization = "${authHeader}"
3902
+ `;
3903
+ if (existing.includes(sectionHeader)) {
3904
+ const idx = existing.indexOf(sectionHeader);
3905
+ const nextSection = existing.indexOf("\n[", idx + sectionHeader.length);
3906
+ const before = existing.slice(0, idx);
3907
+ const after = nextSection >= 0 ? existing.slice(nextSection + 1) : "";
3908
+ existing = before + sectionBlock + (after.length > 0 ? "\n" + after : "");
3909
+ } else {
3910
+ existing = existing.trimEnd() + "\n\n" + sectionBlock;
3911
+ }
3912
+ await mkdir(dirname(codexPath), { recursive: true });
3913
+ await writeFile(codexPath, existing, SECRET_JSON_FILE_OPTIONS);
3914
+ return codexPath;
3915
+ }
3916
+ case "continue": {
3917
+ const dir = join(workspacePath ?? ".", ".continue", "mcpServers");
3918
+ const continuePath = join(dir, `${entryKey}.yaml`);
3919
+ const yamlContent = stringify(
3920
+ { name: entryKey, type: "streamableHttp", url },
3921
+ { indent: 2, lineWidth: 0 }
3922
+ );
3923
+ await mkdir(dir, { recursive: true });
3924
+ await writeFile(continuePath, yamlContent, SECRET_JSON_FILE_OPTIONS);
3925
+ return continuePath;
3926
+ }
3927
+ case "kilo": {
3928
+ const result = await mergeTopLevelKeyedJsonFile(
3929
+ filePath,
3930
+ "mcp",
3931
+ entryKey,
3932
+ { url, headers: { Authorization: authHeader } },
3933
+ { stripJsonComments: true, onExisting: "overwrite", removeKeys: legacyKeys }
3934
+ );
3935
+ return result === "ok" ? filePath : null;
3936
+ }
3937
+ case "opencode": {
3938
+ const result = await mergeTopLevelKeyedJsonFile(
3939
+ filePath,
3940
+ "mcp",
3941
+ entryKey,
3942
+ { type: "streamablehttp", url, headers: { Authorization: authHeader } },
3943
+ { stripJsonComments: false, onExisting: "overwrite", removeKeys: legacyKeys }
3944
+ );
3945
+ return result === "ok" ? filePath : null;
3946
+ }
3947
+ }
3948
+ }
3949
+ var SECRET_JSON_FILE_OPTIONS, style, BANNER, NativePluginPrerequisiteMissingError, CONFIG_DIR, CONFIG_PATH, OPENCLAW_CONFIG_PATH, ANSI_PATTERN, UPSTREAM_AUTH_KNOWN_SCHEME_WITH_PAYLOAD, OPENCLAW_MIN_VERSION, INIT_WIZARD_PLATFORM_REGISTRY, INIT_WIZARD_MENU_SECTIONS, INIT_WIZARD_SELECTION_MAX, INIT_EXISTING_AGENTS_PLATFORM_ACTIONS, PLATFORM_BY_SELECTION, HOSTED_PROXY_PLATFORMS_WITH_URL_KEY, OPENCODE_CONFIG_SCHEMA_URL, DEFAULT_SHIELD_API_BASE_URL, CODING_CLIENTS, CLIENT_DISPLAY_NAMES, CLIENT_RELOAD_INSTRUCTIONS, CODING_CLIENT_TO_PLATFORM;
3686
3950
  var init_config = __esm({
3687
3951
  "src/proxy/config.ts"() {
3688
3952
  init_consent();
@@ -3802,6 +4066,58 @@ var init_config = __esm({
3802
4066
  ]);
3803
4067
  OPENCODE_CONFIG_SCHEMA_URL = "https://opencode.ai/config.json";
3804
4068
  DEFAULT_SHIELD_API_BASE_URL = "https://api.multicorn.ai";
4069
+ CODING_CLIENTS = [
4070
+ "cursor",
4071
+ "cline",
4072
+ "windsurf",
4073
+ "claude",
4074
+ "copilot",
4075
+ "goose",
4076
+ "gemini",
4077
+ "codex",
4078
+ "continue",
4079
+ "kilo",
4080
+ "opencode"
4081
+ ];
4082
+ CLIENT_DISPLAY_NAMES = {
4083
+ cursor: "Cursor",
4084
+ cline: "Cline",
4085
+ windsurf: "Windsurf",
4086
+ claude: "Claude Desktop",
4087
+ copilot: "GitHub Copilot",
4088
+ goose: "Goose",
4089
+ gemini: "Gemini CLI",
4090
+ codex: "Codex CLI",
4091
+ continue: "Continue",
4092
+ kilo: "Kilo Code",
4093
+ opencode: "OpenCode"
4094
+ };
4095
+ CLIENT_RELOAD_INSTRUCTIONS = {
4096
+ cursor: "Restart Cursor or reload the window to pick up the new server.",
4097
+ cline: "Cline picks up config changes automatically.",
4098
+ windsurf: "Restart Windsurf to pick up the new server.",
4099
+ claude: "Restart Claude Desktop to pick up the new server.",
4100
+ copilot: "Reload the VS Code window (Cmd+Shift+P > Reload Window).",
4101
+ goose: "Restart Goose to pick up the new extension.",
4102
+ gemini: "Restart Gemini CLI to pick up the new server.",
4103
+ codex: "Restart Codex CLI to pick up the new server.",
4104
+ continue: "Continue picks up config changes automatically.",
4105
+ kilo: "Kilo Code picks up config changes automatically.",
4106
+ opencode: "Restart OpenCode to pick up the new server."
4107
+ };
4108
+ CODING_CLIENT_TO_PLATFORM = {
4109
+ cursor: "cursor",
4110
+ cline: "cline",
4111
+ windsurf: "windsurf",
4112
+ claude: "claude-desktop",
4113
+ copilot: "github-copilot",
4114
+ goose: "goose",
4115
+ gemini: "gemini-cli",
4116
+ codex: "codex-cli",
4117
+ continue: "continue-dev",
4118
+ kilo: "kilo-code",
4119
+ opencode: "opencode"
4120
+ };
3805
4121
  }
3806
4122
  });
3807
4123
 
@@ -3812,6 +4128,7 @@ var init_types = __esm({
3812
4128
  PERMISSION_LEVELS = {
3813
4129
  Read: "read",
3814
4130
  Write: "write",
4131
+ Delete: "delete",
3815
4132
  Execute: "execute",
3816
4133
  Publish: "publish",
3817
4134
  Create: "create"
@@ -4034,7 +4351,7 @@ function createActionLogger(config) {
4034
4351
  };
4035
4352
  }
4036
4353
  function sleep2(ms) {
4037
- return new Promise((resolve2) => setTimeout(resolve2, ms));
4354
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
4038
4355
  }
4039
4356
  var init_action_logger = __esm({
4040
4357
  "src/logger/action-logger.ts"() {
@@ -4602,9 +4919,9 @@ function createProxyServer(config) {
4602
4919
  timer.unref();
4603
4920
  }
4604
4921
  config.logger.info("Proxy ready.", { agent: config.agentName });
4605
- return new Promise((resolve2) => {
4922
+ return new Promise((resolve3) => {
4606
4923
  childProcess.on("exit", () => {
4607
- resolve2();
4924
+ resolve3();
4608
4925
  });
4609
4926
  });
4610
4927
  }
@@ -4745,7 +5062,7 @@ var init_package = __esm({
4745
5062
  "package.json"() {
4746
5063
  package_default = {
4747
5064
  name: "multicorn-shield",
4748
- version: "1.10.0",
5065
+ version: "1.11.0",
4749
5066
  description: "The control layer for AI agents: permissions, consent, spending limits, and audit logging.",
4750
5067
  license: "MIT",
4751
5068
  author: "Multicorn AI Pty Ltd",
@@ -4836,9 +5153,11 @@ var init_package = __esm({
4836
5153
  ]
4837
5154
  },
4838
5155
  dependencies: {
4839
- "@modelcontextprotocol/sdk": "^1.27.1",
4840
5156
  "@lit/reactive-element": "^2.0.0",
5157
+ "@modelcontextprotocol/sdk": "^1.27.1",
5158
+ "@modelcontextprotocol/server-filesystem": "^2026.1.14",
4841
5159
  lit: "^3.2.0",
5160
+ supergateway: "^3.4.3",
4842
5161
  yaml: "^2.8.2",
4843
5162
  zod: "^4.3.6"
4844
5163
  },
@@ -4913,8 +5232,11 @@ var init_package = __esm({
4913
5232
  rollup: ">=4.59.0",
4914
5233
  picomatch: ">=4.0.4",
4915
5234
  "path-to-regexp": ">=8.4.0",
5235
+ "express>path-to-regexp": ">=0.1.13",
4916
5236
  "node-forge": ">=1.4.0",
4917
- "fast-uri": ">=3.1.2"
5237
+ "fast-uri": ">=3.1.2",
5238
+ hono: ">=4.12.25",
5239
+ ws: ">=8.21.0"
4918
5240
  }
4919
5241
  }
4920
5242
  };
@@ -4929,154 +5251,1213 @@ var init_package_meta = __esm({
4929
5251
  PACKAGE_VERSION = package_default.version;
4930
5252
  }
4931
5253
  });
5254
+ function pidfilePath(agent) {
5255
+ return join(PIDFILE_DIR, `files-${agent}.pid`);
5256
+ }
5257
+ function writePidfile(data) {
5258
+ mkdirSync(PIDFILE_DIR, { recursive: true, mode: 448 });
5259
+ writeFileSync(pidfilePath(data.agent), JSON.stringify(data), {
5260
+ encoding: "utf8",
5261
+ mode: 384
5262
+ });
5263
+ }
5264
+ function readPidfile(agent) {
5265
+ const p = pidfilePath(agent);
5266
+ if (!existsSync(p)) return null;
5267
+ try {
5268
+ return JSON.parse(readFileSync(p, "utf8"));
5269
+ } catch {
5270
+ return null;
5271
+ }
5272
+ }
5273
+ function removePidfile(agent) {
5274
+ const p = pidfilePath(agent);
5275
+ try {
5276
+ unlinkSync(p);
5277
+ } catch {
5278
+ }
5279
+ }
5280
+ function isProcessAlive(pid) {
5281
+ try {
5282
+ process.kill(pid, 0);
5283
+ return true;
5284
+ } catch {
5285
+ return false;
5286
+ }
5287
+ }
5288
+ function listAllPidfiles() {
5289
+ if (!existsSync(PIDFILE_DIR)) return [];
5290
+ const files = readdirSync(PIDFILE_DIR).filter(
5291
+ (f) => f.startsWith("files-") && f.endsWith(".pid")
5292
+ );
5293
+ const results = [];
5294
+ for (const f of files) {
5295
+ try {
5296
+ const data = JSON.parse(readFileSync(join(PIDFILE_DIR, f), "utf8"));
5297
+ results.push(data);
5298
+ } catch {
5299
+ }
5300
+ }
5301
+ return results;
5302
+ }
5303
+ function runStatus() {
5304
+ const sessions = listAllPidfiles();
5305
+ if (sessions.length === 0) {
5306
+ process.stderr.write("No active file-sharing sessions.\n");
5307
+ return;
5308
+ }
5309
+ const proxyReg = readProxyRegistry();
5310
+ const fsReg = readFsRegistry();
5311
+ process.stderr.write("Active sessions:\n\n");
5312
+ for (const s of sessions) {
5313
+ const supervisorAlive = typeof s.supervisorPid === "number" && isProcessAlive(s.supervisorPid);
5314
+ const fsEntry = fsReg[s.dir];
5315
+ const fsAlive = fsEntry !== void 0 && isProcessAlive(fsEntry.pid);
5316
+ const proxyAlive = proxyReg !== null && proxyReg.port === s.proxyPort && isProcessAlive(proxyReg.pid);
5317
+ const agentStatus = supervisorAlive ? style2.green("running") : style2.dim("stopped");
5318
+ process.stderr.write(` ${style2.bold(s.agent)} ${agentStatus}
5319
+ `);
5320
+ process.stderr.write(` Folder: ${s.dir || "(unknown)"}
5321
+ `);
5322
+ process.stderr.write(
5323
+ ` FS server: :${String(s.fsPort)} ${fsAlive ? style2.green("running") : style2.dim("stopped")}
5324
+ `
5325
+ );
5326
+ process.stderr.write(
5327
+ ` Proxy: :${String(s.proxyPort)} ${proxyAlive ? style2.green("running") : style2.dim("stopped")}
5328
+ `
5329
+ );
5330
+ process.stderr.write("\n");
5331
+ if (!supervisorAlive) {
5332
+ removePidfile(s.agent);
5333
+ process.stderr.write(style2.dim(` (cleaned up stale pidfile)
4932
5334
 
4933
- // bin/multicorn-shield.ts
4934
- var multicorn_shield_exports = {};
4935
- __export(multicorn_shield_exports, {
4936
- parseArgs: () => parseArgs,
4937
- resolveWrapConfig: () => resolveWrapConfig,
4938
- runCli: () => runCli
4939
- });
4940
- function parseArgs(argv) {
4941
- const args = argv.slice(2);
4942
- let subcommand = "help";
4943
- let wrapCommand = "";
4944
- let wrapArgs = [];
4945
- let logLevel = "info";
4946
- let baseUrl = void 0;
4947
- let dashboardUrl = "";
4948
- let agentName = "";
4949
- let deleteAgentName = "";
4950
- let apiKey = void 0;
4951
- let verbose = false;
4952
- for (let i = 0; i < args.length; i++) {
4953
- const arg = args[i];
4954
- if (arg === "init") {
4955
- subcommand = "init";
4956
- } else if (arg === "agents") {
4957
- subcommand = "agents";
4958
- } else if (arg === "delete-agent") {
4959
- subcommand = "delete-agent";
4960
- const name = args[i + 1];
4961
- if (name === void 0 || name.startsWith("-")) {
4962
- process.stderr.write("Error: delete-agent requires an agent name.\n");
4963
- process.stderr.write("Example: npx multicorn-shield delete-agent my-agent\n");
4964
- process.exit(1);
4965
- }
4966
- deleteAgentName = name;
4967
- i++;
4968
- } else if (arg === "--wrap") {
4969
- subcommand = "wrap";
4970
- const tail = args.slice(i + 1);
4971
- const remaining = [];
4972
- for (let j = 0; j < tail.length; j++) {
4973
- const token = tail[j];
4974
- if (token === void 0) continue;
4975
- if (remaining.length > 0) {
4976
- remaining.push(token);
4977
- continue;
4978
- }
4979
- if (token === "--agent-name") {
4980
- const value = tail[j + 1];
4981
- if (value !== void 0) {
4982
- agentName = value;
4983
- j++;
4984
- }
4985
- } else if (token === "--log-level") {
4986
- const value = tail[j + 1];
4987
- if (value !== void 0 && isValidLogLevel(value)) {
4988
- logLevel = value;
4989
- j++;
4990
- }
4991
- } else if (token === "--base-url") {
4992
- const value = tail[j + 1];
4993
- if (value !== void 0) {
4994
- baseUrl = value;
4995
- j++;
4996
- }
4997
- } else if (token === "--dashboard-url") {
4998
- const value = tail[j + 1];
4999
- if (value !== void 0) {
5000
- dashboardUrl = value;
5001
- j++;
5002
- }
5003
- } else if (token === "--api-key") {
5004
- const value = tail[j + 1];
5005
- if (value !== void 0) {
5006
- apiKey = value;
5007
- j++;
5008
- }
5009
- } else {
5010
- remaining.push(token);
5011
- }
5012
- }
5013
- if (remaining.length === 0) {
5014
- process.stderr.write("Error: --wrap requires a command to run.\n");
5015
- process.stderr.write("Example: npx multicorn-shield --wrap my-mcp-server\n");
5016
- process.exit(1);
5017
- }
5018
- wrapCommand = remaining[0] ?? "";
5019
- wrapArgs = remaining.slice(1);
5020
- break;
5021
- } else if (arg === "--log-level") {
5022
- const next = args[i + 1];
5023
- if (next !== void 0 && isValidLogLevel(next)) {
5024
- logLevel = next;
5025
- i++;
5026
- }
5027
- } else if (arg === "--base-url") {
5028
- const next = args[i + 1];
5029
- if (next !== void 0) {
5030
- baseUrl = next;
5031
- i++;
5032
- }
5033
- } else if (arg === "--dashboard-url") {
5034
- const next = args[i + 1];
5035
- if (next !== void 0) {
5036
- dashboardUrl = next;
5037
- i++;
5038
- }
5039
- } else if (arg === "--agent-name") {
5040
- const next = args[i + 1];
5041
- if (next !== void 0) {
5042
- agentName = next;
5043
- i++;
5044
- }
5045
- } else if (arg === "--api-key") {
5046
- const next = args[i + 1];
5047
- if (next !== void 0) {
5048
- apiKey = next;
5049
- i++;
5050
- }
5051
- } else if (arg === "--verbose" || arg === "--debug") {
5052
- verbose = true;
5335
+ `));
5053
5336
  }
5054
5337
  }
5055
- return {
5056
- subcommand,
5057
- wrapCommand,
5058
- wrapArgs,
5059
- logLevel,
5060
- baseUrl,
5061
- dashboardUrl,
5062
- agentName,
5063
- deleteAgentName,
5064
- apiKey,
5065
- verbose
5066
- };
5067
5338
  }
5068
- function printHelp() {
5069
- process.stderr.write(
5070
- [
5071
- "multicorn-shield: MCP permission proxy and Shield setup",
5072
- "",
5073
- "Usage:",
5074
- " npx multicorn-shield init",
5075
- " Interactive setup. Saves API key to ~/.multicorn/config.json.",
5076
- "",
5077
- " npx multicorn-shield restore",
5078
- " Restore MCP servers in claude_desktop_config.json from the Shield extension backup.",
5079
- "",
5339
+ async function isPortListening(port) {
5340
+ return new Promise((resolve3) => {
5341
+ const sock = createConnection({ port, host: "127.0.0.1" });
5342
+ sock.once("connect", () => {
5343
+ sock.destroy();
5344
+ resolve3(true);
5345
+ });
5346
+ sock.once("error", () => {
5347
+ sock.destroy();
5348
+ resolve3(false);
5349
+ });
5350
+ });
5351
+ }
5352
+ async function probeProxyHealth(port) {
5353
+ try {
5354
+ const resp = await fetch(`http://127.0.0.1:${String(port)}/health`, {
5355
+ signal: AbortSignal.timeout(2e3)
5356
+ });
5357
+ return resp.ok;
5358
+ } catch {
5359
+ return false;
5360
+ }
5361
+ }
5362
+ async function readProxyVersion(port) {
5363
+ try {
5364
+ const resp = await fetch(`http://127.0.0.1:${String(port)}/health`, {
5365
+ signal: AbortSignal.timeout(2e3)
5366
+ });
5367
+ if (!resp.ok) return null;
5368
+ const body = await resp.json();
5369
+ return typeof body.version === "string" && body.version.length > 0 ? body.version : null;
5370
+ } catch {
5371
+ return null;
5372
+ }
5373
+ }
5374
+ function sleep3(ms) {
5375
+ return new Promise((r) => setTimeout(r, ms));
5376
+ }
5377
+ function readJsonFile(path) {
5378
+ if (!existsSync(path)) return null;
5379
+ try {
5380
+ return JSON.parse(readFileSync(path, "utf8"));
5381
+ } catch {
5382
+ return null;
5383
+ }
5384
+ }
5385
+ function writeJsonFile(path, data) {
5386
+ mkdirSync(PIDFILE_DIR, { recursive: true, mode: 448 });
5387
+ writeFileSync(path, JSON.stringify(data), { encoding: "utf8", mode: 384 });
5388
+ }
5389
+ function readProxyRegistry() {
5390
+ return readJsonFile(PROXY_REGISTRY);
5391
+ }
5392
+ function readFsRegistry() {
5393
+ return readJsonFile(FS_REGISTRY) ?? {};
5394
+ }
5395
+ function canonicalFolder(dir) {
5396
+ const abs = resolve(dir);
5397
+ try {
5398
+ return realpathSync(abs);
5399
+ } catch {
5400
+ return abs;
5401
+ }
5402
+ }
5403
+ function readLock() {
5404
+ return readJsonFile(LOCK_PATH);
5405
+ }
5406
+ function isLockStale(holder, now = Date.now()) {
5407
+ if (holder === null) return true;
5408
+ if (!isProcessAlive(holder.pid)) return true;
5409
+ return now - holder.ts > LOCK_STALE_MS;
5410
+ }
5411
+ async function acquireResourceLock() {
5412
+ mkdirSync(PIDFILE_DIR, { recursive: true, mode: 448 });
5413
+ const deadline = Date.now() + LOCK_WAIT_MS;
5414
+ for (; ; ) {
5415
+ try {
5416
+ writeFileSync(LOCK_PATH, JSON.stringify({ pid: process.pid, ts: Date.now() }), {
5417
+ encoding: "utf8",
5418
+ mode: 384,
5419
+ flag: "wx"
5420
+ });
5421
+ return;
5422
+ } catch {
5423
+ const holder = readLock();
5424
+ if (isLockStale(holder)) {
5425
+ try {
5426
+ unlinkSync(LOCK_PATH);
5427
+ } catch {
5428
+ }
5429
+ continue;
5430
+ }
5431
+ if (Date.now() > deadline) {
5432
+ try {
5433
+ unlinkSync(LOCK_PATH);
5434
+ } catch {
5435
+ }
5436
+ continue;
5437
+ }
5438
+ await sleep3(100);
5439
+ }
5440
+ }
5441
+ }
5442
+ function releaseResourceLock() {
5443
+ const holder = readLock();
5444
+ if (holder !== null && holder.pid === process.pid) {
5445
+ try {
5446
+ unlinkSync(LOCK_PATH);
5447
+ } catch {
5448
+ }
5449
+ }
5450
+ }
5451
+ async function withResourceLock(fn) {
5452
+ await acquireResourceLock();
5453
+ try {
5454
+ return await fn();
5455
+ } finally {
5456
+ releaseResourceLock();
5457
+ }
5458
+ }
5459
+ function liveAgents() {
5460
+ return listAllPidfiles().filter(
5461
+ (p) => typeof p.supervisorPid === "number" && isProcessAlive(p.supervisorPid)
5462
+ );
5463
+ }
5464
+ function agentsReferencingProxy(proxyPort, agents, excludeAgent) {
5465
+ return agents.filter((a) => a.agent !== excludeAgent && a.proxyPort === proxyPort);
5466
+ }
5467
+ function agentsReferencingFolder(folder, agents, excludeAgent) {
5468
+ return agents.filter((a) => a.agent !== excludeAgent && a.dir === folder);
5469
+ }
5470
+ async function nextFreePort(start, claimed, isBusy, range = FS_PORT_SCAN_RANGE) {
5471
+ for (let port = start; port < start + range; port++) {
5472
+ if (claimed.has(port)) continue;
5473
+ if (await isBusy(port)) continue;
5474
+ return port;
5475
+ }
5476
+ throw new Error(
5477
+ `No free port for the filesystem server in range ${String(start)}-${String(start + range)}.`
5478
+ );
5479
+ }
5480
+ async function resolveConfig(opts) {
5481
+ const fromFlag = opts.apiKey;
5482
+ if (fromFlag && fromFlag.length > 0) {
5483
+ return {
5484
+ apiKey: fromFlag,
5485
+ baseUrl: opts.baseUrl ?? DEFAULT_SHIELD_API_BASE_URL
5486
+ };
5487
+ }
5488
+ const envKey = process.env["MULTICORN_API_KEY"];
5489
+ if (typeof envKey === "string" && envKey.length > 0) {
5490
+ return {
5491
+ apiKey: envKey,
5492
+ baseUrl: opts.baseUrl ?? DEFAULT_SHIELD_API_BASE_URL
5493
+ };
5494
+ }
5495
+ const config = await loadConfig();
5496
+ if (config !== null) {
5497
+ return {
5498
+ apiKey: config.apiKey,
5499
+ baseUrl: opts.baseUrl ?? config.baseUrl
5500
+ };
5501
+ }
5502
+ process.stderr.write(
5503
+ "No API key found. Pass --api-key <key> or add it to ~/.multicorn/config.json.\n"
5504
+ );
5505
+ process.exit(1);
5506
+ }
5507
+ function startFsServerDetached(realDir, port) {
5508
+ mkdirSync(PIDFILE_DIR, { recursive: true, mode: 448 });
5509
+ const logFile = join(PIDFILE_DIR, `fs-${String(port)}.log`);
5510
+ const out = openSync(logFile, "a");
5511
+ const err = openSync(logFile, "a");
5512
+ const child = spawn(
5513
+ "npx",
5514
+ [
5515
+ "supergateway",
5516
+ // Serve the child over streamable HTTP at /mcp. Without this, supergateway
5517
+ // defaults to SSE (/sse + /message), but the proxy registers the target as
5518
+ // /mcp - the mismatch makes every request 404 with "Cannot POST /mcp".
5519
+ "--outputTransport",
5520
+ "streamableHttp",
5521
+ "--stdio",
5522
+ `npx @modelcontextprotocol/server-filesystem ${realDir}`,
5523
+ "--port",
5524
+ String(port)
5525
+ ],
5526
+ {
5527
+ stdio: ["ignore", out, err],
5528
+ detached: true,
5529
+ env: { ...process.env }
5530
+ }
5531
+ );
5532
+ child.unref();
5533
+ return child;
5534
+ }
5535
+ function startLocalProxyDetached(port, apiBaseUrl) {
5536
+ mkdirSync(PIDFILE_DIR, { recursive: true, mode: 448 });
5537
+ const logFile = join(PIDFILE_DIR, "proxy.log");
5538
+ const out = openSync(logFile, "a");
5539
+ const err = openSync(logFile, "a");
5540
+ const child = spawn("npx", ["multicorn-proxy"], {
5541
+ stdio: ["ignore", out, err],
5542
+ detached: true,
5543
+ env: {
5544
+ ...process.env,
5545
+ PORT: String(port),
5546
+ HOST: "127.0.0.1",
5547
+ SHIELD_API_BASE_URL: apiBaseUrl,
5548
+ // SAFETY: blanket-allow for private targets is acceptable ONLY because
5549
+ // this is a local single-user proxy. The only registered target is the
5550
+ // filesystem server on the same machine. Do NOT copy this pattern to a
5551
+ // multi-tenant or hosted proxy deployment.
5552
+ ALLOW_PRIVATE_TARGETS: "true"
5553
+ }
5554
+ });
5555
+ child.unref();
5556
+ return child;
5557
+ }
5558
+ async function ensureProxy(proxyPort, apiBaseUrl) {
5559
+ if (await probeProxyHealth(proxyPort)) {
5560
+ const reg2 = readProxyRegistry();
5561
+ const managed = reg2 !== null && reg2.port === proxyPort && isProcessAlive(reg2.pid);
5562
+ return { reused: true, managed };
5563
+ }
5564
+ const reg = readProxyRegistry();
5565
+ if (reg !== null && !isProcessAlive(reg.pid)) {
5566
+ try {
5567
+ unlinkSync(PROXY_REGISTRY);
5568
+ } catch {
5569
+ }
5570
+ }
5571
+ if (await isPortListening(proxyPort)) {
5572
+ throw new Error(
5573
+ `A server is already running on port ${String(proxyPort)} but it's not a healthy Shield proxy. Stop it or re-run with --proxy-port <n>.`
5574
+ );
5575
+ }
5576
+ const child = startLocalProxyDetached(proxyPort, apiBaseUrl);
5577
+ for (let i = 0; i < 30; i++) {
5578
+ await sleep3(500);
5579
+ if (await probeProxyHealth(proxyPort)) {
5580
+ if (child.pid !== void 0) {
5581
+ writeJsonFile(PROXY_REGISTRY, { pid: child.pid, port: proxyPort });
5582
+ }
5583
+ return { reused: false, managed: true };
5584
+ }
5585
+ }
5586
+ try {
5587
+ if (child.pid !== void 0) killWithEscalation(child.pid, true);
5588
+ } catch {
5589
+ }
5590
+ throw new Error(
5591
+ `Could not start the local proxy on port ${String(proxyPort)}. Check the log at ${join(PIDFILE_DIR, "proxy.log")}.`
5592
+ );
5593
+ }
5594
+ async function ensureFsServer(realDir, requestedPort) {
5595
+ const reg = readFsRegistry();
5596
+ const existing = reg[realDir];
5597
+ if (existing !== void 0 && isProcessAlive(existing.pid) && await isPortListening(existing.port)) {
5598
+ return { port: existing.port, reused: true };
5599
+ }
5600
+ if (existing !== void 0) {
5601
+ const rest = Object.fromEntries(Object.entries(reg).filter(([k]) => k !== realDir));
5602
+ writeJsonFile(FS_REGISTRY, rest);
5603
+ }
5604
+ let port;
5605
+ if (requestedPort !== void 0) {
5606
+ if (await isPortListening(requestedPort)) {
5607
+ throw new Error(
5608
+ `A server is already running on port ${String(requestedPort)}. Re-run without --port to auto-pick a free port, or choose another.`
5609
+ );
5610
+ }
5611
+ port = requestedPort;
5612
+ } else {
5613
+ const claimed = new Set(Object.values(readFsRegistry()).map((e) => e.port));
5614
+ port = await nextFreePort(DEFAULT_FS_PORT, claimed, isPortListening);
5615
+ }
5616
+ const child = startFsServerDetached(realDir, port);
5617
+ let ready = false;
5618
+ for (let i = 0; i < 20; i++) {
5619
+ await sleep3(500);
5620
+ if (await isPortListening(port)) {
5621
+ ready = true;
5622
+ break;
5623
+ }
5624
+ }
5625
+ if (!ready) {
5626
+ try {
5627
+ if (child.pid !== void 0) killWithEscalation(child.pid, true);
5628
+ } catch {
5629
+ }
5630
+ throw new Error(
5631
+ `Filesystem server failed to start on port ${String(port)}. Check the directory path and the log at ${join(PIDFILE_DIR, `fs-${String(port)}.log`)}.`
5632
+ );
5633
+ }
5634
+ if (child.pid !== void 0) {
5635
+ const next = readFsRegistry();
5636
+ next[realDir] = { pid: child.pid, port };
5637
+ writeJsonFile(FS_REGISTRY, next);
5638
+ }
5639
+ return { port, reused: false };
5640
+ }
5641
+ function releaseProxyIfUnused(proxyPort, stoppingAgent) {
5642
+ const remaining = agentsReferencingProxy(proxyPort, liveAgents(), stoppingAgent);
5643
+ if (remaining.length > 0) return;
5644
+ const reg = readProxyRegistry();
5645
+ if (reg !== null && reg.port === proxyPort && isProcessAlive(reg.pid)) {
5646
+ killWithEscalation(reg.pid, true);
5647
+ }
5648
+ if (reg !== null && reg.port === proxyPort) {
5649
+ try {
5650
+ unlinkSync(PROXY_REGISTRY);
5651
+ } catch {
5652
+ }
5653
+ }
5654
+ }
5655
+ function releaseFsServerIfUnused(folder, stoppingAgent) {
5656
+ const remaining = agentsReferencingFolder(folder, liveAgents(), stoppingAgent);
5657
+ if (remaining.length > 0) return;
5658
+ const reg = readFsRegistry();
5659
+ const entry = reg[folder];
5660
+ if (entry === void 0) return;
5661
+ if (isProcessAlive(entry.pid)) {
5662
+ killWithEscalation(entry.pid, true);
5663
+ }
5664
+ const rest = Object.fromEntries(Object.entries(reg).filter(([k]) => k !== folder));
5665
+ writeJsonFile(FS_REGISTRY, rest);
5666
+ }
5667
+ function proxyServerSlug(agentLabel) {
5668
+ const t = agentLabel.trim().toLowerCase();
5669
+ const slug = t.replace(/[^a-z0-9._-]/g, "-").replace(/^-+|-+$/g, "");
5670
+ if (slug === "") return "shield-handoff-agent";
5671
+ if (!/^[a-z0-9]/i.test(slug)) return `a-${slug}`;
5672
+ return slug.slice(0, 180);
5673
+ }
5674
+ async function registerAgentAndConfig(apiKey, baseUrl, agentName, fsPort, localDir) {
5675
+ const targetUrl = `http://127.0.0.1:${String(fsPort)}/mcp`;
5676
+ const serverName = proxyServerSlug(agentName);
5677
+ const response = await fetch(`${baseUrl}/api/v1/proxy/config`, {
5678
+ method: "POST",
5679
+ headers: {
5680
+ "Content-Type": "application/json",
5681
+ "X-Multicorn-Key": apiKey
5682
+ },
5683
+ body: JSON.stringify({
5684
+ server_name: serverName,
5685
+ target_url: targetUrl,
5686
+ platform: "other-mcp",
5687
+ agent_name: agentName,
5688
+ local_dir: localDir
5689
+ }),
5690
+ signal: AbortSignal.timeout(1e4)
5691
+ });
5692
+ if (!response.ok) {
5693
+ let detail = `HTTP ${String(response.status)}`;
5694
+ try {
5695
+ const body = await response.json();
5696
+ const errObj = body["error"];
5697
+ if (typeof errObj?.["message"] === "string") detail = errObj["message"];
5698
+ else if (typeof body["message"] === "string") detail = body["message"];
5699
+ } catch {
5700
+ }
5701
+ throw new Error(`Failed to register agent: ${detail}`);
5702
+ }
5703
+ const envelope = await response.json();
5704
+ const data = envelope["data"];
5705
+ const proxyUrl = typeof data?.["proxy_url"] === "string" ? data["proxy_url"] : "";
5706
+ if (proxyUrl.length === 0) {
5707
+ throw new Error("Registration succeeded but no proxy URL was returned.");
5708
+ }
5709
+ let pathSegment = "";
5710
+ try {
5711
+ const parsed = new URL(proxyUrl);
5712
+ pathSegment = parsed.pathname + parsed.search;
5713
+ } catch {
5714
+ pathSegment = proxyUrl;
5715
+ }
5716
+ await grantScope(apiKey, baseUrl, agentName, "filesystem", "read");
5717
+ return { proxyUrl, pathSegment };
5718
+ }
5719
+ async function sendHeartbeat(apiKey, baseUrl, serverName, proxyVersion) {
5720
+ try {
5721
+ await fetch(`${baseUrl}/api/v1/proxy/heartbeat`, {
5722
+ method: "POST",
5723
+ headers: {
5724
+ "Content-Type": "application/json",
5725
+ "X-Multicorn-Key": apiKey
5726
+ },
5727
+ // proxy_version lets the backend stamp the agent's last-seen version + timestamp
5728
+ // from the heartbeat, so the dashboard can flag an out-of-date proxy that needs a
5729
+ // restart even if the editor never connects through it.
5730
+ body: JSON.stringify(
5731
+ proxyVersion !== null ? { server_name: serverName, proxy_version: proxyVersion } : { server_name: serverName }
5732
+ ),
5733
+ signal: AbortSignal.timeout(8e3)
5734
+ });
5735
+ } catch {
5736
+ }
5737
+ }
5738
+ async function grantScope(apiKey, baseUrl, agentName, service, level) {
5739
+ const agentsResp = await fetch(`${baseUrl}/api/v1/agents`, {
5740
+ headers: { "X-Multicorn-Key": apiKey },
5741
+ signal: AbortSignal.timeout(8e3)
5742
+ });
5743
+ if (!agentsResp.ok) return;
5744
+ const agentsBody = await agentsResp.json();
5745
+ const agentsList = agentsBody["data"];
5746
+ if (!Array.isArray(agentsList)) return;
5747
+ const agent = agentsList.find((a) => a["name"] === agentName);
5748
+ if (!agent || typeof agent["id"] !== "string") return;
5749
+ const agentId = agent["id"];
5750
+ await fetch(`${baseUrl}/api/v1/agents/${agentId}/scopes`, {
5751
+ method: "POST",
5752
+ headers: {
5753
+ "Content-Type": "application/json",
5754
+ "X-Multicorn-Key": apiKey
5755
+ },
5756
+ body: JSON.stringify({ service, permission_level: level }),
5757
+ signal: AbortSignal.timeout(8e3)
5758
+ });
5759
+ }
5760
+ function killWithEscalation(pid, group = false) {
5761
+ const signal = (sig) => {
5762
+ if (group) {
5763
+ try {
5764
+ process.kill(-pid, sig);
5765
+ return;
5766
+ } catch {
5767
+ }
5768
+ }
5769
+ process.kill(pid, sig);
5770
+ };
5771
+ try {
5772
+ signal("SIGTERM");
5773
+ } catch {
5774
+ return;
5775
+ }
5776
+ const deadline = Date.now() + 3e3;
5777
+ while (Date.now() < deadline) {
5778
+ if (!isProcessAlive(pid)) return;
5779
+ spawnSync("sleep", ["0.1"], { stdio: "ignore" });
5780
+ }
5781
+ try {
5782
+ signal("SIGKILL");
5783
+ } catch {
5784
+ }
5785
+ }
5786
+ async function runStop(agent) {
5787
+ const data = readPidfile(agent);
5788
+ if (data === null) {
5789
+ process.stderr.write(`No running session found for agent "${agent}".
5790
+ `);
5791
+ process.exit(1);
5792
+ }
5793
+ await withResourceLock(() => {
5794
+ if (typeof data.supervisorPid === "number" && isProcessAlive(data.supervisorPid)) {
5795
+ killWithEscalation(data.supervisorPid);
5796
+ }
5797
+ removePidfile(agent);
5798
+ releaseFsServerIfUnused(data.dir, agent);
5799
+ releaseProxyIfUnused(data.proxyPort, agent);
5800
+ });
5801
+ process.stderr.write(`Stopped agent "${agent}".
5802
+ `);
5803
+ }
5804
+ async function runRestart(opts) {
5805
+ if (opts.agent.length === 0) {
5806
+ process.stderr.write("Error: --agent <name> is required for restart.\n");
5807
+ process.exit(1);
5808
+ }
5809
+ const existing = readPidfile(opts.agent);
5810
+ const dir = opts.dir.length > 0 ? opts.dir : existing?.dir ?? "";
5811
+ if (dir.length === 0) {
5812
+ process.stderr.write(
5813
+ `Don't know which folder to restart agent "${opts.agent}" with.
5814
+ Run it once with the folder: npx multicorn-shield files restart <dir> --agent ${opts.agent}
5815
+ `
5816
+ );
5817
+ process.exit(1);
5818
+ }
5819
+ if (existing !== null) {
5820
+ await runStop(opts.agent);
5821
+ }
5822
+ await runDetached({
5823
+ ...opts,
5824
+ dir,
5825
+ proxyPort: opts.proxyPort ?? existing?.proxyPort});
5826
+ }
5827
+ async function runDetached(opts) {
5828
+ const absDir = resolve(opts.dir);
5829
+ if (!existsSync(absDir)) {
5830
+ process.stderr.write(`Directory not found: ${opts.dir}. Check the path and try again.
5831
+ `);
5832
+ process.exit(1);
5833
+ }
5834
+ const existing = readPidfile(opts.agent);
5835
+ if (existing !== null) {
5836
+ const alive = typeof existing.supervisorPid === "number" && isProcessAlive(existing.supervisorPid);
5837
+ if (alive) {
5838
+ process.stderr.write(
5839
+ `Already running for agent "${opts.agent}" (fs :${String(existing.fsPort)}, proxy :${String(existing.proxyPort)}).
5840
+ Stop with: npx multicorn-shield files stop --agent ${opts.agent}
5841
+ `
5842
+ );
5843
+ return;
5844
+ }
5845
+ removePidfile(opts.agent);
5846
+ }
5847
+ const args = ["files", absDir, "--agent", opts.agent, "--foreground"];
5848
+ if (opts.port !== void 0) args.push("--port", String(opts.port));
5849
+ if (opts.proxyPort !== void 0) args.push("--proxy-port", String(opts.proxyPort));
5850
+ if (opts.apiKey !== void 0) args.push("--api-key", opts.apiKey);
5851
+ if (opts.baseUrl !== void 0) args.push("--base-url", opts.baseUrl);
5852
+ if (opts.client !== void 0) args.push("--client", opts.client);
5853
+ const scriptPath = process.argv[1] ?? resolve("dist/multicorn-shield.js");
5854
+ const logFile = join(PIDFILE_DIR, `files-${opts.agent}.log`);
5855
+ mkdirSync(PIDFILE_DIR, { recursive: true, mode: 448 });
5856
+ const out = openSync(logFile, "a");
5857
+ const err = openSync(logFile, "a");
5858
+ const child = spawn(process.execPath, [scriptPath, ...args], {
5859
+ detached: true,
5860
+ stdio: ["ignore", out, err],
5861
+ env: { ...process.env }
5862
+ });
5863
+ child.unref();
5864
+ let pidData = null;
5865
+ for (let i = 0; i < 60; i++) {
5866
+ await sleep3(500);
5867
+ pidData = readPidfile(opts.agent);
5868
+ if (pidData !== null) break;
5869
+ if (child.pid !== void 0 && !isProcessAlive(child.pid)) break;
5870
+ }
5871
+ if (pidData === null) {
5872
+ process.stderr.write(`Failed to start in background. Check logs: ${logFile}
5873
+ `);
5874
+ process.exit(1);
5875
+ }
5876
+ process.stderr.write("\n");
5877
+ process.stderr.write(
5878
+ ` ${style2.green("\u2713")} Setup complete. Shield is running in the background.
5879
+ `
5880
+ );
5881
+ process.stderr.write(` ${style2.green("\u2713")} Folder: ${absDir}
5882
+ `);
5883
+ process.stderr.write(
5884
+ ` ${style2.green("\u2713")} FS server :${String(pidData.fsPort)}, Proxy :${String(pidData.proxyPort)}
5885
+ `
5886
+ );
5887
+ process.stderr.write("\n");
5888
+ process.stderr.write(` Stop it any time with:
5889
+ `);
5890
+ process.stderr.write(
5891
+ ` ${style2.cyan(`npx multicorn-shield files stop --agent ${opts.agent}`)}
5892
+ `
5893
+ );
5894
+ process.stderr.write("\n");
5895
+ process.stderr.write(style2.dim(` Status: npx multicorn-shield files status
5896
+ `));
5897
+ process.stderr.write(style2.dim(` Logs: ${logFile}
5898
+ `));
5899
+ process.stderr.write("\n");
5900
+ }
5901
+ async function runFilesCommand(opts) {
5902
+ if (opts.status) {
5903
+ runStatus();
5904
+ return;
5905
+ }
5906
+ if (opts.restart) {
5907
+ await runRestart(opts);
5908
+ return;
5909
+ }
5910
+ if (opts.stop) {
5911
+ await runStop(opts.agent);
5912
+ return;
5913
+ }
5914
+ if (!opts.foreground) {
5915
+ await runDetached(opts);
5916
+ return;
5917
+ }
5918
+ const absDir = resolve(opts.dir);
5919
+ if (!existsSync(absDir)) {
5920
+ process.stderr.write(`Directory not found: ${opts.dir}. Check the path and try again.
5921
+ `);
5922
+ process.exit(1);
5923
+ }
5924
+ if (opts.baseUrl && !isAllowedShieldApiBaseUrl(opts.baseUrl)) {
5925
+ process.stderr.write(
5926
+ "Error: --base-url must use HTTPS or http://localhost for local development.\n"
5927
+ );
5928
+ process.exit(1);
5929
+ }
5930
+ const config = await resolveConfig(opts);
5931
+ const realDir = canonicalFolder(absDir);
5932
+ const proxyPort = opts.proxyPort ?? DEFAULT_PROXY_PORT;
5933
+ const existingPidfile = readPidfile(opts.agent);
5934
+ if (existingPidfile !== null) {
5935
+ const supervisorAlive = typeof existingPidfile.supervisorPid === "number" && isProcessAlive(existingPidfile.supervisorPid);
5936
+ if (supervisorAlive) {
5937
+ process.stderr.write(
5938
+ `A session for agent "${opts.agent}" is already running. Run 'files stop --agent ${opts.agent}' first, or use a different --agent name.
5939
+ `
5940
+ );
5941
+ process.exit(1);
5942
+ }
5943
+ removePidfile(opts.agent);
5944
+ }
5945
+ let fsPort;
5946
+ let proxyReused;
5947
+ let fsReused;
5948
+ try {
5949
+ const ensured = await withResourceLock(async () => {
5950
+ const proxyRes = await ensureProxy(proxyPort, config.baseUrl);
5951
+ const fsRes = await ensureFsServer(realDir, opts.port);
5952
+ writePidfile({
5953
+ agent: opts.agent,
5954
+ dir: realDir,
5955
+ supervisorPid: process.pid,
5956
+ fsPort: fsRes.port,
5957
+ proxyPort
5958
+ });
5959
+ return { proxyRes, fsRes };
5960
+ });
5961
+ fsPort = ensured.fsRes.port;
5962
+ proxyReused = ensured.proxyRes.reused;
5963
+ fsReused = ensured.fsRes.reused;
5964
+ } catch (error) {
5965
+ const msg = error instanceof Error ? error.message : String(error);
5966
+ process.stderr.write(`${msg}
5967
+ `);
5968
+ process.exit(1);
5969
+ }
5970
+ let registration;
5971
+ try {
5972
+ registration = await registerAgentAndConfig(
5973
+ config.apiKey,
5974
+ config.baseUrl,
5975
+ opts.agent,
5976
+ fsPort,
5977
+ realDir
5978
+ );
5979
+ } catch (error) {
5980
+ await withResourceLock(() => {
5981
+ removePidfile(opts.agent);
5982
+ releaseFsServerIfUnused(realDir, opts.agent);
5983
+ releaseProxyIfUnused(proxyPort, opts.agent);
5984
+ });
5985
+ const msg = error instanceof Error ? error.message : String(error);
5986
+ process.stderr.write(`Registration failed: ${msg}
5987
+ `);
5988
+ process.exit(1);
5989
+ }
5990
+ const heartbeatServerName = proxyServerSlug(opts.agent);
5991
+ const heartbeatTick = async () => {
5992
+ const proxyVersion = await readProxyVersion(proxyPort);
5993
+ const proxyOk = proxyVersion !== null || await probeProxyHealth(proxyPort);
5994
+ const fsOk = await isPortListening(fsPort);
5995
+ if (proxyOk && fsOk) {
5996
+ await sendHeartbeat(config.apiKey, config.baseUrl, heartbeatServerName, proxyVersion);
5997
+ }
5998
+ };
5999
+ void heartbeatTick();
6000
+ const heartbeatTimer = setInterval(() => {
6001
+ void heartbeatTick();
6002
+ }, HEARTBEAT_INTERVAL_MS);
6003
+ let cleaningUp = false;
6004
+ process.on("SIGINT", () => {
6005
+ if (cleaningUp) return;
6006
+ cleaningUp = true;
6007
+ void (async () => {
6008
+ clearInterval(heartbeatTimer);
6009
+ await withResourceLock(() => {
6010
+ removePidfile(opts.agent);
6011
+ releaseFsServerIfUnused(realDir, opts.agent);
6012
+ releaseProxyIfUnused(proxyPort, opts.agent);
6013
+ });
6014
+ process.exit(0);
6015
+ })();
6016
+ });
6017
+ process.on("SIGTERM", () => {
6018
+ clearInterval(heartbeatTimer);
6019
+ removePidfile(opts.agent);
6020
+ process.exit(0);
6021
+ });
6022
+ const dirLabel = `./${basename(absDir)}`;
6023
+ const localProxyUrl = `http://127.0.0.1:${String(proxyPort)}${registration.pathSegment}`;
6024
+ process.stderr.write("\n");
6025
+ process.stderr.write(
6026
+ ` ${style2.green("\u2713")} ${proxyReused ? "Reusing shared proxy" : "Local proxy running"} (:${String(proxyPort)})
6027
+ `
6028
+ );
6029
+ process.stderr.write(
6030
+ ` ${style2.green("\u2713")} ${fsReused ? "Reusing filesystem server for" : "Filesystem server on"} ${dirLabel} (:${String(fsPort)})
6031
+ `
6032
+ );
6033
+ process.stderr.write(` ${style2.green("\u2713")} Agent '${opts.agent}' registered with Shield
6034
+ `);
6035
+ const writeResult = await autoWriteClientConfig(
6036
+ opts.client,
6037
+ opts.agent,
6038
+ localProxyUrl,
6039
+ config.apiKey,
6040
+ absDir
6041
+ );
6042
+ const firstWritten = writeResult.written[0];
6043
+ if (firstWritten !== void 0) {
6044
+ for (const w of writeResult.written) {
6045
+ process.stderr.write(` ${style2.green("\u2713")} Config written to ${style2.cyan(w.path)}
6046
+ `);
6047
+ }
6048
+ process.stderr.write("\n");
6049
+ process.stderr.write(style2.dim(` ${firstWritten.reload}
6050
+ `));
6051
+ } else if (!writeResult.prompted) {
6052
+ process.stderr.write("\n");
6053
+ process.stderr.write(
6054
+ " Add this to your coding agent's MCP config so it routes through Shield:\n\n"
6055
+ );
6056
+ const configBlock = JSON.stringify(
6057
+ {
6058
+ mcpServers: {
6059
+ [opts.agent]: {
6060
+ url: hostedProxyUrlWithKeyParam(localProxyUrl, config.apiKey),
6061
+ headers: { Authorization: `Bearer ${config.apiKey}` }
6062
+ }
6063
+ }
6064
+ },
6065
+ null,
6066
+ 2
6067
+ );
6068
+ process.stderr.write(style2.cyan(configBlock) + "\n\n");
6069
+ }
6070
+ process.stderr.write(style2.dim(" Write and delete will ask for approval the first time.\n"));
6071
+ process.stderr.write("\n");
6072
+ process.stderr.write(
6073
+ ` ${style2.green("\u2713")} Shield is running (foreground mode). Press Ctrl-C to stop.
6074
+ `
6075
+ );
6076
+ process.stderr.write("\n");
6077
+ }
6078
+ async function autoWriteClientConfig(clientFlag, agentName, localProxyUrl, apiKey, workspacePath) {
6079
+ if (clientFlag !== void 0 && clientFlag.length > 0) {
6080
+ if (clientFlag === "all") {
6081
+ const detected2 = detectInstalledClients();
6082
+ if (detected2.length === 0) return { written: [], prompted: false };
6083
+ const results = [];
6084
+ for (const c of detected2) {
6085
+ const path2 = await writeLocalMcpEntry(c, agentName, localProxyUrl, apiKey, workspacePath);
6086
+ if (path2 !== null) {
6087
+ results.push({ client: c, path: path2, reload: clientReloadInstruction(c) });
6088
+ }
6089
+ }
6090
+ return { written: results, prompted: false };
6091
+ }
6092
+ const client2 = clientFlag;
6093
+ if (!CODING_CLIENTS.includes(client2)) {
6094
+ process.stderr.write(
6095
+ `
6096
+ Unknown --client "${clientFlag}". Valid options: ${CODING_CLIENTS.join(", ")}, all
6097
+ `
6098
+ );
6099
+ return { written: [], prompted: false };
6100
+ }
6101
+ const path = await writeLocalMcpEntry(client2, agentName, localProxyUrl, apiKey, workspacePath);
6102
+ if (path !== null) {
6103
+ return {
6104
+ written: [{ client: client2, path, reload: clientReloadInstruction(client2) }],
6105
+ prompted: false
6106
+ };
6107
+ }
6108
+ process.stderr.write(
6109
+ `
6110
+ Could not write to ${clientDisplayName(client2)} config (parse error or permissions).
6111
+ `
6112
+ );
6113
+ return { written: [], prompted: false };
6114
+ }
6115
+ const detected = detectInstalledClients();
6116
+ if (detected.length === 0) {
6117
+ return { written: [], prompted: false };
6118
+ }
6119
+ if (detected.length === 1) {
6120
+ const client2 = detected[0];
6121
+ if (client2 === void 0) {
6122
+ return { written: [], prompted: false };
6123
+ }
6124
+ const path = await writeLocalMcpEntry(client2, agentName, localProxyUrl, apiKey, workspacePath);
6125
+ if (path !== null) {
6126
+ return {
6127
+ written: [{ client: client2, path, reload: clientReloadInstruction(client2) }],
6128
+ prompted: false
6129
+ };
6130
+ }
6131
+ process.stderr.write(
6132
+ `
6133
+ Could not safely update ${clientDisplayName(client2)} config (parse error or permissions). Left it unchanged.
6134
+ `
6135
+ );
6136
+ return { written: [], prompted: false };
6137
+ }
6138
+ if (!process.stdin.isTTY) {
6139
+ process.stderr.write("\n");
6140
+ process.stderr.write(" Multiple coding agents detected:\n");
6141
+ for (const c of detected) {
6142
+ process.stderr.write(` - ${clientDisplayName(c)} (--client ${c})
6143
+ `);
6144
+ }
6145
+ process.stderr.write(
6146
+ "\n Re-run with --client <name> to write config, or --client all for all.\n"
6147
+ );
6148
+ return { written: [], prompted: true };
6149
+ }
6150
+ process.stderr.write("\n");
6151
+ process.stderr.write(" Multiple coding agents detected. Which should route through Shield?\n\n");
6152
+ for (const [i, c] of detected.entries()) {
6153
+ process.stderr.write(` ${String(i + 1)}) ${clientDisplayName(c)}
6154
+ `);
6155
+ }
6156
+ process.stderr.write(` a) All of them
6157
+ `);
6158
+ process.stderr.write("\n");
6159
+ const choice = await promptLine(" Enter number (or 'a' for all): ");
6160
+ const trimmed = choice.trim().toLowerCase();
6161
+ if (trimmed === "a" || trimmed === "all") {
6162
+ const results = [];
6163
+ for (const c of detected) {
6164
+ const path = await writeLocalMcpEntry(c, agentName, localProxyUrl, apiKey, workspacePath);
6165
+ if (path !== null) {
6166
+ results.push({ client: c, path, reload: clientReloadInstruction(c) });
6167
+ }
6168
+ }
6169
+ return { written: results, prompted: false };
6170
+ }
6171
+ const num = Number.parseInt(trimmed, 10);
6172
+ const client = num >= 1 && num <= detected.length ? detected[num - 1] : void 0;
6173
+ if (client !== void 0) {
6174
+ const path = await writeLocalMcpEntry(client, agentName, localProxyUrl, apiKey, workspacePath);
6175
+ if (path !== null) {
6176
+ return {
6177
+ written: [{ client, path, reload: clientReloadInstruction(client) }],
6178
+ prompted: false
6179
+ };
6180
+ }
6181
+ }
6182
+ process.stderr.write(` Invalid choice. Use --client <name> next time.
6183
+ `);
6184
+ return { written: [], prompted: true };
6185
+ }
6186
+ function promptLine(question) {
6187
+ return new Promise((resolve3) => {
6188
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
6189
+ rl.question(question, (answer) => {
6190
+ rl.close();
6191
+ resolve3(answer);
6192
+ });
6193
+ });
6194
+ }
6195
+ var DEFAULT_FS_PORT, DEFAULT_PROXY_PORT, PIDFILE_DIR, PROXY_REGISTRY, FS_REGISTRY, LOCK_PATH, LOCK_WAIT_MS, LOCK_STALE_MS, FS_PORT_SCAN_RANGE, style2, HEARTBEAT_INTERVAL_MS;
6196
+ var init_files = __esm({
6197
+ "src/commands/files.ts"() {
6198
+ init_config();
6199
+ DEFAULT_FS_PORT = 3005;
6200
+ DEFAULT_PROXY_PORT = 3001;
6201
+ PIDFILE_DIR = process.env["MULTICORN_HOME"] ?? join(homedir(), ".multicorn");
6202
+ PROXY_REGISTRY = join(PIDFILE_DIR, "proxy.json");
6203
+ FS_REGISTRY = join(PIDFILE_DIR, "fs-servers.json");
6204
+ LOCK_PATH = join(PIDFILE_DIR, ".resources.lock");
6205
+ LOCK_WAIT_MS = 6e4;
6206
+ LOCK_STALE_MS = 12e4;
6207
+ FS_PORT_SCAN_RANGE = 200;
6208
+ style2 = {
6209
+ green: (s) => `\x1B[38;2;34;197;94m${s}\x1B[0m`,
6210
+ cyan: (s) => `\x1B[38;2;6;182;212m${s}\x1B[0m`,
6211
+ dim: (s) => `\x1B[2m${s}\x1B[0m`,
6212
+ bold: (s) => `\x1B[1m${s}\x1B[0m`
6213
+ };
6214
+ HEARTBEAT_INTERVAL_MS = 3e4;
6215
+ }
6216
+ });
6217
+
6218
+ // bin/multicorn-shield.ts
6219
+ var multicorn_shield_exports = {};
6220
+ __export(multicorn_shield_exports, {
6221
+ parseArgs: () => parseArgs,
6222
+ resolveWrapConfig: () => resolveWrapConfig,
6223
+ runCli: () => runCli
6224
+ });
6225
+ function parseArgs(argv) {
6226
+ const args = argv.slice(2);
6227
+ let subcommand = "help";
6228
+ let wrapCommand = "";
6229
+ let wrapArgs = [];
6230
+ let logLevel = "info";
6231
+ let baseUrl = void 0;
6232
+ let dashboardUrl = "";
6233
+ let agentName = "";
6234
+ let deleteAgentName = "";
6235
+ let apiKey = void 0;
6236
+ let verbose = false;
6237
+ let filesDir = "";
6238
+ let filesPort = void 0;
6239
+ let filesProxyPort = void 0;
6240
+ let filesStop = false;
6241
+ let filesClient = void 0;
6242
+ let filesForeground = false;
6243
+ let filesStatus = false;
6244
+ let filesRestart = false;
6245
+ for (let i = 0; i < args.length; i++) {
6246
+ const arg = args[i];
6247
+ if (arg === "init") {
6248
+ subcommand = "init";
6249
+ } else if (arg === "files") {
6250
+ subcommand = "files";
6251
+ const tail = args.slice(i + 1);
6252
+ for (let j = 0; j < tail.length; j++) {
6253
+ const token = tail[j];
6254
+ if (token === void 0) continue;
6255
+ if (token === "--agent") {
6256
+ const value = tail[j + 1];
6257
+ if (value !== void 0) {
6258
+ agentName = value;
6259
+ j++;
6260
+ }
6261
+ } else if (token === "--port") {
6262
+ const value = tail[j + 1];
6263
+ if (value !== void 0) {
6264
+ filesPort = Number.parseInt(value, 10);
6265
+ j++;
6266
+ }
6267
+ } else if (token === "--proxy-port") {
6268
+ const value = tail[j + 1];
6269
+ if (value !== void 0) {
6270
+ filesProxyPort = Number.parseInt(value, 10);
6271
+ j++;
6272
+ }
6273
+ } else if (token === "--api-key") {
6274
+ const value = tail[j + 1];
6275
+ if (value !== void 0) {
6276
+ apiKey = value;
6277
+ j++;
6278
+ }
6279
+ } else if (token === "--base-url") {
6280
+ const value = tail[j + 1];
6281
+ if (value !== void 0) {
6282
+ baseUrl = value;
6283
+ j++;
6284
+ }
6285
+ } else if (token === "--client") {
6286
+ const value = tail[j + 1];
6287
+ if (value !== void 0) {
6288
+ filesClient = value;
6289
+ j++;
6290
+ }
6291
+ } else if (token === "--stop") {
6292
+ filesStop = true;
6293
+ } else if (token === "--foreground") {
6294
+ filesForeground = true;
6295
+ } else if (token === "--detach") ; else if (token === "stop") {
6296
+ filesStop = true;
6297
+ } else if (token === "status") {
6298
+ filesStatus = true;
6299
+ } else if (token === "restart") {
6300
+ filesRestart = true;
6301
+ } else if (!token.startsWith("-") && filesDir === "") {
6302
+ filesDir = token;
6303
+ }
6304
+ }
6305
+ break;
6306
+ } else if (arg === "agents") {
6307
+ subcommand = "agents";
6308
+ } else if (arg === "delete-agent") {
6309
+ subcommand = "delete-agent";
6310
+ const name = args[i + 1];
6311
+ if (name === void 0 || name.startsWith("-")) {
6312
+ process.stderr.write("Error: delete-agent requires an agent name.\n");
6313
+ process.stderr.write("Example: npx multicorn-shield delete-agent my-agent\n");
6314
+ process.exit(1);
6315
+ }
6316
+ deleteAgentName = name;
6317
+ i++;
6318
+ } else if (arg === "--wrap") {
6319
+ subcommand = "wrap";
6320
+ const tail = args.slice(i + 1);
6321
+ const remaining = [];
6322
+ for (let j = 0; j < tail.length; j++) {
6323
+ const token = tail[j];
6324
+ if (token === void 0) continue;
6325
+ if (remaining.length > 0) {
6326
+ remaining.push(token);
6327
+ continue;
6328
+ }
6329
+ if (token === "--agent-name") {
6330
+ const value = tail[j + 1];
6331
+ if (value !== void 0) {
6332
+ agentName = value;
6333
+ j++;
6334
+ }
6335
+ } else if (token === "--log-level") {
6336
+ const value = tail[j + 1];
6337
+ if (value !== void 0 && isValidLogLevel(value)) {
6338
+ logLevel = value;
6339
+ j++;
6340
+ }
6341
+ } else if (token === "--base-url") {
6342
+ const value = tail[j + 1];
6343
+ if (value !== void 0) {
6344
+ baseUrl = value;
6345
+ j++;
6346
+ }
6347
+ } else if (token === "--dashboard-url") {
6348
+ const value = tail[j + 1];
6349
+ if (value !== void 0) {
6350
+ dashboardUrl = value;
6351
+ j++;
6352
+ }
6353
+ } else if (token === "--api-key") {
6354
+ const value = tail[j + 1];
6355
+ if (value !== void 0) {
6356
+ apiKey = value;
6357
+ j++;
6358
+ }
6359
+ } else {
6360
+ remaining.push(token);
6361
+ }
6362
+ }
6363
+ if (remaining.length === 0) {
6364
+ process.stderr.write("Error: --wrap requires a command to run.\n");
6365
+ process.stderr.write("Example: npx multicorn-shield --wrap my-mcp-server\n");
6366
+ process.exit(1);
6367
+ }
6368
+ wrapCommand = remaining[0] ?? "";
6369
+ wrapArgs = remaining.slice(1);
6370
+ break;
6371
+ } else if (arg === "--log-level") {
6372
+ const next = args[i + 1];
6373
+ if (next !== void 0 && isValidLogLevel(next)) {
6374
+ logLevel = next;
6375
+ i++;
6376
+ }
6377
+ } else if (arg === "--base-url") {
6378
+ const next = args[i + 1];
6379
+ if (next !== void 0) {
6380
+ baseUrl = next;
6381
+ i++;
6382
+ }
6383
+ } else if (arg === "--dashboard-url") {
6384
+ const next = args[i + 1];
6385
+ if (next !== void 0) {
6386
+ dashboardUrl = next;
6387
+ i++;
6388
+ }
6389
+ } else if (arg === "--agent-name") {
6390
+ const next = args[i + 1];
6391
+ if (next !== void 0) {
6392
+ agentName = next;
6393
+ i++;
6394
+ }
6395
+ } else if (arg === "--api-key") {
6396
+ const next = args[i + 1];
6397
+ if (next !== void 0) {
6398
+ apiKey = next;
6399
+ i++;
6400
+ }
6401
+ } else if (arg === "--verbose" || arg === "--debug") {
6402
+ verbose = true;
6403
+ }
6404
+ }
6405
+ return {
6406
+ subcommand,
6407
+ wrapCommand,
6408
+ wrapArgs,
6409
+ logLevel,
6410
+ baseUrl,
6411
+ dashboardUrl,
6412
+ agentName,
6413
+ deleteAgentName,
6414
+ apiKey,
6415
+ verbose,
6416
+ filesDir,
6417
+ filesPort,
6418
+ filesProxyPort,
6419
+ filesStop,
6420
+ filesClient,
6421
+ filesForeground,
6422
+ filesStatus,
6423
+ filesRestart
6424
+ };
6425
+ }
6426
+ function printHelp() {
6427
+ process.stderr.write(
6428
+ [
6429
+ "multicorn-shield: MCP permission proxy and Shield setup",
6430
+ "",
6431
+ "Usage:",
6432
+ " npx multicorn-shield init",
6433
+ " Interactive setup. Saves API key to ~/.multicorn/config.json.",
6434
+ "",
6435
+ " npx multicorn-shield files <dir> --agent <name> [--client <client>]",
6436
+ " Share a local folder with a coding agent. Starts a filesystem MCP server",
6437
+ " scoped to <dir>, registers the agent, writes your coding agent's MCP config,",
6438
+ " then exits. The service runs in the background until stopped.",
6439
+ "",
6440
+ " --client <name> Target client: cursor, cline, windsurf, claude, copilot,",
6441
+ " goose, gemini, codex, continue, kilo, opencode",
6442
+ " Auto-detected if omitted. Use --client all to write to every",
6443
+ " detected client.",
6444
+ " --foreground Keep the terminal open (for debugging). Default is background.",
6445
+ " --stop Tear down the servers started by a previous `files` invocation.",
6446
+ "",
6447
+ " npx multicorn-shield files stop --agent <name>",
6448
+ " Stop background processes for the named agent.",
6449
+ "",
6450
+ " npx multicorn-shield files restart --agent <name>",
6451
+ " Stop then start the named agent, reusing the folder from its last run.",
6452
+ " Rewrites the coding agent's MCP config entry, so this repairs a stale",
6453
+ " entry that a plain stop/start would leave in place.",
6454
+ "",
6455
+ " npx multicorn-shield files status",
6456
+ " Show all running file-sharing sessions.",
6457
+ "",
6458
+ " npx multicorn-shield restore",
6459
+ " Restore MCP servers in claude_desktop_config.json from the Shield extension backup.",
6460
+ "",
5080
6461
  " npx multicorn-shield agents",
5081
6462
  " List configured agents and show which is the default.",
5082
6463
  "",
@@ -5098,6 +6479,11 @@ function printHelp() {
5098
6479
  "",
5099
6480
  "Examples:",
5100
6481
  " npx multicorn-shield init",
6482
+ " npx multicorn-shield files ./my-repo --agent my-agent",
6483
+ " npx multicorn-shield files ./my-repo --agent my-agent --foreground",
6484
+ " npx multicorn-shield files status",
6485
+ " npx multicorn-shield files stop --agent my-agent",
6486
+ " npx multicorn-shield files restart --agent my-agent",
5101
6487
  " npx multicorn-shield --wrap npx @modelcontextprotocol/server-filesystem /tmp",
5102
6488
  " npx multicorn-shield --wrap my-mcp-server --log-level debug",
5103
6489
  ""
@@ -5128,6 +6514,48 @@ async function runCli() {
5128
6514
  await runInit(cli.baseUrl, { verbose: cli.verbose });
5129
6515
  return;
5130
6516
  }
6517
+ if (cli.subcommand === "files") {
6518
+ if (cli.filesStatus) {
6519
+ await runFilesCommand({
6520
+ dir: "",
6521
+ agent: "",
6522
+ port: void 0,
6523
+ proxyPort: void 0,
6524
+ apiKey: void 0,
6525
+ baseUrl: void 0,
6526
+ stop: false,
6527
+ client: void 0,
6528
+ foreground: true,
6529
+ status: true,
6530
+ restart: false
6531
+ });
6532
+ return;
6533
+ }
6534
+ if (!cli.filesStop && cli.agentName.length === 0) {
6535
+ process.stderr.write("Error: --agent <name> is required for the files command.\n");
6536
+ process.stderr.write("Example: npx multicorn-shield files ./my-repo --agent my-agent\n");
6537
+ process.exit(1);
6538
+ }
6539
+ if (!cli.filesStop && !cli.filesRestart && cli.filesDir.length === 0) {
6540
+ process.stderr.write("Error: a directory path is required.\n");
6541
+ process.stderr.write("Example: npx multicorn-shield files ./my-repo --agent my-agent\n");
6542
+ process.exit(1);
6543
+ }
6544
+ await runFilesCommand({
6545
+ dir: cli.filesDir,
6546
+ agent: cli.agentName,
6547
+ port: cli.filesPort,
6548
+ proxyPort: cli.filesProxyPort,
6549
+ apiKey: cli.apiKey,
6550
+ baseUrl: cli.baseUrl,
6551
+ stop: cli.filesStop,
6552
+ client: cli.filesClient,
6553
+ foreground: cli.filesForeground,
6554
+ status: false,
6555
+ restart: cli.filesRestart
6556
+ });
6557
+ return;
6558
+ }
5131
6559
  if (cli.subcommand === "agents") {
5132
6560
  const config2 = await loadConfig();
5133
6561
  if (config2 === null) {
@@ -5265,6 +6693,7 @@ var init_multicorn_shield = __esm({
5265
6693
  init_consent();
5266
6694
  init_restore();
5267
6695
  init_package_meta();
6696
+ init_files();
5268
6697
  isDirectRun = process.argv[1] !== void 0 && (import.meta.url.endsWith(process.argv[1]) || import.meta.url === `file://${process.argv[1]}` || import.meta.url.endsWith("/multicorn-shield.js") || import.meta.url.endsWith("/multicorn-shield.ts"));
5269
6698
  if (isDirectRun && process.env["VITEST"] === void 0) {
5270
6699
  runCli().catch((error) => {