@boxes-dev/dvb-runtime 1.0.1078 → 1.0.1080

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]="2444e913-d099-55e2-8f4b-b8e55bd2427d")}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;
@@ -5896,8 +6385,37 @@ var init_callbackServer = __esm({
5896
6385
  } catch {
5897
6386
  throw new McpOAuthCompanionError("callback_unavailable", "boxes.dev could not open a local OAuth callback.");
5898
6387
  }
6388
+ const redirectUri = `http://${callbackHostname}:${String(localPort)}${callbackPath}`;
6389
+ const manualInputController = new AbortController();
6390
+ const readManualCallbacks = async (input) => {
6391
+ while (!settled) {
6392
+ let pasted;
6393
+ try {
6394
+ pasted = await input.readCallbackUrl(manualInputController.signal);
6395
+ } catch {
6396
+ return;
6397
+ }
6398
+ if (pasted === null || settled)
6399
+ return;
6400
+ const result = evaluateManualMcpOAuthCallbackUrl({
6401
+ expectedState,
6402
+ input: pasted,
6403
+ redirectUri
6404
+ });
6405
+ if (result.kind === "rejected") {
6406
+ input.reportRejectedCallbackUrl(result.message);
6407
+ } else if (result.kind === "failed") {
6408
+ settleFailure(result.error);
6409
+ } else {
6410
+ callbackAccepted = true;
6411
+ settled = true;
6412
+ resolveCallback(result.callback);
6413
+ }
6414
+ }
6415
+ };
5899
6416
  const close2 = async () => {
5900
6417
  clearTimeout(timeout);
6418
+ manualInputController.abort();
5901
6419
  signal?.removeEventListener("abort", onAbort);
5902
6420
  if (!server.listening)
5903
6421
  return;
@@ -5915,8 +6433,10 @@ var init_callbackServer = __esm({
5915
6433
  signal?.addEventListener("abort", onAbort, { once: true });
5916
6434
  if (signal?.aborted)
5917
6435
  onAbort();
6436
+ if (manualCallbackInput)
6437
+ void readManualCallbacks(manualCallbackInput);
5918
6438
  return {
5919
- redirectUri: `http://${callbackHostname}:${String(localPort)}${callbackPath}`,
6439
+ redirectUri,
5920
6440
  waitForCallback,
5921
6441
  close: close2
5922
6442
  };
@@ -22519,8 +23039,8 @@ var init_ajvProvider_97rDpkRx = __esm({
22519
23039
  const { gen, data, schemaCode, it: it2 } = cxt;
22520
23040
  const prec = it2.opts.multipleOfPrecision;
22521
23041
  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}))`);
23042
+ const invalid2 = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
23043
+ cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid2}))`);
22524
23044
  }
22525
23045
  };
22526
23046
  exports.default = def;
@@ -26257,7 +26777,7 @@ var init_resource = __esm({
26257
26777
 
26258
26778
  // ../../../../shared/devboxCore/dist/mcpOAuth/companion.js
26259
26779
  import { randomBytes } from "node:crypto";
26260
- var DEFAULT_CALLBACK_TIMEOUT_MS, MAX_OAUTH_RESPONSE_BYTES, McpOAuthResponseTooLargeError, requirePublicHttpsUrl, sameUrl, readBoundedResponseBody, createBoundedOAuthFetch, TransientMcpOAuthProvider, buildCanonicalGrant, throwIfCanceled, authorizeMcpOAuthWithSdk;
26780
+ 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
26781
  var init_companion = __esm({
26262
26782
  "../../../../shared/devboxCore/dist/mcpOAuth/companion.js"() {
26263
26783
  "use strict";
@@ -26336,17 +26856,22 @@ var init_companion = __esm({
26336
26856
  clientMetadata;
26337
26857
  resolveClientMetadataUrl;
26338
26858
  expectedState;
26339
- openAuthorizationUrl;
26859
+ recordAuthorizationUrl;
26340
26860
  codeVerifierValue;
26341
26861
  clientInformationValue;
26342
26862
  tokensValue;
26343
26863
  discoveryStateValue;
26344
- constructor({ resolveClientMetadataUrl, clientMetadata, expectedState, openAuthorizationUrl, redirectUrl }) {
26864
+ constructor({ resolveClientMetadataUrl, clientMetadata, expectedState, recordAuthorizationUrl, redirectUrl, restored }) {
26345
26865
  this.redirectUrl = redirectUrl;
26346
26866
  this.resolveClientMetadataUrl = resolveClientMetadataUrl;
26347
26867
  this.clientMetadata = clientMetadata;
26348
26868
  this.expectedState = expectedState;
26349
- this.openAuthorizationUrl = openAuthorizationUrl;
26869
+ this.recordAuthorizationUrl = recordAuthorizationUrl;
26870
+ if (restored) {
26871
+ this.clientInformationValue = restored.clientInformation;
26872
+ this.codeVerifierValue = restored.codeVerifier;
26873
+ this.discoveryStateValue = restored.discoveryState;
26874
+ }
26350
26875
  }
26351
26876
  state() {
26352
26877
  return this.expectedState;
@@ -26371,11 +26896,11 @@ var init_companion = __esm({
26371
26896
  const issuer = tokens.issuer ?? context34?.issuer;
26372
26897
  this.tokensValue = issuer ? { ...tokens, issuer } : tokens;
26373
26898
  }
26374
- async redirectToAuthorization(authorizationUrl) {
26899
+ redirectToAuthorization(authorizationUrl) {
26375
26900
  if (authorizationUrl.protocol !== "https:" && authorizationUrl.protocol !== "http:") {
26376
26901
  throw new McpOAuthCompanionError("sdk_protocol_error", "The authorization server returned an unsupported redirect URL.");
26377
26902
  }
26378
- await this.openAuthorizationUrl(authorizationUrl.toString());
26903
+ this.recordAuthorizationUrl(authorizationUrl.toString());
26379
26904
  }
26380
26905
  saveCodeVerifier(codeVerifier) {
26381
26906
  this.codeVerifierValue = codeVerifier;
@@ -26419,6 +26944,18 @@ var init_companion = __esm({
26419
26944
  discoveryState: this.discoveryStateValue
26420
26945
  };
26421
26946
  }
26947
+ // What the code exchange needs after the redirect: the registered client,
26948
+ // the PKCE verifier, and the discovery result the SDK binds the callback to.
26949
+ pendingState() {
26950
+ if (!this.clientInformationValue?.client_id || !this.codeVerifierValue || !this.discoveryStateValue) {
26951
+ throw new McpOAuthCompanionError("sdk_protocol_error", "The OAuth SDK did not prepare a complete authorization.");
26952
+ }
26953
+ return {
26954
+ clientInformation: this.clientInformationValue,
26955
+ codeVerifier: this.codeVerifierValue,
26956
+ discoveryState: this.discoveryStateValue
26957
+ };
26958
+ }
26422
26959
  clear() {
26423
26960
  this.codeVerifierValue = void 0;
26424
26961
  this.clientInformationValue = void 0;
@@ -26468,14 +27005,108 @@ var init_companion = __esm({
26468
27005
  throw new McpOAuthCompanionError("canceled", "MCP authorization was canceled.");
26469
27006
  }
26470
27007
  };
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) {
27008
+ 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.");
27009
+ normalizeMcpOAuthTarget = ({ serverName, serverUrl }) => {
27010
+ const normalizedUrl = requirePublicHttpsUrl(serverUrl, "The MCP server URL").toString();
27011
+ const normalizedName = serverName.trim();
27012
+ if (!normalizedName || normalizedName.length > 128) {
26475
27013
  throw new McpOAuthCompanionError("invalid_input", "The MCP server name must be between 1 and 128 characters.");
26476
27014
  }
27015
+ return { serverName: normalizedName, serverUrl: normalizedUrl };
27016
+ };
27017
+ createMcpOAuthState = () => randomBytes(32).toString("base64url");
27018
+ createProvider = ({ agent, recordAuthorizationUrl, redirectUri, restored, serverName, serverUrl, state }) => {
27019
+ const profile = resolveMcpOAuthProfile(agent);
27020
+ return new TransientMcpOAuthProvider({
27021
+ resolveClientMetadataUrl: (authorizationServerMetadata) => profile.resolveClientMetadataUrl(serverUrl, authorizationServerMetadata),
27022
+ clientMetadata: profile.buildClientMetadata(serverName, redirectUri),
27023
+ expectedState: state,
27024
+ recordAuthorizationUrl,
27025
+ redirectUrl: redirectUri,
27026
+ restored
27027
+ });
27028
+ };
27029
+ prepareMcpOAuthAuthorizationWithSdk = async ({ agent, fetchFn, redirectUri, serverName: rawServerName, serverUrl: rawServerUrl, signal, state }, sdkAuth) => {
27030
+ const { serverName, serverUrl } = normalizeMcpOAuthTarget({
27031
+ serverName: rawServerName,
27032
+ serverUrl: rawServerUrl
27033
+ });
27034
+ const profile = resolveMcpOAuthProfile(agent);
27035
+ let authorizationUrl = null;
27036
+ const provider = createProvider({
27037
+ agent,
27038
+ recordAuthorizationUrl: (url3) => {
27039
+ authorizationUrl = url3;
27040
+ },
27041
+ redirectUri,
27042
+ restored: null,
27043
+ serverName,
27044
+ serverUrl,
27045
+ state
27046
+ });
27047
+ try {
27048
+ const result = await sdkAuth(provider, {
27049
+ serverUrl,
27050
+ fetchFn: createBoundedOAuthFetch(fetchFn, signal)
27051
+ });
27052
+ if (result !== "REDIRECT" || authorizationUrl === null) {
27053
+ throw new McpOAuthCompanionError("sdk_protocol_error", "The OAuth SDK did not start an authorization redirect.");
27054
+ }
27055
+ return {
27056
+ authorizationUrl,
27057
+ pending: {
27058
+ ...provider.pendingState(),
27059
+ agent,
27060
+ profileVersion: profile.profileVersion,
27061
+ serverName,
27062
+ serverUrl,
27063
+ redirectUri,
27064
+ state
27065
+ }
27066
+ };
27067
+ } finally {
27068
+ provider.clear();
27069
+ }
27070
+ };
27071
+ completeMcpOAuthAuthorizationWithSdk = async ({ authorizationCode, fetchFn, issuer, pending, signal }, sdkAuth) => {
27072
+ const provider = createProvider({
27073
+ agent: pending.agent,
27074
+ recordAuthorizationUrl: () => {
27075
+ throw new McpOAuthCompanionError("sdk_protocol_error", "The OAuth SDK started a second authorization redirect.");
27076
+ },
27077
+ redirectUri: pending.redirectUri,
27078
+ restored: pending,
27079
+ serverName: pending.serverName,
27080
+ serverUrl: pending.serverUrl,
27081
+ state: pending.state
27082
+ });
27083
+ try {
27084
+ const result = await sdkAuth(provider, {
27085
+ serverUrl: pending.serverUrl,
27086
+ authorizationCode,
27087
+ ...issuer ? { iss: issuer } : {},
27088
+ fetchFn: createBoundedOAuthFetch(fetchFn, signal)
27089
+ });
27090
+ if (result !== "AUTHORIZED") {
27091
+ throw new McpOAuthCompanionError("sdk_protocol_error", "The OAuth SDK did not complete authorization.");
27092
+ }
27093
+ return buildCanonicalGrant({
27094
+ agent: pending.agent,
27095
+ now: Date.now(),
27096
+ profileVersion: pending.profileVersion,
27097
+ provider,
27098
+ redirectUri: pending.redirectUri,
27099
+ serverName: pending.serverName,
27100
+ serverUrl: pending.serverUrl
27101
+ });
27102
+ } finally {
27103
+ provider.clear();
27104
+ }
27105
+ };
27106
+ authorizeMcpOAuthWithSdk = async (options, sdkAuth) => {
27107
+ const { serverName, serverUrl } = normalizeMcpOAuthTarget(options);
26477
27108
  const profile = resolveMcpOAuthProfile(options.agent);
26478
- const sdkFetch = createBoundedOAuthFetch(options.fetchFn ?? fetch, options.signal);
27109
+ const fetchFn = options.fetchFn ?? fetch;
26479
27110
  const serverOrigin = new URL(serverUrl).origin;
26480
27111
  const log3 = (event) => options.log?.(event);
26481
27112
  const baseEvent = {
@@ -26483,16 +27114,16 @@ var init_companion = __esm({
26483
27114
  profileVersion: profile.profileVersion,
26484
27115
  serverOrigin
26485
27116
  };
26486
- const state = randomBytes(32).toString("base64url");
27117
+ const state = createMcpOAuthState();
26487
27118
  const callbackPath = profile.buildCallbackPath(serverUrl);
26488
27119
  let callbackListener = null;
26489
- let provider = null;
26490
27120
  try {
26491
27121
  throwIfCanceled(options.signal);
26492
27122
  callbackListener = await startMcpOAuthCallbackListener({
26493
27123
  callbackHostname: profile.callbackHostname,
26494
27124
  callbackPath,
26495
27125
  expectedState: state,
27126
+ ...options.manualCallbackInput ? { manualCallbackInput: options.manualCallbackInput } : {},
26496
27127
  signal: options.signal,
26497
27128
  timeoutMs: options.timeoutMs ?? DEFAULT_CALLBACK_TIMEOUT_MS
26498
27129
  });
@@ -26501,28 +27132,22 @@ var init_companion = __esm({
26501
27132
  event: "callback_listening",
26502
27133
  errorCode: null
26503
27134
  });
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, {
27135
+ const prepared = await prepareMcpOAuthAuthorizationWithSdk({
27136
+ agent: options.agent,
27137
+ fetchFn,
27138
+ redirectUri: callbackListener.redirectUri,
27139
+ serverName,
26520
27140
  serverUrl,
26521
- fetchFn: sdkFetch
27141
+ signal: options.signal,
27142
+ state
27143
+ }, sdkAuth);
27144
+ throwIfCanceled(options.signal);
27145
+ await options.openAuthorizationUrl(prepared.authorizationUrl);
27146
+ log3({
27147
+ ...baseEvent,
27148
+ event: "authorization_opened",
27149
+ errorCode: null
26522
27150
  });
26523
- if (initialResult !== "REDIRECT") {
26524
- throw new McpOAuthCompanionError("sdk_protocol_error", "The OAuth SDK did not start an authorization redirect.");
26525
- }
26526
27151
  const callback = await callbackListener.waitForCallback;
26527
27152
  log3({
26528
27153
  ...baseEvent,
@@ -26530,24 +27155,13 @@ var init_companion = __esm({
26530
27155
  errorCode: null
26531
27156
  });
26532
27157
  throwIfCanceled(options.signal);
26533
- const completedResult = await sdkAuth(provider, {
26534
- serverUrl,
27158
+ const grant = await completeMcpOAuthAuthorizationWithSdk({
26535
27159
  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
- });
27160
+ fetchFn,
27161
+ issuer: callback.issuer,
27162
+ pending: prepared.pending,
27163
+ signal: options.signal
27164
+ }, sdkAuth);
26551
27165
  try {
26552
27166
  await options.uploadGrant(grant);
26553
27167
  } catch {
@@ -26567,7 +27181,7 @@ var init_companion = __esm({
26567
27181
  scope: grant.scope
26568
27182
  };
26569
27183
  } 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.");
27184
+ const safeError = toSafeMcpOAuthError(error55);
26571
27185
  log3({
26572
27186
  ...baseEvent,
26573
27187
  event: safeError.code === "canceled" ? "authorization_canceled" : "authorization_failed",
@@ -26575,7 +27189,6 @@ var init_companion = __esm({
26575
27189
  });
26576
27190
  throw safeError;
26577
27191
  } finally {
26578
- provider?.clear();
26579
27192
  await callbackListener?.close();
26580
27193
  }
26581
27194
  };
@@ -62485,7 +63098,7 @@ var init_instrumentation7 = __esm({
62485
63098
  _patchCreateConnection() {
62486
63099
  return (originalCreateConnection) => {
62487
63100
  const thisPlugin = this;
62488
- return function createConnection2(_connectionUri) {
63101
+ return function createConnection3(_connectionUri) {
62489
63102
  const originalResult = originalCreateConnection(...arguments);
62490
63103
  thisPlugin._wrap(originalResult, "query", thisPlugin._patchQuery(originalResult));
62491
63104
  return originalResult;
@@ -62554,7 +63167,7 @@ var init_instrumentation7 = __esm({
62554
63167
  _patchGetConnection(pool) {
62555
63168
  return (originalGetConnection) => {
62556
63169
  const thisPlugin = this;
62557
- return function getConnection(arg1, arg2, arg3) {
63170
+ return function getConnection2(arg1, arg2, arg3) {
62558
63171
  if (!thisPlugin["_enabled"]) {
62559
63172
  thisPlugin._unwrap(pool, "getConnection");
62560
63173
  return originalGetConnection.apply(pool, arguments);
@@ -69730,9 +70343,9 @@ var init_sentry = __esm({
69730
70343
  uncaughtExceptionMonitorInstalled = false;
69731
70344
  currentDevboxSentryUser = null;
69732
70345
  readBuildMetadata = () => {
69733
- const rawPackageVersion = "1.0.1078";
69734
- const rawGitSha = "8c516f16149b71ba8dc1fd9ba16fda4b614ce8bf";
69735
- const rawSentryRelease = "boxes-dev-dvb@1.0.1078+8c516f16149b71ba8dc1fd9ba16fda4b614ce8bf";
70346
+ const rawPackageVersion = "1.0.1080";
70347
+ const rawGitSha = "7de552e837c4fc499fb68445cfbacd270c3541ed";
70348
+ const rawSentryRelease = "boxes-dev-dvb@1.0.1080+7de552e837c4fc499fb68445cfbacd270c3541ed";
69736
70349
  const packageVersion = typeof rawPackageVersion === "string" ? rawPackageVersion : void 0;
69737
70350
  const gitSha = typeof rawGitSha === "string" ? rawGitSha : void 0;
69738
70351
  const sentryRelease = typeof rawSentryRelease === "string" ? rawSentryRelease : void 0;
@@ -74268,7 +74881,7 @@ the following:
74268
74881
  it. Offer to help finish any remaining setup or run the app with
74269
74882
  port forwarding when relevant.
74270
74883
  - ${snapshotGuidance}
74271
- - Make **New devbox + thread** the main next action. Explain that it will
74884
+ - Make **New thread** the main next action. Explain that it will
74272
74885
  create an isolated machine from the Template box snapshot for the task,
74273
74886
  allowing several tasks to run in parallel with their own files and environments.
74274
74887
  - Explain that **New thread** on an existing devbox will start another agent
@@ -74306,7 +74919,7 @@ still needs attention.>
74306
74919
 
74307
74920
  ${snapshotExample}
74308
74921
 
74309
- **Start your first task:** click **New devbox + thread** and ask the agent to
74922
+ **Start your first task:** click **New thread** and ask the agent to
74310
74923
  build or fix something. It will get its own machine\u2014a **devbox**\u2014created from
74311
74924
  your Template box snapshot. You can work on several tasks in parallel, each
74312
74925
  with its own files and environment.
@@ -75116,7 +75729,7 @@ var init_packageVersion = __esm({
75116
75729
  return path18.join(process.cwd(), "dvb");
75117
75730
  };
75118
75731
  readEmbeddedPackageVersion = () => {
75119
- const raw = "1.0.1078";
75732
+ const raw = "1.0.1080";
75120
75733
  return trimVersion(raw);
75121
75734
  };
75122
75735
  readNearestPackageMetadata = (basePath) => {
@@ -82035,7 +82648,7 @@ var init_wrapper2 = __esm({
82035
82648
  // src/devbox/browser.ts
82036
82649
  import { spawn as spawn3 } from "node:child_process";
82037
82650
  import { readlinkSync } from "node:fs";
82038
- var LINUX_PSEUDO_TTY_PATH_PREFIX, isLinuxPseudoTtyPath, resolveInheritedBrowserOpenTty, buildBrowserOpenCommand, resolveBrowserOpenStdio, openBrowser;
82651
+ var LINUX_PSEUDO_TTY_PATH_PREFIX, isLinuxPseudoTtyPath, resolveInheritedBrowserOpenTty, buildBrowserOpenCommand, resolveBrowserOpenStdio, openBrowser, canOpenLocalBrowser;
82039
82652
  var init_browser = __esm({
82040
82653
  "src/devbox/browser.ts"() {
82041
82654
  "use strict";
@@ -82100,12 +82713,21 @@ var init_browser = __esm({
82100
82713
  env: childEnv,
82101
82714
  stdio: resolveBrowserOpenStdio(platform3)
82102
82715
  });
82716
+ child.on("error", () => void 0);
82103
82717
  child.unref();
82104
82718
  return true;
82105
82719
  } catch {
82106
82720
  return false;
82107
82721
  }
82108
82722
  };
82723
+ canOpenLocalBrowser = ({
82724
+ platform: platform3 = process.platform,
82725
+ env: env3 = process.env
82726
+ } = {}) => {
82727
+ if (env3.SSH_CONNECTION || env3.SSH_TTY) return false;
82728
+ if (platform3 === "linux") return Boolean(env3.DISPLAY || env3.WAYLAND_DISPLAY);
82729
+ return true;
82730
+ };
82109
82731
  }
82110
82732
  });
82111
82733
 
@@ -96027,7 +96649,7 @@ var init_errors4 = __esm({
96027
96649
  });
96028
96650
 
96029
96651
  // src/devbox/commandRegistry/args.ts
96030
- var expandFlagNames, resolveCanonicalFlag, unknownFlagError, missingValueError, collectPositionals, parseCommandArgs, readBooleanFlag, readStringFlag;
96652
+ var expandFlagNames, resolveCanonicalFlag, unknownFlagError, missingValueError, collectPositionals, parseCommandArgs, readBooleanFlag, readStringFlag, readRepeatedStringFlag;
96031
96653
  var init_args = __esm({
96032
96654
  "src/devbox/commandRegistry/args.ts"() {
96033
96655
  "use strict";
@@ -96147,6 +96769,21 @@ var init_args = __esm({
96147
96769
  }
96148
96770
  return void 0;
96149
96771
  };
96772
+ readRepeatedStringFlag = (args, name) => {
96773
+ const values = [];
96774
+ for (let index = 0; index < args.length; index += 1) {
96775
+ const token = args[index];
96776
+ if (token === "--") break;
96777
+ if (token === `--${name}`) {
96778
+ const next = args[index + 1];
96779
+ if (next !== void 0) values.push(next);
96780
+ index += 1;
96781
+ } else if (token?.startsWith(`--${name}=`)) {
96782
+ values.push(token.slice(name.length + 3));
96783
+ }
96784
+ }
96785
+ return values;
96786
+ };
96150
96787
  }
96151
96788
  });
96152
96789
 
@@ -98421,27 +99058,116 @@ var init_catalog = __esm({
98421
99058
  category: "Account",
98422
99059
  summary: "Manage centrally connected MCPs",
98423
99060
  usage: ["dvb mcp <command>"],
99061
+ notes: ["Run these commands on your own computer, not inside a box."],
98424
99062
  children: [
98425
99063
  {
98426
99064
  name: "list",
98427
99065
  summary: "List centrally managed MCP connections",
98428
- usage: ["dvb mcp list [--json]"],
98429
- options: [flag("json", "Output JSON")]
99066
+ usage: ["dvb mcp list [--project <project>] [--json]"],
99067
+ options: [
99068
+ flag(
99069
+ "project",
99070
+ "Show the MCPs available in one project, including MCPs your team manages",
99071
+ { valueName: "project" }
99072
+ ),
99073
+ flag("json", "Output JSON")
99074
+ ]
99075
+ },
99076
+ {
99077
+ name: "add",
99078
+ summary: "Add an MCP and connect it to Codex and Claude",
99079
+ usage: [
99080
+ '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]',
99081
+ "dvb mcp add [options] -- <codex|claude> mcp add ..."
99082
+ ],
99083
+ arguments: [
99084
+ arg(
99085
+ "url-or-setup-command",
99086
+ "MCP URL, or the `codex mcp add` or `claude mcp add` command the provider gave you"
99087
+ )
99088
+ ],
99089
+ options: [
99090
+ flag("name", "Name for this MCP, also used by the agents", {
99091
+ valueName: "name"
99092
+ }),
99093
+ flag("project", "Project name or fingerprint", {
99094
+ valueName: "project"
99095
+ }),
99096
+ flag("all-projects", "Make the MCP available in every project"),
99097
+ flag(
99098
+ "agent",
99099
+ "Add it to only this agent; repeat for both (default: both)",
99100
+ { valueName: "codex|claude" }
99101
+ ),
99102
+ flag("header", "API key or other header to send; repeatable", {
99103
+ valueName: "name: value"
99104
+ }),
99105
+ flag(
99106
+ "no-sign-in",
99107
+ "Use an MCP that also works without an account without signing in"
99108
+ ),
99109
+ flag("no-authorize", "Add the MCP now and sign in later"),
99110
+ flag(
99111
+ "no-browser",
99112
+ "Print the sign-in link without opening a browser"
99113
+ ),
99114
+ flag("json", "Output JSON")
99115
+ ],
99116
+ notes: [
99117
+ "boxes.dev reads a pasted setup command but never runs it. Quote it, or put it after --.",
99118
+ "With one project, the MCP is added to that project. Otherwise, pass --project or --all-projects."
99119
+ ],
99120
+ examples: [
99121
+ "dvb mcp add https://mcp.linear.app/mcp --project my-app",
99122
+ "dvb mcp add --all-projects -- claude mcp add --transport http notion https://mcp.notion.com/mcp"
99123
+ ]
98430
99124
  },
98431
99125
  {
98432
99126
  name: "authorize",
98433
- summary: "Connect an MCP to Codex or Claude",
98434
- usage: ["dvb mcp authorize <connection> --agent <codex|claude>"],
99127
+ summary: "Sign in to an MCP for Codex or Claude",
99128
+ usage: [
99129
+ "dvb mcp authorize <connection> --agent <codex|claude> [--project <project>] [--no-browser]"
99130
+ ],
98435
99131
  arguments: [
98436
99132
  arg("connection", "Connection name or id from `dvb mcp list`")
98437
99133
  ],
98438
99134
  options: [
98439
99135
  flag("agent", "Coding agent to authorize", {
98440
99136
  valueName: "codex|claude"
98441
- })
99137
+ }),
99138
+ flag("project", "Project the MCP is available in", {
99139
+ valueName: "project"
99140
+ }),
99141
+ flag(
99142
+ "no-browser",
99143
+ "Print the sign-in link without opening a browser"
99144
+ )
98442
99145
  ],
98443
99146
  notes: [
98444
- "MCP authorization does not require Codex, Claude, or either coding-agent account locally."
99147
+ "MCP authorization does not require Codex, Claude, or either coding-agent account locally.",
99148
+ "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."
99149
+ ]
99150
+ },
99151
+ {
99152
+ name: "remove",
99153
+ summary: "Remove an MCP, or remove it from one agent",
99154
+ usage: [
99155
+ "dvb mcp remove <connection> [--agent <codex|claude>] [--project <project>] [--json]"
99156
+ ],
99157
+ arguments: [
99158
+ arg("connection", "Connection name or id from `dvb mcp list`")
99159
+ ],
99160
+ options: [
99161
+ flag("agent", "Remove the MCP from only this agent", {
99162
+ valueName: "codex|claude"
99163
+ }),
99164
+ flag("project", "Project the MCP is available in", {
99165
+ valueName: "project"
99166
+ }),
99167
+ flag("json", "Output JSON")
99168
+ ],
99169
+ notes: [
99170
+ "MCPs your team manages can only be removed from one agent at a time."
98445
99171
  ]
98446
99172
  }
98447
99173
  ]
@@ -99211,7 +99937,7 @@ var init_catalog = __esm({
99211
99937
  "When the follow-up arrives: next (default), idle, steer, or queue",
99212
99938
  { valueName: "mode" }
99213
99939
  ),
99214
- flag("turn", "Exact active Codex turn id to steer", {
99940
+ flag("turn", "Exact active turn id to steer", {
99215
99941
  valueName: "active-turn-id"
99216
99942
  }),
99217
99943
  flag("idempotency-key", "Caller-owned retry key", {
@@ -99221,7 +99947,8 @@ var init_catalog = __esm({
99221
99947
  ],
99222
99948
  notes: [
99223
99949
  "`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`."
99950
+ "`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`.",
99951
+ "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
99952
  ]
99226
99953
  },
99227
99954
  {
@@ -142006,14 +142733,14 @@ var init_threadCreateActions = __esm({
142006
142733
  return {
142007
142734
  defaultForkCreateDisabledReason: "Loading snapshot state...",
142008
142735
  defaultForkSnapshotPreference: "use_last_snapshot",
142009
- forkCreateLabel: "New devbox + thread"
142736
+ forkCreateLabel: "New thread"
142010
142737
  };
142011
142738
  }
142012
142739
  if (snapshotMetadata.available) {
142013
142740
  return {
142014
142741
  defaultForkCreateDisabledReason: null,
142015
142742
  defaultForkSnapshotPreference: "use_last_snapshot",
142016
- forkCreateLabel: "New devbox + thread"
142743
+ forkCreateLabel: "New thread"
142017
142744
  };
142018
142745
  }
142019
142746
  return {
@@ -142793,7 +143520,7 @@ var init_onboxAgentPermissionRequestPresentation = __esm({
142793
143520
  case "edit-personal-environment":
142794
143521
  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
143522
  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.";
143523
+ 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
143524
  case "edit-team-template":
142798
143525
  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
143526
  }
@@ -232481,7 +233208,7 @@ var init_exec = __esm({
232481
233208
  });
232482
233209
 
232483
233210
  // src/devbox/commands/exec.ts
232484
- var invalidExecArgs, readOptionValue, parsePositiveInteger, parseDurationMs, parseExecArgs, readCommandStdin, defaultDependencies9, resolveProcessExitCode, runExecWithDependencies, runExec;
233211
+ var invalidExecArgs, readOptionValue2, parsePositiveInteger, parseDurationMs, parseExecArgs, readCommandStdin, defaultDependencies9, resolveProcessExitCode, runExecWithDependencies, runExec;
232485
233212
  var init_exec2 = __esm({
232486
233213
  "src/devbox/commands/exec.ts"() {
232487
233214
  "use strict";
@@ -232497,7 +233224,7 @@ var init_exec2 = __esm({
232497
233224
  message
232498
233225
  });
232499
233226
  };
232500
- readOptionValue = ({
233227
+ readOptionValue2 = ({
232501
233228
  args,
232502
233229
  index,
232503
233230
  option
@@ -232574,7 +233301,7 @@ var init_exec2 = __esm({
232574
233301
  if (name !== "--project" && name !== "--target" && name !== "--cwd" && name !== "--timeout" && name !== "--max-output-bytes") {
232575
233302
  invalidExecArgs(`Unknown option: ${option}`);
232576
233303
  }
232577
- const value = usesInlineValue ? option.slice(equalsIndex + 1).trim() : readOptionValue({ args: options, index, option: name });
233304
+ const value = usesInlineValue ? option.slice(equalsIndex + 1).trim() : readOptionValue2({ args: options, index, option: name });
232578
233305
  if (!value) {
232579
233306
  return invalidExecArgs(`\`${name}\` requires a value.`);
232580
233307
  }
@@ -245579,6 +246306,7 @@ var init_localPrepService = __esm({
245579
246306
  homeDir: homeDir2 = os23.homedir(),
245580
246307
  isPackaged = false,
245581
246308
  localScanRunner,
246309
+ onActiveLocalWorkChange = null,
245582
246310
  onEvent = null,
245583
246311
  prepareScanExecution,
245584
246312
  reportRecoverableError = null,
@@ -245847,10 +246575,16 @@ var init_localPrepService = __esm({
245847
246575
  };
245848
246576
  const withActiveLocalWork = async (fn) => {
245849
246577
  activeLocalWorkCount += 1;
246578
+ if (activeLocalWorkCount === 1) {
246579
+ onActiveLocalWorkChange?.();
246580
+ }
245850
246581
  try {
245851
246582
  return await fn();
245852
246583
  } finally {
245853
246584
  activeLocalWorkCount = Math.max(0, activeLocalWorkCount - 1);
246585
+ if (activeLocalWorkCount === 0) {
246586
+ onActiveLocalWorkChange?.();
246587
+ }
245854
246588
  }
245855
246589
  };
245856
246590
  const statePathFor = (projectId) => resolveDesktopInitLocalPrepStatePath({
@@ -291620,23 +292354,211 @@ var init_mount = __esm({
291620
292354
  }
291621
292355
  });
291622
292356
 
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"() {
292357
+ // src/devbox/commands/mcpArgs.ts
292358
+ var MCP_LIST_USAGE, MCP_ADD_USAGE, MCP_AUTHORIZE_USAGE, MCP_REMOVE_USAGE, readProject, parseAgent, parseConnectionSelector, parseListArgs2, parseAuthorizeArgs, parseRemoveArgs, parseHeader2, parseAddArgs;
292359
+ var init_mcpArgs = __esm({
292360
+ "src/devbox/commands/mcpArgs.ts"() {
291627
292361
  "use strict";
291628
- init_server();
291629
292362
  init_devboxCore();
291630
- init_browser();
291631
292363
  init_args();
291632
292364
  init_errors4();
292365
+ MCP_LIST_USAGE = "Usage: dvb mcp list [--project <project>] [--json]";
292366
+ 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]';
292367
+ MCP_AUTHORIZE_USAGE = "Usage: dvb mcp authorize <connection> --agent <codex|claude> [--project <project>] [--no-browser]";
292368
+ MCP_REMOVE_USAGE = "Usage: dvb mcp remove <connection> [--agent <codex|claude>] [--project <project>] [--json]";
292369
+ readProject = (flags) => readStringFlag(flags, "project")?.trim() || null;
292370
+ parseAgent = (commandPath, value) => {
292371
+ if (value !== "codex" && value !== "claude") {
292372
+ throw usageError(
292373
+ commandPath,
292374
+ "Choose an agent with `--agent codex` or `--agent claude`."
292375
+ );
292376
+ }
292377
+ return value;
292378
+ };
292379
+ parseConnectionSelector = (commandPath, positionals, usage2) => {
292380
+ if (positionals.length !== 1) throw usageError(commandPath, usage2);
292381
+ const selector = positionals[0]?.trim() ?? "";
292382
+ if (!selector || selector.length > 256) {
292383
+ throw usageError(commandPath, "The MCP connection name or id is invalid.");
292384
+ }
292385
+ return selector;
292386
+ };
292387
+ parseListArgs2 = (args) => {
292388
+ const commandPath = ["mcp", "list"];
292389
+ const { flags, positionals } = parseCommandArgs({
292390
+ args,
292391
+ commandPath,
292392
+ flagLabel: "mcp list",
292393
+ boolean: ["json"],
292394
+ string: ["project"]
292395
+ });
292396
+ if (positionals.length > 0) throw usageError(commandPath, MCP_LIST_USAGE);
292397
+ return { json: readBooleanFlag(flags, "json"), project: readProject(flags) };
292398
+ };
292399
+ parseAuthorizeArgs = (args) => {
292400
+ const commandPath = ["mcp", "authorize"];
292401
+ const { flags, positionals } = parseCommandArgs({
292402
+ args,
292403
+ commandPath,
292404
+ flagLabel: "mcp authorize",
292405
+ boolean: ["no-browser"],
292406
+ string: ["agent", "project"]
292407
+ });
292408
+ return {
292409
+ selector: parseConnectionSelector(
292410
+ commandPath,
292411
+ positionals,
292412
+ MCP_AUTHORIZE_USAGE
292413
+ ),
292414
+ agent: parseAgent(commandPath, readStringFlag(flags, "agent")),
292415
+ project: readProject(flags),
292416
+ browser: !readBooleanFlag(flags, "no-browser")
292417
+ };
292418
+ };
292419
+ parseRemoveArgs = (args) => {
292420
+ const commandPath = ["mcp", "remove"];
292421
+ const { flags, positionals } = parseCommandArgs({
292422
+ args,
292423
+ commandPath,
292424
+ flagLabel: "mcp remove",
292425
+ boolean: ["json"],
292426
+ string: ["agent", "project"]
292427
+ });
292428
+ const agent = readStringFlag(flags, "agent");
292429
+ return {
292430
+ selector: parseConnectionSelector(
292431
+ commandPath,
292432
+ positionals,
292433
+ MCP_REMOVE_USAGE
292434
+ ),
292435
+ agent: agent === void 0 ? null : parseAgent(commandPath, agent),
292436
+ project: readProject(flags),
292437
+ json: readBooleanFlag(flags, "json")
292438
+ };
292439
+ };
292440
+ parseHeader2 = (value) => {
292441
+ const separator = value.indexOf(":");
292442
+ const name = separator < 0 ? "" : value.slice(0, separator).trim();
292443
+ const headerValue = separator < 0 ? "" : value.slice(separator + 1).trim();
292444
+ if (!name || !headerValue) {
292445
+ throw usageError(
292446
+ ["mcp", "add"],
292447
+ 'Write each header as --header "<name>: <value>", for example --header "Authorization: Bearer <key>".'
292448
+ );
292449
+ }
292450
+ return { name, value: headerValue };
292451
+ };
292452
+ parseAddArgs = (args) => {
292453
+ const commandPath = ["mcp", "add"];
292454
+ const separator = args.indexOf("--");
292455
+ const ownArgs = separator < 0 ? args : args.slice(0, separator);
292456
+ const pastedArgv = separator < 0 ? [] : args.slice(separator + 1);
292457
+ const { flags, positionals } = parseCommandArgs({
292458
+ args: ownArgs,
292459
+ commandPath,
292460
+ flagLabel: "mcp add",
292461
+ boolean: [
292462
+ "all-projects",
292463
+ "no-sign-in",
292464
+ "no-authorize",
292465
+ "no-browser",
292466
+ "json"
292467
+ ],
292468
+ string: ["name", "project", "agent", "header"]
292469
+ });
292470
+ if (positionals.length === 0 === (pastedArgv.length === 0)) {
292471
+ throw usageError(commandPath, MCP_ADD_USAGE);
292472
+ }
292473
+ const project = readProject(flags);
292474
+ const allProjects = readBooleanFlag(flags, "all-projects");
292475
+ if (project !== null && allProjects) {
292476
+ throw usageError(
292477
+ commandPath,
292478
+ "Choose either --project or --all-projects, not both."
292479
+ );
292480
+ }
292481
+ const name = readStringFlag(flags, "name")?.trim() || null;
292482
+ if (name !== null && !isValidMcpNativeName(name)) {
292483
+ throw usageError(
292484
+ commandPath,
292485
+ "MCP names can use letters, numbers, hyphens, and underscores, up to 128 characters."
292486
+ );
292487
+ }
292488
+ const agentValues = readRepeatedStringFlag(ownArgs, "agent");
292489
+ const agents = agentValues.length === 0 ? null : [
292490
+ ...new Set(
292491
+ agentValues.map((value) => parseAgent(commandPath, value))
292492
+ )
292493
+ ];
292494
+ return {
292495
+ // A single argument is a URL or a quoted setup command. Several arguments
292496
+ // are an unquoted setup command.
292497
+ input: pastedArgv.length > 0 ? pastedArgv : positionals.length === 1 ? positionals[0] ?? "" : positionals,
292498
+ name,
292499
+ project,
292500
+ allProjects,
292501
+ agents,
292502
+ headers: readRepeatedStringFlag(ownArgs, "header").map(parseHeader2),
292503
+ signIn: !readBooleanFlag(flags, "no-sign-in"),
292504
+ authorize: !readBooleanFlag(flags, "no-authorize"),
292505
+ browser: !readBooleanFlag(flags, "no-browser"),
292506
+ json: readBooleanFlag(flags, "json")
292507
+ };
292508
+ };
292509
+ }
292510
+ });
292511
+
292512
+ // src/devbox/commands/mcpSession.ts
292513
+ var listAllConnections, listProjectConnections, getConnection, reconcileTeamConnections, inspectServer, createConnection2, setStaticHeaders, connectAgent, disconnectAgent, removeConnection, startAuthorization2, completeAuthorization, cancelAuthorization, listCliProjects, toUserFacingMcpError, createDefaultMcpCliSession;
292514
+ var init_mcpSession = __esm({
292515
+ "src/devbox/commands/mcpSession.ts"() {
292516
+ "use strict";
292517
+ init_server();
292518
+ init_values();
292519
+ init_devboxCore();
292520
+ init_threadInventory();
292521
+ init_queryRefs();
291633
292522
  init_controlPlane();
292523
+ init_errors5();
291634
292524
  init_context2();
291635
- listConnections = makeFunctionReference("mcpConnections:listAllForViewer");
292525
+ listAllConnections = makeFunctionReference("mcpConnections:listAllForViewer");
292526
+ listProjectConnections = makeFunctionReference("mcpConnections:listForViewer");
292527
+ getConnection = makeFunctionReference("mcpConnections:getForViewer");
292528
+ reconcileTeamConnections = makeFunctionReference("mcpTeamConnections:reconcileForViewer");
292529
+ inspectServer = makeFunctionReference("mcpSetupPreflightNode:inspectForViewer");
292530
+ createConnection2 = makeFunctionReference("mcpConnections:createForViewer");
292531
+ setStaticHeaders = makeFunctionReference("mcpCredentials:setStaticHeadersForViewer");
292532
+ connectAgent = makeFunctionReference("mcpConnections:connectAgentForViewer");
292533
+ disconnectAgent = makeFunctionReference("mcpConnections:disconnectAgentForViewer");
292534
+ removeConnection = makeFunctionReference("mcpConnections:removeForViewer");
291636
292535
  startAuthorization2 = makeFunctionReference("mcpAgentBindings:startAuthorizationForViewer");
291637
292536
  completeAuthorization = makeFunctionReference("mcpAgentBindings:completeAuthorizationForViewer");
291638
292537
  cancelAuthorization = makeFunctionReference("mcpAgentBindings:cancelAuthorizationForViewer");
291639
- createDefaultSession = async () => {
292538
+ listCliProjects = async (client) => {
292539
+ const result = await client.query(listAgentViewProjectsV2, {});
292540
+ if (result.contractVersion !== CLI_AGENT_VIEW_PROJECT_CONTRACT_VERSION) {
292541
+ throw new CliAgentToolError({
292542
+ code: "contract_version_unsupported",
292543
+ message: `Project inventory returned unsupported contract version ${String(result.contractVersion)}.`
292544
+ });
292545
+ }
292546
+ return result.projects.map(adaptCliAgentViewProjectSummaryV2);
292547
+ };
292548
+ toUserFacingMcpError = (error55) => {
292549
+ if (!(error55 instanceof ConvexError)) return error55;
292550
+ const data = error55.data;
292551
+ if (typeof data !== "object" || data === null) return error55;
292552
+ const record3 = data;
292553
+ if (typeof record3.message !== "string") return error55;
292554
+ if (record3.code === "mcp_native_name_conflict" && typeof record3.suggestedNativeName === "string") {
292555
+ return new Error(
292556
+ `${record3.message} Choose another name with --name, for example --name ${record3.suggestedNativeName}.`
292557
+ );
292558
+ }
292559
+ return new Error(record3.message);
292560
+ };
292561
+ createDefaultMcpCliSession = async () => {
291640
292562
  const tokenContext = await createCliControlPlaneTokenContext({
291641
292563
  allowInteractiveLogin: process.stdin.isTTY === true,
291642
292564
  tokenProviderMode: "bounded"
@@ -291645,7 +292567,25 @@ var init_mcp = __esm({
291645
292567
  tokenContext.getToken
291646
292568
  );
291647
292569
  return {
291648
- list: async () => await client.query(listConnections, {}),
292570
+ listAll: async () => await client.query(listAllConnections, {}),
292571
+ listForProject: async (primaryInstanceId) => {
292572
+ await client.mutation(reconcileTeamConnections, { primaryInstanceId });
292573
+ return await client.query(listProjectConnections, { primaryInstanceId });
292574
+ },
292575
+ get: async (connectionId) => await client.query(getConnection, { connectionId }),
292576
+ listProjects: async () => await listCliProjects(client),
292577
+ inspect: async (url3) => await client.action(inspectServer, { url: url3 }),
292578
+ create: async (request2) => await client.mutation(createConnection2, request2),
292579
+ setStaticHeaders: async (request2) => {
292580
+ await client.mutation(setStaticHeaders, request2);
292581
+ },
292582
+ connectAgent: async (request2) => {
292583
+ await client.mutation(connectAgent, request2);
292584
+ },
292585
+ disconnectAgent: async (request2) => await client.mutation(disconnectAgent, request2),
292586
+ remove: async (request2) => {
292587
+ await client.mutation(removeConnection, request2);
292588
+ },
291649
292589
  start: async (request2) => await client.mutation(startAuthorization2, request2),
291650
292590
  complete: async (request2) => {
291651
292591
  await client.mutation(completeAuthorization, request2);
@@ -291656,116 +292596,290 @@ var init_mcp = __esm({
291656
292596
  close: async () => await client.close()
291657
292597
  };
291658
292598
  };
292599
+ }
292600
+ });
292601
+
292602
+ // src/devbox/commands/mcpSignIn.ts
292603
+ import readline6 from "node:readline/promises";
292604
+ var MCP_AGENT_LABELS, createStdinLineReader, createMcpTerminalSignIn;
292605
+ var init_mcpSignIn = __esm({
292606
+ "src/devbox/commands/mcpSignIn.ts"() {
292607
+ "use strict";
292608
+ MCP_AGENT_LABELS = {
292609
+ codex: "Codex",
292610
+ claude: "Claude"
292611
+ };
292612
+ createStdinLineReader = () => {
292613
+ const rl = readline6.createInterface({
292614
+ input: process.stdin,
292615
+ output: process.stdout,
292616
+ terminal: false
292617
+ });
292618
+ let closed = false;
292619
+ rl.on("close", () => {
292620
+ closed = true;
292621
+ });
292622
+ return {
292623
+ question: async (prompt, signal) => {
292624
+ if (closed || signal.aborted) return null;
292625
+ try {
292626
+ return await rl.question(prompt, { signal });
292627
+ } catch (error55) {
292628
+ if (closed || signal.aborted) return null;
292629
+ throw error55;
292630
+ }
292631
+ },
292632
+ close: () => rl.close()
292633
+ };
292634
+ };
292635
+ createMcpTerminalSignIn = ({
292636
+ agent,
292637
+ connectionName,
292638
+ terminal: terminal2
292639
+ }) => {
292640
+ let markShown = () => void 0;
292641
+ const shown = new Promise((resolve3) => {
292642
+ markShown = resolve3;
292643
+ });
292644
+ const lineReader = terminal2.lineReader;
292645
+ return {
292646
+ openAuthorizationUrl: async (url3) => {
292647
+ terminal2.print(
292648
+ `Open this link to sign in to ${connectionName} for ${MCP_AGENT_LABELS[agent]}:
292649
+
292650
+ ${url3}
292651
+ `
292652
+ );
292653
+ if (terminal2.browserAvailable && terminal2.openBrowser(url3)) {
292654
+ terminal2.print("Your browser should open it now.");
292655
+ }
292656
+ terminal2.print(
292657
+ 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..."
292658
+ );
292659
+ markShown();
292660
+ },
292661
+ manualCallbackInput: lineReader ? {
292662
+ readCallbackUrl: async (signal) => {
292663
+ await Promise.race([
292664
+ shown,
292665
+ new Promise((resolve3) => {
292666
+ signal.addEventListener("abort", () => resolve3(), {
292667
+ once: true
292668
+ });
292669
+ })
292670
+ ]);
292671
+ if (signal.aborted) return null;
292672
+ let line = "";
292673
+ while (line !== null && !line.trim()) {
292674
+ line = await lineReader.question(
292675
+ "Paste the address, or wait for sign-in to finish: ",
292676
+ signal
292677
+ );
292678
+ }
292679
+ if (line === null && signal.aborted) terminal2.print("");
292680
+ return line;
292681
+ },
292682
+ reportRejectedCallbackUrl: (message) => terminal2.print(message)
292683
+ } : null
292684
+ };
292685
+ };
292686
+ }
292687
+ });
292688
+
292689
+ // src/devbox/commands/mcp.ts
292690
+ 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;
292691
+ var init_mcp = __esm({
292692
+ "src/devbox/commands/mcp.ts"() {
292693
+ "use strict";
292694
+ init_devboxCore();
292695
+ init_browser();
292696
+ init_identifiers();
292697
+ init_mcpArgs();
292698
+ init_mcpSession();
292699
+ init_mcpSignIn();
291659
292700
  defaultDependencies10 = {
291660
- createSession: createDefaultSession,
292701
+ createSession: createDefaultMcpCliSession,
291661
292702
  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
- },
292703
+ openBrowser: (url3) => openBrowser(url3),
292704
+ browserAvailable: canOpenLocalBrowser(),
292705
+ createLineReader: () => process.stdin.isTTY === true ? createStdinLineReader() : null,
292706
+ readEnv: (name) => process.env[name],
291669
292707
  subscribeInterrupt: (listener) => {
291670
292708
  process.once("SIGINT", listener);
291671
292709
  return () => process.off("SIGINT", listener);
291672
292710
  },
291673
- print: console.log
292711
+ print: console.log,
292712
+ printStatus: console.error
292713
+ };
292714
+ TEMPLATE_MANAGED_SENTENCES = {
292715
+ custom_oauth_client: "This command uses custom OAuth settings that boxes.dev can't manage yet.",
292716
+ insecure_url: "boxes.dev can only manage MCPs served over public HTTPS.",
292717
+ legacy_sse: "This command uses the older SSE transport, which boxes.dev doesn't manage.",
292718
+ stdio: "This command installs an MCP that runs on the machine itself, so boxes.dev can't manage it centrally.",
292719
+ unsupported_option: "This command uses options boxes.dev can't manage yet."
291674
292720
  };
291675
292721
  bindingStatus = (connection, agent) => connection.bindings.find((binding) => binding.agent === agent)?.status ?? "not_added";
291676
- renderConnections = (connections) => {
292722
+ projectForConnection = (connection, projects) => connection.scope.kind === "project" ? projects.find(
292723
+ (project) => project.primaryInstanceId === connection.scope.primaryInstanceId
292724
+ ) ?? null : null;
292725
+ describeScope = (connection, projects) => {
292726
+ if (connection.scope.kind === "all_projects") return "all projects";
292727
+ const project = projectForConnection(connection, projects);
292728
+ return `project ${project?.projectAlias ?? connection.scope.primaryInstanceId ?? "unknown"}`;
292729
+ };
292730
+ renderConnections = (connections, projects) => {
291677
292731
  if (connections.length === 0) return "No centrally managed MCPs.";
291678
292732
  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}`
292733
+ (connection) => [
292734
+ connection.displayName,
292735
+ ` id: ${connection.connectionId}`,
292736
+ ` name: ${connection.nativeName}`,
292737
+ ` scope: ${describeScope(connection, projects)}`,
292738
+ ...connection.teamTemplateId ? [" managed by: your team"] : [],
292739
+ ` auth: ${connection.authMode}`,
292740
+ ` Codex: ${bindingStatus(connection, "codex")}`,
292741
+ ` Claude: ${bindingStatus(connection, "claude")}`,
292742
+ ` url: ${connection.url}`
292743
+ ].join("\n")
291687
292744
  ).join("\n\n");
291688
292745
  };
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;
292746
+ serializeConnection = (connection, projects) => {
292747
+ const project = projectForConnection(connection, projects);
292748
+ return {
292749
+ connectionId: connection.connectionId,
292750
+ displayName: connection.displayName,
292751
+ nativeName: connection.nativeName,
292752
+ url: connection.url,
292753
+ authMode: connection.authMode,
292754
+ scope: connection.scope,
292755
+ project: project ? { name: project.projectAlias, fingerprint: project.projectFingerprint } : null,
292756
+ teamManaged: Boolean(connection.teamTemplateId),
292757
+ agents: {
292758
+ codex: bindingStatus(connection, "codex"),
292759
+ claude: bindingStatus(connection, "claude")
292760
+ }
292761
+ };
292762
+ };
292763
+ uniqueMatch = (matches2, selector, projectSelected) => {
291710
292764
  if (matches2.length > 1) {
291711
292765
  throw new Error(
291712
- `More than one MCP is named ${JSON.stringify(selector)}. Run \`dvb mcp list\` and use its id.`
292766
+ `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
292767
  );
291714
292768
  }
291715
- return null;
292769
+ return matches2[0] ?? null;
291716
292770
  };
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") };
292771
+ resolveConnection = (connections, selector, projectSelected = false) => connections.find((connection) => connection.connectionId === selector) ?? uniqueMatch(
292772
+ connections.filter((connection) => connection.nativeName === selector),
292773
+ selector,
292774
+ projectSelected
292775
+ ) ?? uniqueMatch(
292776
+ connections.filter((connection) => connection.displayName === selector),
292777
+ selector,
292778
+ projectSelected
292779
+ );
292780
+ resolveProject = (projects, selector) => resolveCliAgentToolProject({ selector, projects });
292781
+ loadConnections = async (session, projectSelector) => {
292782
+ const projects = await session.listProjects();
292783
+ const connections = projectSelector === null ? await session.listAll() : await session.listForProject(
292784
+ resolveProject(projects, projectSelector).primaryInstanceId
292785
+ );
292786
+ return { connections, projects };
291728
292787
  };
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
- );
292788
+ requireConnection = (connections, selector, projectSelector) => {
292789
+ const connection = resolveConnection(
292790
+ connections,
292791
+ selector,
292792
+ projectSelector !== null
292793
+ );
292794
+ if (connection) return connection;
292795
+ throw new Error(
292796
+ `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>." : ""}`
292797
+ );
292798
+ };
292799
+ readableSelector = (connection, connections) => {
292800
+ try {
292801
+ return resolveConnection(connections, connection.nativeName)?.connectionId === connection.connectionId ? connection.nativeName : connection.connectionId;
292802
+ } catch {
292803
+ return connection.connectionId;
291748
292804
  }
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
- );
292805
+ };
292806
+ authorizeAgent = async ({
292807
+ agent,
292808
+ browser,
292809
+ connection,
292810
+ dependencies,
292811
+ lineReader,
292812
+ session
292813
+ }) => {
292814
+ const abortController = new AbortController();
292815
+ const unsubscribe4 = dependencies.subscribeInterrupt(
292816
+ () => abortController.abort()
292817
+ );
292818
+ let attempt = null;
292819
+ let completed = false;
292820
+ try {
292821
+ attempt = await session.start({ agent, connectionId: connection.connectionId }).catch((error55) => {
292822
+ throw toUserFacingMcpError(error55);
292823
+ });
292824
+ const signIn = createMcpTerminalSignIn({
292825
+ agent,
292826
+ connectionName: connection.displayName,
292827
+ terminal: {
292828
+ print: dependencies.printStatus,
292829
+ openBrowser: dependencies.openBrowser,
292830
+ browserAvailable: browser && dependencies.browserAvailable,
292831
+ lineReader
292832
+ }
292833
+ });
292834
+ const startedAttempt = attempt;
292835
+ return await dependencies.authorize({
292836
+ agent,
292837
+ serverName: startedAttempt.serverName,
292838
+ serverUrl: startedAttempt.serverUrl,
292839
+ signal: abortController.signal,
292840
+ openAuthorizationUrl: signIn.openAuthorizationUrl,
292841
+ ...signIn.manualCallbackInput ? { manualCallbackInput: signIn.manualCallbackInput } : {},
292842
+ uploadGrant: async (grant) => {
292843
+ await session.complete({
292844
+ attemptNonce: startedAttempt.attemptNonce,
292845
+ bindingId: startedAttempt.bindingId,
292846
+ grant
292847
+ });
292848
+ completed = true;
292849
+ }
292850
+ });
292851
+ } catch (error55) {
292852
+ if (attempt && !completed) {
292853
+ const startedAttempt = attempt;
292854
+ await session.cancel({
292855
+ attemptNonce: startedAttempt.attemptNonce,
292856
+ bindingId: startedAttempt.bindingId
292857
+ }).catch(() => void 0);
292858
+ }
292859
+ throw error55;
292860
+ } finally {
292861
+ unsubscribe4();
291755
292862
  }
291756
- return { selector, agent };
291757
292863
  };
291758
292864
  runMcpListWithDependencies = async (args, dependencies) => {
291759
292865
  const parsed = parseListArgs2(args);
291760
292866
  const session = await dependencies.createSession();
291761
292867
  try {
291762
- const connections = await session.list();
292868
+ const { connections, projects } = await loadConnections(
292869
+ session,
292870
+ parsed.project
292871
+ );
291763
292872
  dependencies.print(
291764
292873
  parsed.json ? JSON.stringify(
291765
- { ok: true, connections: serializeConnections(connections) },
292874
+ {
292875
+ ok: true,
292876
+ connections: connections.map(
292877
+ (connection) => serializeConnection(connection, projects)
292878
+ )
292879
+ },
291766
292880
  null,
291767
292881
  2
291768
- ) : renderConnections(connections)
292882
+ ) : renderConnections(connections, projects)
291769
292883
  );
291770
292884
  } finally {
291771
292885
  await session.close();
@@ -291774,54 +292888,265 @@ var init_mcp = __esm({
291774
292888
  runMcpAuthorizeWithDependencies = async (args, dependencies) => {
291775
292889
  const parsed = parseAuthorizeArgs(args);
291776
292890
  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;
292891
+ const lineReader = dependencies.createLineReader();
291783
292892
  try {
291784
- const connections = await session.list();
291785
- const connection = resolveConnection(connections, parsed.selector);
291786
- if (!connection) {
292893
+ const { connections } = await loadConnections(session, parsed.project);
292894
+ const connection = requireConnection(
292895
+ connections,
292896
+ parsed.selector,
292897
+ parsed.project
292898
+ );
292899
+ const receipt = await authorizeAgent({
292900
+ agent: parsed.agent,
292901
+ browser: parsed.browser,
292902
+ connection,
292903
+ dependencies,
292904
+ lineReader,
292905
+ session
292906
+ });
292907
+ dependencies.print(
292908
+ `${connection.displayName} is connected to ${MCP_AGENT_LABELS[parsed.agent]}.`
292909
+ );
292910
+ return receipt;
292911
+ } finally {
292912
+ lineReader?.close();
292913
+ await session.close();
292914
+ }
292915
+ };
292916
+ selectProjectForAdd = (projects, selector) => {
292917
+ if (selector !== null) return resolveProject(projects, selector);
292918
+ const only = projects[0];
292919
+ if (projects.length === 1 && only) return only;
292920
+ if (projects.length === 0) {
292921
+ throw new Error(
292922
+ "You don't have a boxes.dev project yet. Add --all-projects to make this MCP available in every project."
292923
+ );
292924
+ }
292925
+ throw new Error(
292926
+ `Choose a project with --project <name>, or add --all-projects. Your projects: ${projects.map((project) => project.projectAlias).join(", ")}.`
292927
+ );
292928
+ };
292929
+ planAdd = (parsed, readEnv) => {
292930
+ const imported = typeof parsed.input === "string" ? parseMcpCommandImport(parsed.input) : parseMcpAddArgv(parsed.input);
292931
+ if (imported.kind === "invalid") throw new Error(imported.message);
292932
+ if (imported.kind === "template_managed") {
292933
+ throw new Error(
292934
+ `${TEMPLATE_MANAGED_SENTENCES[imported.reason]} Run it on your Template box instead.`
292935
+ );
292936
+ }
292937
+ const headers = [...imported.staticHeaders, ...parsed.headers];
292938
+ const hasAuthorizationHeader = parsed.headers.some(
292939
+ (header) => header.name.toLowerCase() === "authorization"
292940
+ );
292941
+ if (imported.bearerTokenEnvVar !== null && !hasAuthorizationHeader) {
292942
+ const token = readEnv(imported.bearerTokenEnvVar)?.trim();
292943
+ if (!token) {
291787
292944
  throw new Error(
291788
- `MCP ${JSON.stringify(parsed.selector)} was not found. Run \`dvb mcp list\` to see available connections.`
292945
+ `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
292946
  );
291790
292947
  }
291791
- attempt = await session.start({
291792
- agent: parsed.agent,
291793
- connectionId: connection.connectionId
292948
+ headers.push({ name: "Authorization", value: `Bearer ${token}` });
292949
+ }
292950
+ return {
292951
+ imported,
292952
+ agents: parsed.agents ?? (imported.requestedAgent ? [imported.requestedAgent] : ["codex", "claude"]),
292953
+ scopeKind: parsed.allProjects ? "all_projects" : parsed.project !== null ? "project" : imported.requestedScope,
292954
+ headers
292955
+ };
292956
+ };
292957
+ resolveAuthMode = async ({
292958
+ headers,
292959
+ imported,
292960
+ session,
292961
+ signIn
292962
+ }) => {
292963
+ if (headers.length > 0) {
292964
+ return {
292965
+ authMode: "static_headers",
292966
+ displayName: imported.displayName,
292967
+ signInOptional: false
292968
+ };
292969
+ }
292970
+ const preflight = await session.inspect(imported.url);
292971
+ const displayName = preflight.displayName ?? imported.displayName;
292972
+ switch (preflight.classification) {
292973
+ case "unreachable":
292974
+ throw new Error(
292975
+ "boxes.dev couldn't reach this server. Check the URL and try again."
292976
+ );
292977
+ case "static_or_manual":
292978
+ case "unknown":
292979
+ if (!signIn) {
292980
+ return { authMode: "none", displayName, signInOptional: false };
292981
+ }
292982
+ throw new Error(
292983
+ `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.`
292984
+ );
292985
+ case "none":
292986
+ return { authMode: "none", displayName, signInOptional: false };
292987
+ case "oauth":
292988
+ if (!signIn && !preflight.signInOptional) {
292989
+ throw new Error(
292990
+ "This MCP requires signing in. Remove --no-sign-in and try again."
292991
+ );
292992
+ }
292993
+ return {
292994
+ authMode: signIn ? "oauth" : "none",
292995
+ displayName,
292996
+ signInOptional: preflight.signInOptional
292997
+ };
292998
+ }
292999
+ };
293000
+ runMcpAddWithDependencies = async (args, dependencies) => {
293001
+ const parsed = parseAddArgs(args);
293002
+ const plan = planAdd(parsed, dependencies.readEnv);
293003
+ const status = parsed.json ? dependencies.printStatus : dependencies.print;
293004
+ const session = await dependencies.createSession();
293005
+ const lineReader = parsed.authorize && !parsed.json ? dependencies.createLineReader() : null;
293006
+ try {
293007
+ const projects = await session.listProjects();
293008
+ const project = plan.scopeKind === "project" ? selectProjectForAdd(projects, parsed.project) : null;
293009
+ const { authMode, displayName, signInOptional } = await resolveAuthMode({
293010
+ headers: plan.headers,
293011
+ imported: plan.imported,
293012
+ session,
293013
+ signIn: parsed.signIn
293014
+ });
293015
+ const created = await session.create({
293016
+ displayName: parsed.name ?? displayName,
293017
+ nativeName: parsed.name ?? plan.imported.nativeName,
293018
+ scopeKind: plan.scopeKind,
293019
+ primaryInstanceId: project?.primaryInstanceId ?? null,
293020
+ url: plan.imported.url,
293021
+ authMode,
293022
+ signInOptional
293023
+ }).catch((error55) => {
293024
+ throw toUserFacingMcpError(error55);
291794
293025
  });
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
293026
+ let connection = await session.get(created.connectionId);
293027
+ status(
293028
+ `Added ${connection.displayName} to ${project ? `project ${project.projectAlias}` : "all projects"}.`
293029
+ );
293030
+ let signingIn = null;
293031
+ const signInLater = [];
293032
+ try {
293033
+ if (authMode === "static_headers") {
293034
+ await session.setStaticHeaders({
293035
+ connectionId: created.connectionId,
293036
+ headers: plan.headers
291807
293037
  });
291808
- completed = true;
291809
293038
  }
291810
- });
291811
- dependencies.print(
291812
- `${connection.displayName} is connected to ${parsed.agent === "codex" ? "Codex" : "Claude"}.`
293039
+ for (const agent of plan.agents) {
293040
+ if (authMode !== "oauth") {
293041
+ await session.connectAgent({
293042
+ connectionId: created.connectionId,
293043
+ agent
293044
+ });
293045
+ } else if (parsed.authorize) {
293046
+ signingIn = agent;
293047
+ await authorizeAgent({
293048
+ agent,
293049
+ browser: parsed.browser,
293050
+ connection,
293051
+ dependencies,
293052
+ lineReader,
293053
+ session
293054
+ });
293055
+ signingIn = null;
293056
+ } else {
293057
+ signInLater.push(agent);
293058
+ }
293059
+ }
293060
+ } catch (error55) {
293061
+ const userError = toUserFacingMcpError(error55);
293062
+ const reason = userError instanceof Error ? userError.message : String(userError);
293063
+ if (signingIn === null) {
293064
+ throw new Error(
293065
+ `${connection.displayName} was added, but connecting it to the agents didn't finish: ${reason}`
293066
+ );
293067
+ }
293068
+ const selector = readableSelector(connection, await session.listAll());
293069
+ throw new Error(
293070
+ `${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}`
293071
+ );
293072
+ }
293073
+ connection = await session.get(created.connectionId);
293074
+ if (signInLater.length > 0) {
293075
+ const selector = readableSelector(connection, await session.listAll());
293076
+ status(
293077
+ [
293078
+ "To sign in, run:",
293079
+ ...signInLater.map(
293080
+ (agent) => ` dvb mcp authorize ${selector} --agent ${agent}`
293081
+ )
293082
+ ].join("\n")
293083
+ );
293084
+ }
293085
+ const connectedAgents = plan.agents.filter((agent) => bindingStatus(connection, agent) === "connected").map((agent) => MCP_AGENT_LABELS[agent]);
293086
+ if (parsed.json) {
293087
+ dependencies.print(
293088
+ JSON.stringify(
293089
+ { ok: true, connection: serializeConnection(connection, projects) },
293090
+ null,
293091
+ 2
293092
+ )
293093
+ );
293094
+ } else if (connectedAgents.length > 0) {
293095
+ dependencies.print(
293096
+ `${connection.displayName} is connected to ${connectedAgents.join(" and ")}.`
293097
+ );
293098
+ }
293099
+ } finally {
293100
+ lineReader?.close();
293101
+ await session.close();
293102
+ }
293103
+ };
293104
+ runMcpRemoveWithDependencies = async (args, dependencies) => {
293105
+ const parsed = parseRemoveArgs(args);
293106
+ const session = await dependencies.createSession();
293107
+ try {
293108
+ const { connections } = await loadConnections(session, parsed.project);
293109
+ const connection = requireConnection(
293110
+ connections,
293111
+ parsed.selector,
293112
+ parsed.project
291813
293113
  );
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);
293114
+ let changed = true;
293115
+ try {
293116
+ if (parsed.agent) {
293117
+ ({ changed } = await session.disconnectAgent({
293118
+ connectionId: connection.connectionId,
293119
+ agent: parsed.agent
293120
+ }));
293121
+ } else if (connection.teamTemplateId) {
293122
+ throw new Error(
293123
+ "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."
293124
+ );
293125
+ } else {
293126
+ await session.remove({ connectionId: connection.connectionId });
293127
+ }
293128
+ } catch (error55) {
293129
+ throw toUserFacingMcpError(error55);
291821
293130
  }
291822
- throw error55;
293131
+ if (parsed.json) {
293132
+ dependencies.print(
293133
+ JSON.stringify(
293134
+ {
293135
+ ok: true,
293136
+ connectionId: connection.connectionId,
293137
+ agent: parsed.agent,
293138
+ changed
293139
+ },
293140
+ null,
293141
+ 2
293142
+ )
293143
+ );
293144
+ return;
293145
+ }
293146
+ dependencies.print(
293147
+ 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]}.`
293148
+ );
291823
293149
  } finally {
291824
- unsubscribe4();
291825
293150
  await session.close();
291826
293151
  }
291827
293152
  };
@@ -291829,6 +293154,8 @@ var init_mcp = __esm({
291829
293154
  runMcpAuthorize = async (args) => {
291830
293155
  await runMcpAuthorizeWithDependencies(args, defaultDependencies10);
291831
293156
  };
293157
+ runMcpAdd = async (args) => await runMcpAddWithDependencies(args, defaultDependencies10);
293158
+ runMcpRemove = async (args) => await runMcpRemoveWithDependencies(args, defaultDependencies10);
291832
293159
  }
291833
293160
  });
291834
293161
 
@@ -293347,7 +294674,7 @@ var init_projectMaintenanceHistory = __esm({
293347
294674
  // src/devbox/commands/projectLifecycleMaintenance.ts
293348
294675
  import fs80 from "node:fs/promises";
293349
294676
  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;
294677
+ 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
294678
  var init_projectLifecycleMaintenance2 = __esm({
293352
294679
  "src/devbox/commands/projectLifecycleMaintenance.ts"() {
293353
294680
  "use strict";
@@ -293575,14 +294902,14 @@ ${watchLines.join("\n")}` : "GitHub watches: none",
293575
294902
  `Repeating schedule: ${result.schedule.enabled ? "on" : "off"}`,
293576
294903
  result.triggerActive ? "At least one maintenance trigger is active." : "No maintenance trigger is active."
293577
294904
  ].join("\n");
293578
- resolveProject = async (client, selector) => await resolveCliAgentToolProjectSelection(client, selector);
294905
+ resolveProject2 = async (client, selector) => await resolveCliAgentToolProjectSelection(client, selector);
293579
294906
  runProjectLifecycleWithDependencies = async (args, dependencies) => {
293580
294907
  const parsed = parseProjectLifecycleArgs(args);
293581
294908
  await runResourceCommand({
293582
294909
  json: parsed.json,
293583
294910
  dependencies,
293584
294911
  load: async ({ client }, requestId2) => {
293585
- const project = await resolveProject(client, parsed.project);
294912
+ const project = await resolveProject2(client, parsed.project);
293586
294913
  if (parsed.command === "get") {
293587
294914
  return {
293588
294915
  operation: "get",
@@ -293645,7 +294972,7 @@ ${watchLines.join("\n")}` : "GitHub watches: none",
293645
294972
  json: parsed.json,
293646
294973
  dependencies,
293647
294974
  load: async ({ client }, requestId2) => {
293648
- const project = await resolveProject(client, parsed.project);
294975
+ const project = await resolveProject2(client, parsed.project);
293649
294976
  if (parsed.command === "get") {
293650
294977
  return {
293651
294978
  operation: "get",
@@ -293951,7 +295278,7 @@ var init_reset = __esm({
293951
295278
  import fs81 from "node:fs/promises";
293952
295279
  import os41 from "node:os";
293953
295280
  import path103 from "node:path";
293954
- import readline6 from "node:readline/promises";
295281
+ import readline7 from "node:readline/promises";
293955
295282
  import { spawnSync as spawnSync7 } from "node:child_process";
293956
295283
  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
295284
  var init_uninstall = __esm({
@@ -294304,7 +295631,7 @@ var init_uninstall = __esm({
294304
295631
  );
294305
295632
  }
294306
295633
  const phrase = "uninstall";
294307
- const rl = readline6.createInterface({
295634
+ const rl = readline7.createInterface({
294308
295635
  input: process.stdin,
294309
295636
  output: process.stdout
294310
295637
  });
@@ -298713,7 +300040,9 @@ var init_dispatch = __esm({
298713
300040
  ["report-bug", runReportBug],
298714
300041
  ["agents", runAgents],
298715
300042
  ["mcp list", runMcpList],
300043
+ ["mcp add", runMcpAdd],
298716
300044
  ["mcp authorize", runMcpAuthorize],
300045
+ ["mcp remove", runMcpRemove],
298717
300046
  ["permissions get", runAgentPermissionsGet],
298718
300047
  ["permissions set", runAgentPermissionsSet],
298719
300048
  ["permissions requests", runAgentPermissionRequests],
@@ -299482,4 +300811,4 @@ react/cjs/react-jsx-runtime.development.js:
299482
300811
  *)
299483
300812
  */
299484
300813
 
299485
- //# debugId=249a0abb-e483-5aa3-b76c-e668263ae2b8
300814
+ //# debugId=2444e913-d099-55e2-8f4b-b8e55bd2427d