@boxes-dev/dvb-runtime 1.0.1079 → 1.0.1081

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/bin/dvb.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="249a0abb-e483-5aa3-b76c-e668263ae2b8")}catch(e){}}();
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4b9bb473-e618-5a79-8a86-c0fdba0f0295")}catch(e){}}();
4
4
  import { createRequire as __dvbCreateRequire } from "node:module";
5
5
  import { dirname as __dvbDirname } from "node:path";
6
6
  import { fileURLToPath as __dvbFileURLToPath } from "node:url";
@@ -5515,12 +5515,453 @@ var init_codexLocalImageFrame = __esm({
5515
5515
  });
5516
5516
 
5517
5517
  // ../../../../shared/devboxCore/dist/mcpCommandImport.js
5518
- var MCP_COMMAND_IMPORT_MAX_INPUT_CHARS, MCP_COMMAND_IMPORT_MAX_ARG_CHARS;
5518
+ var MCP_COMMAND_IMPORT_MAX_INPUT_CHARS, MCP_COMMAND_IMPORT_MAX_ARG_CHARS, MCP_COMMAND_IMPORT_MAX_ARGS, invalid, templateManaged, tokenizePastedCommand, NATIVE_NAME_PATTERN, HEADER_NAME_PATTERN, ENV_NAME_PATTERN, isValidMcpNativeName, nameFromUrl, parseHttpsUrl, parseHeader, hasDuplicateHeaders, readOptionValue, parseCodexAdd, parseClaudeAdd, parseMcpAddArgv, parseMcpCommandImport;
5519
5519
  var init_mcpCommandImport = __esm({
5520
5520
  "../../../../shared/devboxCore/dist/mcpCommandImport.js"() {
5521
5521
  "use strict";
5522
5522
  MCP_COMMAND_IMPORT_MAX_INPUT_CHARS = 16 * 1024;
5523
5523
  MCP_COMMAND_IMPORT_MAX_ARG_CHARS = 8 * 1024;
5524
+ MCP_COMMAND_IMPORT_MAX_ARGS = 128;
5525
+ invalid = (code2, message) => ({ kind: "invalid", code: code2, message });
5526
+ templateManaged = (agent, reason, message) => ({
5527
+ kind: "template_managed",
5528
+ agent,
5529
+ reason,
5530
+ message
5531
+ });
5532
+ tokenizePastedCommand = (input) => {
5533
+ const value = input.trim();
5534
+ if (!value) {
5535
+ return {
5536
+ kind: "error",
5537
+ code: "empty",
5538
+ message: "Paste an MCP URL or setup command."
5539
+ };
5540
+ }
5541
+ if (value.length > MCP_COMMAND_IMPORT_MAX_INPUT_CHARS) {
5542
+ return {
5543
+ kind: "error",
5544
+ code: "too_large",
5545
+ message: "The pasted MCP setup command is too large."
5546
+ };
5547
+ }
5548
+ if (value.includes("\0") || /[\r\n]/.test(value)) {
5549
+ return {
5550
+ kind: "error",
5551
+ code: "unsafe_shell_syntax",
5552
+ message: "Paste exactly one MCP setup command without shell control syntax."
5553
+ };
5554
+ }
5555
+ const argv = [];
5556
+ let current = "";
5557
+ let quote2 = null;
5558
+ let escaped = false;
5559
+ let started = false;
5560
+ const push = () => {
5561
+ if (!started) {
5562
+ return;
5563
+ }
5564
+ argv.push(current);
5565
+ current = "";
5566
+ started = false;
5567
+ };
5568
+ for (const character of value) {
5569
+ if (escaped) {
5570
+ current += character;
5571
+ escaped = false;
5572
+ started = true;
5573
+ continue;
5574
+ }
5575
+ if (quote2 === "single") {
5576
+ if (character === "'") {
5577
+ quote2 = null;
5578
+ } else {
5579
+ current += character;
5580
+ }
5581
+ started = true;
5582
+ continue;
5583
+ }
5584
+ if (quote2 === "double") {
5585
+ if (character === '"') {
5586
+ quote2 = null;
5587
+ started = true;
5588
+ continue;
5589
+ }
5590
+ if (character === "\\") {
5591
+ escaped = true;
5592
+ continue;
5593
+ }
5594
+ if (character === "$" || character === "`") {
5595
+ return {
5596
+ kind: "error",
5597
+ code: "unsafe_shell_syntax",
5598
+ message: "Shell substitutions are not allowed in pasted MCP commands."
5599
+ };
5600
+ }
5601
+ current += character;
5602
+ started = true;
5603
+ continue;
5604
+ }
5605
+ if (/\s/.test(character)) {
5606
+ push();
5607
+ continue;
5608
+ }
5609
+ if (character === "'") {
5610
+ quote2 = "single";
5611
+ started = true;
5612
+ continue;
5613
+ }
5614
+ if (character === '"') {
5615
+ quote2 = "double";
5616
+ started = true;
5617
+ continue;
5618
+ }
5619
+ if (character === "\\") {
5620
+ escaped = true;
5621
+ started = true;
5622
+ continue;
5623
+ }
5624
+ if (";&|<>`(){}[]".includes(character) || character === "$") {
5625
+ return {
5626
+ kind: "error",
5627
+ code: "unsafe_shell_syntax",
5628
+ message: "Shell operators and substitutions are not allowed in pasted MCP commands."
5629
+ };
5630
+ }
5631
+ current += character;
5632
+ started = true;
5633
+ }
5634
+ if (quote2 !== null || escaped) {
5635
+ return {
5636
+ kind: "error",
5637
+ code: "unterminated_quote",
5638
+ message: "The pasted MCP setup command has an unfinished quote or escape."
5639
+ };
5640
+ }
5641
+ push();
5642
+ if (argv.length === 0 || argv.length > MCP_COMMAND_IMPORT_MAX_ARGS || argv.some((entry) => entry.length > MCP_COMMAND_IMPORT_MAX_ARG_CHARS)) {
5643
+ return {
5644
+ kind: "error",
5645
+ code: "too_large",
5646
+ message: "The pasted MCP setup command is too large."
5647
+ };
5648
+ }
5649
+ return { kind: "ok", argv };
5650
+ };
5651
+ NATIVE_NAME_PATTERN = /^[A-Za-z0-9_-]+$/;
5652
+ HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
5653
+ ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
5654
+ isValidMcpNativeName = (value) => value.length > 0 && value.length <= 128 && NATIVE_NAME_PATTERN.test(value);
5655
+ nameFromUrl = (url3) => {
5656
+ const parts = url3.hostname.toLowerCase().split(".").filter(Boolean);
5657
+ const preferred = parts.find((part) => part !== "www" && part !== "mcp") ?? "mcp";
5658
+ const normalized = preferred.replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 128);
5659
+ return normalized || "mcp";
5660
+ };
5661
+ parseHttpsUrl = (value) => {
5662
+ try {
5663
+ const url3 = new URL(value);
5664
+ if (url3.protocol !== "https:" || !url3.hostname || url3.username || url3.password || url3.hash) {
5665
+ return null;
5666
+ }
5667
+ return url3;
5668
+ } catch {
5669
+ return null;
5670
+ }
5671
+ };
5672
+ parseHeader = (value) => {
5673
+ const separator = value.indexOf(":");
5674
+ if (separator <= 0) {
5675
+ return null;
5676
+ }
5677
+ const name = value.slice(0, separator).trim();
5678
+ const headerValue = value.slice(separator + 1).trim();
5679
+ if (!HEADER_NAME_PATTERN.test(name) || /[\r\n]/.test(headerValue) || headerValue.length === 0) {
5680
+ return null;
5681
+ }
5682
+ return { name, value: headerValue };
5683
+ };
5684
+ hasDuplicateHeaders = (headers) => {
5685
+ const names = /* @__PURE__ */ new Set();
5686
+ for (const header of headers) {
5687
+ const normalized = header.name.toLowerCase();
5688
+ if (names.has(normalized)) {
5689
+ return true;
5690
+ }
5691
+ names.add(normalized);
5692
+ }
5693
+ return false;
5694
+ };
5695
+ readOptionValue = ({ argv, index, option }) => {
5696
+ const entry = argv[index] ?? "";
5697
+ const equalsPrefix = `${option}=`;
5698
+ if (entry.startsWith(equalsPrefix)) {
5699
+ const value2 = entry.slice(equalsPrefix.length);
5700
+ return value2 ? { value: value2, nextIndex: index } : invalid("missing_value", `${option} requires a value.`);
5701
+ }
5702
+ const value = argv[index + 1];
5703
+ return value && value !== "--" ? { value, nextIndex: index + 1 } : invalid("missing_value", `${option} requires a value.`);
5704
+ };
5705
+ parseCodexAdd = (argv) => {
5706
+ const args = argv.slice(3);
5707
+ let name = null;
5708
+ let urlValue = null;
5709
+ let bearerTokenEnvVar = null;
5710
+ let templateReason = null;
5711
+ for (let index = 0; index < args.length; index += 1) {
5712
+ const entry = args[index] ?? "";
5713
+ if (entry === "--") {
5714
+ templateReason = "stdio";
5715
+ break;
5716
+ }
5717
+ if (entry === "--env" || entry.startsWith("--env=")) {
5718
+ const parsed = readOptionValue({ argv: args, index, option: "--env" });
5719
+ if ("kind" in parsed)
5720
+ return parsed;
5721
+ index = parsed.nextIndex;
5722
+ templateReason = "stdio";
5723
+ continue;
5724
+ }
5725
+ if (entry === "--url" || entry.startsWith("--url=")) {
5726
+ const parsed = readOptionValue({ argv: args, index, option: "--url" });
5727
+ if ("kind" in parsed)
5728
+ return parsed;
5729
+ if (urlValue !== null) {
5730
+ return invalid("unknown_option", "Codex --url may be provided only once.");
5731
+ }
5732
+ urlValue = parsed.value;
5733
+ index = parsed.nextIndex;
5734
+ continue;
5735
+ }
5736
+ if (entry === "--bearer-token-env-var" || entry.startsWith("--bearer-token-env-var=")) {
5737
+ const parsed = readOptionValue({
5738
+ argv: args,
5739
+ index,
5740
+ option: "--bearer-token-env-var"
5741
+ });
5742
+ if ("kind" in parsed)
5743
+ return parsed;
5744
+ if (!ENV_NAME_PATTERN.test(parsed.value)) {
5745
+ return invalid("missing_value", "--bearer-token-env-var requires a valid environment variable name.");
5746
+ }
5747
+ bearerTokenEnvVar = parsed.value;
5748
+ index = parsed.nextIndex;
5749
+ continue;
5750
+ }
5751
+ if (entry === "--oauth-client-id" || entry.startsWith("--oauth-client-id=") || entry === "--oauth-resource" || entry.startsWith("--oauth-resource=")) {
5752
+ const option = entry.startsWith("--oauth-client-id") ? "--oauth-client-id" : "--oauth-resource";
5753
+ const parsed = readOptionValue({ argv: args, index, option });
5754
+ if ("kind" in parsed)
5755
+ return parsed;
5756
+ index = parsed.nextIndex;
5757
+ templateReason = "custom_oauth_client";
5758
+ continue;
5759
+ }
5760
+ if (entry.startsWith("-")) {
5761
+ return invalid("unknown_option", `Unsupported Codex MCP option: ${entry}`);
5762
+ }
5763
+ if (name !== null) {
5764
+ templateReason = "stdio";
5765
+ break;
5766
+ }
5767
+ name = entry;
5768
+ }
5769
+ if (templateReason !== null) {
5770
+ const message = templateReason === "custom_oauth_client" ? "This Codex command supplies custom OAuth settings and must remain Template-managed in v0." : "This Codex command adds a local stdio MCP and must remain Template-managed in v0.";
5771
+ return templateManaged("codex", templateReason, message);
5772
+ }
5773
+ if (name === null || !isValidMcpNativeName(name)) {
5774
+ return invalid("invalid_name", "Codex MCP names may contain only letters, numbers, '-' and '_'.");
5775
+ }
5776
+ if (urlValue === null) {
5777
+ return invalid("invalid_url", "Codex remote MCP commands require --url.");
5778
+ }
5779
+ const url3 = parseHttpsUrl(urlValue);
5780
+ if (!url3) {
5781
+ return templateManaged("codex", "insecure_url", "Centrally managed MCP URLs must use public HTTPS; run this command natively to keep it Template-managed.");
5782
+ }
5783
+ return {
5784
+ kind: "managed",
5785
+ source: "codex",
5786
+ displayName: name,
5787
+ nativeName: name,
5788
+ url: url3.toString(),
5789
+ requestedAgent: "codex",
5790
+ requestedScope: "project",
5791
+ requiresAllProjectsConfirmation: false,
5792
+ staticHeaders: [],
5793
+ bearerTokenEnvVar
5794
+ };
5795
+ };
5796
+ parseClaudeAdd = (argv) => {
5797
+ const args = argv.slice(3);
5798
+ const positionals = [];
5799
+ const headers = [];
5800
+ let scope = "local";
5801
+ let transport = null;
5802
+ let afterDoubleDash = false;
5803
+ let templateReason = null;
5804
+ for (let index = 0; index < args.length; index += 1) {
5805
+ const entry = args[index] ?? "";
5806
+ if (afterDoubleDash) {
5807
+ positionals.push(entry);
5808
+ continue;
5809
+ }
5810
+ if (entry === "--") {
5811
+ afterDoubleDash = true;
5812
+ templateReason = "stdio";
5813
+ continue;
5814
+ }
5815
+ const optionAliases = {
5816
+ "-s": "--scope",
5817
+ "-t": "--transport",
5818
+ "-e": "--env",
5819
+ "-H": "--header"
5820
+ };
5821
+ const canonicalEntry = optionAliases[entry] ?? entry;
5822
+ if (canonicalEntry === "--scope" || canonicalEntry.startsWith("--scope=")) {
5823
+ const parsed = readOptionValue({
5824
+ argv: args,
5825
+ index,
5826
+ option: canonicalEntry === "--scope" ? entry : "--scope"
5827
+ });
5828
+ if ("kind" in parsed)
5829
+ return parsed;
5830
+ scope = parsed.value;
5831
+ index = parsed.nextIndex;
5832
+ continue;
5833
+ }
5834
+ if (canonicalEntry === "--transport" || canonicalEntry.startsWith("--transport=")) {
5835
+ const parsed = readOptionValue({
5836
+ argv: args,
5837
+ index,
5838
+ option: canonicalEntry === "--transport" ? entry : "--transport"
5839
+ });
5840
+ if ("kind" in parsed)
5841
+ return parsed;
5842
+ transport = parsed.value;
5843
+ index = parsed.nextIndex;
5844
+ continue;
5845
+ }
5846
+ if (canonicalEntry === "--header" || canonicalEntry.startsWith("--header=")) {
5847
+ const parsed = readOptionValue({
5848
+ argv: args,
5849
+ index,
5850
+ option: canonicalEntry === "--header" ? entry : "--header"
5851
+ });
5852
+ if ("kind" in parsed)
5853
+ return parsed;
5854
+ const header = parseHeader(parsed.value);
5855
+ if (!header) {
5856
+ return invalid("invalid_header", "Claude MCP headers must use the form 'Header-Name: value'.");
5857
+ }
5858
+ headers.push(header);
5859
+ index = parsed.nextIndex;
5860
+ continue;
5861
+ }
5862
+ if (canonicalEntry === "--env" || canonicalEntry.startsWith("--env=")) {
5863
+ const parsed = readOptionValue({
5864
+ argv: args,
5865
+ index,
5866
+ option: canonicalEntry === "--env" ? entry : "--env"
5867
+ });
5868
+ if ("kind" in parsed)
5869
+ return parsed;
5870
+ index = parsed.nextIndex;
5871
+ templateReason = "unsupported_option";
5872
+ continue;
5873
+ }
5874
+ if (entry === "--client-id" || entry.startsWith("--client-id=") || entry === "--callback-port" || entry.startsWith("--callback-port=")) {
5875
+ const option = entry.startsWith("--client-id") ? "--client-id" : "--callback-port";
5876
+ const parsed = readOptionValue({ argv: args, index, option });
5877
+ if ("kind" in parsed)
5878
+ return parsed;
5879
+ index = parsed.nextIndex;
5880
+ templateReason = "custom_oauth_client";
5881
+ continue;
5882
+ }
5883
+ if (entry === "--client-secret" || entry === "--xaa") {
5884
+ templateReason = "custom_oauth_client";
5885
+ continue;
5886
+ }
5887
+ if (entry.startsWith("-")) {
5888
+ return invalid("unknown_option", `Unsupported Claude MCP option: ${entry}`);
5889
+ }
5890
+ positionals.push(entry);
5891
+ }
5892
+ if (!["local", "project", "user"].includes(scope)) {
5893
+ return invalid("invalid_scope", "Claude MCP scope must be local, project, or user.");
5894
+ }
5895
+ if (transport !== "http") {
5896
+ const reason = transport === "sse" ? "legacy_sse" : "stdio";
5897
+ return templateManaged("claude", reason, transport === "sse" ? "Legacy SSE MCPs remain Template-managed in v0." : "Claude stdio MCPs remain Template-managed in v0.");
5898
+ }
5899
+ if (templateReason !== null) {
5900
+ return templateManaged("claude", templateReason, templateReason === "custom_oauth_client" ? "This Claude command supplies custom OAuth settings and must remain Template-managed in v0." : "This Claude command uses options that are not centrally managed in v0.");
5901
+ }
5902
+ const name = positionals[0];
5903
+ const urlValue = positionals[1];
5904
+ if (name === void 0 || !isValidMcpNativeName(name) || positionals.length !== 2) {
5905
+ return invalid("invalid_name", "Claude remote MCP commands need one common agent-safe name and one URL.");
5906
+ }
5907
+ if (hasDuplicateHeaders(headers)) {
5908
+ return invalid("invalid_header", "Provide each Claude MCP header only once.");
5909
+ }
5910
+ const url3 = urlValue ? parseHttpsUrl(urlValue) : null;
5911
+ if (!url3) {
5912
+ return templateManaged("claude", "insecure_url", "Centrally managed MCP URLs must use public HTTPS; run this command natively to keep it Template-managed.");
5913
+ }
5914
+ const allProjects = scope === "user";
5915
+ return {
5916
+ kind: "managed",
5917
+ source: "claude",
5918
+ displayName: name,
5919
+ nativeName: name,
5920
+ url: url3.toString(),
5921
+ requestedAgent: "claude",
5922
+ requestedScope: allProjects ? "all_projects" : "project",
5923
+ requiresAllProjectsConfirmation: allProjects,
5924
+ staticHeaders: headers,
5925
+ bearerTokenEnvVar: null
5926
+ };
5927
+ };
5928
+ parseMcpAddArgv = (argv) => {
5929
+ if (argv.length === 0 || argv.length > MCP_COMMAND_IMPORT_MAX_ARGS || argv.some((entry) => typeof entry !== "string" || entry.length === 0 || entry.length > MCP_COMMAND_IMPORT_MAX_ARG_CHARS)) {
5930
+ return invalid("too_large", "The MCP setup command is empty or too large.");
5931
+ }
5932
+ const mutableArgv = [...argv];
5933
+ if (mutableArgv[1] !== "mcp" || mutableArgv[2] !== "add") {
5934
+ return invalid("unsupported_command", "Paste a plain MCP URL, 'codex mcp add', or 'claude mcp add' command.");
5935
+ }
5936
+ if (mutableArgv[0] === "codex") {
5937
+ return parseCodexAdd(mutableArgv);
5938
+ }
5939
+ if (mutableArgv[0] === "claude") {
5940
+ return parseClaudeAdd(mutableArgv);
5941
+ }
5942
+ return invalid("unsupported_command", "Only Codex and Claude MCP setup commands are supported.");
5943
+ };
5944
+ parseMcpCommandImport = (input) => {
5945
+ const trimmed = input.trim();
5946
+ const plainUrl = parseHttpsUrl(trimmed);
5947
+ if (plainUrl) {
5948
+ const nativeName = nameFromUrl(plainUrl);
5949
+ return {
5950
+ kind: "managed",
5951
+ source: "url",
5952
+ displayName: nativeName,
5953
+ nativeName,
5954
+ url: plainUrl.toString(),
5955
+ requestedAgent: null,
5956
+ requestedScope: "project",
5957
+ requiresAllProjectsConfirmation: false,
5958
+ staticHeaders: [],
5959
+ bearerTokenEnvVar: null
5960
+ };
5961
+ }
5962
+ const tokenized = tokenizePastedCommand(input);
5963
+ return tokenized.kind === "ok" ? parseMcpAddArgv(tokenized.argv) : invalid(tokenized.code, tokenized.message);
5964
+ };
5524
5965
  }
5525
5966
  });
5526
5967
 
@@ -5799,7 +6240,7 @@ var init_types = __esm({
5799
6240
  // ../../../../shared/devboxCore/dist/mcpOAuth/callbackServer.js
5800
6241
  import { timingSafeEqual } from "node:crypto";
5801
6242
  import http from "node:http";
5802
- var MAX_CALLBACK_TARGET_CHARS, safeStateEqual, writeHtml, startMcpOAuthCallbackListener;
6243
+ var MAX_CALLBACK_TARGET_CHARS, safeStateEqual, writeHtml, evaluateManualMcpOAuthCallbackUrl, startMcpOAuthCallbackListener;
5803
6244
  var init_callbackServer = __esm({
5804
6245
  "../../../../shared/devboxCore/dist/mcpOAuth/callbackServer.js"() {
5805
6246
  "use strict";
@@ -5824,7 +6265,55 @@ var init_callbackServer = __esm({
5824
6265
  message: "You can close this tab and return to boxes.dev."
5825
6266
  }));
5826
6267
  };
5827
- startMcpOAuthCallbackListener = async ({ callbackHostname, callbackPath, expectedState, signal, timeoutMs }) => {
6268
+ evaluateManualMcpOAuthCallbackUrl = ({ expectedState, input, redirectUri }) => {
6269
+ const expected = new URL(redirectUri);
6270
+ const trimmed = input.trim();
6271
+ if (trimmed.length > MAX_CALLBACK_TARGET_CHARS) {
6272
+ return { kind: "rejected", message: "That address is too long." };
6273
+ }
6274
+ let parsed;
6275
+ try {
6276
+ parsed = new URL(trimmed);
6277
+ } catch {
6278
+ return {
6279
+ kind: "rejected",
6280
+ message: `Paste the full address from your browser's address bar. It starts with ${expected.origin}${expected.pathname}.`
6281
+ };
6282
+ }
6283
+ if (parsed.origin !== expected.origin || parsed.pathname !== expected.pathname) {
6284
+ return {
6285
+ kind: "rejected",
6286
+ message: `That address isn't from this sign-in. Paste the address that starts with ${expected.origin}${expected.pathname}.`
6287
+ };
6288
+ }
6289
+ if (!safeStateEqual(expectedState, parsed.searchParams.get("state") ?? "")) {
6290
+ return {
6291
+ kind: "rejected",
6292
+ message: "That address is from a different sign-in attempt. Paste the address from the link above."
6293
+ };
6294
+ }
6295
+ if (parsed.searchParams.get("error")) {
6296
+ return {
6297
+ kind: "failed",
6298
+ error: new McpOAuthCompanionError("provider_denied", "The OAuth provider did not authorize this connection.")
6299
+ };
6300
+ }
6301
+ const authorizationCode = parsed.searchParams.get("code") ?? "";
6302
+ if (!authorizationCode) {
6303
+ return {
6304
+ kind: "rejected",
6305
+ message: "That address is missing its sign-in code. Copy the whole address and paste it again."
6306
+ };
6307
+ }
6308
+ return {
6309
+ kind: "accepted",
6310
+ callback: {
6311
+ authorizationCode,
6312
+ issuer: parsed.searchParams.get("iss") ?? void 0
6313
+ }
6314
+ };
6315
+ };
6316
+ startMcpOAuthCallbackListener = async ({ callbackHostname, callbackPath, expectedState, manualCallbackInput, signal, timeoutMs }) => {
5828
6317
  let settled = false;
5829
6318
  let callbackAccepted = false;
5830
6319
  let resolveCallback = () => void 0;
@@ -5834,17 +6323,20 @@ var init_callbackServer = __esm({
5834
6323
  rejectCallback = reject;
5835
6324
  });
5836
6325
  void waitForCallback.catch(() => void 0);
5837
- const settleFailure = (error55) => {
6326
+ const settleFailure = (error55, response) => {
5838
6327
  if (settled)
5839
6328
  return;
5840
6329
  settled = true;
5841
- rejectCallback(error55);
6330
+ if (response)
6331
+ response.once("close", () => rejectCallback(error55));
6332
+ else
6333
+ rejectCallback(error55);
5842
6334
  };
5843
6335
  const server = http.createServer((request2, response) => {
5844
6336
  const target = request2.url ?? "";
5845
6337
  if (target.length > MAX_CALLBACK_TARGET_CHARS) {
6338
+ settleFailure(new McpOAuthCompanionError("sdk_protocol_error", "The OAuth callback was too large."), response);
5846
6339
  writeHtml(response, 414, "Authentication failed");
5847
- settleFailure(new McpOAuthCompanionError("sdk_protocol_error", "The OAuth callback was too large."));
5848
6340
  return;
5849
6341
  }
5850
6342
  if (request2.method !== "GET") {
@@ -5862,29 +6354,31 @@ var init_callbackServer = __esm({
5862
6354
  }
5863
6355
  const state = parsed.searchParams.get("state") ?? "";
5864
6356
  if (!safeStateEqual(expectedState, state)) {
6357
+ settleFailure(new McpOAuthCompanionError("state_mismatch", "The OAuth callback state did not match."), response);
5865
6358
  writeHtml(response, 400, "Authentication failed");
5866
- settleFailure(new McpOAuthCompanionError("state_mismatch", "The OAuth callback state did not match."));
5867
6359
  return;
5868
6360
  }
5869
6361
  const providerError = parsed.searchParams.get("error");
5870
6362
  if (providerError) {
6363
+ settleFailure(new McpOAuthCompanionError("provider_denied", "The OAuth provider did not authorize this connection."), response);
5871
6364
  writeHtml(response, 200, "Authentication was not completed");
5872
- settleFailure(new McpOAuthCompanionError("provider_denied", "The OAuth provider did not authorize this connection."));
5873
6365
  return;
5874
6366
  }
5875
6367
  const authorizationCode = parsed.searchParams.get("code") ?? "";
5876
6368
  if (!authorizationCode) {
6369
+ settleFailure(new McpOAuthCompanionError("sdk_protocol_error", "The OAuth callback did not include an authorization code."), response);
5877
6370
  writeHtml(response, 400, "Authentication failed");
5878
- settleFailure(new McpOAuthCompanionError("sdk_protocol_error", "The OAuth callback did not include an authorization code."));
5879
6371
  return;
5880
6372
  }
5881
6373
  callbackAccepted = true;
5882
6374
  settled = true;
5883
- writeHtml(response, 200, "Authentication successful");
5884
- resolveCallback({
5885
- authorizationCode,
5886
- issuer: parsed.searchParams.get("iss") ?? void 0
6375
+ response.once("close", () => {
6376
+ resolveCallback({
6377
+ authorizationCode,
6378
+ issuer: parsed.searchParams.get("iss") ?? void 0
6379
+ });
5887
6380
  });
6381
+ writeHtml(response, 200, "Authentication successful");
5888
6382
  });
5889
6383
  let localPort;
5890
6384
  try {
@@ -5896,12 +6390,44 @@ var init_callbackServer = __esm({
5896
6390
  } catch {
5897
6391
  throw new McpOAuthCompanionError("callback_unavailable", "boxes.dev could not open a local OAuth callback.");
5898
6392
  }
6393
+ const redirectUri = `http://${callbackHostname}:${String(localPort)}${callbackPath}`;
6394
+ const manualInputController = new AbortController();
6395
+ const readManualCallbacks = async (input) => {
6396
+ while (!settled) {
6397
+ let pasted;
6398
+ try {
6399
+ pasted = await input.readCallbackUrl(manualInputController.signal);
6400
+ } catch {
6401
+ return;
6402
+ }
6403
+ if (pasted === null || settled)
6404
+ return;
6405
+ const result = evaluateManualMcpOAuthCallbackUrl({
6406
+ expectedState,
6407
+ input: pasted,
6408
+ redirectUri
6409
+ });
6410
+ if (result.kind === "rejected") {
6411
+ input.reportRejectedCallbackUrl(result.message);
6412
+ } else if (result.kind === "failed") {
6413
+ settleFailure(result.error);
6414
+ } else {
6415
+ callbackAccepted = true;
6416
+ settled = true;
6417
+ resolveCallback(result.callback);
6418
+ }
6419
+ }
6420
+ };
5899
6421
  const close2 = async () => {
5900
6422
  clearTimeout(timeout);
6423
+ manualInputController.abort();
5901
6424
  signal?.removeEventListener("abort", onAbort);
5902
6425
  if (!server.listening)
5903
6426
  return;
5904
- await new Promise((resolve3) => server.close(() => resolve3()));
6427
+ await new Promise((resolve3) => {
6428
+ server.close(() => resolve3());
6429
+ server.closeAllConnections();
6430
+ });
5905
6431
  };
5906
6432
  const onAbort = () => {
5907
6433
  settleFailure(new McpOAuthCompanionError("canceled", "MCP authorization was canceled."));
@@ -5915,8 +6441,10 @@ var init_callbackServer = __esm({
5915
6441
  signal?.addEventListener("abort", onAbort, { once: true });
5916
6442
  if (signal?.aborted)
5917
6443
  onAbort();
6444
+ if (manualCallbackInput)
6445
+ void readManualCallbacks(manualCallbackInput);
5918
6446
  return {
5919
- redirectUri: `http://${callbackHostname}:${String(localPort)}${callbackPath}`,
6447
+ redirectUri,
5920
6448
  waitForCallback,
5921
6449
  close: close2
5922
6450
  };
@@ -22519,8 +23047,8 @@ var init_ajvProvider_97rDpkRx = __esm({
22519
23047
  const { gen, data, schemaCode, it: it2 } = cxt;
22520
23048
  const prec = it2.opts.multipleOfPrecision;
22521
23049
  const res = gen.let("res");
22522
- const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
22523
- cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
23050
+ const invalid2 = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
23051
+ cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid2}))`);
22524
23052
  }
22525
23053
  };
22526
23054
  exports.default = def;
@@ -26257,7 +26785,7 @@ var init_resource = __esm({
26257
26785
 
26258
26786
  // ../../../../shared/devboxCore/dist/mcpOAuth/companion.js
26259
26787
  import { randomBytes } from "node:crypto";
26260
- var DEFAULT_CALLBACK_TIMEOUT_MS, MAX_OAUTH_RESPONSE_BYTES, McpOAuthResponseTooLargeError, requirePublicHttpsUrl, sameUrl, readBoundedResponseBody, createBoundedOAuthFetch, TransientMcpOAuthProvider, buildCanonicalGrant, throwIfCanceled, authorizeMcpOAuthWithSdk;
26788
+ var DEFAULT_CALLBACK_TIMEOUT_MS, MAX_OAUTH_RESPONSE_BYTES, McpOAuthResponseTooLargeError, requirePublicHttpsUrl, sameUrl, readBoundedResponseBody, createBoundedOAuthFetch, TransientMcpOAuthProvider, buildCanonicalGrant, throwIfCanceled, toSafeMcpOAuthError, normalizeMcpOAuthTarget, createMcpOAuthState, createProvider, prepareMcpOAuthAuthorizationWithSdk, completeMcpOAuthAuthorizationWithSdk, authorizeMcpOAuthWithSdk;
26261
26789
  var init_companion = __esm({
26262
26790
  "../../../../shared/devboxCore/dist/mcpOAuth/companion.js"() {
26263
26791
  "use strict";
@@ -26336,17 +26864,22 @@ var init_companion = __esm({
26336
26864
  clientMetadata;
26337
26865
  resolveClientMetadataUrl;
26338
26866
  expectedState;
26339
- openAuthorizationUrl;
26867
+ recordAuthorizationUrl;
26340
26868
  codeVerifierValue;
26341
26869
  clientInformationValue;
26342
26870
  tokensValue;
26343
26871
  discoveryStateValue;
26344
- constructor({ resolveClientMetadataUrl, clientMetadata, expectedState, openAuthorizationUrl, redirectUrl }) {
26872
+ constructor({ resolveClientMetadataUrl, clientMetadata, expectedState, recordAuthorizationUrl, redirectUrl, restored }) {
26345
26873
  this.redirectUrl = redirectUrl;
26346
26874
  this.resolveClientMetadataUrl = resolveClientMetadataUrl;
26347
26875
  this.clientMetadata = clientMetadata;
26348
26876
  this.expectedState = expectedState;
26349
- this.openAuthorizationUrl = openAuthorizationUrl;
26877
+ this.recordAuthorizationUrl = recordAuthorizationUrl;
26878
+ if (restored) {
26879
+ this.clientInformationValue = restored.clientInformation;
26880
+ this.codeVerifierValue = restored.codeVerifier;
26881
+ this.discoveryStateValue = restored.discoveryState;
26882
+ }
26350
26883
  }
26351
26884
  state() {
26352
26885
  return this.expectedState;
@@ -26371,11 +26904,11 @@ var init_companion = __esm({
26371
26904
  const issuer = tokens.issuer ?? context34?.issuer;
26372
26905
  this.tokensValue = issuer ? { ...tokens, issuer } : tokens;
26373
26906
  }
26374
- async redirectToAuthorization(authorizationUrl) {
26907
+ redirectToAuthorization(authorizationUrl) {
26375
26908
  if (authorizationUrl.protocol !== "https:" && authorizationUrl.protocol !== "http:") {
26376
26909
  throw new McpOAuthCompanionError("sdk_protocol_error", "The authorization server returned an unsupported redirect URL.");
26377
26910
  }
26378
- await this.openAuthorizationUrl(authorizationUrl.toString());
26911
+ this.recordAuthorizationUrl(authorizationUrl.toString());
26379
26912
  }
26380
26913
  saveCodeVerifier(codeVerifier) {
26381
26914
  this.codeVerifierValue = codeVerifier;
@@ -26419,6 +26952,18 @@ var init_companion = __esm({
26419
26952
  discoveryState: this.discoveryStateValue
26420
26953
  };
26421
26954
  }
26955
+ // What the code exchange needs after the redirect: the registered client,
26956
+ // the PKCE verifier, and the discovery result the SDK binds the callback to.
26957
+ pendingState() {
26958
+ if (!this.clientInformationValue?.client_id || !this.codeVerifierValue || !this.discoveryStateValue) {
26959
+ throw new McpOAuthCompanionError("sdk_protocol_error", "The OAuth SDK did not prepare a complete authorization.");
26960
+ }
26961
+ return {
26962
+ clientInformation: this.clientInformationValue,
26963
+ codeVerifier: this.codeVerifierValue,
26964
+ discoveryState: this.discoveryStateValue
26965
+ };
26966
+ }
26422
26967
  clear() {
26423
26968
  this.codeVerifierValue = void 0;
26424
26969
  this.clientInformationValue = void 0;
@@ -26468,14 +27013,108 @@ var init_companion = __esm({
26468
27013
  throw new McpOAuthCompanionError("canceled", "MCP authorization was canceled.");
26469
27014
  }
26470
27015
  };
26471
- authorizeMcpOAuthWithSdk = async (options, sdkAuth) => {
26472
- const serverUrl = requirePublicHttpsUrl(options.serverUrl, "The MCP server URL").toString();
26473
- const serverName = options.serverName.trim();
26474
- if (!serverName || serverName.length > 128) {
27016
+ toSafeMcpOAuthError = (error55) => error55 instanceof McpOAuthResponseTooLargeError ? new McpOAuthCompanionError("response_too_large", "The OAuth server response was too large.") : error55 instanceof McpOAuthCompanionError ? error55 : new McpOAuthCompanionError("sdk_protocol_error", "The MCP OAuth protocol did not complete.");
27017
+ normalizeMcpOAuthTarget = ({ serverName, serverUrl }) => {
27018
+ const normalizedUrl = requirePublicHttpsUrl(serverUrl, "The MCP server URL").toString();
27019
+ const normalizedName = serverName.trim();
27020
+ if (!normalizedName || normalizedName.length > 128) {
26475
27021
  throw new McpOAuthCompanionError("invalid_input", "The MCP server name must be between 1 and 128 characters.");
26476
27022
  }
27023
+ return { serverName: normalizedName, serverUrl: normalizedUrl };
27024
+ };
27025
+ createMcpOAuthState = () => randomBytes(32).toString("base64url");
27026
+ createProvider = ({ agent, recordAuthorizationUrl, redirectUri, restored, serverName, serverUrl, state }) => {
27027
+ const profile = resolveMcpOAuthProfile(agent);
27028
+ return new TransientMcpOAuthProvider({
27029
+ resolveClientMetadataUrl: (authorizationServerMetadata) => profile.resolveClientMetadataUrl(serverUrl, authorizationServerMetadata),
27030
+ clientMetadata: profile.buildClientMetadata(serverName, redirectUri),
27031
+ expectedState: state,
27032
+ recordAuthorizationUrl,
27033
+ redirectUrl: redirectUri,
27034
+ restored
27035
+ });
27036
+ };
27037
+ prepareMcpOAuthAuthorizationWithSdk = async ({ agent, fetchFn, redirectUri, serverName: rawServerName, serverUrl: rawServerUrl, signal, state }, sdkAuth) => {
27038
+ const { serverName, serverUrl } = normalizeMcpOAuthTarget({
27039
+ serverName: rawServerName,
27040
+ serverUrl: rawServerUrl
27041
+ });
27042
+ const profile = resolveMcpOAuthProfile(agent);
27043
+ let authorizationUrl = null;
27044
+ const provider = createProvider({
27045
+ agent,
27046
+ recordAuthorizationUrl: (url3) => {
27047
+ authorizationUrl = url3;
27048
+ },
27049
+ redirectUri,
27050
+ restored: null,
27051
+ serverName,
27052
+ serverUrl,
27053
+ state
27054
+ });
27055
+ try {
27056
+ const result = await sdkAuth(provider, {
27057
+ serverUrl,
27058
+ fetchFn: createBoundedOAuthFetch(fetchFn, signal)
27059
+ });
27060
+ if (result !== "REDIRECT" || authorizationUrl === null) {
27061
+ throw new McpOAuthCompanionError("sdk_protocol_error", "The OAuth SDK did not start an authorization redirect.");
27062
+ }
27063
+ return {
27064
+ authorizationUrl,
27065
+ pending: {
27066
+ ...provider.pendingState(),
27067
+ agent,
27068
+ profileVersion: profile.profileVersion,
27069
+ serverName,
27070
+ serverUrl,
27071
+ redirectUri,
27072
+ state
27073
+ }
27074
+ };
27075
+ } finally {
27076
+ provider.clear();
27077
+ }
27078
+ };
27079
+ completeMcpOAuthAuthorizationWithSdk = async ({ authorizationCode, fetchFn, issuer, pending, signal }, sdkAuth) => {
27080
+ const provider = createProvider({
27081
+ agent: pending.agent,
27082
+ recordAuthorizationUrl: () => {
27083
+ throw new McpOAuthCompanionError("sdk_protocol_error", "The OAuth SDK started a second authorization redirect.");
27084
+ },
27085
+ redirectUri: pending.redirectUri,
27086
+ restored: pending,
27087
+ serverName: pending.serverName,
27088
+ serverUrl: pending.serverUrl,
27089
+ state: pending.state
27090
+ });
27091
+ try {
27092
+ const result = await sdkAuth(provider, {
27093
+ serverUrl: pending.serverUrl,
27094
+ authorizationCode,
27095
+ ...issuer ? { iss: issuer } : {},
27096
+ fetchFn: createBoundedOAuthFetch(fetchFn, signal)
27097
+ });
27098
+ if (result !== "AUTHORIZED") {
27099
+ throw new McpOAuthCompanionError("sdk_protocol_error", "The OAuth SDK did not complete authorization.");
27100
+ }
27101
+ return buildCanonicalGrant({
27102
+ agent: pending.agent,
27103
+ now: Date.now(),
27104
+ profileVersion: pending.profileVersion,
27105
+ provider,
27106
+ redirectUri: pending.redirectUri,
27107
+ serverName: pending.serverName,
27108
+ serverUrl: pending.serverUrl
27109
+ });
27110
+ } finally {
27111
+ provider.clear();
27112
+ }
27113
+ };
27114
+ authorizeMcpOAuthWithSdk = async (options, sdkAuth) => {
27115
+ const { serverName, serverUrl } = normalizeMcpOAuthTarget(options);
26477
27116
  const profile = resolveMcpOAuthProfile(options.agent);
26478
- const sdkFetch = createBoundedOAuthFetch(options.fetchFn ?? fetch, options.signal);
27117
+ const fetchFn = options.fetchFn ?? fetch;
26479
27118
  const serverOrigin = new URL(serverUrl).origin;
26480
27119
  const log3 = (event) => options.log?.(event);
26481
27120
  const baseEvent = {
@@ -26483,16 +27122,16 @@ var init_companion = __esm({
26483
27122
  profileVersion: profile.profileVersion,
26484
27123
  serverOrigin
26485
27124
  };
26486
- const state = randomBytes(32).toString("base64url");
27125
+ const state = createMcpOAuthState();
26487
27126
  const callbackPath = profile.buildCallbackPath(serverUrl);
26488
27127
  let callbackListener = null;
26489
- let provider = null;
26490
27128
  try {
26491
27129
  throwIfCanceled(options.signal);
26492
27130
  callbackListener = await startMcpOAuthCallbackListener({
26493
27131
  callbackHostname: profile.callbackHostname,
26494
27132
  callbackPath,
26495
27133
  expectedState: state,
27134
+ ...options.manualCallbackInput ? { manualCallbackInput: options.manualCallbackInput } : {},
26496
27135
  signal: options.signal,
26497
27136
  timeoutMs: options.timeoutMs ?? DEFAULT_CALLBACK_TIMEOUT_MS
26498
27137
  });
@@ -26501,28 +27140,22 @@ var init_companion = __esm({
26501
27140
  event: "callback_listening",
26502
27141
  errorCode: null
26503
27142
  });
26504
- provider = new TransientMcpOAuthProvider({
26505
- resolveClientMetadataUrl: (authorizationServerMetadata) => profile.resolveClientMetadataUrl(serverUrl, authorizationServerMetadata),
26506
- clientMetadata: profile.buildClientMetadata(serverName, callbackListener.redirectUri),
26507
- expectedState: state,
26508
- openAuthorizationUrl: async (authorizationUrl) => {
26509
- throwIfCanceled(options.signal);
26510
- await options.openAuthorizationUrl(authorizationUrl);
26511
- log3({
26512
- ...baseEvent,
26513
- event: "authorization_opened",
26514
- errorCode: null
26515
- });
26516
- },
26517
- redirectUrl: callbackListener.redirectUri
26518
- });
26519
- const initialResult = await sdkAuth(provider, {
27143
+ const prepared = await prepareMcpOAuthAuthorizationWithSdk({
27144
+ agent: options.agent,
27145
+ fetchFn,
27146
+ redirectUri: callbackListener.redirectUri,
27147
+ serverName,
26520
27148
  serverUrl,
26521
- fetchFn: sdkFetch
27149
+ signal: options.signal,
27150
+ state
27151
+ }, sdkAuth);
27152
+ throwIfCanceled(options.signal);
27153
+ await options.openAuthorizationUrl(prepared.authorizationUrl);
27154
+ log3({
27155
+ ...baseEvent,
27156
+ event: "authorization_opened",
27157
+ errorCode: null
26522
27158
  });
26523
- if (initialResult !== "REDIRECT") {
26524
- throw new McpOAuthCompanionError("sdk_protocol_error", "The OAuth SDK did not start an authorization redirect.");
26525
- }
26526
27159
  const callback = await callbackListener.waitForCallback;
26527
27160
  log3({
26528
27161
  ...baseEvent,
@@ -26530,24 +27163,13 @@ var init_companion = __esm({
26530
27163
  errorCode: null
26531
27164
  });
26532
27165
  throwIfCanceled(options.signal);
26533
- const completedResult = await sdkAuth(provider, {
26534
- serverUrl,
27166
+ const grant = await completeMcpOAuthAuthorizationWithSdk({
26535
27167
  authorizationCode: callback.authorizationCode,
26536
- ...callback.issuer ? { iss: callback.issuer } : {},
26537
- fetchFn: sdkFetch
26538
- });
26539
- if (completedResult !== "AUTHORIZED") {
26540
- throw new McpOAuthCompanionError("sdk_protocol_error", "The OAuth SDK did not complete authorization.");
26541
- }
26542
- const grant = buildCanonicalGrant({
26543
- agent: options.agent,
26544
- now: Date.now(),
26545
- profileVersion: profile.profileVersion,
26546
- provider,
26547
- redirectUri: callbackListener.redirectUri,
26548
- serverName,
26549
- serverUrl
26550
- });
27168
+ fetchFn,
27169
+ issuer: callback.issuer,
27170
+ pending: prepared.pending,
27171
+ signal: options.signal
27172
+ }, sdkAuth);
26551
27173
  try {
26552
27174
  await options.uploadGrant(grant);
26553
27175
  } catch {
@@ -26567,7 +27189,7 @@ var init_companion = __esm({
26567
27189
  scope: grant.scope
26568
27190
  };
26569
27191
  } catch (error55) {
26570
- const safeError = error55 instanceof McpOAuthResponseTooLargeError ? new McpOAuthCompanionError("response_too_large", "The OAuth server response was too large.") : error55 instanceof McpOAuthCompanionError ? error55 : new McpOAuthCompanionError("sdk_protocol_error", "The MCP OAuth protocol did not complete.");
27192
+ const safeError = toSafeMcpOAuthError(error55);
26571
27193
  log3({
26572
27194
  ...baseEvent,
26573
27195
  event: safeError.code === "canceled" ? "authorization_canceled" : "authorization_failed",
@@ -26575,7 +27197,6 @@ var init_companion = __esm({
26575
27197
  });
26576
27198
  throw safeError;
26577
27199
  } finally {
26578
- provider?.clear();
26579
27200
  await callbackListener?.close();
26580
27201
  }
26581
27202
  };
@@ -26836,6 +27457,9 @@ var init_chatGptBrowserSignIn = __esm({
26836
27457
  server.close(() => resolve3());
26837
27458
  server.closeIdleConnections();
26838
27459
  });
27460
+ if (stage === "settled") {
27461
+ server.closeAllConnections();
27462
+ }
26839
27463
  return shutDown;
26840
27464
  };
26841
27465
  const settle = (error55) => {
@@ -62485,7 +63109,7 @@ var init_instrumentation7 = __esm({
62485
63109
  _patchCreateConnection() {
62486
63110
  return (originalCreateConnection) => {
62487
63111
  const thisPlugin = this;
62488
- return function createConnection2(_connectionUri) {
63112
+ return function createConnection3(_connectionUri) {
62489
63113
  const originalResult = originalCreateConnection(...arguments);
62490
63114
  thisPlugin._wrap(originalResult, "query", thisPlugin._patchQuery(originalResult));
62491
63115
  return originalResult;
@@ -62554,7 +63178,7 @@ var init_instrumentation7 = __esm({
62554
63178
  _patchGetConnection(pool) {
62555
63179
  return (originalGetConnection) => {
62556
63180
  const thisPlugin = this;
62557
- return function getConnection(arg1, arg2, arg3) {
63181
+ return function getConnection2(arg1, arg2, arg3) {
62558
63182
  if (!thisPlugin["_enabled"]) {
62559
63183
  thisPlugin._unwrap(pool, "getConnection");
62560
63184
  return originalGetConnection.apply(pool, arguments);
@@ -69730,9 +70354,9 @@ var init_sentry = __esm({
69730
70354
  uncaughtExceptionMonitorInstalled = false;
69731
70355
  currentDevboxSentryUser = null;
69732
70356
  readBuildMetadata = () => {
69733
- const rawPackageVersion = "1.0.1079";
69734
- const rawGitSha = "b4796ddf10b015d808aba367f5eeb521c6ea0812";
69735
- const rawSentryRelease = "boxes-dev-dvb@1.0.1079+b4796ddf10b015d808aba367f5eeb521c6ea0812";
70357
+ const rawPackageVersion = "1.0.1081";
70358
+ const rawGitSha = "13a23bcb8c308616abb295a6dd2553104ca405c0";
70359
+ const rawSentryRelease = "boxes-dev-dvb@1.0.1081+13a23bcb8c308616abb295a6dd2553104ca405c0";
69736
70360
  const packageVersion = typeof rawPackageVersion === "string" ? rawPackageVersion : void 0;
69737
70361
  const gitSha = typeof rawGitSha === "string" ? rawGitSha : void 0;
69738
70362
  const sentryRelease = typeof rawSentryRelease === "string" ? rawSentryRelease : void 0;
@@ -74268,7 +74892,7 @@ the following:
74268
74892
  it. Offer to help finish any remaining setup or run the app with
74269
74893
  port forwarding when relevant.
74270
74894
  - ${snapshotGuidance}
74271
- - Make **New devbox + thread** the main next action. Explain that it will
74895
+ - Make **New thread** the main next action. Explain that it will
74272
74896
  create an isolated machine from the Template box snapshot for the task,
74273
74897
  allowing several tasks to run in parallel with their own files and environments.
74274
74898
  - Explain that **New thread** on an existing devbox will start another agent
@@ -74306,7 +74930,7 @@ still needs attention.>
74306
74930
 
74307
74931
  ${snapshotExample}
74308
74932
 
74309
- **Start your first task:** click **New devbox + thread** and ask the agent to
74933
+ **Start your first task:** click **New thread** and ask the agent to
74310
74934
  build or fix something. It will get its own machine\u2014a **devbox**\u2014created from
74311
74935
  your Template box snapshot. You can work on several tasks in parallel, each
74312
74936
  with its own files and environment.
@@ -75116,7 +75740,7 @@ var init_packageVersion = __esm({
75116
75740
  return path18.join(process.cwd(), "dvb");
75117
75741
  };
75118
75742
  readEmbeddedPackageVersion = () => {
75119
- const raw = "1.0.1079";
75743
+ const raw = "1.0.1081";
75120
75744
  return trimVersion(raw);
75121
75745
  };
75122
75746
  readNearestPackageMetadata = (basePath) => {
@@ -82035,7 +82659,7 @@ var init_wrapper2 = __esm({
82035
82659
  // src/devbox/browser.ts
82036
82660
  import { spawn as spawn3 } from "node:child_process";
82037
82661
  import { readlinkSync } from "node:fs";
82038
- var LINUX_PSEUDO_TTY_PATH_PREFIX, isLinuxPseudoTtyPath, resolveInheritedBrowserOpenTty, buildBrowserOpenCommand, resolveBrowserOpenStdio, openBrowser;
82662
+ var LINUX_PSEUDO_TTY_PATH_PREFIX, isLinuxPseudoTtyPath, resolveInheritedBrowserOpenTty, buildBrowserOpenCommand, resolveBrowserOpenStdio, openBrowser, canOpenLocalBrowser;
82039
82663
  var init_browser = __esm({
82040
82664
  "src/devbox/browser.ts"() {
82041
82665
  "use strict";
@@ -82100,12 +82724,21 @@ var init_browser = __esm({
82100
82724
  env: childEnv,
82101
82725
  stdio: resolveBrowserOpenStdio(platform3)
82102
82726
  });
82727
+ child.on("error", () => void 0);
82103
82728
  child.unref();
82104
82729
  return true;
82105
82730
  } catch {
82106
82731
  return false;
82107
82732
  }
82108
82733
  };
82734
+ canOpenLocalBrowser = ({
82735
+ platform: platform3 = process.platform,
82736
+ env: env3 = process.env
82737
+ } = {}) => {
82738
+ if (env3.SSH_CONNECTION || env3.SSH_TTY) return false;
82739
+ if (platform3 === "linux") return Boolean(env3.DISPLAY || env3.WAYLAND_DISPLAY);
82740
+ return true;
82741
+ };
82109
82742
  }
82110
82743
  });
82111
82744
 
@@ -90461,6 +91094,10 @@ var init_controlPlane = __esm({
90461
91094
  }
90462
91095
  const code2 = url3.searchParams.get("code");
90463
91096
  const error55 = url3.searchParams.get("error");
91097
+ res.once("close", () => {
91098
+ if (code2) waiter.resolve(code2);
91099
+ else waiter.reject(new Error("OAuth failed."));
91100
+ });
90464
91101
  res.statusCode = code2 ? 200 : 400;
90465
91102
  res.setHeader("content-type", "text/html; charset=utf-8");
90466
91103
  if (code2) {
@@ -90479,11 +91116,6 @@ var init_controlPlane = __esm({
90479
91116
  })
90480
91117
  );
90481
91118
  }
90482
- if (code2) {
90483
- waiter.resolve(code2);
90484
- } else {
90485
- waiter.reject(new Error("OAuth failed."));
90486
- }
90487
91119
  });
90488
91120
  const waiter = (() => {
90489
91121
  let resolveFn;
@@ -90510,6 +91142,7 @@ var init_controlPlane = __esm({
90510
91142
  waitForCode: () => waiter.promise,
90511
91143
  close: () => new Promise((closeResolve) => {
90512
91144
  server.close(() => closeResolve());
91145
+ server.closeAllConnections();
90513
91146
  })
90514
91147
  });
90515
91148
  });
@@ -96027,7 +96660,7 @@ var init_errors4 = __esm({
96027
96660
  });
96028
96661
 
96029
96662
  // src/devbox/commandRegistry/args.ts
96030
- var expandFlagNames, resolveCanonicalFlag, unknownFlagError, missingValueError, collectPositionals, parseCommandArgs, readBooleanFlag, readStringFlag;
96663
+ var expandFlagNames, resolveCanonicalFlag, unknownFlagError, missingValueError, collectPositionals, parseCommandArgs, readBooleanFlag, readStringFlag, readRepeatedStringFlag;
96031
96664
  var init_args = __esm({
96032
96665
  "src/devbox/commandRegistry/args.ts"() {
96033
96666
  "use strict";
@@ -96147,6 +96780,21 @@ var init_args = __esm({
96147
96780
  }
96148
96781
  return void 0;
96149
96782
  };
96783
+ readRepeatedStringFlag = (args, name) => {
96784
+ const values = [];
96785
+ for (let index = 0; index < args.length; index += 1) {
96786
+ const token = args[index];
96787
+ if (token === "--") break;
96788
+ if (token === `--${name}`) {
96789
+ const next = args[index + 1];
96790
+ if (next !== void 0) values.push(next);
96791
+ index += 1;
96792
+ } else if (token?.startsWith(`--${name}=`)) {
96793
+ values.push(token.slice(name.length + 3));
96794
+ }
96795
+ }
96796
+ return values;
96797
+ };
96150
96798
  }
96151
96799
  });
96152
96800
 
@@ -98421,27 +99069,116 @@ var init_catalog = __esm({
98421
99069
  category: "Account",
98422
99070
  summary: "Manage centrally connected MCPs",
98423
99071
  usage: ["dvb mcp <command>"],
99072
+ notes: ["Run these commands on your own computer, not inside a box."],
98424
99073
  children: [
98425
99074
  {
98426
99075
  name: "list",
98427
99076
  summary: "List centrally managed MCP connections",
98428
- usage: ["dvb mcp list [--json]"],
98429
- options: [flag("json", "Output JSON")]
99077
+ usage: ["dvb mcp list [--project <project>] [--json]"],
99078
+ options: [
99079
+ flag(
99080
+ "project",
99081
+ "Show the MCPs available in one project, including MCPs your team manages",
99082
+ { valueName: "project" }
99083
+ ),
99084
+ flag("json", "Output JSON")
99085
+ ]
99086
+ },
99087
+ {
99088
+ name: "add",
99089
+ summary: "Add an MCP and connect it to Codex and Claude",
99090
+ usage: [
99091
+ 'dvb mcp add <url-or-setup-command> [--name <name>] [--project <project> | --all-projects] [--agent <codex|claude>] [--header "<name>: <value>"] [--no-sign-in] [--no-authorize] [--no-browser] [--json]',
99092
+ "dvb mcp add [options] -- <codex|claude> mcp add ..."
99093
+ ],
99094
+ arguments: [
99095
+ arg(
99096
+ "url-or-setup-command",
99097
+ "MCP URL, or the `codex mcp add` or `claude mcp add` command the provider gave you"
99098
+ )
99099
+ ],
99100
+ options: [
99101
+ flag("name", "Name for this MCP, also used by the agents", {
99102
+ valueName: "name"
99103
+ }),
99104
+ flag("project", "Project name or fingerprint", {
99105
+ valueName: "project"
99106
+ }),
99107
+ flag("all-projects", "Make the MCP available in every project"),
99108
+ flag(
99109
+ "agent",
99110
+ "Add it to only this agent; repeat for both (default: both)",
99111
+ { valueName: "codex|claude" }
99112
+ ),
99113
+ flag("header", "API key or other header to send; repeatable", {
99114
+ valueName: "name: value"
99115
+ }),
99116
+ flag(
99117
+ "no-sign-in",
99118
+ "Use an MCP that also works without an account without signing in"
99119
+ ),
99120
+ flag("no-authorize", "Add the MCP now and sign in later"),
99121
+ flag(
99122
+ "no-browser",
99123
+ "Print the sign-in link without opening a browser"
99124
+ ),
99125
+ flag("json", "Output JSON")
99126
+ ],
99127
+ notes: [
99128
+ "boxes.dev reads a pasted setup command but never runs it. Quote it, or put it after --.",
99129
+ "With one project, the MCP is added to that project. Otherwise, pass --project or --all-projects."
99130
+ ],
99131
+ examples: [
99132
+ "dvb mcp add https://mcp.linear.app/mcp --project my-app",
99133
+ "dvb mcp add --all-projects -- claude mcp add --transport http notion https://mcp.notion.com/mcp"
99134
+ ]
98430
99135
  },
98431
99136
  {
98432
99137
  name: "authorize",
98433
- summary: "Connect an MCP to Codex or Claude",
98434
- usage: ["dvb mcp authorize <connection> --agent <codex|claude>"],
99138
+ summary: "Sign in to an MCP for Codex or Claude",
99139
+ usage: [
99140
+ "dvb mcp authorize <connection> --agent <codex|claude> [--project <project>] [--no-browser]"
99141
+ ],
98435
99142
  arguments: [
98436
99143
  arg("connection", "Connection name or id from `dvb mcp list`")
98437
99144
  ],
98438
99145
  options: [
98439
99146
  flag("agent", "Coding agent to authorize", {
98440
99147
  valueName: "codex|claude"
98441
- })
99148
+ }),
99149
+ flag("project", "Project the MCP is available in", {
99150
+ valueName: "project"
99151
+ }),
99152
+ flag(
99153
+ "no-browser",
99154
+ "Print the sign-in link without opening a browser"
99155
+ )
99156
+ ],
99157
+ notes: [
99158
+ "MCP authorization does not require Codex, Claude, or either coding-agent account locally.",
99159
+ "Over SSH or without a browser, open the printed link on any computer. When the browser ends on a page that doesn't load, paste that page's address back into the terminal."
99160
+ ]
99161
+ },
99162
+ {
99163
+ name: "remove",
99164
+ summary: "Remove an MCP, or remove it from one agent",
99165
+ usage: [
99166
+ "dvb mcp remove <connection> [--agent <codex|claude>] [--project <project>] [--json]"
99167
+ ],
99168
+ arguments: [
99169
+ arg("connection", "Connection name or id from `dvb mcp list`")
99170
+ ],
99171
+ options: [
99172
+ flag("agent", "Remove the MCP from only this agent", {
99173
+ valueName: "codex|claude"
99174
+ }),
99175
+ flag("project", "Project the MCP is available in", {
99176
+ valueName: "project"
99177
+ }),
99178
+ flag("json", "Output JSON")
98442
99179
  ],
98443
99180
  notes: [
98444
- "MCP authorization does not require Codex, Claude, or either coding-agent account locally."
99181
+ "MCPs your team manages can only be removed from one agent at a time."
98445
99182
  ]
98446
99183
  }
98447
99184
  ]
@@ -99211,7 +99948,7 @@ var init_catalog = __esm({
99211
99948
  "When the follow-up arrives: next (default), idle, steer, or queue",
99212
99949
  { valueName: "mode" }
99213
99950
  ),
99214
- flag("turn", "Exact active Codex turn id to steer", {
99951
+ flag("turn", "Exact active turn id to steer", {
99215
99952
  valueName: "active-turn-id"
99216
99953
  }),
99217
99954
  flag("idempotency-key", "Caller-owned retry key", {
@@ -99221,7 +99958,8 @@ var init_catalog = __esm({
99221
99958
  ],
99222
99959
  notes: [
99223
99960
  "`next` starts a turn when the thread is idle and otherwise queues the follow-up behind the active turn.",
99224
- "`idle` fails while a turn is active, `queue` fails while the thread is idle, and `steer` adds the follow-up to the exact active Codex turn given by `--turn`."
99961
+ "`idle` fails while a turn is active, `queue` fails while the thread is idle, and `steer` adds the follow-up to the exact active turn given by `--turn`.",
99962
+ "Claude reads a steer at its next opportunity without interrupting a running tool. It can't be steered while it runs in a terminal or waits for an answer to a question."
99225
99963
  ]
99226
99964
  },
99227
99965
  {
@@ -142006,14 +142744,14 @@ var init_threadCreateActions = __esm({
142006
142744
  return {
142007
142745
  defaultForkCreateDisabledReason: "Loading snapshot state...",
142008
142746
  defaultForkSnapshotPreference: "use_last_snapshot",
142009
- forkCreateLabel: "New devbox + thread"
142747
+ forkCreateLabel: "New thread"
142010
142748
  };
142011
142749
  }
142012
142750
  if (snapshotMetadata.available) {
142013
142751
  return {
142014
142752
  defaultForkCreateDisabledReason: null,
142015
142753
  defaultForkSnapshotPreference: "use_last_snapshot",
142016
- forkCreateLabel: "New devbox + thread"
142754
+ forkCreateLabel: "New thread"
142017
142755
  };
142018
142756
  }
142019
142757
  return {
@@ -142793,7 +143531,7 @@ var init_onboxAgentPermissionRequestPresentation = __esm({
142793
143531
  case "edit-personal-environment":
142794
143532
  return "For the next 3 hours, the agent in this thread will be able to add, change, and remove your own environment variables in this project. Changes will reach all your devboxes in this project.";
142795
143533
  case "edit-automations":
142796
- return "For the next 3 hours, the agent in this thread will be able to create, change, pause, run, and delete your automations in this project. Each run will start a new agent thread on a new devbox, without this conversation, and will use box-hours.";
143534
+ return "For the next 3 hours, the agent in this thread will be able to create, change, pause, run, and delete your automations in this project. Each run will either start a new agent thread on a new devbox, without this conversation, or send the prompt to an existing thread, such as this one. Runs will use box-hours.";
142797
143535
  case "edit-team-template":
142798
143536
  return `For the next 3 hours, the agent in this thread will be able to edit ${teamTemplateName === null ? "your team's Team Template" : `the "${teamTemplateName}" Team Template`}, including its settings and environment variables, change settings in this project and your account's auto-wake preference, and save new versions for your team. Agent permission defaults remain user-only.`;
142799
143537
  }
@@ -232481,7 +233219,7 @@ var init_exec = __esm({
232481
233219
  });
232482
233220
 
232483
233221
  // src/devbox/commands/exec.ts
232484
- var invalidExecArgs, readOptionValue, parsePositiveInteger, parseDurationMs, parseExecArgs, readCommandStdin, defaultDependencies9, resolveProcessExitCode, runExecWithDependencies, runExec;
233222
+ var invalidExecArgs, readOptionValue2, parsePositiveInteger, parseDurationMs, parseExecArgs, readCommandStdin, defaultDependencies9, resolveProcessExitCode, runExecWithDependencies, runExec;
232485
233223
  var init_exec2 = __esm({
232486
233224
  "src/devbox/commands/exec.ts"() {
232487
233225
  "use strict";
@@ -232497,7 +233235,7 @@ var init_exec2 = __esm({
232497
233235
  message
232498
233236
  });
232499
233237
  };
232500
- readOptionValue = ({
233238
+ readOptionValue2 = ({
232501
233239
  args,
232502
233240
  index,
232503
233241
  option
@@ -232574,7 +233312,7 @@ var init_exec2 = __esm({
232574
233312
  if (name !== "--project" && name !== "--target" && name !== "--cwd" && name !== "--timeout" && name !== "--max-output-bytes") {
232575
233313
  invalidExecArgs(`Unknown option: ${option}`);
232576
233314
  }
232577
- const value = usesInlineValue ? option.slice(equalsIndex + 1).trim() : readOptionValue({ args: options, index, option: name });
233315
+ const value = usesInlineValue ? option.slice(equalsIndex + 1).trim() : readOptionValue2({ args: options, index, option: name });
232578
233316
  if (!value) {
232579
233317
  return invalidExecArgs(`\`${name}\` requires a value.`);
232580
233318
  }
@@ -245579,6 +246317,7 @@ var init_localPrepService = __esm({
245579
246317
  homeDir: homeDir2 = os23.homedir(),
245580
246318
  isPackaged = false,
245581
246319
  localScanRunner,
246320
+ onActiveLocalWorkChange = null,
245582
246321
  onEvent = null,
245583
246322
  prepareScanExecution,
245584
246323
  reportRecoverableError = null,
@@ -245847,10 +246586,16 @@ var init_localPrepService = __esm({
245847
246586
  };
245848
246587
  const withActiveLocalWork = async (fn) => {
245849
246588
  activeLocalWorkCount += 1;
246589
+ if (activeLocalWorkCount === 1) {
246590
+ onActiveLocalWorkChange?.();
246591
+ }
245850
246592
  try {
245851
246593
  return await fn();
245852
246594
  } finally {
245853
246595
  activeLocalWorkCount = Math.max(0, activeLocalWorkCount - 1);
246596
+ if (activeLocalWorkCount === 0) {
246597
+ onActiveLocalWorkChange?.();
246598
+ }
245854
246599
  }
245855
246600
  };
245856
246601
  const statePathFor = (projectId) => resolveDesktopInitLocalPrepStatePath({
@@ -263788,7 +264533,7 @@ var init_gitSsh = __esm({
263788
264533
  });
263789
264534
 
263790
264535
  // src/devbox/commands/agentInit/github.ts
263791
- var GITHUB_USAGE, startAgentInitGithubConnection, runAgentInitGithub, isGithubConnectionReady, readInstallUrl, connectAgentInitGithub, manageAgentInitGithubCliAccess;
264536
+ var GITHUB_USAGE, startAgentInitGithubConnection, runAgentInitGithub, isGithubConnectionReady, findAgentInitGithubAccessIssue, readInstallUrl, connectAgentInitGithub, manageAgentInitGithubCliAccess;
263792
264537
  var init_github = __esm({
263793
264538
  "src/devbox/commands/agentInit/github.ts"() {
263794
264539
  "use strict";
@@ -263883,6 +264628,18 @@ var init_github = __esm({
263883
264628
  const fields = connection;
263884
264629
  return fields["connectionStatus"] === "connected" && fields["tokenStatus"] === "valid" && fields["authorizationStatus"] === "current" && fields["credentialUpgradeStatus"] !== "update_available";
263885
264630
  };
264631
+ findAgentInitGithubAccessIssue = async ({
264632
+ client,
264633
+ projectLayoutRepos
264634
+ }) => {
264635
+ const connectionResult = await client.getGithubConnection({});
264636
+ const resolution = resolveAgentInitManagedGithubAccess({
264637
+ connectionResult,
264638
+ inventoryResult: isGithubConnectionReady(connectionResult) ? await client.listGithubRepositories({}) : null,
264639
+ projectLayoutRepos
264640
+ });
264641
+ return resolution.ok ? null : resolution.issue;
264642
+ };
263886
264643
  readInstallUrl = (result) => {
263887
264644
  if (!result || typeof result !== "object") return null;
263888
264645
  const fields = result;
@@ -265369,6 +266126,8 @@ var init_start = __esm({
265369
266126
  init_seed();
265370
266127
  init_check();
265371
266128
  init_githubAccess();
266129
+ init_parse6();
266130
+ init_github();
265372
266131
  init_progressReport();
265373
266132
  init_guidance();
265374
266133
  init_silencedConsole();
@@ -265440,13 +266199,13 @@ var init_start = __esm({
265440
266199
  fs56.rm(statePaths.preparedBundleStatePath, { force: true })
265441
266200
  ]);
265442
266201
  }
266202
+ const projectLayoutRepos = readAgentInitProjectLayoutRepos({
266203
+ repo,
266204
+ validation
266205
+ });
265443
266206
  let manifestSeeded = false;
265444
266207
  const manifestExists = await fileExists3(statePaths.manifestPath);
265445
266208
  if (!manifestExists || reseed) {
265446
- const projectLayoutRepos = readAgentInitProjectLayoutRepos({
265447
- repo,
265448
- validation
265449
- });
265450
266209
  const [agentConfigScan, threadScan, untrackedTree] = await withSilencedConsole(
265451
266210
  async () => Promise.all([
265452
266211
  scanDesktopAgentConfig({ localRepoRoot: repo.repoRoot }).catch(
@@ -265517,6 +266276,16 @@ var init_start = __esm({
265517
266276
  phase: checkStillPasses ? "ready_to_launch" : "preparing"
265518
266277
  }
265519
266278
  });
266279
+ const parsedManifest = manifestText === null ? null : parseAgentInitManifest(manifestText);
266280
+ const githubAccessIssue = parsedManifest?.ok === true && parsedManifest.manifest.version !== 1 && parsedManifest.manifest.githubAccess === "managed" ? await findAgentInitGithubAccessIssue({
266281
+ client: context34.controlPlaneClient,
266282
+ projectLayoutRepos
266283
+ }).catch((error55) => {
266284
+ console.warn(
266285
+ `Could not check GitHub access yet: ${error55 instanceof Error ? error55.message : String(error55)}`
266286
+ );
266287
+ return null;
266288
+ }) : null;
265520
266289
  if (json3) {
265521
266290
  console.log(
265522
266291
  JSON.stringify(
@@ -265529,7 +266298,8 @@ var init_start = __esm({
265529
266298
  projectId: repo.projectId,
265530
266299
  projectRoot: repo.repoRoot,
265531
266300
  stagingDir: statePaths.stagingDir,
265532
- projectGuidance: buildProjectSelectionGuidance(validation.project)
266301
+ projectGuidance: buildProjectSelectionGuidance(validation.project),
266302
+ githubAccessIssue
265533
266303
  },
265534
266304
  null,
265535
266305
  2
@@ -265547,6 +266317,13 @@ var init_start = __esm({
265547
266317
  console.log(
265548
266318
  `Staging folder for edited file copies: ${statePaths.stagingDir}`
265549
266319
  );
266320
+ if (githubAccessIssue) {
266321
+ console.log("");
266322
+ console.log(`GitHub access: ${githubAccessIssue.message}`);
266323
+ console.log(
266324
+ `Start on this first so the user can finish on GitHub while you investigate. ${githubAccessIssue.fix}`
266325
+ );
266326
+ }
265550
266327
  console.log("");
265551
266328
  console.log("Next steps:");
265552
266329
  console.log(
@@ -291620,23 +292397,211 @@ var init_mount = __esm({
291620
292397
  }
291621
292398
  });
291622
292399
 
291623
- // src/devbox/commands/mcp.ts
291624
- var listConnections, startAuthorization2, completeAuthorization, cancelAuthorization, createDefaultSession, defaultDependencies10, bindingStatus, renderConnections, serializeConnections, resolveConnection, parseListArgs2, parseAuthorizeArgs, runMcpListWithDependencies, runMcpAuthorizeWithDependencies, runMcpList, runMcpAuthorize;
291625
- var init_mcp = __esm({
291626
- "src/devbox/commands/mcp.ts"() {
292400
+ // src/devbox/commands/mcpArgs.ts
292401
+ var MCP_LIST_USAGE, MCP_ADD_USAGE, MCP_AUTHORIZE_USAGE, MCP_REMOVE_USAGE, readProject, parseAgent, parseConnectionSelector, parseListArgs2, parseAuthorizeArgs, parseRemoveArgs, parseHeader2, parseAddArgs;
292402
+ var init_mcpArgs = __esm({
292403
+ "src/devbox/commands/mcpArgs.ts"() {
291627
292404
  "use strict";
291628
- init_server();
291629
292405
  init_devboxCore();
291630
- init_browser();
291631
292406
  init_args();
291632
292407
  init_errors4();
292408
+ MCP_LIST_USAGE = "Usage: dvb mcp list [--project <project>] [--json]";
292409
+ MCP_ADD_USAGE = 'Usage: dvb mcp add <url-or-setup-command> [--name <name>] [--project <project> | --all-projects] [--agent <codex|claude>] [--header "<name>: <value>"] [--no-sign-in] [--no-authorize] [--no-browser] [--json]';
292410
+ MCP_AUTHORIZE_USAGE = "Usage: dvb mcp authorize <connection> --agent <codex|claude> [--project <project>] [--no-browser]";
292411
+ MCP_REMOVE_USAGE = "Usage: dvb mcp remove <connection> [--agent <codex|claude>] [--project <project>] [--json]";
292412
+ readProject = (flags) => readStringFlag(flags, "project")?.trim() || null;
292413
+ parseAgent = (commandPath, value) => {
292414
+ if (value !== "codex" && value !== "claude") {
292415
+ throw usageError(
292416
+ commandPath,
292417
+ "Choose an agent with `--agent codex` or `--agent claude`."
292418
+ );
292419
+ }
292420
+ return value;
292421
+ };
292422
+ parseConnectionSelector = (commandPath, positionals, usage2) => {
292423
+ if (positionals.length !== 1) throw usageError(commandPath, usage2);
292424
+ const selector = positionals[0]?.trim() ?? "";
292425
+ if (!selector || selector.length > 256) {
292426
+ throw usageError(commandPath, "The MCP connection name or id is invalid.");
292427
+ }
292428
+ return selector;
292429
+ };
292430
+ parseListArgs2 = (args) => {
292431
+ const commandPath = ["mcp", "list"];
292432
+ const { flags, positionals } = parseCommandArgs({
292433
+ args,
292434
+ commandPath,
292435
+ flagLabel: "mcp list",
292436
+ boolean: ["json"],
292437
+ string: ["project"]
292438
+ });
292439
+ if (positionals.length > 0) throw usageError(commandPath, MCP_LIST_USAGE);
292440
+ return { json: readBooleanFlag(flags, "json"), project: readProject(flags) };
292441
+ };
292442
+ parseAuthorizeArgs = (args) => {
292443
+ const commandPath = ["mcp", "authorize"];
292444
+ const { flags, positionals } = parseCommandArgs({
292445
+ args,
292446
+ commandPath,
292447
+ flagLabel: "mcp authorize",
292448
+ boolean: ["no-browser"],
292449
+ string: ["agent", "project"]
292450
+ });
292451
+ return {
292452
+ selector: parseConnectionSelector(
292453
+ commandPath,
292454
+ positionals,
292455
+ MCP_AUTHORIZE_USAGE
292456
+ ),
292457
+ agent: parseAgent(commandPath, readStringFlag(flags, "agent")),
292458
+ project: readProject(flags),
292459
+ browser: !readBooleanFlag(flags, "no-browser")
292460
+ };
292461
+ };
292462
+ parseRemoveArgs = (args) => {
292463
+ const commandPath = ["mcp", "remove"];
292464
+ const { flags, positionals } = parseCommandArgs({
292465
+ args,
292466
+ commandPath,
292467
+ flagLabel: "mcp remove",
292468
+ boolean: ["json"],
292469
+ string: ["agent", "project"]
292470
+ });
292471
+ const agent = readStringFlag(flags, "agent");
292472
+ return {
292473
+ selector: parseConnectionSelector(
292474
+ commandPath,
292475
+ positionals,
292476
+ MCP_REMOVE_USAGE
292477
+ ),
292478
+ agent: agent === void 0 ? null : parseAgent(commandPath, agent),
292479
+ project: readProject(flags),
292480
+ json: readBooleanFlag(flags, "json")
292481
+ };
292482
+ };
292483
+ parseHeader2 = (value) => {
292484
+ const separator = value.indexOf(":");
292485
+ const name = separator < 0 ? "" : value.slice(0, separator).trim();
292486
+ const headerValue = separator < 0 ? "" : value.slice(separator + 1).trim();
292487
+ if (!name || !headerValue) {
292488
+ throw usageError(
292489
+ ["mcp", "add"],
292490
+ 'Write each header as --header "<name>: <value>", for example --header "Authorization: Bearer <key>".'
292491
+ );
292492
+ }
292493
+ return { name, value: headerValue };
292494
+ };
292495
+ parseAddArgs = (args) => {
292496
+ const commandPath = ["mcp", "add"];
292497
+ const separator = args.indexOf("--");
292498
+ const ownArgs = separator < 0 ? args : args.slice(0, separator);
292499
+ const pastedArgv = separator < 0 ? [] : args.slice(separator + 1);
292500
+ const { flags, positionals } = parseCommandArgs({
292501
+ args: ownArgs,
292502
+ commandPath,
292503
+ flagLabel: "mcp add",
292504
+ boolean: [
292505
+ "all-projects",
292506
+ "no-sign-in",
292507
+ "no-authorize",
292508
+ "no-browser",
292509
+ "json"
292510
+ ],
292511
+ string: ["name", "project", "agent", "header"]
292512
+ });
292513
+ if (positionals.length === 0 === (pastedArgv.length === 0)) {
292514
+ throw usageError(commandPath, MCP_ADD_USAGE);
292515
+ }
292516
+ const project = readProject(flags);
292517
+ const allProjects = readBooleanFlag(flags, "all-projects");
292518
+ if (project !== null && allProjects) {
292519
+ throw usageError(
292520
+ commandPath,
292521
+ "Choose either --project or --all-projects, not both."
292522
+ );
292523
+ }
292524
+ const name = readStringFlag(flags, "name")?.trim() || null;
292525
+ if (name !== null && !isValidMcpNativeName(name)) {
292526
+ throw usageError(
292527
+ commandPath,
292528
+ "MCP names can use letters, numbers, hyphens, and underscores, up to 128 characters."
292529
+ );
292530
+ }
292531
+ const agentValues = readRepeatedStringFlag(ownArgs, "agent");
292532
+ const agents = agentValues.length === 0 ? null : [
292533
+ ...new Set(
292534
+ agentValues.map((value) => parseAgent(commandPath, value))
292535
+ )
292536
+ ];
292537
+ return {
292538
+ // A single argument is a URL or a quoted setup command. Several arguments
292539
+ // are an unquoted setup command.
292540
+ input: pastedArgv.length > 0 ? pastedArgv : positionals.length === 1 ? positionals[0] ?? "" : positionals,
292541
+ name,
292542
+ project,
292543
+ allProjects,
292544
+ agents,
292545
+ headers: readRepeatedStringFlag(ownArgs, "header").map(parseHeader2),
292546
+ signIn: !readBooleanFlag(flags, "no-sign-in"),
292547
+ authorize: !readBooleanFlag(flags, "no-authorize"),
292548
+ browser: !readBooleanFlag(flags, "no-browser"),
292549
+ json: readBooleanFlag(flags, "json")
292550
+ };
292551
+ };
292552
+ }
292553
+ });
292554
+
292555
+ // src/devbox/commands/mcpSession.ts
292556
+ var listAllConnections, listProjectConnections, getConnection, reconcileTeamConnections, inspectServer, createConnection2, setStaticHeaders, connectAgent, disconnectAgent, removeConnection, startAuthorization2, completeAuthorization, cancelAuthorization, listCliProjects, toUserFacingMcpError, createDefaultMcpCliSession;
292557
+ var init_mcpSession = __esm({
292558
+ "src/devbox/commands/mcpSession.ts"() {
292559
+ "use strict";
292560
+ init_server();
292561
+ init_values();
292562
+ init_devboxCore();
292563
+ init_threadInventory();
292564
+ init_queryRefs();
291633
292565
  init_controlPlane();
292566
+ init_errors5();
291634
292567
  init_context2();
291635
- listConnections = makeFunctionReference("mcpConnections:listAllForViewer");
292568
+ listAllConnections = makeFunctionReference("mcpConnections:listAllForViewer");
292569
+ listProjectConnections = makeFunctionReference("mcpConnections:listForViewer");
292570
+ getConnection = makeFunctionReference("mcpConnections:getForViewer");
292571
+ reconcileTeamConnections = makeFunctionReference("mcpTeamConnections:reconcileForViewer");
292572
+ inspectServer = makeFunctionReference("mcpSetupPreflightNode:inspectForViewer");
292573
+ createConnection2 = makeFunctionReference("mcpConnections:createForViewer");
292574
+ setStaticHeaders = makeFunctionReference("mcpCredentials:setStaticHeadersForViewer");
292575
+ connectAgent = makeFunctionReference("mcpConnections:connectAgentForViewer");
292576
+ disconnectAgent = makeFunctionReference("mcpConnections:disconnectAgentForViewer");
292577
+ removeConnection = makeFunctionReference("mcpConnections:removeForViewer");
291636
292578
  startAuthorization2 = makeFunctionReference("mcpAgentBindings:startAuthorizationForViewer");
291637
292579
  completeAuthorization = makeFunctionReference("mcpAgentBindings:completeAuthorizationForViewer");
291638
292580
  cancelAuthorization = makeFunctionReference("mcpAgentBindings:cancelAuthorizationForViewer");
291639
- createDefaultSession = async () => {
292581
+ listCliProjects = async (client) => {
292582
+ const result = await client.query(listAgentViewProjectsV2, {});
292583
+ if (result.contractVersion !== CLI_AGENT_VIEW_PROJECT_CONTRACT_VERSION) {
292584
+ throw new CliAgentToolError({
292585
+ code: "contract_version_unsupported",
292586
+ message: `Project inventory returned unsupported contract version ${String(result.contractVersion)}.`
292587
+ });
292588
+ }
292589
+ return result.projects.map(adaptCliAgentViewProjectSummaryV2);
292590
+ };
292591
+ toUserFacingMcpError = (error55) => {
292592
+ if (!(error55 instanceof ConvexError)) return error55;
292593
+ const data = error55.data;
292594
+ if (typeof data !== "object" || data === null) return error55;
292595
+ const record3 = data;
292596
+ if (typeof record3.message !== "string") return error55;
292597
+ if (record3.code === "mcp_native_name_conflict" && typeof record3.suggestedNativeName === "string") {
292598
+ return new Error(
292599
+ `${record3.message} Choose another name with --name, for example --name ${record3.suggestedNativeName}.`
292600
+ );
292601
+ }
292602
+ return new Error(record3.message);
292603
+ };
292604
+ createDefaultMcpCliSession = async () => {
291640
292605
  const tokenContext = await createCliControlPlaneTokenContext({
291641
292606
  allowInteractiveLogin: process.stdin.isTTY === true,
291642
292607
  tokenProviderMode: "bounded"
@@ -291645,7 +292610,25 @@ var init_mcp = __esm({
291645
292610
  tokenContext.getToken
291646
292611
  );
291647
292612
  return {
291648
- list: async () => await client.query(listConnections, {}),
292613
+ listAll: async () => await client.query(listAllConnections, {}),
292614
+ listForProject: async (primaryInstanceId) => {
292615
+ await client.mutation(reconcileTeamConnections, { primaryInstanceId });
292616
+ return await client.query(listProjectConnections, { primaryInstanceId });
292617
+ },
292618
+ get: async (connectionId) => await client.query(getConnection, { connectionId }),
292619
+ listProjects: async () => await listCliProjects(client),
292620
+ inspect: async (url3) => await client.action(inspectServer, { url: url3 }),
292621
+ create: async (request2) => await client.mutation(createConnection2, request2),
292622
+ setStaticHeaders: async (request2) => {
292623
+ await client.mutation(setStaticHeaders, request2);
292624
+ },
292625
+ connectAgent: async (request2) => {
292626
+ await client.mutation(connectAgent, request2);
292627
+ },
292628
+ disconnectAgent: async (request2) => await client.mutation(disconnectAgent, request2),
292629
+ remove: async (request2) => {
292630
+ await client.mutation(removeConnection, request2);
292631
+ },
291649
292632
  start: async (request2) => await client.mutation(startAuthorization2, request2),
291650
292633
  complete: async (request2) => {
291651
292634
  await client.mutation(completeAuthorization, request2);
@@ -291656,116 +292639,290 @@ var init_mcp = __esm({
291656
292639
  close: async () => await client.close()
291657
292640
  };
291658
292641
  };
292642
+ }
292643
+ });
292644
+
292645
+ // src/devbox/commands/mcpSignIn.ts
292646
+ import readline6 from "node:readline/promises";
292647
+ var MCP_AGENT_LABELS, createStdinLineReader, createMcpTerminalSignIn;
292648
+ var init_mcpSignIn = __esm({
292649
+ "src/devbox/commands/mcpSignIn.ts"() {
292650
+ "use strict";
292651
+ MCP_AGENT_LABELS = {
292652
+ codex: "Codex",
292653
+ claude: "Claude"
292654
+ };
292655
+ createStdinLineReader = () => {
292656
+ const rl = readline6.createInterface({
292657
+ input: process.stdin,
292658
+ output: process.stdout,
292659
+ terminal: false
292660
+ });
292661
+ let closed = false;
292662
+ rl.on("close", () => {
292663
+ closed = true;
292664
+ });
292665
+ return {
292666
+ question: async (prompt, signal) => {
292667
+ if (closed || signal.aborted) return null;
292668
+ try {
292669
+ return await rl.question(prompt, { signal });
292670
+ } catch (error55) {
292671
+ if (closed || signal.aborted) return null;
292672
+ throw error55;
292673
+ }
292674
+ },
292675
+ close: () => rl.close()
292676
+ };
292677
+ };
292678
+ createMcpTerminalSignIn = ({
292679
+ agent,
292680
+ connectionName,
292681
+ terminal: terminal2
292682
+ }) => {
292683
+ let markShown = () => void 0;
292684
+ const shown = new Promise((resolve3) => {
292685
+ markShown = resolve3;
292686
+ });
292687
+ const lineReader = terminal2.lineReader;
292688
+ return {
292689
+ openAuthorizationUrl: async (url3) => {
292690
+ terminal2.print(
292691
+ `Open this link to sign in to ${connectionName} for ${MCP_AGENT_LABELS[agent]}:
292692
+
292693
+ ${url3}
292694
+ `
292695
+ );
292696
+ if (terminal2.browserAvailable && terminal2.openBrowser(url3)) {
292697
+ terminal2.print("Your browser should open it now.");
292698
+ }
292699
+ terminal2.print(
292700
+ lineReader ? "If you sign in on another computer, your browser will end on a page that doesn't load. Copy that page's full address and paste it here." : "Waiting for you to finish signing in..."
292701
+ );
292702
+ markShown();
292703
+ },
292704
+ manualCallbackInput: lineReader ? {
292705
+ readCallbackUrl: async (signal) => {
292706
+ await Promise.race([
292707
+ shown,
292708
+ new Promise((resolve3) => {
292709
+ signal.addEventListener("abort", () => resolve3(), {
292710
+ once: true
292711
+ });
292712
+ })
292713
+ ]);
292714
+ if (signal.aborted) return null;
292715
+ let line = "";
292716
+ while (line !== null && !line.trim()) {
292717
+ line = await lineReader.question(
292718
+ "Paste the address, or wait for sign-in to finish: ",
292719
+ signal
292720
+ );
292721
+ }
292722
+ if (line === null && signal.aborted) terminal2.print("");
292723
+ return line;
292724
+ },
292725
+ reportRejectedCallbackUrl: (message) => terminal2.print(message)
292726
+ } : null
292727
+ };
292728
+ };
292729
+ }
292730
+ });
292731
+
292732
+ // src/devbox/commands/mcp.ts
292733
+ var defaultDependencies10, TEMPLATE_MANAGED_SENTENCES, bindingStatus, projectForConnection, describeScope, renderConnections, serializeConnection, uniqueMatch, resolveConnection, resolveProject, loadConnections, requireConnection, readableSelector, authorizeAgent, runMcpListWithDependencies, runMcpAuthorizeWithDependencies, selectProjectForAdd, planAdd, resolveAuthMode, runMcpAddWithDependencies, runMcpRemoveWithDependencies, runMcpList, runMcpAuthorize, runMcpAdd, runMcpRemove;
292734
+ var init_mcp = __esm({
292735
+ "src/devbox/commands/mcp.ts"() {
292736
+ "use strict";
292737
+ init_devboxCore();
292738
+ init_browser();
292739
+ init_identifiers();
292740
+ init_mcpArgs();
292741
+ init_mcpSession();
292742
+ init_mcpSignIn();
291659
292743
  defaultDependencies10 = {
291660
- createSession: createDefaultSession,
292744
+ createSession: createDefaultMcpCliSession,
291661
292745
  authorize: authorizeMcpOAuth,
291662
- openAuthorizationUrl: async (url3) => {
291663
- if (!openBrowser(url3)) {
291664
- throw new Error(
291665
- "Could not open the MCP sign-in page. Open this command from the boxes.dev desktop app or check your browser configuration."
291666
- );
291667
- }
291668
- },
292746
+ openBrowser: (url3) => openBrowser(url3),
292747
+ browserAvailable: canOpenLocalBrowser(),
292748
+ createLineReader: () => process.stdin.isTTY === true ? createStdinLineReader() : null,
292749
+ readEnv: (name) => process.env[name],
291669
292750
  subscribeInterrupt: (listener) => {
291670
292751
  process.once("SIGINT", listener);
291671
292752
  return () => process.off("SIGINT", listener);
291672
292753
  },
291673
- print: console.log
292754
+ print: console.log,
292755
+ printStatus: console.error
292756
+ };
292757
+ TEMPLATE_MANAGED_SENTENCES = {
292758
+ custom_oauth_client: "This command uses custom OAuth settings that boxes.dev can't manage yet.",
292759
+ insecure_url: "boxes.dev can only manage MCPs served over public HTTPS.",
292760
+ legacy_sse: "This command uses the older SSE transport, which boxes.dev doesn't manage.",
292761
+ stdio: "This command installs an MCP that runs on the machine itself, so boxes.dev can't manage it centrally.",
292762
+ unsupported_option: "This command uses options boxes.dev can't manage yet."
291674
292763
  };
291675
292764
  bindingStatus = (connection, agent) => connection.bindings.find((binding) => binding.agent === agent)?.status ?? "not_added";
291676
- renderConnections = (connections) => {
292765
+ projectForConnection = (connection, projects) => connection.scope.kind === "project" ? projects.find(
292766
+ (project) => project.primaryInstanceId === connection.scope.primaryInstanceId
292767
+ ) ?? null : null;
292768
+ describeScope = (connection, projects) => {
292769
+ if (connection.scope.kind === "all_projects") return "all projects";
292770
+ const project = projectForConnection(connection, projects);
292771
+ return `project ${project?.projectAlias ?? connection.scope.primaryInstanceId ?? "unknown"}`;
292772
+ };
292773
+ renderConnections = (connections, projects) => {
291677
292774
  if (connections.length === 0) return "No centrally managed MCPs.";
291678
292775
  return connections.map(
291679
- (connection) => `${connection.displayName}
291680
- id: ${connection.connectionId}
291681
- name: ${connection.nativeName}
291682
- scope: ${connection.scope.kind === "project" ? "project" : "all projects"}
291683
- auth: ${connection.authMode}
291684
- Codex: ${bindingStatus(connection, "codex")}
291685
- Claude: ${bindingStatus(connection, "claude")}
291686
- url: ${connection.url}`
292776
+ (connection) => [
292777
+ connection.displayName,
292778
+ ` id: ${connection.connectionId}`,
292779
+ ` name: ${connection.nativeName}`,
292780
+ ` scope: ${describeScope(connection, projects)}`,
292781
+ ...connection.teamTemplateId ? [" managed by: your team"] : [],
292782
+ ` auth: ${connection.authMode}`,
292783
+ ` Codex: ${bindingStatus(connection, "codex")}`,
292784
+ ` Claude: ${bindingStatus(connection, "claude")}`,
292785
+ ` url: ${connection.url}`
292786
+ ].join("\n")
291687
292787
  ).join("\n\n");
291688
292788
  };
291689
- serializeConnections = (connections) => connections.map((connection) => ({
291690
- connectionId: connection.connectionId,
291691
- displayName: connection.displayName,
291692
- nativeName: connection.nativeName,
291693
- url: connection.url,
291694
- authMode: connection.authMode,
291695
- scope: connection.scope,
291696
- agents: {
291697
- codex: bindingStatus(connection, "codex"),
291698
- claude: bindingStatus(connection, "claude")
291699
- }
291700
- }));
291701
- resolveConnection = (connections, selector) => {
291702
- const byId = connections.find(
291703
- (connection) => connection.connectionId === selector
291704
- );
291705
- if (byId) return byId;
291706
- const matches2 = connections.filter(
291707
- (connection) => connection.nativeName === selector || connection.displayName === selector
291708
- );
291709
- if (matches2.length === 1) return matches2[0] ?? null;
292789
+ serializeConnection = (connection, projects) => {
292790
+ const project = projectForConnection(connection, projects);
292791
+ return {
292792
+ connectionId: connection.connectionId,
292793
+ displayName: connection.displayName,
292794
+ nativeName: connection.nativeName,
292795
+ url: connection.url,
292796
+ authMode: connection.authMode,
292797
+ scope: connection.scope,
292798
+ project: project ? { name: project.projectAlias, fingerprint: project.projectFingerprint } : null,
292799
+ teamManaged: Boolean(connection.teamTemplateId),
292800
+ agents: {
292801
+ codex: bindingStatus(connection, "codex"),
292802
+ claude: bindingStatus(connection, "claude")
292803
+ }
292804
+ };
292805
+ };
292806
+ uniqueMatch = (matches2, selector, projectSelected) => {
291710
292807
  if (matches2.length > 1) {
291711
292808
  throw new Error(
291712
- `More than one MCP is named ${JSON.stringify(selector)}. Run \`dvb mcp list\` and use its id.`
292809
+ `More than one MCP is named ${JSON.stringify(selector)}. ${projectSelected ? "Run `dvb mcp list` and use its id." : "Add --project <project>, or run `dvb mcp list` and use its id."}`
291713
292810
  );
291714
292811
  }
291715
- return null;
292812
+ return matches2[0] ?? null;
291716
292813
  };
291717
- parseListArgs2 = (args) => {
291718
- const { flags, positionals } = parseCommandArgs({
291719
- args,
291720
- commandPath: ["mcp", "list"],
291721
- flagLabel: "mcp list",
291722
- boolean: ["json"]
291723
- });
291724
- if (positionals.length > 0) {
291725
- throw usageError(["mcp", "list"], "Usage: dvb mcp list [--json]");
291726
- }
291727
- return { json: readBooleanFlag(flags, "json") };
292814
+ resolveConnection = (connections, selector, projectSelected = false) => connections.find((connection) => connection.connectionId === selector) ?? uniqueMatch(
292815
+ connections.filter((connection) => connection.nativeName === selector),
292816
+ selector,
292817
+ projectSelected
292818
+ ) ?? uniqueMatch(
292819
+ connections.filter((connection) => connection.displayName === selector),
292820
+ selector,
292821
+ projectSelected
292822
+ );
292823
+ resolveProject = (projects, selector) => resolveCliAgentToolProject({ selector, projects });
292824
+ loadConnections = async (session, projectSelector) => {
292825
+ const projects = await session.listProjects();
292826
+ const connections = projectSelector === null ? await session.listAll() : await session.listForProject(
292827
+ resolveProject(projects, projectSelector).primaryInstanceId
292828
+ );
292829
+ return { connections, projects };
291728
292830
  };
291729
- parseAuthorizeArgs = (args) => {
291730
- const { flags, positionals } = parseCommandArgs({
291731
- args,
291732
- commandPath: ["mcp", "authorize"],
291733
- flagLabel: "mcp authorize",
291734
- string: ["agent"]
291735
- });
291736
- if (positionals.length !== 1) {
291737
- throw usageError(
291738
- ["mcp", "authorize"],
291739
- "Usage: dvb mcp authorize <connection> --agent <codex|claude>"
291740
- );
291741
- }
291742
- const selector = positionals[0]?.trim() ?? "";
291743
- if (!selector || selector.length > 256) {
291744
- throw usageError(
291745
- ["mcp", "authorize"],
291746
- "The MCP connection name or id is invalid."
291747
- );
292831
+ requireConnection = (connections, selector, projectSelector) => {
292832
+ const connection = resolveConnection(
292833
+ connections,
292834
+ selector,
292835
+ projectSelector !== null
292836
+ );
292837
+ if (connection) return connection;
292838
+ throw new Error(
292839
+ `MCP ${JSON.stringify(selector)} was not found. Run \`dvb mcp list\` to see your MCPs.${projectSelector === null ? " If your team manages it, add --project <project>." : ""}`
292840
+ );
292841
+ };
292842
+ readableSelector = (connection, connections) => {
292843
+ try {
292844
+ return resolveConnection(connections, connection.nativeName)?.connectionId === connection.connectionId ? connection.nativeName : connection.connectionId;
292845
+ } catch {
292846
+ return connection.connectionId;
291748
292847
  }
291749
- const agent = readStringFlag(flags, "agent");
291750
- if (agent !== "codex" && agent !== "claude") {
291751
- throw usageError(
291752
- ["mcp", "authorize"],
291753
- "Choose an agent with `--agent codex` or `--agent claude`."
291754
- );
292848
+ };
292849
+ authorizeAgent = async ({
292850
+ agent,
292851
+ browser,
292852
+ connection,
292853
+ dependencies,
292854
+ lineReader,
292855
+ session
292856
+ }) => {
292857
+ const abortController = new AbortController();
292858
+ const unsubscribe4 = dependencies.subscribeInterrupt(
292859
+ () => abortController.abort()
292860
+ );
292861
+ let attempt = null;
292862
+ let completed = false;
292863
+ try {
292864
+ attempt = await session.start({ agent, connectionId: connection.connectionId }).catch((error55) => {
292865
+ throw toUserFacingMcpError(error55);
292866
+ });
292867
+ const signIn = createMcpTerminalSignIn({
292868
+ agent,
292869
+ connectionName: connection.displayName,
292870
+ terminal: {
292871
+ print: dependencies.printStatus,
292872
+ openBrowser: dependencies.openBrowser,
292873
+ browserAvailable: browser && dependencies.browserAvailable,
292874
+ lineReader
292875
+ }
292876
+ });
292877
+ const startedAttempt = attempt;
292878
+ return await dependencies.authorize({
292879
+ agent,
292880
+ serverName: startedAttempt.serverName,
292881
+ serverUrl: startedAttempt.serverUrl,
292882
+ signal: abortController.signal,
292883
+ openAuthorizationUrl: signIn.openAuthorizationUrl,
292884
+ ...signIn.manualCallbackInput ? { manualCallbackInput: signIn.manualCallbackInput } : {},
292885
+ uploadGrant: async (grant) => {
292886
+ await session.complete({
292887
+ attemptNonce: startedAttempt.attemptNonce,
292888
+ bindingId: startedAttempt.bindingId,
292889
+ grant
292890
+ });
292891
+ completed = true;
292892
+ }
292893
+ });
292894
+ } catch (error55) {
292895
+ if (attempt && !completed) {
292896
+ const startedAttempt = attempt;
292897
+ await session.cancel({
292898
+ attemptNonce: startedAttempt.attemptNonce,
292899
+ bindingId: startedAttempt.bindingId
292900
+ }).catch(() => void 0);
292901
+ }
292902
+ throw error55;
292903
+ } finally {
292904
+ unsubscribe4();
291755
292905
  }
291756
- return { selector, agent };
291757
292906
  };
291758
292907
  runMcpListWithDependencies = async (args, dependencies) => {
291759
292908
  const parsed = parseListArgs2(args);
291760
292909
  const session = await dependencies.createSession();
291761
292910
  try {
291762
- const connections = await session.list();
292911
+ const { connections, projects } = await loadConnections(
292912
+ session,
292913
+ parsed.project
292914
+ );
291763
292915
  dependencies.print(
291764
292916
  parsed.json ? JSON.stringify(
291765
- { ok: true, connections: serializeConnections(connections) },
292917
+ {
292918
+ ok: true,
292919
+ connections: connections.map(
292920
+ (connection) => serializeConnection(connection, projects)
292921
+ )
292922
+ },
291766
292923
  null,
291767
292924
  2
291768
- ) : renderConnections(connections)
292925
+ ) : renderConnections(connections, projects)
291769
292926
  );
291770
292927
  } finally {
291771
292928
  await session.close();
@@ -291774,54 +292931,265 @@ var init_mcp = __esm({
291774
292931
  runMcpAuthorizeWithDependencies = async (args, dependencies) => {
291775
292932
  const parsed = parseAuthorizeArgs(args);
291776
292933
  const session = await dependencies.createSession();
291777
- const abortController = new AbortController();
291778
- const unsubscribe4 = dependencies.subscribeInterrupt(
291779
- () => abortController.abort()
291780
- );
291781
- let attempt = null;
291782
- let completed = false;
292934
+ const lineReader = dependencies.createLineReader();
291783
292935
  try {
291784
- const connections = await session.list();
291785
- const connection = resolveConnection(connections, parsed.selector);
291786
- if (!connection) {
292936
+ const { connections } = await loadConnections(session, parsed.project);
292937
+ const connection = requireConnection(
292938
+ connections,
292939
+ parsed.selector,
292940
+ parsed.project
292941
+ );
292942
+ const receipt = await authorizeAgent({
292943
+ agent: parsed.agent,
292944
+ browser: parsed.browser,
292945
+ connection,
292946
+ dependencies,
292947
+ lineReader,
292948
+ session
292949
+ });
292950
+ dependencies.print(
292951
+ `${connection.displayName} is connected to ${MCP_AGENT_LABELS[parsed.agent]}.`
292952
+ );
292953
+ return receipt;
292954
+ } finally {
292955
+ lineReader?.close();
292956
+ await session.close();
292957
+ }
292958
+ };
292959
+ selectProjectForAdd = (projects, selector) => {
292960
+ if (selector !== null) return resolveProject(projects, selector);
292961
+ const only = projects[0];
292962
+ if (projects.length === 1 && only) return only;
292963
+ if (projects.length === 0) {
292964
+ throw new Error(
292965
+ "You don't have a boxes.dev project yet. Add --all-projects to make this MCP available in every project."
292966
+ );
292967
+ }
292968
+ throw new Error(
292969
+ `Choose a project with --project <name>, or add --all-projects. Your projects: ${projects.map((project) => project.projectAlias).join(", ")}.`
292970
+ );
292971
+ };
292972
+ planAdd = (parsed, readEnv) => {
292973
+ const imported = typeof parsed.input === "string" ? parseMcpCommandImport(parsed.input) : parseMcpAddArgv(parsed.input);
292974
+ if (imported.kind === "invalid") throw new Error(imported.message);
292975
+ if (imported.kind === "template_managed") {
292976
+ throw new Error(
292977
+ `${TEMPLATE_MANAGED_SENTENCES[imported.reason]} Run it on your Template box instead.`
292978
+ );
292979
+ }
292980
+ const headers = [...imported.staticHeaders, ...parsed.headers];
292981
+ const hasAuthorizationHeader = parsed.headers.some(
292982
+ (header) => header.name.toLowerCase() === "authorization"
292983
+ );
292984
+ if (imported.bearerTokenEnvVar !== null && !hasAuthorizationHeader) {
292985
+ const token = readEnv(imported.bearerTokenEnvVar)?.trim();
292986
+ if (!token) {
291787
292987
  throw new Error(
291788
- `MCP ${JSON.stringify(parsed.selector)} was not found. Run \`dvb mcp list\` to see available connections.`
292988
+ `This command reads its token from ${imported.bearerTokenEnvVar}, which isn't set here. Set it in this terminal, or pass the token with --header "Authorization: Bearer <token>".`
291789
292989
  );
291790
292990
  }
291791
- attempt = await session.start({
291792
- agent: parsed.agent,
291793
- connectionId: connection.connectionId
292991
+ headers.push({ name: "Authorization", value: `Bearer ${token}` });
292992
+ }
292993
+ return {
292994
+ imported,
292995
+ agents: parsed.agents ?? (imported.requestedAgent ? [imported.requestedAgent] : ["codex", "claude"]),
292996
+ scopeKind: parsed.allProjects ? "all_projects" : parsed.project !== null ? "project" : imported.requestedScope,
292997
+ headers
292998
+ };
292999
+ };
293000
+ resolveAuthMode = async ({
293001
+ headers,
293002
+ imported,
293003
+ session,
293004
+ signIn
293005
+ }) => {
293006
+ if (headers.length > 0) {
293007
+ return {
293008
+ authMode: "static_headers",
293009
+ displayName: imported.displayName,
293010
+ signInOptional: false
293011
+ };
293012
+ }
293013
+ const preflight = await session.inspect(imported.url);
293014
+ const displayName = preflight.displayName ?? imported.displayName;
293015
+ switch (preflight.classification) {
293016
+ case "unreachable":
293017
+ throw new Error(
293018
+ "boxes.dev couldn't reach this server. Check the URL and try again."
293019
+ );
293020
+ case "static_or_manual":
293021
+ case "unknown":
293022
+ if (!signIn) {
293023
+ return { authMode: "none", displayName, signInOptional: false };
293024
+ }
293025
+ throw new Error(
293026
+ `boxes.dev couldn't tell how this MCP signs in. Add its API key with --header "Authorization: Bearer <key>", or add --no-sign-in to use it without signing in.`
293027
+ );
293028
+ case "none":
293029
+ return { authMode: "none", displayName, signInOptional: false };
293030
+ case "oauth":
293031
+ if (!signIn && !preflight.signInOptional) {
293032
+ throw new Error(
293033
+ "This MCP requires signing in. Remove --no-sign-in and try again."
293034
+ );
293035
+ }
293036
+ return {
293037
+ authMode: signIn ? "oauth" : "none",
293038
+ displayName,
293039
+ signInOptional: preflight.signInOptional
293040
+ };
293041
+ }
293042
+ };
293043
+ runMcpAddWithDependencies = async (args, dependencies) => {
293044
+ const parsed = parseAddArgs(args);
293045
+ const plan = planAdd(parsed, dependencies.readEnv);
293046
+ const status = parsed.json ? dependencies.printStatus : dependencies.print;
293047
+ const session = await dependencies.createSession();
293048
+ const lineReader = parsed.authorize && !parsed.json ? dependencies.createLineReader() : null;
293049
+ try {
293050
+ const projects = await session.listProjects();
293051
+ const project = plan.scopeKind === "project" ? selectProjectForAdd(projects, parsed.project) : null;
293052
+ const { authMode, displayName, signInOptional } = await resolveAuthMode({
293053
+ headers: plan.headers,
293054
+ imported: plan.imported,
293055
+ session,
293056
+ signIn: parsed.signIn
293057
+ });
293058
+ const created = await session.create({
293059
+ displayName: parsed.name ?? displayName,
293060
+ nativeName: parsed.name ?? plan.imported.nativeName,
293061
+ scopeKind: plan.scopeKind,
293062
+ primaryInstanceId: project?.primaryInstanceId ?? null,
293063
+ url: plan.imported.url,
293064
+ authMode,
293065
+ signInOptional
293066
+ }).catch((error55) => {
293067
+ throw toUserFacingMcpError(error55);
291794
293068
  });
291795
- const receipt = await dependencies.authorize({
291796
- agent: parsed.agent,
291797
- serverName: attempt.serverName,
291798
- serverUrl: attempt.serverUrl,
291799
- signal: abortController.signal,
291800
- openAuthorizationUrl: dependencies.openAuthorizationUrl,
291801
- uploadGrant: async (grant) => {
291802
- if (!attempt) throw new Error("MCP authorization was not started.");
291803
- await session.complete({
291804
- attemptNonce: attempt.attemptNonce,
291805
- bindingId: attempt.bindingId,
291806
- grant
293069
+ let connection = await session.get(created.connectionId);
293070
+ status(
293071
+ `Added ${connection.displayName} to ${project ? `project ${project.projectAlias}` : "all projects"}.`
293072
+ );
293073
+ let signingIn = null;
293074
+ const signInLater = [];
293075
+ try {
293076
+ if (authMode === "static_headers") {
293077
+ await session.setStaticHeaders({
293078
+ connectionId: created.connectionId,
293079
+ headers: plan.headers
291807
293080
  });
291808
- completed = true;
291809
293081
  }
291810
- });
291811
- dependencies.print(
291812
- `${connection.displayName} is connected to ${parsed.agent === "codex" ? "Codex" : "Claude"}.`
293082
+ for (const agent of plan.agents) {
293083
+ if (authMode !== "oauth") {
293084
+ await session.connectAgent({
293085
+ connectionId: created.connectionId,
293086
+ agent
293087
+ });
293088
+ } else if (parsed.authorize) {
293089
+ signingIn = agent;
293090
+ await authorizeAgent({
293091
+ agent,
293092
+ browser: parsed.browser,
293093
+ connection,
293094
+ dependencies,
293095
+ lineReader,
293096
+ session
293097
+ });
293098
+ signingIn = null;
293099
+ } else {
293100
+ signInLater.push(agent);
293101
+ }
293102
+ }
293103
+ } catch (error55) {
293104
+ const userError = toUserFacingMcpError(error55);
293105
+ const reason = userError instanceof Error ? userError.message : String(userError);
293106
+ if (signingIn === null) {
293107
+ throw new Error(
293108
+ `${connection.displayName} was added, but connecting it to the agents didn't finish: ${reason}`
293109
+ );
293110
+ }
293111
+ const selector = readableSelector(connection, await session.listAll());
293112
+ throw new Error(
293113
+ `${connection.displayName} was added, but signing in for ${MCP_AGENT_LABELS[signingIn]} didn't finish: ${reason} To try again, run: dvb mcp authorize ${selector} --agent ${signingIn}`
293114
+ );
293115
+ }
293116
+ connection = await session.get(created.connectionId);
293117
+ if (signInLater.length > 0) {
293118
+ const selector = readableSelector(connection, await session.listAll());
293119
+ status(
293120
+ [
293121
+ "To sign in, run:",
293122
+ ...signInLater.map(
293123
+ (agent) => ` dvb mcp authorize ${selector} --agent ${agent}`
293124
+ )
293125
+ ].join("\n")
293126
+ );
293127
+ }
293128
+ const connectedAgents = plan.agents.filter((agent) => bindingStatus(connection, agent) === "connected").map((agent) => MCP_AGENT_LABELS[agent]);
293129
+ if (parsed.json) {
293130
+ dependencies.print(
293131
+ JSON.stringify(
293132
+ { ok: true, connection: serializeConnection(connection, projects) },
293133
+ null,
293134
+ 2
293135
+ )
293136
+ );
293137
+ } else if (connectedAgents.length > 0) {
293138
+ dependencies.print(
293139
+ `${connection.displayName} is connected to ${connectedAgents.join(" and ")}.`
293140
+ );
293141
+ }
293142
+ } finally {
293143
+ lineReader?.close();
293144
+ await session.close();
293145
+ }
293146
+ };
293147
+ runMcpRemoveWithDependencies = async (args, dependencies) => {
293148
+ const parsed = parseRemoveArgs(args);
293149
+ const session = await dependencies.createSession();
293150
+ try {
293151
+ const { connections } = await loadConnections(session, parsed.project);
293152
+ const connection = requireConnection(
293153
+ connections,
293154
+ parsed.selector,
293155
+ parsed.project
291813
293156
  );
291814
- return receipt;
291815
- } catch (error55) {
291816
- if (attempt && !completed) {
291817
- await session.cancel({
291818
- attemptNonce: attempt.attemptNonce,
291819
- bindingId: attempt.bindingId
291820
- }).catch(() => void 0);
293157
+ let changed = true;
293158
+ try {
293159
+ if (parsed.agent) {
293160
+ ({ changed } = await session.disconnectAgent({
293161
+ connectionId: connection.connectionId,
293162
+ agent: parsed.agent
293163
+ }));
293164
+ } else if (connection.teamTemplateId) {
293165
+ throw new Error(
293166
+ "Your team manages this MCP, so it can't be removed. To stop using it, remove it from one agent with --agent codex or --agent claude."
293167
+ );
293168
+ } else {
293169
+ await session.remove({ connectionId: connection.connectionId });
293170
+ }
293171
+ } catch (error55) {
293172
+ throw toUserFacingMcpError(error55);
291821
293173
  }
291822
- throw error55;
293174
+ if (parsed.json) {
293175
+ dependencies.print(
293176
+ JSON.stringify(
293177
+ {
293178
+ ok: true,
293179
+ connectionId: connection.connectionId,
293180
+ agent: parsed.agent,
293181
+ changed
293182
+ },
293183
+ null,
293184
+ 2
293185
+ )
293186
+ );
293187
+ return;
293188
+ }
293189
+ dependencies.print(
293190
+ parsed.agent === null ? `Removed ${connection.displayName}.` : changed ? `Removed ${connection.displayName} from ${MCP_AGENT_LABELS[parsed.agent]}.` : `${connection.displayName} wasn't added to ${MCP_AGENT_LABELS[parsed.agent]}.`
293191
+ );
291823
293192
  } finally {
291824
- unsubscribe4();
291825
293193
  await session.close();
291826
293194
  }
291827
293195
  };
@@ -291829,6 +293197,8 @@ var init_mcp = __esm({
291829
293197
  runMcpAuthorize = async (args) => {
291830
293198
  await runMcpAuthorizeWithDependencies(args, defaultDependencies10);
291831
293199
  };
293200
+ runMcpAdd = async (args) => await runMcpAddWithDependencies(args, defaultDependencies10);
293201
+ runMcpRemove = async (args) => await runMcpRemoveWithDependencies(args, defaultDependencies10);
291832
293202
  }
291833
293203
  });
291834
293204
 
@@ -293347,7 +294717,7 @@ var init_projectMaintenanceHistory = __esm({
293347
294717
  // src/devbox/commands/projectLifecycleMaintenance.ts
293348
294718
  import fs80 from "node:fs/promises";
293349
294719
  import path102 from "node:path";
293350
- var LIFECYCLE_SCRIPT_MAX_BYTES, WATCH_FILE_MAX_BYTES, getLifecycle, patchLifecycle, getMaintenance, applyMaintenance, parseInteger, parseProjectLifecycleArgs, parseProjectMaintenanceArgs, readTextFile4, defaultDependencies11, requireLifecycle, renderLifecycle2, renderLifecycleApplied, maintenanceApplyResult, renderMaintenance, renderMaintenanceApplied, resolveProject, runProjectLifecycleWithDependencies, runProjectMaintenanceWithDependencies, runProjectLifecycle, runProjectMaintenance;
294720
+ var LIFECYCLE_SCRIPT_MAX_BYTES, WATCH_FILE_MAX_BYTES, getLifecycle, patchLifecycle, getMaintenance, applyMaintenance, parseInteger, parseProjectLifecycleArgs, parseProjectMaintenanceArgs, readTextFile4, defaultDependencies11, requireLifecycle, renderLifecycle2, renderLifecycleApplied, maintenanceApplyResult, renderMaintenance, renderMaintenanceApplied, resolveProject2, runProjectLifecycleWithDependencies, runProjectMaintenanceWithDependencies, runProjectLifecycle, runProjectMaintenance;
293351
294721
  var init_projectLifecycleMaintenance2 = __esm({
293352
294722
  "src/devbox/commands/projectLifecycleMaintenance.ts"() {
293353
294723
  "use strict";
@@ -293575,14 +294945,14 @@ ${watchLines.join("\n")}` : "GitHub watches: none",
293575
294945
  `Repeating schedule: ${result.schedule.enabled ? "on" : "off"}`,
293576
294946
  result.triggerActive ? "At least one maintenance trigger is active." : "No maintenance trigger is active."
293577
294947
  ].join("\n");
293578
- resolveProject = async (client, selector) => await resolveCliAgentToolProjectSelection(client, selector);
294948
+ resolveProject2 = async (client, selector) => await resolveCliAgentToolProjectSelection(client, selector);
293579
294949
  runProjectLifecycleWithDependencies = async (args, dependencies) => {
293580
294950
  const parsed = parseProjectLifecycleArgs(args);
293581
294951
  await runResourceCommand({
293582
294952
  json: parsed.json,
293583
294953
  dependencies,
293584
294954
  load: async ({ client }, requestId2) => {
293585
- const project = await resolveProject(client, parsed.project);
294955
+ const project = await resolveProject2(client, parsed.project);
293586
294956
  if (parsed.command === "get") {
293587
294957
  return {
293588
294958
  operation: "get",
@@ -293645,7 +295015,7 @@ ${watchLines.join("\n")}` : "GitHub watches: none",
293645
295015
  json: parsed.json,
293646
295016
  dependencies,
293647
295017
  load: async ({ client }, requestId2) => {
293648
- const project = await resolveProject(client, parsed.project);
295018
+ const project = await resolveProject2(client, parsed.project);
293649
295019
  if (parsed.command === "get") {
293650
295020
  return {
293651
295021
  operation: "get",
@@ -293951,7 +295321,7 @@ var init_reset = __esm({
293951
295321
  import fs81 from "node:fs/promises";
293952
295322
  import os41 from "node:os";
293953
295323
  import path103 from "node:path";
293954
- import readline6 from "node:readline/promises";
295324
+ import readline7 from "node:readline/promises";
293955
295325
  import { spawnSync as spawnSync7 } from "node:child_process";
293956
295326
  var PROCESS_EXIT_POLL_INTERVAL_MS, PROCESS_EXIT_GRACE_MS, PROCESS_FORCE_KILL_TIMEOUT_MS, parseUninstallArgs, escapeRegExp, resolveCliName3, rcMarkers2, resolveCompletionTargets, readTextFile5, sleep8, isProcessAlive2, waitForPidExit2, signalPid2, terminatePid, parseUpdaterDaemonPidsFromPs, listUpdaterDaemonPids, readUpdaterDaemonRecord, stopUpdaterDaemons, removeFile, removeDir, removeDirIfEmpty, removeRcBlock2, shouldTryRemoveRuntimeDir, confirmUninstall, summarizeResults, runUninstall;
293957
295327
  var init_uninstall = __esm({
@@ -294304,7 +295674,7 @@ var init_uninstall = __esm({
294304
295674
  );
294305
295675
  }
294306
295676
  const phrase = "uninstall";
294307
- const rl = readline6.createInterface({
295677
+ const rl = readline7.createInterface({
294308
295678
  input: process.stdin,
294309
295679
  output: process.stdout
294310
295680
  });
@@ -298713,7 +300083,9 @@ var init_dispatch = __esm({
298713
300083
  ["report-bug", runReportBug],
298714
300084
  ["agents", runAgents],
298715
300085
  ["mcp list", runMcpList],
300086
+ ["mcp add", runMcpAdd],
298716
300087
  ["mcp authorize", runMcpAuthorize],
300088
+ ["mcp remove", runMcpRemove],
298717
300089
  ["permissions get", runAgentPermissionsGet],
298718
300090
  ["permissions set", runAgentPermissionsSet],
298719
300091
  ["permissions requests", runAgentPermissionRequests],
@@ -299482,4 +300854,4 @@ react/cjs/react-jsx-runtime.development.js:
299482
300854
  *)
299483
300855
  */
299484
300856
 
299485
- //# debugId=249a0abb-e483-5aa3-b76c-e668263ae2b8
300857
+ //# debugId=4b9bb473-e618-5a79-8a86-c0fdba0f0295