@mcp-use/cli 3.1.5-canary.4 → 3.2.0-canary.5

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/index.cjs CHANGED
@@ -6,6 +6,13 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
9
16
  var __copyProps = (to, from, except, desc) => {
10
17
  if (from && typeof from === "object" || typeof from === "function") {
11
18
  for (let key of __getOwnPropNames(from))
@@ -24,1133 +31,1276 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
31
  ));
25
32
 
26
33
  // ../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.14_tsx@4.21.0_typescript@5.9.3_yaml@2.8.3/node_modules/tsup/assets/cjs_shims.js
27
- var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
28
- var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
34
+ var getImportMetaUrl, importMetaUrl;
35
+ var init_cjs_shims = __esm({
36
+ "../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.14_tsx@4.21.0_typescript@5.9.3_yaml@2.8.3/node_modules/tsup/assets/cjs_shims.js"() {
37
+ "use strict";
38
+ getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
39
+ importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
40
+ }
41
+ });
29
42
 
30
- // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
31
- var ANSI_BACKGROUND_OFFSET = 10;
32
- var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
33
- var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
34
- var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
35
- var styles = {
36
- modifier: {
37
- reset: [0, 0],
38
- // 21 isn't widely supported and 22 does the same thing
39
- bold: [1, 22],
40
- dim: [2, 22],
41
- italic: [3, 23],
42
- underline: [4, 24],
43
- overline: [53, 55],
44
- inverse: [7, 27],
45
- hidden: [8, 28],
46
- strikethrough: [9, 29]
47
- },
48
- color: {
49
- black: [30, 39],
50
- red: [31, 39],
51
- green: [32, 39],
52
- yellow: [33, 39],
53
- blue: [34, 39],
54
- magenta: [35, 39],
55
- cyan: [36, 39],
56
- white: [37, 39],
57
- // Bright color
58
- blackBright: [90, 39],
59
- gray: [90, 39],
60
- // Alias of `blackBright`
61
- grey: [90, 39],
62
- // Alias of `blackBright`
63
- redBright: [91, 39],
64
- greenBright: [92, 39],
65
- yellowBright: [93, 39],
66
- blueBright: [94, 39],
67
- magentaBright: [95, 39],
68
- cyanBright: [96, 39],
69
- whiteBright: [97, 39]
70
- },
71
- bgColor: {
72
- bgBlack: [40, 49],
73
- bgRed: [41, 49],
74
- bgGreen: [42, 49],
75
- bgYellow: [43, 49],
76
- bgBlue: [44, 49],
77
- bgMagenta: [45, 49],
78
- bgCyan: [46, 49],
79
- bgWhite: [47, 49],
80
- // Bright color
81
- bgBlackBright: [100, 49],
82
- bgGray: [100, 49],
83
- // Alias of `bgBlackBright`
84
- bgGrey: [100, 49],
85
- // Alias of `bgBlackBright`
86
- bgRedBright: [101, 49],
87
- bgGreenBright: [102, 49],
88
- bgYellowBright: [103, 49],
89
- bgBlueBright: [104, 49],
90
- bgMagentaBright: [105, 49],
91
- bgCyanBright: [106, 49],
92
- bgWhiteBright: [107, 49]
43
+ // ../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
44
+ function hasDockerEnv() {
45
+ try {
46
+ import_node_fs.default.statSync("/.dockerenv");
47
+ return true;
48
+ } catch {
49
+ return false;
93
50
  }
94
- };
95
- var modifierNames = Object.keys(styles.modifier);
96
- var foregroundColorNames = Object.keys(styles.color);
97
- var backgroundColorNames = Object.keys(styles.bgColor);
98
- var colorNames = [...foregroundColorNames, ...backgroundColorNames];
99
- function assembleStyles() {
100
- const codes = /* @__PURE__ */ new Map();
101
- for (const [groupName, group] of Object.entries(styles)) {
102
- for (const [styleName, style] of Object.entries(group)) {
103
- styles[styleName] = {
104
- open: `\x1B[${style[0]}m`,
105
- close: `\x1B[${style[1]}m`
106
- };
107
- group[styleName] = styles[styleName];
108
- codes.set(style[0], style[1]);
109
- }
110
- Object.defineProperty(styles, groupName, {
111
- value: group,
112
- enumerable: false
113
- });
51
+ }
52
+ function hasDockerCGroup() {
53
+ try {
54
+ return import_node_fs.default.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
55
+ } catch {
56
+ return false;
114
57
  }
115
- Object.defineProperty(styles, "codes", {
116
- value: codes,
117
- enumerable: false
118
- });
119
- styles.color.close = "\x1B[39m";
120
- styles.bgColor.close = "\x1B[49m";
121
- styles.color.ansi = wrapAnsi16();
122
- styles.color.ansi256 = wrapAnsi256();
123
- styles.color.ansi16m = wrapAnsi16m();
124
- styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
125
- styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
126
- styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
127
- Object.defineProperties(styles, {
128
- rgbToAnsi256: {
129
- value(red, green, blue) {
130
- if (red === green && green === blue) {
131
- if (red < 8) {
132
- return 16;
133
- }
134
- if (red > 248) {
135
- return 231;
136
- }
137
- return Math.round((red - 8) / 247 * 24) + 232;
138
- }
139
- return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
140
- },
141
- enumerable: false
142
- },
143
- hexToRgb: {
144
- value(hex) {
145
- const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
146
- if (!matches) {
147
- return [0, 0, 0];
58
+ }
59
+ function isDocker() {
60
+ if (isDockerCached === void 0) {
61
+ isDockerCached = hasDockerEnv() || hasDockerCGroup();
62
+ }
63
+ return isDockerCached;
64
+ }
65
+ var import_node_fs, isDockerCached;
66
+ var init_is_docker = __esm({
67
+ "../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js"() {
68
+ "use strict";
69
+ init_cjs_shims();
70
+ import_node_fs = __toESM(require("fs"), 1);
71
+ }
72
+ });
73
+
74
+ // ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
75
+ function isInsideContainer() {
76
+ if (cachedResult === void 0) {
77
+ cachedResult = hasContainerEnv() || isDocker();
78
+ }
79
+ return cachedResult;
80
+ }
81
+ var import_node_fs2, cachedResult, hasContainerEnv;
82
+ var init_is_inside_container = __esm({
83
+ "../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js"() {
84
+ "use strict";
85
+ init_cjs_shims();
86
+ import_node_fs2 = __toESM(require("fs"), 1);
87
+ init_is_docker();
88
+ hasContainerEnv = () => {
89
+ try {
90
+ import_node_fs2.default.statSync("/run/.containerenv");
91
+ return true;
92
+ } catch {
93
+ return false;
94
+ }
95
+ };
96
+ }
97
+ });
98
+
99
+ // ../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
100
+ var import_node_process2, import_node_os2, import_node_fs3, isWsl, is_wsl_default;
101
+ var init_is_wsl = __esm({
102
+ "../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js"() {
103
+ "use strict";
104
+ init_cjs_shims();
105
+ import_node_process2 = __toESM(require("process"), 1);
106
+ import_node_os2 = __toESM(require("os"), 1);
107
+ import_node_fs3 = __toESM(require("fs"), 1);
108
+ init_is_inside_container();
109
+ isWsl = () => {
110
+ if (import_node_process2.default.platform !== "linux") {
111
+ return false;
112
+ }
113
+ if (import_node_os2.default.release().toLowerCase().includes("microsoft")) {
114
+ if (isInsideContainer()) {
115
+ return false;
148
116
  }
149
- let [colorString] = matches;
150
- if (colorString.length === 3) {
151
- colorString = [...colorString].map((character) => character + character).join("");
117
+ return true;
118
+ }
119
+ try {
120
+ return import_node_fs3.default.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
121
+ } catch {
122
+ return false;
123
+ }
124
+ };
125
+ is_wsl_default = import_node_process2.default.env.__IS_WSL_TEST__ ? isWsl : isWsl();
126
+ }
127
+ });
128
+
129
+ // ../../node_modules/.pnpm/powershell-utils@0.1.0/node_modules/powershell-utils/index.js
130
+ var import_node_process3, import_node_buffer, import_node_util, import_node_child_process, import_promises, execFile, powerShellPath, executePowerShell;
131
+ var init_powershell_utils = __esm({
132
+ "../../node_modules/.pnpm/powershell-utils@0.1.0/node_modules/powershell-utils/index.js"() {
133
+ "use strict";
134
+ init_cjs_shims();
135
+ import_node_process3 = __toESM(require("process"), 1);
136
+ import_node_buffer = require("buffer");
137
+ import_node_util = require("util");
138
+ import_node_child_process = __toESM(require("child_process"), 1);
139
+ import_promises = __toESM(require("fs/promises"), 1);
140
+ execFile = (0, import_node_util.promisify)(import_node_child_process.default.execFile);
141
+ powerShellPath = () => `${import_node_process3.default.env.SYSTEMROOT || import_node_process3.default.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
142
+ executePowerShell = async (command, options = {}) => {
143
+ const {
144
+ powerShellPath: psPath,
145
+ ...execFileOptions
146
+ } = options;
147
+ const encodedCommand = executePowerShell.encodeCommand(command);
148
+ return execFile(
149
+ psPath ?? powerShellPath(),
150
+ [
151
+ ...executePowerShell.argumentsPrefix,
152
+ encodedCommand
153
+ ],
154
+ {
155
+ encoding: "utf8",
156
+ ...execFileOptions
152
157
  }
153
- const integer = Number.parseInt(colorString, 16);
154
- return [
155
- /* eslint-disable no-bitwise */
156
- integer >> 16 & 255,
157
- integer >> 8 & 255,
158
- integer & 255
159
- /* eslint-enable no-bitwise */
160
- ];
161
- },
162
- enumerable: false
163
- },
164
- hexToAnsi256: {
165
- value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
166
- enumerable: false
167
- },
168
- ansi256ToAnsi: {
169
- value(code) {
170
- if (code < 8) {
171
- return 30 + code;
158
+ );
159
+ };
160
+ executePowerShell.argumentsPrefix = [
161
+ "-NoProfile",
162
+ "-NonInteractive",
163
+ "-ExecutionPolicy",
164
+ "Bypass",
165
+ "-EncodedCommand"
166
+ ];
167
+ executePowerShell.encodeCommand = (command) => import_node_buffer.Buffer.from(command, "utf16le").toString("base64");
168
+ executePowerShell.escapeArgument = (value) => `'${String(value).replaceAll("'", "''")}'`;
169
+ }
170
+ });
171
+
172
+ // ../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/utilities.js
173
+ function parseMountPointFromConfig(content) {
174
+ for (const line of content.split("\n")) {
175
+ if (/^\s*#/.test(line)) {
176
+ continue;
177
+ }
178
+ const match = /^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(line);
179
+ if (!match) {
180
+ continue;
181
+ }
182
+ return match.groups.mountPoint.trim().replaceAll(/^["']|["']$/g, "");
183
+ }
184
+ }
185
+ var init_utilities = __esm({
186
+ "../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/utilities.js"() {
187
+ "use strict";
188
+ init_cjs_shims();
189
+ }
190
+ });
191
+
192
+ // ../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/index.js
193
+ var import_node_util2, import_node_child_process2, import_promises2, execFile2, wslDrivesMountPoint, powerShellPathFromWsl, powerShellPath2, canAccessPowerShellPromise, canAccessPowerShell, wslDefaultBrowser, convertWslPathToWindows;
194
+ var init_wsl_utils = __esm({
195
+ "../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/index.js"() {
196
+ "use strict";
197
+ init_cjs_shims();
198
+ import_node_util2 = require("util");
199
+ import_node_child_process2 = __toESM(require("child_process"), 1);
200
+ import_promises2 = __toESM(require("fs/promises"), 1);
201
+ init_is_wsl();
202
+ init_powershell_utils();
203
+ init_utilities();
204
+ init_is_wsl();
205
+ execFile2 = (0, import_node_util2.promisify)(import_node_child_process2.default.execFile);
206
+ wslDrivesMountPoint = /* @__PURE__ */ (() => {
207
+ const defaultMountPoint = "/mnt/";
208
+ let mountPoint;
209
+ return async function() {
210
+ if (mountPoint) {
211
+ return mountPoint;
172
212
  }
173
- if (code < 16) {
174
- return 90 + (code - 8);
213
+ const configFilePath = "/etc/wsl.conf";
214
+ let isConfigFileExists = false;
215
+ try {
216
+ await import_promises2.default.access(configFilePath, import_promises2.constants.F_OK);
217
+ isConfigFileExists = true;
218
+ } catch {
175
219
  }
176
- let red;
177
- let green;
178
- let blue;
179
- if (code >= 232) {
180
- red = ((code - 232) * 10 + 8) / 255;
181
- green = red;
182
- blue = red;
183
- } else {
184
- code -= 16;
185
- const remainder = code % 36;
186
- red = Math.floor(code / 36) / 5;
187
- green = Math.floor(remainder / 6) / 5;
188
- blue = remainder % 6 / 5;
220
+ if (!isConfigFileExists) {
221
+ return defaultMountPoint;
189
222
  }
190
- const value = Math.max(red, green, blue) * 2;
191
- if (value === 0) {
192
- return 30;
223
+ const configContent = await import_promises2.default.readFile(configFilePath, { encoding: "utf8" });
224
+ const parsedMountPoint = parseMountPointFromConfig(configContent);
225
+ if (parsedMountPoint === void 0) {
226
+ return defaultMountPoint;
193
227
  }
194
- let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
195
- if (value === 2) {
196
- result += 60;
228
+ mountPoint = parsedMountPoint;
229
+ mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
230
+ return mountPoint;
231
+ };
232
+ })();
233
+ powerShellPathFromWsl = async () => {
234
+ const mountPoint = await wslDrivesMountPoint();
235
+ return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
236
+ };
237
+ powerShellPath2 = is_wsl_default ? powerShellPathFromWsl : powerShellPath;
238
+ canAccessPowerShell = async () => {
239
+ canAccessPowerShellPromise ??= (async () => {
240
+ try {
241
+ const psPath = await powerShellPath2();
242
+ await import_promises2.default.access(psPath, import_promises2.constants.X_OK);
243
+ return true;
244
+ } catch {
245
+ return false;
197
246
  }
198
- return result;
199
- },
200
- enumerable: false
201
- },
202
- rgbToAnsi: {
203
- value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
204
- enumerable: false
247
+ })();
248
+ return canAccessPowerShellPromise;
249
+ };
250
+ wslDefaultBrowser = async () => {
251
+ const psPath = await powerShellPath2();
252
+ const command = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
253
+ const { stdout } = await executePowerShell(command, { powerShellPath: psPath });
254
+ return stdout.trim();
255
+ };
256
+ convertWslPathToWindows = async (path8) => {
257
+ if (/^[a-z]+:\/\//i.test(path8)) {
258
+ return path8;
259
+ }
260
+ try {
261
+ const { stdout } = await execFile2("wslpath", ["-aw", path8], { encoding: "utf8" });
262
+ return stdout.trim();
263
+ } catch {
264
+ return path8;
265
+ }
266
+ };
267
+ }
268
+ });
269
+
270
+ // ../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
271
+ function defineLazyProperty(object, propertyName, valueGetter) {
272
+ const define = (value) => Object.defineProperty(object, propertyName, { value, enumerable: true, writable: true });
273
+ Object.defineProperty(object, propertyName, {
274
+ configurable: true,
275
+ enumerable: true,
276
+ get() {
277
+ const result = valueGetter();
278
+ define(result);
279
+ return result;
205
280
  },
206
- hexToAnsi: {
207
- value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
208
- enumerable: false
281
+ set(value) {
282
+ define(value);
209
283
  }
210
284
  });
211
- return styles;
285
+ return object;
212
286
  }
213
- var ansiStyles = assembleStyles();
214
- var ansi_styles_default = ansiStyles;
287
+ var init_define_lazy_prop = __esm({
288
+ "../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js"() {
289
+ "use strict";
290
+ init_cjs_shims();
291
+ }
292
+ });
215
293
 
216
- // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/supports-color/index.js
217
- var import_node_process = __toESM(require("process"), 1);
218
- var import_node_os = __toESM(require("os"), 1);
219
- var import_node_tty = __toESM(require("tty"), 1);
220
- function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
221
- const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
222
- const position = argv.indexOf(prefix + flag);
223
- const terminatorPosition = argv.indexOf("--");
224
- return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
225
- }
226
- var { env } = import_node_process.default;
227
- var flagForceColor;
228
- if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
229
- flagForceColor = 0;
230
- } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
231
- flagForceColor = 1;
232
- }
233
- function envForceColor() {
234
- if ("FORCE_COLOR" in env) {
235
- if (env.FORCE_COLOR === "true") {
236
- return 1;
237
- }
238
- if (env.FORCE_COLOR === "false") {
239
- return 0;
240
- }
241
- return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
294
+ // ../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js
295
+ async function defaultBrowserId() {
296
+ if (import_node_process4.default.platform !== "darwin") {
297
+ throw new Error("macOS only");
242
298
  }
243
- }
244
- function translateLevel(level) {
245
- if (level === 0) {
246
- return false;
299
+ const { stdout } = await execFileAsync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
300
+ const match = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
301
+ const browserId = match?.groups.id ?? "com.apple.Safari";
302
+ if (browserId === "com.apple.safari") {
303
+ return "com.apple.Safari";
247
304
  }
248
- return {
249
- level,
250
- hasBasic: true,
251
- has256: level >= 2,
252
- has16m: level >= 3
253
- };
305
+ return browserId;
254
306
  }
255
- function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
256
- const noFlagForceColor = envForceColor();
257
- if (noFlagForceColor !== void 0) {
258
- flagForceColor = noFlagForceColor;
259
- }
260
- const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
261
- if (forceColor === 0) {
262
- return 0;
263
- }
264
- if (sniffFlags) {
265
- if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
266
- return 3;
267
- }
268
- if (hasFlag("color=256")) {
269
- return 2;
270
- }
271
- }
272
- if ("TF_BUILD" in env && "AGENT_NAME" in env) {
273
- return 1;
307
+ var import_node_util3, import_node_process4, import_node_child_process3, execFileAsync;
308
+ var init_default_browser_id = __esm({
309
+ "../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js"() {
310
+ "use strict";
311
+ init_cjs_shims();
312
+ import_node_util3 = require("util");
313
+ import_node_process4 = __toESM(require("process"), 1);
314
+ import_node_child_process3 = require("child_process");
315
+ execFileAsync = (0, import_node_util3.promisify)(import_node_child_process3.execFile);
274
316
  }
275
- if (haveStream && !streamIsTTY && forceColor === void 0) {
276
- return 0;
317
+ });
318
+
319
+ // ../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js
320
+ async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
321
+ if (import_node_process5.default.platform !== "darwin") {
322
+ throw new Error("macOS only");
277
323
  }
278
- const min = forceColor || 0;
279
- if (env.TERM === "dumb") {
280
- return min;
324
+ const outputArguments = humanReadableOutput ? [] : ["-ss"];
325
+ const execOptions = {};
326
+ if (signal) {
327
+ execOptions.signal = signal;
281
328
  }
282
- if (import_node_process.default.platform === "win32") {
283
- const osRelease = import_node_os.default.release().split(".");
284
- if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
285
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
286
- }
287
- return 1;
329
+ const { stdout } = await execFileAsync2("osascript", ["-e", script, outputArguments], execOptions);
330
+ return stdout.trim();
331
+ }
332
+ var import_node_process5, import_node_util4, import_node_child_process4, execFileAsync2;
333
+ var init_run_applescript = __esm({
334
+ "../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js"() {
335
+ "use strict";
336
+ init_cjs_shims();
337
+ import_node_process5 = __toESM(require("process"), 1);
338
+ import_node_util4 = require("util");
339
+ import_node_child_process4 = require("child_process");
340
+ execFileAsync2 = (0, import_node_util4.promisify)(import_node_child_process4.execFile);
288
341
  }
289
- if ("CI" in env) {
290
- if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
291
- return 3;
292
- }
293
- if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
294
- return 1;
295
- }
296
- return min;
342
+ });
343
+
344
+ // ../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
345
+ async function bundleName(bundleId) {
346
+ return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
347
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
348
+ }
349
+ var init_bundle_name = __esm({
350
+ "../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js"() {
351
+ "use strict";
352
+ init_cjs_shims();
353
+ init_run_applescript();
297
354
  }
298
- if ("TEAMCITY_VERSION" in env) {
299
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
355
+ });
356
+
357
+ // ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/windows.js
358
+ async function defaultBrowser(_execFileAsync = execFileAsync3) {
359
+ const { stdout } = await _execFileAsync("reg", [
360
+ "QUERY",
361
+ " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
362
+ "/v",
363
+ "ProgId"
364
+ ]);
365
+ const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
366
+ if (!match) {
367
+ throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
300
368
  }
301
- if (env.COLORTERM === "truecolor") {
302
- return 3;
369
+ const { id } = match.groups;
370
+ const dotIndex = id.lastIndexOf(".");
371
+ const hyphenIndex = id.lastIndexOf("-");
372
+ const baseIdByDot = dotIndex === -1 ? void 0 : id.slice(0, dotIndex);
373
+ const baseIdByHyphen = hyphenIndex === -1 ? void 0 : id.slice(0, hyphenIndex);
374
+ return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? { name: id, id };
375
+ }
376
+ var import_node_util5, import_node_child_process5, execFileAsync3, windowsBrowserProgIds, _windowsBrowserProgIdMap, UnknownBrowserError;
377
+ var init_windows = __esm({
378
+ "../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/windows.js"() {
379
+ "use strict";
380
+ init_cjs_shims();
381
+ import_node_util5 = require("util");
382
+ import_node_child_process5 = require("child_process");
383
+ execFileAsync3 = (0, import_node_util5.promisify)(import_node_child_process5.execFile);
384
+ windowsBrowserProgIds = {
385
+ MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
386
+ // The missing `L` is correct.
387
+ MSEdgeBHTML: { name: "Edge Beta", id: "com.microsoft.edge.beta" },
388
+ MSEdgeDHTML: { name: "Edge Dev", id: "com.microsoft.edge.dev" },
389
+ AppXq0fevzme2pys62n3e0fbqa7peapykr8v: { name: "Edge", id: "com.microsoft.edge.old" },
390
+ ChromeHTML: { name: "Chrome", id: "com.google.chrome" },
391
+ ChromeBHTML: { name: "Chrome Beta", id: "com.google.chrome.beta" },
392
+ ChromeDHTML: { name: "Chrome Dev", id: "com.google.chrome.dev" },
393
+ ChromiumHTM: { name: "Chromium", id: "org.chromium.Chromium" },
394
+ BraveHTML: { name: "Brave", id: "com.brave.Browser" },
395
+ BraveBHTML: { name: "Brave Beta", id: "com.brave.Browser.beta" },
396
+ BraveDHTML: { name: "Brave Dev", id: "com.brave.Browser.dev" },
397
+ BraveSSHTM: { name: "Brave Nightly", id: "com.brave.Browser.nightly" },
398
+ FirefoxURL: { name: "Firefox", id: "org.mozilla.firefox" },
399
+ OperaStable: { name: "Opera", id: "com.operasoftware.Opera" },
400
+ VivaldiHTM: { name: "Vivaldi", id: "com.vivaldi.Vivaldi" },
401
+ "IE.HTTP": { name: "Internet Explorer", id: "com.microsoft.ie" }
402
+ };
403
+ _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
404
+ UnknownBrowserError = class extends Error {
405
+ };
303
406
  }
304
- if (env.TERM === "xterm-kitty") {
305
- return 3;
407
+ });
408
+
409
+ // ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
410
+ async function defaultBrowser2() {
411
+ if (import_node_process6.default.platform === "darwin") {
412
+ const id = await defaultBrowserId();
413
+ const name = await bundleName(id);
414
+ return { name, id };
306
415
  }
307
- if (env.TERM === "xterm-ghostty") {
308
- return 3;
416
+ if (import_node_process6.default.platform === "linux") {
417
+ const { stdout } = await execFileAsync4("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
418
+ const id = stdout.trim();
419
+ const name = titleize(id.replace(/.desktop$/, "").replace("-", " "));
420
+ return { name, id };
309
421
  }
310
- if (env.TERM === "wezterm") {
311
- return 3;
422
+ if (import_node_process6.default.platform === "win32") {
423
+ return defaultBrowser();
312
424
  }
313
- if ("TERM_PROGRAM" in env) {
314
- const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
315
- switch (env.TERM_PROGRAM) {
316
- case "iTerm.app": {
317
- return version >= 3 ? 3 : 2;
318
- }
319
- case "Apple_Terminal": {
320
- return 2;
321
- }
322
- }
425
+ throw new Error("Only macOS, Linux, and Windows are supported");
426
+ }
427
+ var import_node_util6, import_node_process6, import_node_child_process6, execFileAsync4, titleize;
428
+ var init_default_browser = __esm({
429
+ "../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js"() {
430
+ "use strict";
431
+ init_cjs_shims();
432
+ import_node_util6 = require("util");
433
+ import_node_process6 = __toESM(require("process"), 1);
434
+ import_node_child_process6 = require("child_process");
435
+ init_default_browser_id();
436
+ init_bundle_name();
437
+ init_windows();
438
+ init_windows();
439
+ execFileAsync4 = (0, import_node_util6.promisify)(import_node_child_process6.execFile);
440
+ titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
323
441
  }
324
- if (/-256(color)?$/i.test(env.TERM)) {
325
- return 2;
442
+ });
443
+
444
+ // ../../node_modules/.pnpm/is-in-ssh@1.0.0/node_modules/is-in-ssh/index.js
445
+ var import_node_process7, isInSsh, is_in_ssh_default;
446
+ var init_is_in_ssh = __esm({
447
+ "../../node_modules/.pnpm/is-in-ssh@1.0.0/node_modules/is-in-ssh/index.js"() {
448
+ "use strict";
449
+ init_cjs_shims();
450
+ import_node_process7 = __toESM(require("process"), 1);
451
+ isInSsh = Boolean(import_node_process7.default.env.SSH_CONNECTION || import_node_process7.default.env.SSH_CLIENT || import_node_process7.default.env.SSH_TTY);
452
+ is_in_ssh_default = isInSsh;
326
453
  }
327
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
328
- return 1;
454
+ });
455
+
456
+ // ../../node_modules/.pnpm/open@11.0.0/node_modules/open/index.js
457
+ var open_exports = {};
458
+ __export(open_exports, {
459
+ apps: () => apps,
460
+ default: () => open_default,
461
+ openApp: () => openApp
462
+ });
463
+ function detectArchBinary(binary) {
464
+ if (typeof binary === "string" || Array.isArray(binary)) {
465
+ return binary;
329
466
  }
330
- if ("COLORTERM" in env) {
331
- return 1;
467
+ const { [arch]: archBinary } = binary;
468
+ if (!archBinary) {
469
+ throw new Error(`${arch} is not supported`);
332
470
  }
333
- return min;
334
- }
335
- function createSupportsColor(stream, options = {}) {
336
- const level = _supportsColor(stream, {
337
- streamIsTTY: stream && stream.isTTY,
338
- ...options
339
- });
340
- return translateLevel(level);
471
+ return archBinary;
341
472
  }
342
- var supportsColor = {
343
- stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
344
- stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
345
- };
346
- var supports_color_default = supportsColor;
347
-
348
- // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js
349
- function stringReplaceAll(string, substring, replacer) {
350
- let index = string.indexOf(substring);
351
- if (index === -1) {
352
- return string;
473
+ function detectPlatformBinary({ [platform]: platformBinary }, { wsl } = {}) {
474
+ if (wsl && is_wsl_default) {
475
+ return detectArchBinary(wsl);
353
476
  }
354
- const substringLength = substring.length;
355
- let endIndex = 0;
356
- let returnValue = "";
357
- do {
358
- returnValue += string.slice(endIndex, index) + substring + replacer;
359
- endIndex = index + substringLength;
360
- index = string.indexOf(substring, endIndex);
361
- } while (index !== -1);
362
- returnValue += string.slice(endIndex);
363
- return returnValue;
364
- }
365
- function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
366
- let endIndex = 0;
367
- let returnValue = "";
368
- do {
369
- const gotCR = string[index - 1] === "\r";
370
- returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
371
- endIndex = index + 1;
372
- index = string.indexOf("\n", endIndex);
373
- } while (index !== -1);
374
- returnValue += string.slice(endIndex);
375
- return returnValue;
477
+ if (!platformBinary) {
478
+ throw new Error(`${platform} is not supported`);
479
+ }
480
+ return detectArchBinary(platformBinary);
376
481
  }
482
+ var import_node_process8, import_node_path, import_node_url, import_node_child_process7, import_promises3, fallbackAttemptSymbol, __dirname2, localXdgOpenPath, platform, arch, tryEachApp, baseOpen, open, openApp, apps, open_default;
483
+ var init_open = __esm({
484
+ "../../node_modules/.pnpm/open@11.0.0/node_modules/open/index.js"() {
485
+ "use strict";
486
+ init_cjs_shims();
487
+ import_node_process8 = __toESM(require("process"), 1);
488
+ import_node_path = __toESM(require("path"), 1);
489
+ import_node_url = require("url");
490
+ import_node_child_process7 = __toESM(require("child_process"), 1);
491
+ import_promises3 = __toESM(require("fs/promises"), 1);
492
+ init_wsl_utils();
493
+ init_powershell_utils();
494
+ init_define_lazy_prop();
495
+ init_default_browser();
496
+ init_is_inside_container();
497
+ init_is_in_ssh();
498
+ fallbackAttemptSymbol = /* @__PURE__ */ Symbol("fallbackAttempt");
499
+ __dirname2 = importMetaUrl ? import_node_path.default.dirname((0, import_node_url.fileURLToPath)(importMetaUrl)) : "";
500
+ localXdgOpenPath = import_node_path.default.join(__dirname2, "xdg-open");
501
+ ({ platform, arch } = import_node_process8.default);
502
+ tryEachApp = async (apps2, opener) => {
503
+ if (apps2.length === 0) {
504
+ return;
505
+ }
506
+ const errors = [];
507
+ for (const app of apps2) {
508
+ try {
509
+ return await opener(app);
510
+ } catch (error) {
511
+ errors.push(error);
512
+ }
513
+ }
514
+ throw new AggregateError(errors, "Failed to open in all supported apps");
515
+ };
516
+ baseOpen = async (options) => {
517
+ options = {
518
+ wait: false,
519
+ background: false,
520
+ newInstance: false,
521
+ allowNonzeroExitCode: false,
522
+ ...options
523
+ };
524
+ const isFallbackAttempt = options[fallbackAttemptSymbol] === true;
525
+ delete options[fallbackAttemptSymbol];
526
+ if (Array.isArray(options.app)) {
527
+ return tryEachApp(options.app, (singleApp) => baseOpen({
528
+ ...options,
529
+ app: singleApp,
530
+ [fallbackAttemptSymbol]: true
531
+ }));
532
+ }
533
+ let { name: app, arguments: appArguments = [] } = options.app ?? {};
534
+ appArguments = [...appArguments];
535
+ if (Array.isArray(app)) {
536
+ return tryEachApp(app, (appName) => baseOpen({
537
+ ...options,
538
+ app: {
539
+ name: appName,
540
+ arguments: appArguments
541
+ },
542
+ [fallbackAttemptSymbol]: true
543
+ }));
544
+ }
545
+ if (app === "browser" || app === "browserPrivate") {
546
+ const ids = {
547
+ "com.google.chrome": "chrome",
548
+ "google-chrome.desktop": "chrome",
549
+ "com.brave.browser": "brave",
550
+ "org.mozilla.firefox": "firefox",
551
+ "firefox.desktop": "firefox",
552
+ "com.microsoft.msedge": "edge",
553
+ "com.microsoft.edge": "edge",
554
+ "com.microsoft.edgemac": "edge",
555
+ "microsoft-edge.desktop": "edge",
556
+ "com.apple.safari": "safari"
557
+ };
558
+ const flags = {
559
+ chrome: "--incognito",
560
+ brave: "--incognito",
561
+ firefox: "--private-window",
562
+ edge: "--inPrivate"
563
+ // Safari doesn't support private mode via command line
564
+ };
565
+ let browser;
566
+ if (is_wsl_default) {
567
+ const progId = await wslDefaultBrowser();
568
+ const browserInfo = _windowsBrowserProgIdMap.get(progId);
569
+ browser = browserInfo ?? {};
570
+ } else {
571
+ browser = await defaultBrowser2();
572
+ }
573
+ if (browser.id in ids) {
574
+ const browserName = ids[browser.id.toLowerCase()];
575
+ if (app === "browserPrivate") {
576
+ if (browserName === "safari") {
577
+ throw new Error("Safari doesn't support opening in private mode via command line");
578
+ }
579
+ appArguments.push(flags[browserName]);
580
+ }
581
+ return baseOpen({
582
+ ...options,
583
+ app: {
584
+ name: apps[browserName],
585
+ arguments: appArguments
586
+ }
587
+ });
588
+ }
589
+ throw new Error(`${browser.name} is not supported as a default browser`);
590
+ }
591
+ let command;
592
+ const cliArguments = [];
593
+ const childProcessOptions = {};
594
+ let shouldUseWindowsInWsl = false;
595
+ if (is_wsl_default && !isInsideContainer() && !is_in_ssh_default && !app) {
596
+ shouldUseWindowsInWsl = await canAccessPowerShell();
597
+ }
598
+ if (platform === "darwin") {
599
+ command = "open";
600
+ if (options.wait) {
601
+ cliArguments.push("--wait-apps");
602
+ }
603
+ if (options.background) {
604
+ cliArguments.push("--background");
605
+ }
606
+ if (options.newInstance) {
607
+ cliArguments.push("--new");
608
+ }
609
+ if (app) {
610
+ cliArguments.push("-a", app);
611
+ }
612
+ } else if (platform === "win32" || shouldUseWindowsInWsl) {
613
+ command = await powerShellPath2();
614
+ cliArguments.push(...executePowerShell.argumentsPrefix);
615
+ if (!is_wsl_default) {
616
+ childProcessOptions.windowsVerbatimArguments = true;
617
+ }
618
+ if (is_wsl_default && options.target) {
619
+ options.target = await convertWslPathToWindows(options.target);
620
+ }
621
+ const encodedArguments = ["$ProgressPreference = 'SilentlyContinue';", "Start"];
622
+ if (options.wait) {
623
+ encodedArguments.push("-Wait");
624
+ }
625
+ if (app) {
626
+ encodedArguments.push(executePowerShell.escapeArgument(app));
627
+ if (options.target) {
628
+ appArguments.push(options.target);
629
+ }
630
+ } else if (options.target) {
631
+ encodedArguments.push(executePowerShell.escapeArgument(options.target));
632
+ }
633
+ if (appArguments.length > 0) {
634
+ appArguments = appArguments.map((argument) => executePowerShell.escapeArgument(argument));
635
+ encodedArguments.push("-ArgumentList", appArguments.join(","));
636
+ }
637
+ options.target = executePowerShell.encodeCommand(encodedArguments.join(" "));
638
+ if (!options.wait) {
639
+ childProcessOptions.stdio = "ignore";
640
+ }
641
+ } else {
642
+ if (app) {
643
+ command = app;
644
+ } else {
645
+ const isBundled = !__dirname2 || __dirname2 === "/";
646
+ let exeLocalXdgOpen = false;
647
+ try {
648
+ await import_promises3.default.access(localXdgOpenPath, import_promises3.constants.X_OK);
649
+ exeLocalXdgOpen = true;
650
+ } catch {
651
+ }
652
+ const useSystemXdgOpen = import_node_process8.default.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen);
653
+ command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
654
+ }
655
+ if (appArguments.length > 0) {
656
+ cliArguments.push(...appArguments);
657
+ }
658
+ if (!options.wait) {
659
+ childProcessOptions.stdio = "ignore";
660
+ childProcessOptions.detached = true;
661
+ }
662
+ }
663
+ if (platform === "darwin" && appArguments.length > 0) {
664
+ cliArguments.push("--args", ...appArguments);
665
+ }
666
+ if (options.target) {
667
+ cliArguments.push(options.target);
668
+ }
669
+ const subprocess = import_node_child_process7.default.spawn(command, cliArguments, childProcessOptions);
670
+ if (options.wait) {
671
+ return new Promise((resolve2, reject) => {
672
+ subprocess.once("error", reject);
673
+ subprocess.once("close", (exitCode) => {
674
+ if (!options.allowNonzeroExitCode && exitCode !== 0) {
675
+ reject(new Error(`Exited with code ${exitCode}`));
676
+ return;
677
+ }
678
+ resolve2(subprocess);
679
+ });
680
+ });
681
+ }
682
+ if (isFallbackAttempt) {
683
+ return new Promise((resolve2, reject) => {
684
+ subprocess.once("error", reject);
685
+ subprocess.once("spawn", () => {
686
+ subprocess.once("close", (exitCode) => {
687
+ subprocess.off("error", reject);
688
+ if (exitCode !== 0) {
689
+ reject(new Error(`Exited with code ${exitCode}`));
690
+ return;
691
+ }
692
+ subprocess.unref();
693
+ resolve2(subprocess);
694
+ });
695
+ });
696
+ });
697
+ }
698
+ subprocess.unref();
699
+ return new Promise((resolve2, reject) => {
700
+ subprocess.once("error", reject);
701
+ subprocess.once("spawn", () => {
702
+ subprocess.off("error", reject);
703
+ resolve2(subprocess);
704
+ });
705
+ });
706
+ };
707
+ open = (target, options) => {
708
+ if (typeof target !== "string") {
709
+ throw new TypeError("Expected a `target`");
710
+ }
711
+ return baseOpen({
712
+ ...options,
713
+ target
714
+ });
715
+ };
716
+ openApp = (name, options) => {
717
+ if (typeof name !== "string" && !Array.isArray(name)) {
718
+ throw new TypeError("Expected a valid `name`");
719
+ }
720
+ const { arguments: appArguments = [] } = options ?? {};
721
+ if (appArguments !== void 0 && appArguments !== null && !Array.isArray(appArguments)) {
722
+ throw new TypeError("Expected `appArguments` as Array type");
723
+ }
724
+ return baseOpen({
725
+ ...options,
726
+ app: {
727
+ name,
728
+ arguments: appArguments
729
+ }
730
+ });
731
+ };
732
+ apps = {
733
+ browser: "browser",
734
+ browserPrivate: "browserPrivate"
735
+ };
736
+ defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
737
+ darwin: "google chrome",
738
+ win32: "chrome",
739
+ // `chromium-browser` is the older deb package name used by Ubuntu/Debian before snap.
740
+ linux: ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]
741
+ }, {
742
+ wsl: {
743
+ ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
744
+ x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
745
+ }
746
+ }));
747
+ defineLazyProperty(apps, "brave", () => detectPlatformBinary({
748
+ darwin: "brave browser",
749
+ win32: "brave",
750
+ linux: ["brave-browser", "brave"]
751
+ }, {
752
+ wsl: {
753
+ ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
754
+ x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
755
+ }
756
+ }));
757
+ defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
758
+ darwin: "firefox",
759
+ win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
760
+ linux: "firefox"
761
+ }, {
762
+ wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
763
+ }));
764
+ defineLazyProperty(apps, "edge", () => detectPlatformBinary({
765
+ darwin: "microsoft edge",
766
+ win32: "msedge",
767
+ linux: ["microsoft-edge", "microsoft-edge-dev"]
768
+ }, {
769
+ wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
770
+ }));
771
+ defineLazyProperty(apps, "safari", () => detectPlatformBinary({
772
+ darwin: "Safari"
773
+ }));
774
+ open_default = open;
775
+ }
776
+ });
777
+
778
+ // src/index.ts
779
+ init_cjs_shims();
377
780
 
378
781
  // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js
379
- var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
380
- var GENERATOR = /* @__PURE__ */ Symbol("GENERATOR");
381
- var STYLER = /* @__PURE__ */ Symbol("STYLER");
382
- var IS_EMPTY = /* @__PURE__ */ Symbol("IS_EMPTY");
383
- var levelMapping = [
384
- "ansi",
385
- "ansi",
386
- "ansi256",
387
- "ansi16m"
388
- ];
389
- var styles2 = /* @__PURE__ */ Object.create(null);
390
- var applyOptions = (object, options = {}) => {
391
- if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
392
- throw new Error("The `level` option should be an integer from 0 to 3");
393
- }
394
- const colorLevel = stdoutColor ? stdoutColor.level : 0;
395
- object.level = options.level === void 0 ? colorLevel : options.level;
396
- };
397
- var chalkFactory = (options) => {
398
- const chalk2 = (...strings) => strings.join(" ");
399
- applyOptions(chalk2, options);
400
- Object.setPrototypeOf(chalk2, createChalk.prototype);
401
- return chalk2;
402
- };
403
- function createChalk(options) {
404
- return chalkFactory(options);
405
- }
406
- Object.setPrototypeOf(createChalk.prototype, Function.prototype);
407
- for (const [styleName, style] of Object.entries(ansi_styles_default)) {
408
- styles2[styleName] = {
409
- get() {
410
- const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
411
- Object.defineProperty(this, styleName, { value: builder });
412
- return builder;
413
- }
414
- };
415
- }
416
- styles2.visible = {
417
- get() {
418
- const builder = createBuilder(this, this[STYLER], true);
419
- Object.defineProperty(this, "visible", { value: builder });
420
- return builder;
421
- }
422
- };
423
- var getModelAnsi = (model, level, type, ...arguments_) => {
424
- if (model === "rgb") {
425
- if (level === "ansi16m") {
426
- return ansi_styles_default[type].ansi16m(...arguments_);
427
- }
428
- if (level === "ansi256") {
429
- return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
430
- }
431
- return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
432
- }
433
- if (model === "hex") {
434
- return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
782
+ init_cjs_shims();
783
+
784
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
785
+ init_cjs_shims();
786
+ var ANSI_BACKGROUND_OFFSET = 10;
787
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
788
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
789
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
790
+ var styles = {
791
+ modifier: {
792
+ reset: [0, 0],
793
+ // 21 isn't widely supported and 22 does the same thing
794
+ bold: [1, 22],
795
+ dim: [2, 22],
796
+ italic: [3, 23],
797
+ underline: [4, 24],
798
+ overline: [53, 55],
799
+ inverse: [7, 27],
800
+ hidden: [8, 28],
801
+ strikethrough: [9, 29]
802
+ },
803
+ color: {
804
+ black: [30, 39],
805
+ red: [31, 39],
806
+ green: [32, 39],
807
+ yellow: [33, 39],
808
+ blue: [34, 39],
809
+ magenta: [35, 39],
810
+ cyan: [36, 39],
811
+ white: [37, 39],
812
+ // Bright color
813
+ blackBright: [90, 39],
814
+ gray: [90, 39],
815
+ // Alias of `blackBright`
816
+ grey: [90, 39],
817
+ // Alias of `blackBright`
818
+ redBright: [91, 39],
819
+ greenBright: [92, 39],
820
+ yellowBright: [93, 39],
821
+ blueBright: [94, 39],
822
+ magentaBright: [95, 39],
823
+ cyanBright: [96, 39],
824
+ whiteBright: [97, 39]
825
+ },
826
+ bgColor: {
827
+ bgBlack: [40, 49],
828
+ bgRed: [41, 49],
829
+ bgGreen: [42, 49],
830
+ bgYellow: [43, 49],
831
+ bgBlue: [44, 49],
832
+ bgMagenta: [45, 49],
833
+ bgCyan: [46, 49],
834
+ bgWhite: [47, 49],
835
+ // Bright color
836
+ bgBlackBright: [100, 49],
837
+ bgGray: [100, 49],
838
+ // Alias of `bgBlackBright`
839
+ bgGrey: [100, 49],
840
+ // Alias of `bgBlackBright`
841
+ bgRedBright: [101, 49],
842
+ bgGreenBright: [102, 49],
843
+ bgYellowBright: [103, 49],
844
+ bgBlueBright: [104, 49],
845
+ bgMagentaBright: [105, 49],
846
+ bgCyanBright: [106, 49],
847
+ bgWhiteBright: [107, 49]
435
848
  }
436
- return ansi_styles_default[type][model](...arguments_);
437
849
  };
438
- var usedModels = ["rgb", "hex", "ansi256"];
439
- for (const model of usedModels) {
440
- styles2[model] = {
441
- get() {
442
- const { level } = this;
443
- return function(...arguments_) {
444
- const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
445
- return createBuilder(this, styler, this[IS_EMPTY]);
446
- };
447
- }
448
- };
449
- const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
450
- styles2[bgModel] = {
451
- get() {
452
- const { level } = this;
453
- return function(...arguments_) {
454
- const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
455
- return createBuilder(this, styler, this[IS_EMPTY]);
850
+ var modifierNames = Object.keys(styles.modifier);
851
+ var foregroundColorNames = Object.keys(styles.color);
852
+ var backgroundColorNames = Object.keys(styles.bgColor);
853
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
854
+ function assembleStyles() {
855
+ const codes = /* @__PURE__ */ new Map();
856
+ for (const [groupName, group] of Object.entries(styles)) {
857
+ for (const [styleName, style] of Object.entries(group)) {
858
+ styles[styleName] = {
859
+ open: `\x1B[${style[0]}m`,
860
+ close: `\x1B[${style[1]}m`
456
861
  };
862
+ group[styleName] = styles[styleName];
863
+ codes.set(style[0], style[1]);
457
864
  }
458
- };
459
- }
460
- var proto = Object.defineProperties(() => {
461
- }, {
462
- ...styles2,
463
- level: {
464
- enumerable: true,
465
- get() {
466
- return this[GENERATOR].level;
467
- },
468
- set(level) {
469
- this[GENERATOR].level = level;
470
- }
471
- }
472
- });
473
- var createStyler = (open2, close, parent) => {
474
- let openAll;
475
- let closeAll;
476
- if (parent === void 0) {
477
- openAll = open2;
478
- closeAll = close;
479
- } else {
480
- openAll = parent.openAll + open2;
481
- closeAll = close + parent.closeAll;
482
- }
483
- return {
484
- open: open2,
485
- close,
486
- openAll,
487
- closeAll,
488
- parent
489
- };
490
- };
491
- var createBuilder = (self, _styler, _isEmpty) => {
492
- const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
493
- Object.setPrototypeOf(builder, proto);
494
- builder[GENERATOR] = self;
495
- builder[STYLER] = _styler;
496
- builder[IS_EMPTY] = _isEmpty;
497
- return builder;
498
- };
499
- var applyStyle = (self, string) => {
500
- if (self.level <= 0 || !string) {
501
- return self[IS_EMPTY] ? "" : string;
502
- }
503
- let styler = self[STYLER];
504
- if (styler === void 0) {
505
- return string;
865
+ Object.defineProperty(styles, groupName, {
866
+ value: group,
867
+ enumerable: false
868
+ });
506
869
  }
507
- const { openAll, closeAll } = styler;
508
- if (string.includes("\x1B")) {
509
- while (styler !== void 0) {
510
- string = stringReplaceAll(string, styler.close, styler.open);
511
- styler = styler.parent;
870
+ Object.defineProperty(styles, "codes", {
871
+ value: codes,
872
+ enumerable: false
873
+ });
874
+ styles.color.close = "\x1B[39m";
875
+ styles.bgColor.close = "\x1B[49m";
876
+ styles.color.ansi = wrapAnsi16();
877
+ styles.color.ansi256 = wrapAnsi256();
878
+ styles.color.ansi16m = wrapAnsi16m();
879
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
880
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
881
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
882
+ Object.defineProperties(styles, {
883
+ rgbToAnsi256: {
884
+ value(red, green, blue) {
885
+ if (red === green && green === blue) {
886
+ if (red < 8) {
887
+ return 16;
888
+ }
889
+ if (red > 248) {
890
+ return 231;
891
+ }
892
+ return Math.round((red - 8) / 247 * 24) + 232;
893
+ }
894
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
895
+ },
896
+ enumerable: false
897
+ },
898
+ hexToRgb: {
899
+ value(hex) {
900
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
901
+ if (!matches) {
902
+ return [0, 0, 0];
903
+ }
904
+ let [colorString] = matches;
905
+ if (colorString.length === 3) {
906
+ colorString = [...colorString].map((character) => character + character).join("");
907
+ }
908
+ const integer = Number.parseInt(colorString, 16);
909
+ return [
910
+ /* eslint-disable no-bitwise */
911
+ integer >> 16 & 255,
912
+ integer >> 8 & 255,
913
+ integer & 255
914
+ /* eslint-enable no-bitwise */
915
+ ];
916
+ },
917
+ enumerable: false
918
+ },
919
+ hexToAnsi256: {
920
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
921
+ enumerable: false
922
+ },
923
+ ansi256ToAnsi: {
924
+ value(code) {
925
+ if (code < 8) {
926
+ return 30 + code;
927
+ }
928
+ if (code < 16) {
929
+ return 90 + (code - 8);
930
+ }
931
+ let red;
932
+ let green;
933
+ let blue;
934
+ if (code >= 232) {
935
+ red = ((code - 232) * 10 + 8) / 255;
936
+ green = red;
937
+ blue = red;
938
+ } else {
939
+ code -= 16;
940
+ const remainder = code % 36;
941
+ red = Math.floor(code / 36) / 5;
942
+ green = Math.floor(remainder / 6) / 5;
943
+ blue = remainder % 6 / 5;
944
+ }
945
+ const value = Math.max(red, green, blue) * 2;
946
+ if (value === 0) {
947
+ return 30;
948
+ }
949
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
950
+ if (value === 2) {
951
+ result += 60;
952
+ }
953
+ return result;
954
+ },
955
+ enumerable: false
956
+ },
957
+ rgbToAnsi: {
958
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
959
+ enumerable: false
960
+ },
961
+ hexToAnsi: {
962
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
963
+ enumerable: false
512
964
  }
513
- }
514
- const lfIndex = string.indexOf("\n");
515
- if (lfIndex !== -1) {
516
- string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
517
- }
518
- return openAll + string + closeAll;
519
- };
520
- Object.defineProperties(createChalk.prototype, styles2);
521
- var chalk = createChalk();
522
- var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
523
- var source_default = chalk;
524
-
525
- // src/index.ts
526
- var import_commander6 = require("commander");
527
- var import_config8 = require("dotenv/config");
528
- var import_node_child_process9 = require("child_process");
529
- var import_node_fs11 = require("fs");
530
- var import_promises7 = require("fs/promises");
531
- var import_node_module2 = require("module");
532
- var import_node_path9 = __toESM(require("path"), 1);
533
- var import_node_url3 = require("url");
534
-
535
- // ../../node_modules/.pnpm/open@11.0.0/node_modules/open/index.js
536
- var import_node_process8 = __toESM(require("process"), 1);
537
- var import_node_path = __toESM(require("path"), 1);
538
- var import_node_url = require("url");
539
- var import_node_child_process7 = __toESM(require("child_process"), 1);
540
- var import_promises3 = __toESM(require("fs/promises"), 1);
541
-
542
- // ../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/index.js
543
- var import_node_util2 = require("util");
544
- var import_node_child_process2 = __toESM(require("child_process"), 1);
545
- var import_promises2 = __toESM(require("fs/promises"), 1);
546
-
547
- // ../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
548
- var import_node_process2 = __toESM(require("process"), 1);
549
- var import_node_os2 = __toESM(require("os"), 1);
550
- var import_node_fs3 = __toESM(require("fs"), 1);
551
-
552
- // ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
553
- var import_node_fs2 = __toESM(require("fs"), 1);
965
+ });
966
+ return styles;
967
+ }
968
+ var ansiStyles = assembleStyles();
969
+ var ansi_styles_default = ansiStyles;
554
970
 
555
- // ../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
556
- var import_node_fs = __toESM(require("fs"), 1);
557
- var isDockerCached;
558
- function hasDockerEnv() {
559
- try {
560
- import_node_fs.default.statSync("/.dockerenv");
561
- return true;
562
- } catch {
563
- return false;
564
- }
971
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/supports-color/index.js
972
+ init_cjs_shims();
973
+ var import_node_process = __toESM(require("process"), 1);
974
+ var import_node_os = __toESM(require("os"), 1);
975
+ var import_node_tty = __toESM(require("tty"), 1);
976
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
977
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
978
+ const position = argv.indexOf(prefix + flag);
979
+ const terminatorPosition = argv.indexOf("--");
980
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
565
981
  }
566
- function hasDockerCGroup() {
567
- try {
568
- return import_node_fs.default.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
569
- } catch {
570
- return false;
571
- }
982
+ var { env } = import_node_process.default;
983
+ var flagForceColor;
984
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
985
+ flagForceColor = 0;
986
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
987
+ flagForceColor = 1;
572
988
  }
573
- function isDocker() {
574
- if (isDockerCached === void 0) {
575
- isDockerCached = hasDockerEnv() || hasDockerCGroup();
989
+ function envForceColor() {
990
+ if ("FORCE_COLOR" in env) {
991
+ if (env.FORCE_COLOR === "true") {
992
+ return 1;
993
+ }
994
+ if (env.FORCE_COLOR === "false") {
995
+ return 0;
996
+ }
997
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
576
998
  }
577
- return isDockerCached;
578
999
  }
579
-
580
- // ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
581
- var cachedResult;
582
- var hasContainerEnv = () => {
583
- try {
584
- import_node_fs2.default.statSync("/run/.containerenv");
585
- return true;
586
- } catch {
1000
+ function translateLevel(level) {
1001
+ if (level === 0) {
587
1002
  return false;
588
1003
  }
589
- };
590
- function isInsideContainer() {
591
- if (cachedResult === void 0) {
592
- cachedResult = hasContainerEnv() || isDocker();
1004
+ return {
1005
+ level,
1006
+ hasBasic: true,
1007
+ has256: level >= 2,
1008
+ has16m: level >= 3
1009
+ };
1010
+ }
1011
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
1012
+ const noFlagForceColor = envForceColor();
1013
+ if (noFlagForceColor !== void 0) {
1014
+ flagForceColor = noFlagForceColor;
593
1015
  }
594
- return cachedResult;
595
- }
596
-
597
- // ../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
598
- var isWsl = () => {
599
- if (import_node_process2.default.platform !== "linux") {
600
- return false;
1016
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
1017
+ if (forceColor === 0) {
1018
+ return 0;
601
1019
  }
602
- if (import_node_os2.default.release().toLowerCase().includes("microsoft")) {
603
- if (isInsideContainer()) {
604
- return false;
1020
+ if (sniffFlags) {
1021
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
1022
+ return 3;
1023
+ }
1024
+ if (hasFlag("color=256")) {
1025
+ return 2;
605
1026
  }
606
- return true;
607
1027
  }
608
- try {
609
- return import_node_fs3.default.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
610
- } catch {
611
- return false;
1028
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
1029
+ return 1;
612
1030
  }
613
- };
614
- var is_wsl_default = import_node_process2.default.env.__IS_WSL_TEST__ ? isWsl : isWsl();
615
-
616
- // ../../node_modules/.pnpm/powershell-utils@0.1.0/node_modules/powershell-utils/index.js
617
- var import_node_process3 = __toESM(require("process"), 1);
618
- var import_node_buffer = require("buffer");
619
- var import_node_util = require("util");
620
- var import_node_child_process = __toESM(require("child_process"), 1);
621
- var import_promises = __toESM(require("fs/promises"), 1);
622
- var execFile = (0, import_node_util.promisify)(import_node_child_process.default.execFile);
623
- var powerShellPath = () => `${import_node_process3.default.env.SYSTEMROOT || import_node_process3.default.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
624
- var executePowerShell = async (command, options = {}) => {
625
- const {
626
- powerShellPath: psPath,
627
- ...execFileOptions
628
- } = options;
629
- const encodedCommand = executePowerShell.encodeCommand(command);
630
- return execFile(
631
- psPath ?? powerShellPath(),
632
- [
633
- ...executePowerShell.argumentsPrefix,
634
- encodedCommand
635
- ],
636
- {
637
- encoding: "utf8",
638
- ...execFileOptions
639
- }
640
- );
641
- };
642
- executePowerShell.argumentsPrefix = [
643
- "-NoProfile",
644
- "-NonInteractive",
645
- "-ExecutionPolicy",
646
- "Bypass",
647
- "-EncodedCommand"
648
- ];
649
- executePowerShell.encodeCommand = (command) => import_node_buffer.Buffer.from(command, "utf16le").toString("base64");
650
- executePowerShell.escapeArgument = (value) => `'${String(value).replaceAll("'", "''")}'`;
651
-
652
- // ../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/utilities.js
653
- function parseMountPointFromConfig(content) {
654
- for (const line of content.split("\n")) {
655
- if (/^\s*#/.test(line)) {
656
- continue;
657
- }
658
- const match = /^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(line);
659
- if (!match) {
660
- continue;
661
- }
662
- return match.groups.mountPoint.trim().replaceAll(/^["']|["']$/g, "");
1031
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
1032
+ return 0;
663
1033
  }
664
- }
665
-
666
- // ../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/index.js
667
- var execFile2 = (0, import_node_util2.promisify)(import_node_child_process2.default.execFile);
668
- var wslDrivesMountPoint = /* @__PURE__ */ (() => {
669
- const defaultMountPoint = "/mnt/";
670
- let mountPoint;
671
- return async function() {
672
- if (mountPoint) {
673
- return mountPoint;
674
- }
675
- const configFilePath = "/etc/wsl.conf";
676
- let isConfigFileExists = false;
677
- try {
678
- await import_promises2.default.access(configFilePath, import_promises2.constants.F_OK);
679
- isConfigFileExists = true;
680
- } catch {
681
- }
682
- if (!isConfigFileExists) {
683
- return defaultMountPoint;
1034
+ const min = forceColor || 0;
1035
+ if (env.TERM === "dumb") {
1036
+ return min;
1037
+ }
1038
+ if (import_node_process.default.platform === "win32") {
1039
+ const osRelease = import_node_os.default.release().split(".");
1040
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
1041
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
684
1042
  }
685
- const configContent = await import_promises2.default.readFile(configFilePath, { encoding: "utf8" });
686
- const parsedMountPoint = parseMountPointFromConfig(configContent);
687
- if (parsedMountPoint === void 0) {
688
- return defaultMountPoint;
1043
+ return 1;
1044
+ }
1045
+ if ("CI" in env) {
1046
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
1047
+ return 3;
689
1048
  }
690
- mountPoint = parsedMountPoint;
691
- mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
692
- return mountPoint;
693
- };
694
- })();
695
- var powerShellPathFromWsl = async () => {
696
- const mountPoint = await wslDrivesMountPoint();
697
- return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
698
- };
699
- var powerShellPath2 = is_wsl_default ? powerShellPathFromWsl : powerShellPath;
700
- var canAccessPowerShellPromise;
701
- var canAccessPowerShell = async () => {
702
- canAccessPowerShellPromise ??= (async () => {
703
- try {
704
- const psPath = await powerShellPath2();
705
- await import_promises2.default.access(psPath, import_promises2.constants.X_OK);
706
- return true;
707
- } catch {
708
- return false;
1049
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
1050
+ return 1;
709
1051
  }
710
- })();
711
- return canAccessPowerShellPromise;
712
- };
713
- var wslDefaultBrowser = async () => {
714
- const psPath = await powerShellPath2();
715
- const command = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
716
- const { stdout } = await executePowerShell(command, { powerShellPath: psPath });
717
- return stdout.trim();
718
- };
719
- var convertWslPathToWindows = async (path8) => {
720
- if (/^[a-z]+:\/\//i.test(path8)) {
721
- return path8;
1052
+ return min;
722
1053
  }
723
- try {
724
- const { stdout } = await execFile2("wslpath", ["-aw", path8], { encoding: "utf8" });
725
- return stdout.trim();
726
- } catch {
727
- return path8;
1054
+ if ("TEAMCITY_VERSION" in env) {
1055
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
728
1056
  }
729
- };
730
-
731
- // ../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
732
- function defineLazyProperty(object, propertyName, valueGetter) {
733
- const define = (value) => Object.defineProperty(object, propertyName, { value, enumerable: true, writable: true });
734
- Object.defineProperty(object, propertyName, {
735
- configurable: true,
736
- enumerable: true,
737
- get() {
738
- const result = valueGetter();
739
- define(result);
740
- return result;
741
- },
742
- set(value) {
743
- define(value);
1057
+ if (env.COLORTERM === "truecolor") {
1058
+ return 3;
1059
+ }
1060
+ if (env.TERM === "xterm-kitty") {
1061
+ return 3;
1062
+ }
1063
+ if (env.TERM === "xterm-ghostty") {
1064
+ return 3;
1065
+ }
1066
+ if (env.TERM === "wezterm") {
1067
+ return 3;
1068
+ }
1069
+ if ("TERM_PROGRAM" in env) {
1070
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
1071
+ switch (env.TERM_PROGRAM) {
1072
+ case "iTerm.app": {
1073
+ return version >= 3 ? 3 : 2;
1074
+ }
1075
+ case "Apple_Terminal": {
1076
+ return 2;
1077
+ }
744
1078
  }
745
- });
746
- return object;
747
- }
748
-
749
- // ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
750
- var import_node_util6 = require("util");
751
- var import_node_process6 = __toESM(require("process"), 1);
752
- var import_node_child_process6 = require("child_process");
753
-
754
- // ../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js
755
- var import_node_util3 = require("util");
756
- var import_node_process4 = __toESM(require("process"), 1);
757
- var import_node_child_process3 = require("child_process");
758
- var execFileAsync = (0, import_node_util3.promisify)(import_node_child_process3.execFile);
759
- async function defaultBrowserId() {
760
- if (import_node_process4.default.platform !== "darwin") {
761
- throw new Error("macOS only");
762
1079
  }
763
- const { stdout } = await execFileAsync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
764
- const match = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
765
- const browserId = match?.groups.id ?? "com.apple.Safari";
766
- if (browserId === "com.apple.safari") {
767
- return "com.apple.Safari";
1080
+ if (/-256(color)?$/i.test(env.TERM)) {
1081
+ return 2;
768
1082
  }
769
- return browserId;
770
- }
771
-
772
- // ../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js
773
- var import_node_process5 = __toESM(require("process"), 1);
774
- var import_node_util4 = require("util");
775
- var import_node_child_process4 = require("child_process");
776
- var execFileAsync2 = (0, import_node_util4.promisify)(import_node_child_process4.execFile);
777
- async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
778
- if (import_node_process5.default.platform !== "darwin") {
779
- throw new Error("macOS only");
1083
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
1084
+ return 1;
780
1085
  }
781
- const outputArguments = humanReadableOutput ? [] : ["-ss"];
782
- const execOptions = {};
783
- if (signal) {
784
- execOptions.signal = signal;
1086
+ if ("COLORTERM" in env) {
1087
+ return 1;
785
1088
  }
786
- const { stdout } = await execFileAsync2("osascript", ["-e", script, outputArguments], execOptions);
787
- return stdout.trim();
1089
+ return min;
788
1090
  }
789
-
790
- // ../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
791
- async function bundleName(bundleId) {
792
- return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
793
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
1091
+ function createSupportsColor(stream, options = {}) {
1092
+ const level = _supportsColor(stream, {
1093
+ streamIsTTY: stream && stream.isTTY,
1094
+ ...options
1095
+ });
1096
+ return translateLevel(level);
794
1097
  }
795
-
796
- // ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/windows.js
797
- var import_node_util5 = require("util");
798
- var import_node_child_process5 = require("child_process");
799
- var execFileAsync3 = (0, import_node_util5.promisify)(import_node_child_process5.execFile);
800
- var windowsBrowserProgIds = {
801
- MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
802
- // The missing `L` is correct.
803
- MSEdgeBHTML: { name: "Edge Beta", id: "com.microsoft.edge.beta" },
804
- MSEdgeDHTML: { name: "Edge Dev", id: "com.microsoft.edge.dev" },
805
- AppXq0fevzme2pys62n3e0fbqa7peapykr8v: { name: "Edge", id: "com.microsoft.edge.old" },
806
- ChromeHTML: { name: "Chrome", id: "com.google.chrome" },
807
- ChromeBHTML: { name: "Chrome Beta", id: "com.google.chrome.beta" },
808
- ChromeDHTML: { name: "Chrome Dev", id: "com.google.chrome.dev" },
809
- ChromiumHTM: { name: "Chromium", id: "org.chromium.Chromium" },
810
- BraveHTML: { name: "Brave", id: "com.brave.Browser" },
811
- BraveBHTML: { name: "Brave Beta", id: "com.brave.Browser.beta" },
812
- BraveDHTML: { name: "Brave Dev", id: "com.brave.Browser.dev" },
813
- BraveSSHTM: { name: "Brave Nightly", id: "com.brave.Browser.nightly" },
814
- FirefoxURL: { name: "Firefox", id: "org.mozilla.firefox" },
815
- OperaStable: { name: "Opera", id: "com.operasoftware.Opera" },
816
- VivaldiHTM: { name: "Vivaldi", id: "com.vivaldi.Vivaldi" },
817
- "IE.HTTP": { name: "Internet Explorer", id: "com.microsoft.ie" }
818
- };
819
- var _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
820
- var UnknownBrowserError = class extends Error {
1098
+ var supportsColor = {
1099
+ stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
1100
+ stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
821
1101
  };
822
- async function defaultBrowser(_execFileAsync = execFileAsync3) {
823
- const { stdout } = await _execFileAsync("reg", [
824
- "QUERY",
825
- " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
826
- "/v",
827
- "ProgId"
828
- ]);
829
- const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
830
- if (!match) {
831
- throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
832
- }
833
- const { id } = match.groups;
834
- const dotIndex = id.lastIndexOf(".");
835
- const hyphenIndex = id.lastIndexOf("-");
836
- const baseIdByDot = dotIndex === -1 ? void 0 : id.slice(0, dotIndex);
837
- const baseIdByHyphen = hyphenIndex === -1 ? void 0 : id.slice(0, hyphenIndex);
838
- return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? { name: id, id };
839
- }
1102
+ var supports_color_default = supportsColor;
840
1103
 
841
- // ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
842
- var execFileAsync4 = (0, import_node_util6.promisify)(import_node_child_process6.execFile);
843
- var titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
844
- async function defaultBrowser2() {
845
- if (import_node_process6.default.platform === "darwin") {
846
- const id = await defaultBrowserId();
847
- const name = await bundleName(id);
848
- return { name, id };
849
- }
850
- if (import_node_process6.default.platform === "linux") {
851
- const { stdout } = await execFileAsync4("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
852
- const id = stdout.trim();
853
- const name = titleize(id.replace(/.desktop$/, "").replace("-", " "));
854
- return { name, id };
855
- }
856
- if (import_node_process6.default.platform === "win32") {
857
- return defaultBrowser();
1104
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js
1105
+ init_cjs_shims();
1106
+ function stringReplaceAll(string, substring, replacer) {
1107
+ let index = string.indexOf(substring);
1108
+ if (index === -1) {
1109
+ return string;
858
1110
  }
859
- throw new Error("Only macOS, Linux, and Windows are supported");
1111
+ const substringLength = substring.length;
1112
+ let endIndex = 0;
1113
+ let returnValue = "";
1114
+ do {
1115
+ returnValue += string.slice(endIndex, index) + substring + replacer;
1116
+ endIndex = index + substringLength;
1117
+ index = string.indexOf(substring, endIndex);
1118
+ } while (index !== -1);
1119
+ returnValue += string.slice(endIndex);
1120
+ return returnValue;
1121
+ }
1122
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
1123
+ let endIndex = 0;
1124
+ let returnValue = "";
1125
+ do {
1126
+ const gotCR = string[index - 1] === "\r";
1127
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
1128
+ endIndex = index + 1;
1129
+ index = string.indexOf("\n", endIndex);
1130
+ } while (index !== -1);
1131
+ returnValue += string.slice(endIndex);
1132
+ return returnValue;
860
1133
  }
861
1134
 
862
- // ../../node_modules/.pnpm/is-in-ssh@1.0.0/node_modules/is-in-ssh/index.js
863
- var import_node_process7 = __toESM(require("process"), 1);
864
- var isInSsh = Boolean(import_node_process7.default.env.SSH_CONNECTION || import_node_process7.default.env.SSH_CLIENT || import_node_process7.default.env.SSH_TTY);
865
- var is_in_ssh_default = isInSsh;
866
-
867
- // ../../node_modules/.pnpm/open@11.0.0/node_modules/open/index.js
868
- var fallbackAttemptSymbol = /* @__PURE__ */ Symbol("fallbackAttempt");
869
- var __dirname2 = importMetaUrl ? import_node_path.default.dirname((0, import_node_url.fileURLToPath)(importMetaUrl)) : "";
870
- var localXdgOpenPath = import_node_path.default.join(__dirname2, "xdg-open");
871
- var { platform, arch } = import_node_process8.default;
872
- var tryEachApp = async (apps2, opener) => {
873
- if (apps2.length === 0) {
874
- return;
875
- }
876
- const errors = [];
877
- for (const app of apps2) {
878
- try {
879
- return await opener(app);
880
- } catch (error) {
881
- errors.push(error);
882
- }
1135
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js
1136
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
1137
+ var GENERATOR = /* @__PURE__ */ Symbol("GENERATOR");
1138
+ var STYLER = /* @__PURE__ */ Symbol("STYLER");
1139
+ var IS_EMPTY = /* @__PURE__ */ Symbol("IS_EMPTY");
1140
+ var levelMapping = [
1141
+ "ansi",
1142
+ "ansi",
1143
+ "ansi256",
1144
+ "ansi16m"
1145
+ ];
1146
+ var styles2 = /* @__PURE__ */ Object.create(null);
1147
+ var applyOptions = (object, options = {}) => {
1148
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
1149
+ throw new Error("The `level` option should be an integer from 0 to 3");
883
1150
  }
884
- throw new AggregateError(errors, "Failed to open in all supported apps");
1151
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
1152
+ object.level = options.level === void 0 ? colorLevel : options.level;
1153
+ };
1154
+ var chalkFactory = (options) => {
1155
+ const chalk2 = (...strings) => strings.join(" ");
1156
+ applyOptions(chalk2, options);
1157
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
1158
+ return chalk2;
885
1159
  };
886
- var baseOpen = async (options) => {
887
- options = {
888
- wait: false,
889
- background: false,
890
- newInstance: false,
891
- allowNonzeroExitCode: false,
892
- ...options
1160
+ function createChalk(options) {
1161
+ return chalkFactory(options);
1162
+ }
1163
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
1164
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
1165
+ styles2[styleName] = {
1166
+ get() {
1167
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
1168
+ Object.defineProperty(this, styleName, { value: builder });
1169
+ return builder;
1170
+ }
893
1171
  };
894
- const isFallbackAttempt = options[fallbackAttemptSymbol] === true;
895
- delete options[fallbackAttemptSymbol];
896
- if (Array.isArray(options.app)) {
897
- return tryEachApp(options.app, (singleApp) => baseOpen({
898
- ...options,
899
- app: singleApp,
900
- [fallbackAttemptSymbol]: true
901
- }));
902
- }
903
- let { name: app, arguments: appArguments = [] } = options.app ?? {};
904
- appArguments = [...appArguments];
905
- if (Array.isArray(app)) {
906
- return tryEachApp(app, (appName) => baseOpen({
907
- ...options,
908
- app: {
909
- name: appName,
910
- arguments: appArguments
911
- },
912
- [fallbackAttemptSymbol]: true
913
- }));
1172
+ }
1173
+ styles2.visible = {
1174
+ get() {
1175
+ const builder = createBuilder(this, this[STYLER], true);
1176
+ Object.defineProperty(this, "visible", { value: builder });
1177
+ return builder;
914
1178
  }
915
- if (app === "browser" || app === "browserPrivate") {
916
- const ids = {
917
- "com.google.chrome": "chrome",
918
- "google-chrome.desktop": "chrome",
919
- "com.brave.browser": "brave",
920
- "org.mozilla.firefox": "firefox",
921
- "firefox.desktop": "firefox",
922
- "com.microsoft.msedge": "edge",
923
- "com.microsoft.edge": "edge",
924
- "com.microsoft.edgemac": "edge",
925
- "microsoft-edge.desktop": "edge",
926
- "com.apple.safari": "safari"
927
- };
928
- const flags = {
929
- chrome: "--incognito",
930
- brave: "--incognito",
931
- firefox: "--private-window",
932
- edge: "--inPrivate"
933
- // Safari doesn't support private mode via command line
934
- };
935
- let browser;
936
- if (is_wsl_default) {
937
- const progId = await wslDefaultBrowser();
938
- const browserInfo = _windowsBrowserProgIdMap.get(progId);
939
- browser = browserInfo ?? {};
940
- } else {
941
- browser = await defaultBrowser2();
1179
+ };
1180
+ var getModelAnsi = (model, level, type, ...arguments_) => {
1181
+ if (model === "rgb") {
1182
+ if (level === "ansi16m") {
1183
+ return ansi_styles_default[type].ansi16m(...arguments_);
942
1184
  }
943
- if (browser.id in ids) {
944
- const browserName = ids[browser.id.toLowerCase()];
945
- if (app === "browserPrivate") {
946
- if (browserName === "safari") {
947
- throw new Error("Safari doesn't support opening in private mode via command line");
948
- }
949
- appArguments.push(flags[browserName]);
950
- }
951
- return baseOpen({
952
- ...options,
953
- app: {
954
- name: apps[browserName],
955
- arguments: appArguments
956
- }
957
- });
1185
+ if (level === "ansi256") {
1186
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
958
1187
  }
959
- throw new Error(`${browser.name} is not supported as a default browser`);
1188
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
960
1189
  }
961
- let command;
962
- const cliArguments = [];
963
- const childProcessOptions = {};
964
- let shouldUseWindowsInWsl = false;
965
- if (is_wsl_default && !isInsideContainer() && !is_in_ssh_default && !app) {
966
- shouldUseWindowsInWsl = await canAccessPowerShell();
1190
+ if (model === "hex") {
1191
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
967
1192
  }
968
- if (platform === "darwin") {
969
- command = "open";
970
- if (options.wait) {
971
- cliArguments.push("--wait-apps");
972
- }
973
- if (options.background) {
974
- cliArguments.push("--background");
975
- }
976
- if (options.newInstance) {
977
- cliArguments.push("--new");
978
- }
979
- if (app) {
980
- cliArguments.push("-a", app);
981
- }
982
- } else if (platform === "win32" || shouldUseWindowsInWsl) {
983
- command = await powerShellPath2();
984
- cliArguments.push(...executePowerShell.argumentsPrefix);
985
- if (!is_wsl_default) {
986
- childProcessOptions.windowsVerbatimArguments = true;
987
- }
988
- if (is_wsl_default && options.target) {
989
- options.target = await convertWslPathToWindows(options.target);
990
- }
991
- const encodedArguments = ["$ProgressPreference = 'SilentlyContinue';", "Start"];
992
- if (options.wait) {
993
- encodedArguments.push("-Wait");
994
- }
995
- if (app) {
996
- encodedArguments.push(executePowerShell.escapeArgument(app));
997
- if (options.target) {
998
- appArguments.push(options.target);
999
- }
1000
- } else if (options.target) {
1001
- encodedArguments.push(executePowerShell.escapeArgument(options.target));
1002
- }
1003
- if (appArguments.length > 0) {
1004
- appArguments = appArguments.map((argument) => executePowerShell.escapeArgument(argument));
1005
- encodedArguments.push("-ArgumentList", appArguments.join(","));
1006
- }
1007
- options.target = executePowerShell.encodeCommand(encodedArguments.join(" "));
1008
- if (!options.wait) {
1009
- childProcessOptions.stdio = "ignore";
1010
- }
1011
- } else {
1012
- if (app) {
1013
- command = app;
1014
- } else {
1015
- const isBundled = !__dirname2 || __dirname2 === "/";
1016
- let exeLocalXdgOpen = false;
1017
- try {
1018
- await import_promises3.default.access(localXdgOpenPath, import_promises3.constants.X_OK);
1019
- exeLocalXdgOpen = true;
1020
- } catch {
1021
- }
1022
- const useSystemXdgOpen = import_node_process8.default.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen);
1023
- command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
1193
+ return ansi_styles_default[type][model](...arguments_);
1194
+ };
1195
+ var usedModels = ["rgb", "hex", "ansi256"];
1196
+ for (const model of usedModels) {
1197
+ styles2[model] = {
1198
+ get() {
1199
+ const { level } = this;
1200
+ return function(...arguments_) {
1201
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
1202
+ return createBuilder(this, styler, this[IS_EMPTY]);
1203
+ };
1024
1204
  }
1025
- if (appArguments.length > 0) {
1026
- cliArguments.push(...appArguments);
1205
+ };
1206
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
1207
+ styles2[bgModel] = {
1208
+ get() {
1209
+ const { level } = this;
1210
+ return function(...arguments_) {
1211
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
1212
+ return createBuilder(this, styler, this[IS_EMPTY]);
1213
+ };
1027
1214
  }
1028
- if (!options.wait) {
1029
- childProcessOptions.stdio = "ignore";
1030
- childProcessOptions.detached = true;
1215
+ };
1216
+ }
1217
+ var proto = Object.defineProperties(() => {
1218
+ }, {
1219
+ ...styles2,
1220
+ level: {
1221
+ enumerable: true,
1222
+ get() {
1223
+ return this[GENERATOR].level;
1224
+ },
1225
+ set(level) {
1226
+ this[GENERATOR].level = level;
1031
1227
  }
1032
1228
  }
1033
- if (platform === "darwin" && appArguments.length > 0) {
1034
- cliArguments.push("--args", ...appArguments);
1035
- }
1036
- if (options.target) {
1037
- cliArguments.push(options.target);
1038
- }
1039
- const subprocess = import_node_child_process7.default.spawn(command, cliArguments, childProcessOptions);
1040
- if (options.wait) {
1041
- return new Promise((resolve2, reject) => {
1042
- subprocess.once("error", reject);
1043
- subprocess.once("close", (exitCode) => {
1044
- if (!options.allowNonzeroExitCode && exitCode !== 0) {
1045
- reject(new Error(`Exited with code ${exitCode}`));
1046
- return;
1047
- }
1048
- resolve2(subprocess);
1049
- });
1050
- });
1051
- }
1052
- if (isFallbackAttempt) {
1053
- return new Promise((resolve2, reject) => {
1054
- subprocess.once("error", reject);
1055
- subprocess.once("spawn", () => {
1056
- subprocess.once("close", (exitCode) => {
1057
- subprocess.off("error", reject);
1058
- if (exitCode !== 0) {
1059
- reject(new Error(`Exited with code ${exitCode}`));
1060
- return;
1061
- }
1062
- subprocess.unref();
1063
- resolve2(subprocess);
1064
- });
1065
- });
1066
- });
1229
+ });
1230
+ var createStyler = (open2, close, parent) => {
1231
+ let openAll;
1232
+ let closeAll;
1233
+ if (parent === void 0) {
1234
+ openAll = open2;
1235
+ closeAll = close;
1236
+ } else {
1237
+ openAll = parent.openAll + open2;
1238
+ closeAll = close + parent.closeAll;
1067
1239
  }
1068
- subprocess.unref();
1069
- return new Promise((resolve2, reject) => {
1070
- subprocess.once("error", reject);
1071
- subprocess.once("spawn", () => {
1072
- subprocess.off("error", reject);
1073
- resolve2(subprocess);
1074
- });
1075
- });
1240
+ return {
1241
+ open: open2,
1242
+ close,
1243
+ openAll,
1244
+ closeAll,
1245
+ parent
1246
+ };
1076
1247
  };
1077
- var open = (target, options) => {
1078
- if (typeof target !== "string") {
1079
- throw new TypeError("Expected a `target`");
1080
- }
1081
- return baseOpen({
1082
- ...options,
1083
- target
1084
- });
1248
+ var createBuilder = (self, _styler, _isEmpty) => {
1249
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
1250
+ Object.setPrototypeOf(builder, proto);
1251
+ builder[GENERATOR] = self;
1252
+ builder[STYLER] = _styler;
1253
+ builder[IS_EMPTY] = _isEmpty;
1254
+ return builder;
1085
1255
  };
1086
- function detectArchBinary(binary) {
1087
- if (typeof binary === "string" || Array.isArray(binary)) {
1088
- return binary;
1256
+ var applyStyle = (self, string) => {
1257
+ if (self.level <= 0 || !string) {
1258
+ return self[IS_EMPTY] ? "" : string;
1089
1259
  }
1090
- const { [arch]: archBinary } = binary;
1091
- if (!archBinary) {
1092
- throw new Error(`${arch} is not supported`);
1260
+ let styler = self[STYLER];
1261
+ if (styler === void 0) {
1262
+ return string;
1093
1263
  }
1094
- return archBinary;
1095
- }
1096
- function detectPlatformBinary({ [platform]: platformBinary }, { wsl } = {}) {
1097
- if (wsl && is_wsl_default) {
1098
- return detectArchBinary(wsl);
1264
+ const { openAll, closeAll } = styler;
1265
+ if (string.includes("\x1B")) {
1266
+ while (styler !== void 0) {
1267
+ string = stringReplaceAll(string, styler.close, styler.open);
1268
+ styler = styler.parent;
1269
+ }
1099
1270
  }
1100
- if (!platformBinary) {
1101
- throw new Error(`${platform} is not supported`);
1271
+ const lfIndex = string.indexOf("\n");
1272
+ if (lfIndex !== -1) {
1273
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
1102
1274
  }
1103
- return detectArchBinary(platformBinary);
1104
- }
1105
- var apps = {
1106
- browser: "browser",
1107
- browserPrivate: "browserPrivate"
1275
+ return openAll + string + closeAll;
1108
1276
  };
1109
- defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
1110
- darwin: "google chrome",
1111
- win32: "chrome",
1112
- // `chromium-browser` is the older deb package name used by Ubuntu/Debian before snap.
1113
- linux: ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]
1114
- }, {
1115
- wsl: {
1116
- ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
1117
- x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
1118
- }
1119
- }));
1120
- defineLazyProperty(apps, "brave", () => detectPlatformBinary({
1121
- darwin: "brave browser",
1122
- win32: "brave",
1123
- linux: ["brave-browser", "brave"]
1124
- }, {
1125
- wsl: {
1126
- ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
1127
- x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
1128
- }
1129
- }));
1130
- defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
1131
- darwin: "firefox",
1132
- win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
1133
- linux: "firefox"
1134
- }, {
1135
- wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
1136
- }));
1137
- defineLazyProperty(apps, "edge", () => detectPlatformBinary({
1138
- darwin: "microsoft edge",
1139
- win32: "msedge",
1140
- linux: ["microsoft-edge", "microsoft-edge-dev"]
1141
- }, {
1142
- wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
1143
- }));
1144
- defineLazyProperty(apps, "safari", () => detectPlatformBinary({
1145
- darwin: "Safari"
1146
- }));
1147
- var open_default = open;
1277
+ Object.defineProperties(createChalk.prototype, styles2);
1278
+ var chalk = createChalk();
1279
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
1280
+ var source_default = chalk;
1148
1281
 
1149
1282
  // src/index.ts
1283
+ var import_commander6 = require("commander");
1284
+ var import_config8 = require("dotenv/config");
1285
+ var import_node_child_process9 = require("child_process");
1286
+ var import_node_fs11 = require("fs");
1287
+ var import_promises7 = require("fs/promises");
1288
+ var import_node_module2 = require("module");
1289
+ var import_node_path9 = __toESM(require("path"), 1);
1290
+ var import_node_url3 = require("url");
1291
+ init_open();
1150
1292
  var import_vite_plugin_singlefile = require("vite-plugin-singlefile");
1151
1293
  var import_zod = require("zod");
1152
1294
 
1295
+ // src/commands/auth.ts
1296
+ init_cjs_shims();
1297
+ init_open();
1298
+
1299
+ // src/utils/api.ts
1300
+ init_cjs_shims();
1301
+
1153
1302
  // src/utils/config.ts
1303
+ init_cjs_shims();
1154
1304
  var import_node_fs4 = require("fs");
1155
1305
  var import_node_os3 = __toESM(require("os"), 1);
1156
1306
  var import_node_path2 = __toESM(require("path"), 1);
@@ -1340,8 +1490,8 @@ var McpUseAPI = class _McpUseAPI {
1340
1490
  // ── Organization ID resolution ──────────────────────────────────
1341
1491
  async resolveOrganizationId() {
1342
1492
  if (this.orgId) return this.orgId;
1343
- const auth = await this.testAuth();
1344
- const id = auth.default_org_id;
1493
+ const auth2 = await this.testAuth();
1494
+ const id = auth2.default_org_id;
1345
1495
  if (!id) {
1346
1496
  throw new Error(
1347
1497
  "No organization set. Run `mcp-use org switch` or use --org to specify one."
@@ -1529,6 +1679,7 @@ var McpUseAPI = class _McpUseAPI {
1529
1679
  };
1530
1680
 
1531
1681
  // src/utils/errors.ts
1682
+ init_cjs_shims();
1532
1683
  function handleCommandError(error, context) {
1533
1684
  if (error instanceof ApiUnauthorizedError) {
1534
1685
  console.error(
@@ -1875,52 +2026,113 @@ async function whoamiCommand() {
1875
2026
  }
1876
2027
 
1877
2028
  // src/commands/client.ts
2029
+ init_cjs_shims();
1878
2030
  var import_commander = require("commander");
1879
2031
  var import_client = require("mcp-use/client");
1880
2032
  var import_server = require("mcp-use/server");
1881
- var import_node_readline = require("readline");
2033
+ var import_node_readline2 = require("readline");
1882
2034
 
1883
2035
  // src/utils/format.ts
1884
- function formatTable(data, columns) {
2036
+ init_cjs_shims();
2037
+ var ANSI_RE = /\x1b\[[0-9;]*m/g;
2038
+ var GUTTER = " ";
2039
+ var MIN_TRUNCATABLE_WIDTH = 8;
2040
+ var DEFAULT_MAX_WIDTH = 100;
2041
+ function stripAnsi(s) {
2042
+ return s.replace(ANSI_RE, "");
2043
+ }
2044
+ function visibleWidth(s) {
2045
+ return stripAnsi(s).length;
2046
+ }
2047
+ function padCell(s, width) {
2048
+ const w = visibleWidth(s);
2049
+ if (w >= width) return s;
2050
+ return s + " ".repeat(width - w);
2051
+ }
2052
+ function truncateCell(s, width) {
2053
+ if (width <= 0) return "";
2054
+ const plain = stripAnsi(s);
2055
+ if (plain.length <= width) return s;
2056
+ if (width === 1) return "\u2026";
2057
+ return plain.slice(0, width - 1) + "\u2026";
2058
+ }
2059
+ function formatTable(data, columns, options = {}) {
2060
+ const tsv = options.tsv ?? !process.stdout.isTTY;
2061
+ if (tsv) {
2062
+ return data.map(
2063
+ (row) => columns.map(
2064
+ (c) => stripAnsi(String(row[c.key] ?? "")).replace(/[\t\r\n]+/g, " ")
2065
+ ).join(" ")
2066
+ ).join("\n");
2067
+ }
1885
2068
  if (data.length === 0) {
1886
2069
  return source_default.gray("No items found");
1887
2070
  }
1888
- const widths = columns.map((col) => {
1889
- const maxDataWidth = Math.max(
1890
- ...data.map((row) => String(row[col.key] || "").length)
1891
- );
1892
- const headerWidth = col.header.length;
1893
- return col.width || Math.max(maxDataWidth, headerWidth, 10);
2071
+ const maxWidth = options.maxWidth ?? process.stdout.columns ?? DEFAULT_MAX_WIDTH;
2072
+ const natural = columns.map((col) => {
2073
+ const headerW = col.header.length;
2074
+ const dataW = data.reduce((m, row) => {
2075
+ return Math.max(m, visibleWidth(String(row[col.key] ?? "")));
2076
+ }, 0);
2077
+ return Math.max(headerW, dataW);
1894
2078
  });
1895
- const createRow = (values, bold = false) => {
1896
- const cells = values.map((val, i) => {
1897
- const padded = val.padEnd(widths[i]);
1898
- return bold ? source_default.bold(padded) : padded;
1899
- });
1900
- return `\u2502 ${cells.join(" \u2502 ")} \u2502`;
1901
- };
1902
- const separator = (char) => {
1903
- const parts = widths.map((w) => char.repeat(w + 2));
1904
- if (char === "\u2500") {
1905
- return `\u251C${parts.join("\u253C")}\u2524`;
2079
+ const widths = columns.map((c, i) => c.width ?? natural[i]);
2080
+ const overhead = GUTTER.length * (columns.length - 1);
2081
+ const totalWidth = () => widths.reduce((s, w) => s + w, 0) + overhead;
2082
+ if (totalWidth() > maxWidth) {
2083
+ const truncIdxs = columns.map((c, i) => c.truncate ? i : -1).filter((i) => i >= 0);
2084
+ if (truncIdxs.length > 0) {
2085
+ const fixedSum = columns.reduce(
2086
+ (s, c, i) => s + (c.truncate ? 0 : widths[i]),
2087
+ 0
2088
+ );
2089
+ const remaining = Math.max(
2090
+ truncIdxs.length * MIN_TRUNCATABLE_WIDTH,
2091
+ maxWidth - fixedSum - overhead
2092
+ );
2093
+ const truncSum = truncIdxs.reduce((s, i) => s + widths[i], 0) || 1;
2094
+ let used = 0;
2095
+ truncIdxs.forEach((i, idx) => {
2096
+ if (idx === truncIdxs.length - 1) {
2097
+ widths[i] = Math.max(MIN_TRUNCATABLE_WIDTH, remaining - used);
2098
+ } else {
2099
+ const share = Math.max(
2100
+ MIN_TRUNCATABLE_WIDTH,
2101
+ Math.floor(widths[i] / truncSum * remaining)
2102
+ );
2103
+ widths[i] = share;
2104
+ used += share;
2105
+ }
2106
+ });
1906
2107
  }
1907
- return `\u2514${parts.join("\u2534")}\u2518`;
1908
- };
2108
+ }
1909
2109
  const lines = [];
1910
- lines.push(`\u250C${widths.map((w) => "\u2500".repeat(w + 2)).join("\u252C")}\u2510`);
1911
- lines.push(
1912
- createRow(
1913
- columns.map((c) => c.header),
1914
- true
1915
- )
1916
- );
1917
- lines.push(separator("\u2500"));
1918
- data.forEach((row) => {
1919
- lines.push(createRow(columns.map((c) => String(row[c.key] || ""))));
2110
+ const headerCells = columns.map((c, i) => {
2111
+ const text = c.header.toUpperCase();
2112
+ const cell = i === columns.length - 1 ? text : padCell(text, widths[i]);
2113
+ return source_default.bold(cell);
1920
2114
  });
1921
- lines.push(separator("\u2500"));
2115
+ lines.push(headerCells.join(GUTTER).trimEnd());
2116
+ for (const row of data) {
2117
+ const cells = columns.map((c, i) => {
2118
+ let v = String(row[c.key] ?? "");
2119
+ if (visibleWidth(v) > widths[i]) {
2120
+ v = truncateCell(v, widths[i]);
2121
+ }
2122
+ return i === columns.length - 1 ? v : padCell(v, widths[i]);
2123
+ });
2124
+ lines.push(cells.join(GUTTER).trimEnd());
2125
+ }
1922
2126
  return lines.join("\n");
1923
2127
  }
2128
+ function isStdoutTty() {
2129
+ return Boolean(process.stdout.isTTY);
2130
+ }
2131
+ function formatToolMode(annotations) {
2132
+ if (annotations?.readOnlyHint === true) return source_default.green("read-only");
2133
+ if (annotations?.destructiveHint === true) return source_default.red("destructive");
2134
+ return source_default.yellow("write");
2135
+ }
1924
2136
  function formatJson(data, pretty = true) {
1925
2137
  if (pretty) {
1926
2138
  return JSON.stringify(data, null, 2);
@@ -1929,20 +2141,26 @@ function formatJson(data, pretty = true) {
1929
2141
  }
1930
2142
  function formatToolCall(result) {
1931
2143
  const lines = [];
1932
- if (result.isError) {
2144
+ const { isError, structuredContent } = result;
2145
+ const hasContent = !!result.content?.length;
2146
+ const hasStructured = structuredContent !== void 0 && structuredContent !== null;
2147
+ if (isError) {
1933
2148
  lines.push(source_default.red("\u2717 Tool execution failed"));
1934
2149
  lines.push("");
1935
2150
  } else {
1936
2151
  lines.push(source_default.green("\u2713 Tool executed successfully"));
1937
2152
  lines.push("");
1938
2153
  }
1939
- if (result.content && result.content.length > 0) {
2154
+ if (hasContent) {
2155
+ if (isError) {
2156
+ lines.push(source_default.red.bold("Error details:"));
2157
+ }
1940
2158
  result.content.forEach((item, index) => {
1941
2159
  if (result.content.length > 1) {
1942
2160
  lines.push(source_default.bold(`Content ${index + 1}:`));
1943
2161
  }
1944
2162
  if (item.type === "text") {
1945
- lines.push(item.text);
2163
+ lines.push(isError ? source_default.red(item.text) : item.text);
1946
2164
  } else if (item.type === "image") {
1947
2165
  lines.push(source_default.cyan(`[Image: ${item.mimeType || "unknown type"}]`));
1948
2166
  if (item.data) {
@@ -1964,6 +2182,16 @@ function formatToolCall(result) {
1964
2182
  }
1965
2183
  });
1966
2184
  }
2185
+ if (hasStructured) {
2186
+ if (hasContent) lines.push("");
2187
+ lines.push(
2188
+ source_default.bold(isError ? "Structured error data:" : "Structured content:")
2189
+ );
2190
+ lines.push(formatJson(structuredContent));
2191
+ }
2192
+ if (isError && !hasContent && !hasStructured) {
2193
+ lines.push(source_default.gray("(no error details provided by server)"));
2194
+ }
1967
2195
  return lines.join("\n");
1968
2196
  }
1969
2197
  function formatResourceContent(content) {
@@ -2109,14 +2337,213 @@ function formatPromptMessages(messages) {
2109
2337
  }
2110
2338
  }
2111
2339
  }
2112
- if (index < messages.length - 1) {
2113
- lines.push("");
2340
+ if (index < messages.length - 1) {
2341
+ lines.push("");
2342
+ }
2343
+ });
2344
+ return lines.join("\n");
2345
+ }
2346
+
2347
+ // src/utils/parse-args.ts
2348
+ init_cjs_shims();
2349
+ function parseToolArgs(rawArgs, inputSchema) {
2350
+ if (!rawArgs || rawArgs.length === 0) return {};
2351
+ if (rawArgs.length === 1) {
2352
+ const trimmed = rawArgs[0].trim();
2353
+ if (trimmed.startsWith("{")) {
2354
+ try {
2355
+ const parsed = JSON.parse(trimmed);
2356
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
2357
+ throw new Error("expected a JSON object");
2358
+ }
2359
+ return parsed;
2360
+ } catch (err) {
2361
+ throw new Error(`Invalid JSON arguments: ${err.message}`);
2362
+ }
2363
+ }
2364
+ }
2365
+ const props = inputSchema?.properties ?? {};
2366
+ const result = {};
2367
+ for (const raw of rawArgs) {
2368
+ const token = raw.startsWith("--") ? raw.slice(2) : raw;
2369
+ const jsonIdx = token.indexOf(":=");
2370
+ const eqIdx = token.indexOf("=");
2371
+ let key;
2372
+ let rawValue;
2373
+ let forceJson = false;
2374
+ if (jsonIdx !== -1 && (eqIdx === -1 || jsonIdx < eqIdx)) {
2375
+ key = token.slice(0, jsonIdx);
2376
+ rawValue = token.slice(jsonIdx + 2);
2377
+ forceJson = true;
2378
+ } else if (eqIdx !== -1) {
2379
+ key = token.slice(0, eqIdx);
2380
+ rawValue = token.slice(eqIdx + 1);
2381
+ } else {
2382
+ throw new Error(
2383
+ `Invalid argument '${raw}'. Use key=value or key:=jsonvalue.`
2384
+ );
2385
+ }
2386
+ if (!key) {
2387
+ throw new Error(`Empty key in argument '${raw}'`);
2388
+ }
2389
+ result[key] = coerceArgValue(rawValue, props[key], forceJson, key);
2390
+ }
2391
+ return result;
2392
+ }
2393
+ function coerceArgValue(value, propSchema, forceJson, key) {
2394
+ if (forceJson) {
2395
+ try {
2396
+ return JSON.parse(value);
2397
+ } catch (err) {
2398
+ throw new Error(
2399
+ `Invalid JSON value for '${key}': ${err.message}`
2400
+ );
2401
+ }
2402
+ }
2403
+ const types = Array.isArray(propSchema?.type) ? propSchema.type : propSchema?.type ? [propSchema.type] : [];
2404
+ if (types.includes("null") && (value === "null" || value === "")) {
2405
+ return null;
2406
+ }
2407
+ if (types.includes("integer")) {
2408
+ const n = Number(value);
2409
+ if (!Number.isFinite(n) || !Number.isInteger(n)) {
2410
+ throw new Error(`Expected integer for '${key}', got '${value}'`);
2411
+ }
2412
+ return n;
2413
+ }
2414
+ if (types.includes("number")) {
2415
+ const n = Number(value);
2416
+ if (!Number.isFinite(n)) {
2417
+ throw new Error(`Expected number for '${key}', got '${value}'`);
2418
+ }
2419
+ return n;
2420
+ }
2421
+ if (types.includes("boolean")) {
2422
+ if (value === "true" || value === "1") return true;
2423
+ if (value === "false" || value === "0") return false;
2424
+ throw new Error(
2425
+ `Expected boolean (true/false) for '${key}', got '${value}'`
2426
+ );
2427
+ }
2428
+ if (types.includes("array") || types.includes("object")) {
2429
+ try {
2430
+ return JSON.parse(value);
2431
+ } catch (err) {
2432
+ const wanted = types.includes("array") ? "array" : "object";
2433
+ throw new Error(
2434
+ `Expected JSON ${wanted} for '${key}'. Tip: use ${key}:=<json>. ${err.message}`
2435
+ );
2436
+ }
2437
+ }
2438
+ return value;
2439
+ }
2440
+ function parsePromptArgs(rawArgs) {
2441
+ if (!rawArgs || rawArgs.length === 0) return {};
2442
+ if (rawArgs.length === 1) {
2443
+ const trimmed = rawArgs[0].trim();
2444
+ if (trimmed.startsWith("{")) {
2445
+ try {
2446
+ const parsed = JSON.parse(trimmed);
2447
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
2448
+ throw new Error("expected a JSON object");
2449
+ }
2450
+ const out = {};
2451
+ for (const [k, v] of Object.entries(parsed)) {
2452
+ out[k] = typeof v === "string" ? v : JSON.stringify(v);
2453
+ }
2454
+ return out;
2455
+ } catch (err) {
2456
+ throw new Error(`Invalid JSON arguments: ${err.message}`);
2457
+ }
2458
+ }
2459
+ }
2460
+ const result = {};
2461
+ for (const raw of rawArgs) {
2462
+ const token = raw.startsWith("--") ? raw.slice(2) : raw;
2463
+ const eqIdx = token.indexOf("=");
2464
+ if (eqIdx === -1) {
2465
+ throw new Error(`Invalid argument '${raw}'. Use key=value.`);
2466
+ }
2467
+ const key = token.slice(0, eqIdx);
2468
+ const value = token.slice(eqIdx + 1);
2469
+ if (!key) {
2470
+ throw new Error(`Empty key in argument '${raw}'`);
2471
+ }
2472
+ result[key] = value;
2473
+ }
2474
+ return result;
2475
+ }
2476
+
2477
+ // src/utils/oauth.ts
2478
+ init_cjs_shims();
2479
+ var import_node = require("mcp-use/auth/node");
2480
+ var import_node_readline = require("readline");
2481
+ async function buildOAuthProvider(serverUrl, options = {}) {
2482
+ return import_node.NodeOAuthClientProvider.create(serverUrl, {
2483
+ clientName: "mcp-use CLI",
2484
+ clientUri: "https://mcp-use.com",
2485
+ storageKeyPrefix: "mcp:auth",
2486
+ ...options,
2487
+ openBrowser: async (url) => {
2488
+ if (!process.stdout.isTTY) {
2489
+ console.error(`
2490
+ Open this URL in a browser to authenticate:`);
2491
+ console.error(` ${url}
2492
+ `);
2493
+ return;
2494
+ }
2495
+ const { default: open2 } = await Promise.resolve().then(() => (init_open(), open_exports));
2496
+ await open2(url);
2114
2497
  }
2115
2498
  });
2116
- return lines.join("\n");
2499
+ }
2500
+ async function runOAuthFlow(provider, serverUrl, print = console.error.bind(console)) {
2501
+ print(
2502
+ process.stdout.isTTY ? `\u2192 Opening browser to authenticate...` : `\u2192 OAuth authentication required.`
2503
+ );
2504
+ print(
2505
+ ` Listening on http://127.0.0.1:${provider.callbackPort}/callback (waiting up to 5m)`
2506
+ );
2507
+ if (!provider.hasPendingFlow) {
2508
+ const result = await (0, import_node.auth)(provider, { serverUrl });
2509
+ if (result === "AUTHORIZED") {
2510
+ return;
2511
+ }
2512
+ if (result !== "REDIRECT") {
2513
+ throw new import_node.OAuthFlowError(
2514
+ "unexpected_auth_result",
2515
+ `auth() returned ${result}`
2516
+ );
2517
+ }
2518
+ }
2519
+ const code = await provider.getAuthorizationCode();
2520
+ await (0, import_node.auth)(provider, { serverUrl, authorizationCode: code });
2521
+ }
2522
+ function isUnauthorized(err) {
2523
+ if (err instanceof import_node.UnauthorizedError) return true;
2524
+ if (err instanceof Error && err.name === "UnauthorizedError") return true;
2525
+ if (err instanceof Error && err.code === 401) {
2526
+ return true;
2527
+ }
2528
+ return false;
2529
+ }
2530
+ async function promptYesNo(question, defaultYes = true) {
2531
+ if (!process.stdin.isTTY) return false;
2532
+ const rl = (0, import_node_readline.createInterface)({ input: process.stdin, output: process.stderr });
2533
+ try {
2534
+ const answer = await new Promise((resolve2) => {
2535
+ rl.question(`${question} ${defaultYes ? "[Y/n] " : "[y/N] "}`, resolve2);
2536
+ });
2537
+ const trimmed = answer.trim().toLowerCase();
2538
+ if (!trimmed) return defaultYes;
2539
+ return trimmed === "y" || trimmed === "yes";
2540
+ } finally {
2541
+ rl.close();
2542
+ }
2117
2543
  }
2118
2544
 
2119
2545
  // src/utils/session-storage.ts
2546
+ init_cjs_shims();
2120
2547
  var import_node_os4 = require("os");
2121
2548
  var import_node_path3 = require("path");
2122
2549
  var import_promises4 = require("fs/promises");
@@ -2196,8 +2623,133 @@ async function updateSessionInfo(name, serverInfo, capabilities) {
2196
2623
  }
2197
2624
  }
2198
2625
 
2626
+ // src/commands/client-auth.ts
2627
+ init_cjs_shims();
2628
+ async function resolveSession(sessionArg) {
2629
+ let name = sessionArg;
2630
+ if (!name) {
2631
+ const active = await getActiveSession();
2632
+ if (!active) {
2633
+ console.error(formatError("No active session"));
2634
+ return null;
2635
+ }
2636
+ name = active.name;
2637
+ }
2638
+ const config = await getSession(name);
2639
+ if (!config) {
2640
+ console.error(formatError(`Session '${name}' not found`));
2641
+ return null;
2642
+ }
2643
+ if (config.type !== "http") {
2644
+ console.error(formatError("Auth commands only apply to HTTP sessions"));
2645
+ return null;
2646
+ }
2647
+ if (config.authMode !== "oauth") {
2648
+ console.error(
2649
+ formatError(
2650
+ `Session '${name}' was not authenticated via OAuth (authMode=${config.authMode ?? "bearer"})`
2651
+ )
2652
+ );
2653
+ return null;
2654
+ }
2655
+ return { name, url: config.url };
2656
+ }
2657
+ function formatExpiresIn(expSec) {
2658
+ const ms = expSec * 1e3 - Date.now();
2659
+ if (ms <= 0) return "expired";
2660
+ const mins = Math.round(ms / 6e4);
2661
+ if (mins < 60) return `${mins}m`;
2662
+ const hours = Math.floor(mins / 60);
2663
+ const rem = mins % 60;
2664
+ return rem ? `${hours}h${rem}m` : `${hours}h`;
2665
+ }
2666
+ function decodeJwtExp(token) {
2667
+ try {
2668
+ const parts = token.split(".");
2669
+ if (parts.length < 2) return null;
2670
+ const payload = JSON.parse(
2671
+ Buffer.from(parts[1], "base64url").toString("utf-8")
2672
+ );
2673
+ return typeof payload.exp === "number" ? payload.exp : null;
2674
+ } catch {
2675
+ return null;
2676
+ }
2677
+ }
2678
+ async function authStatusCommand(sessionArg) {
2679
+ const target = await resolveSession(sessionArg);
2680
+ if (!target) {
2681
+ process.exit(1);
2682
+ }
2683
+ const provider = await buildOAuthProvider(target.url);
2684
+ const tokens = await provider.tokens();
2685
+ const fields = {
2686
+ session: target.name,
2687
+ url: target.url,
2688
+ tokens: tokens?.access_token ? "present" : "missing"
2689
+ };
2690
+ if (tokens?.scope) fields.scope = tokens.scope;
2691
+ if (tokens?.access_token) {
2692
+ const exp = decodeJwtExp(tokens.access_token);
2693
+ fields.expires_in = exp ? formatExpiresIn(exp) : "unknown (opaque token)";
2694
+ }
2695
+ fields.refresh = tokens?.refresh_token ? "available" : "missing";
2696
+ console.log(formatKeyValue(fields));
2697
+ if (!tokens?.access_token) process.exit(1);
2698
+ }
2699
+ async function authRefreshCommand(sessionArg) {
2700
+ const target = await resolveSession(sessionArg);
2701
+ if (!target) {
2702
+ process.exit(1);
2703
+ }
2704
+ const provider = await buildOAuthProvider(target.url);
2705
+ const refreshed = await provider.forceRefresh();
2706
+ if (!refreshed) {
2707
+ console.error(
2708
+ formatError(
2709
+ "Refresh failed (no refresh_token, or server rejected). Re-connect to re-authenticate."
2710
+ )
2711
+ );
2712
+ console.error(
2713
+ formatInfo(
2714
+ `Run: mcp-use client connect ${target.url} --name ${target.name}`
2715
+ )
2716
+ );
2717
+ process.exit(1);
2718
+ }
2719
+ const exp = refreshed.access_token ? decodeJwtExp(refreshed.access_token) : null;
2720
+ console.log(
2721
+ formatSuccess(
2722
+ `Refreshed access token${exp ? ` (expires in ${formatExpiresIn(exp)})` : ""}`
2723
+ )
2724
+ );
2725
+ }
2726
+ async function authLogoutCommand(sessionArg) {
2727
+ const target = await resolveSession(sessionArg);
2728
+ if (!target) {
2729
+ process.exit(1);
2730
+ }
2731
+ const provider = await buildOAuthProvider(target.url);
2732
+ await provider.invalidateCredentials("all");
2733
+ console.log(formatSuccess(`Removed tokens for ${target.url}`));
2734
+ console.log(
2735
+ formatInfo(
2736
+ `Session '${target.name}' kept; reconnect with \`mcp-use client connect\`.`
2737
+ )
2738
+ );
2739
+ }
2740
+
2199
2741
  // src/commands/client.ts
2200
2742
  var activeSessions = /* @__PURE__ */ new Map();
2743
+ async function cleanupAndExit(code) {
2744
+ for (const [name, { client }] of activeSessions) {
2745
+ try {
2746
+ await client.closeAllSessions();
2747
+ } catch {
2748
+ }
2749
+ activeSessions.delete(name);
2750
+ }
2751
+ process.exit(code);
2752
+ }
2201
2753
  async function getOrRestoreSession(sessionName) {
2202
2754
  if (!sessionName) {
2203
2755
  const active = await getActiveSession();
@@ -2224,12 +2776,22 @@ async function getOrRestoreSession(sessionName) {
2224
2776
  try {
2225
2777
  const client = new import_client.MCPClient();
2226
2778
  const cliClientInfo = getCliClientInfo();
2779
+ let authProvider;
2227
2780
  if (config.type === "http") {
2228
- client.addServer(sessionName, {
2229
- url: config.url,
2230
- headers: config.authToken ? { Authorization: `Bearer ${config.authToken}` } : void 0,
2231
- clientInfo: cliClientInfo
2232
- });
2781
+ if (config.authMode === "oauth") {
2782
+ authProvider = await buildOAuthProvider(config.url);
2783
+ client.addServer(sessionName, {
2784
+ url: config.url,
2785
+ authProvider,
2786
+ clientInfo: cliClientInfo
2787
+ });
2788
+ } else {
2789
+ client.addServer(sessionName, {
2790
+ url: config.url,
2791
+ headers: config.authToken ? { Authorization: `Bearer ${config.authToken}` } : void 0,
2792
+ clientInfo: cliClientInfo
2793
+ });
2794
+ }
2233
2795
  } else if (config.type === "stdio") {
2234
2796
  client.addServer(sessionName, {
2235
2797
  command: config.command,
@@ -2241,7 +2803,30 @@ async function getOrRestoreSession(sessionName) {
2241
2803
  console.error(formatError(`Unknown session type: ${config.type}`));
2242
2804
  return null;
2243
2805
  }
2244
- const session = await client.createSession(sessionName);
2806
+ let session;
2807
+ try {
2808
+ session = await client.createSession(sessionName);
2809
+ } catch (err) {
2810
+ if (config.type === "http" && config.authMode === "oauth" && authProvider && isUnauthorized(err)) {
2811
+ const reAuth = await promptYesNo(
2812
+ `! Tokens for session '${sessionName}' expired and could not refresh. Re-authenticate now?`,
2813
+ true
2814
+ );
2815
+ if (!reAuth) {
2816
+ console.error(formatError(`Tokens expired and could not refresh.`));
2817
+ console.error(
2818
+ formatInfo(
2819
+ `Run: mcp-use client connect ${config.url} --name ${sessionName}`
2820
+ )
2821
+ );
2822
+ return null;
2823
+ }
2824
+ await runOAuthFlow(authProvider, config.url);
2825
+ session = await client.createSession(sessionName);
2826
+ } else {
2827
+ throw err;
2828
+ }
2829
+ }
2245
2830
  activeSessions.set(sessionName, { client, session });
2246
2831
  console.error(formatInfo(`Reconnected to session '${sessionName}'`));
2247
2832
  return { name: sessionName, session };
@@ -2291,16 +2876,40 @@ async function connectCommand(urlOrCommand, options) {
2291
2876
  });
2292
2877
  } else {
2293
2878
  console.error(formatInfo(`Connecting to ${urlOrCommand}...`));
2879
+ const wantOAuth = !options.auth && options.oauth !== false;
2880
+ let authProvider;
2881
+ if (wantOAuth) {
2882
+ const authTimeoutMs = options.authTimeout ? Number.parseInt(options.authTimeout, 10) : void 0;
2883
+ authProvider = await buildOAuthProvider(urlOrCommand, {
2884
+ ...authTimeoutMs ? { authTimeoutMs } : {}
2885
+ });
2886
+ }
2294
2887
  client.addServer(sessionName, {
2295
2888
  url: urlOrCommand,
2296
- headers: options.auth ? { Authorization: `Bearer ${options.auth}` } : void 0,
2889
+ ...authProvider ? { authProvider } : options.auth ? { headers: { Authorization: `Bearer ${options.auth}` } } : {},
2297
2890
  clientInfo: cliClientInfo
2298
2891
  });
2299
- session = await client.createSession(sessionName);
2892
+ try {
2893
+ session = await client.createSession(sessionName);
2894
+ } catch (err) {
2895
+ if (authProvider && isUnauthorized(err)) {
2896
+ console.error(
2897
+ formatWarning(
2898
+ "Server requires authentication. Starting OAuth flow."
2899
+ )
2900
+ );
2901
+ await runOAuthFlow(authProvider, urlOrCommand);
2902
+ console.error(formatSuccess("Authentication successful"));
2903
+ session = await client.createSession(sessionName);
2904
+ } else {
2905
+ throw err;
2906
+ }
2907
+ }
2300
2908
  await saveSession(sessionName, {
2301
2909
  type: "http",
2302
2910
  url: urlOrCommand,
2303
- authToken: options.auth,
2911
+ authMode: authProvider ? "oauth" : options.auth ? "bearer" : void 0,
2912
+ authToken: authProvider ? void 0 : options.auth,
2304
2913
  lastUsed: (/* @__PURE__ */ new Date()).toISOString()
2305
2914
  });
2306
2915
  }
@@ -2336,8 +2945,9 @@ async function connectCommand(urlOrCommand, options) {
2336
2945
  );
2337
2946
  } catch (error) {
2338
2947
  console.error(formatError(`Connection failed: ${error.message}`));
2339
- process.exit(1);
2948
+ await cleanupAndExit(1);
2340
2949
  }
2950
+ await cleanupAndExit(0);
2341
2951
  }
2342
2952
  async function disconnectCommand(sessionName, options) {
2343
2953
  try {
@@ -2347,13 +2957,13 @@ async function disconnectCommand(sessionName, options) {
2347
2957
  activeSessions.delete(name);
2348
2958
  console.log(formatSuccess(`Disconnected from ${name}`));
2349
2959
  }
2350
- return;
2960
+ await cleanupAndExit(0);
2351
2961
  }
2352
2962
  if (!sessionName) {
2353
2963
  const active = await getActiveSession();
2354
2964
  if (!active) {
2355
2965
  console.error(formatError("No active session to disconnect"));
2356
- return;
2966
+ await cleanupAndExit(0);
2357
2967
  }
2358
2968
  sessionName = active.name;
2359
2969
  }
@@ -2367,43 +2977,52 @@ async function disconnectCommand(sessionName, options) {
2367
2977
  }
2368
2978
  } catch (error) {
2369
2979
  console.error(formatError(`Failed to disconnect: ${error.message}`));
2370
- process.exit(1);
2980
+ await cleanupAndExit(1);
2371
2981
  }
2982
+ await cleanupAndExit(0);
2372
2983
  }
2373
2984
  async function listSessionsCommand() {
2374
2985
  try {
2375
2986
  const sessions = await listAllSessions();
2376
2987
  if (sessions.length === 0) {
2377
- console.log(formatInfo("No saved sessions"));
2378
- console.log(
2379
- formatInfo("Connect to a server with: npx mcp-use client connect <url>")
2380
- );
2988
+ if (isStdoutTty()) {
2989
+ console.log(formatInfo("No saved sessions"));
2990
+ console.log(
2991
+ formatInfo(
2992
+ "Connect to a server with: npx mcp-use client connect <url>"
2993
+ )
2994
+ );
2995
+ }
2381
2996
  return;
2382
2997
  }
2383
- console.log(formatHeader("Saved Sessions:"));
2384
- console.log("");
2998
+ const tty2 = isStdoutTty();
2999
+ if (tty2) {
3000
+ console.log(formatHeader("Saved Sessions:"));
3001
+ console.log("");
3002
+ }
2385
3003
  const tableData = sessions.map((s) => ({
2386
3004
  name: s.isActive ? source_default.green.bold(`${s.name} *`) : s.name,
2387
3005
  type: s.config.type,
2388
3006
  target: s.config.type === "http" ? s.config.url || "" : `${s.config.command} ${(s.config.args || []).join(" ")}`,
2389
- server: s.config.serverInfo?.name || "unknown",
2390
- status: activeSessions.has(s.name) ? source_default.green("connected") : source_default.gray("disconnected")
3007
+ server: s.config.serverInfo?.name || "unknown"
2391
3008
  }));
2392
3009
  console.log(
2393
3010
  formatTable(tableData, [
2394
3011
  { key: "name", header: "Name" },
2395
3012
  { key: "type", header: "Type" },
2396
- { key: "target", header: "Target", width: 40 },
2397
- { key: "server", header: "Server" },
2398
- { key: "status", header: "Status" }
3013
+ { key: "target", header: "Target", truncate: true },
3014
+ { key: "server", header: "Server" }
2399
3015
  ])
2400
3016
  );
2401
- console.log("");
2402
- console.log(source_default.gray("* = active session"));
3017
+ if (tty2) {
3018
+ console.log("");
3019
+ console.log(source_default.gray("* = active session"));
3020
+ }
2403
3021
  } catch (error) {
2404
3022
  console.error(formatError(`Failed to list sessions: ${error.message}`));
2405
- process.exit(1);
3023
+ await cleanupAndExit(1);
2406
3024
  }
3025
+ await cleanupAndExit(0);
2407
3026
  }
2408
3027
  async function switchSessionCommand(name) {
2409
3028
  try {
@@ -2411,44 +3030,70 @@ async function switchSessionCommand(name) {
2411
3030
  console.log(formatSuccess(`Switched to session '${name}'`));
2412
3031
  } catch (error) {
2413
3032
  console.error(formatError(`Failed to switch session: ${error.message}`));
2414
- process.exit(1);
3033
+ await cleanupAndExit(1);
2415
3034
  }
3035
+ await cleanupAndExit(0);
2416
3036
  }
2417
3037
  async function listToolsCommand(options) {
2418
3038
  try {
2419
3039
  const result = await getOrRestoreSession(options.session || null);
2420
- if (!result) return;
3040
+ if (!result) {
3041
+ await cleanupAndExit(1);
3042
+ }
2421
3043
  const { session } = result;
2422
3044
  const tools = await session.listTools();
2423
3045
  if (options.json) {
2424
3046
  console.log(formatJson(tools));
2425
- return;
2426
- }
2427
- if (tools.length === 0) {
2428
- console.log(formatInfo("No tools available"));
2429
- return;
3047
+ } else if (tools.length === 0) {
3048
+ if (isStdoutTty()) console.log(formatInfo("No tools available"));
3049
+ } else {
3050
+ const tty2 = isStdoutTty();
3051
+ if (tty2) {
3052
+ console.log(formatHeader(`Available Tools (${tools.length}):`));
3053
+ console.log("");
3054
+ }
3055
+ const tableData = tools.map((tool) => {
3056
+ const props = tool.inputSchema?.properties ?? {};
3057
+ const required = tool.inputSchema?.required ?? [];
3058
+ const total = Object.keys(props).length;
3059
+ const reqCount = Array.isArray(required) ? required.length : 0;
3060
+ const argsCell = total === 0 ? source_default.gray("\u2014") : `${reqCount}/${total}`;
3061
+ return {
3062
+ name: source_default.bold(tool.name),
3063
+ mode: formatToolMode(tool.annotations),
3064
+ args: argsCell,
3065
+ description: tool.description || source_default.gray("(no description)")
3066
+ };
3067
+ });
3068
+ console.log(
3069
+ formatTable(tableData, [
3070
+ { key: "name", header: "Tool" },
3071
+ { key: "mode", header: "Mode" },
3072
+ { key: "args", header: "Args" },
3073
+ { key: "description", header: "Description", truncate: true }
3074
+ ])
3075
+ );
3076
+ if (tty2) {
3077
+ console.log("");
3078
+ console.log(
3079
+ source_default.gray(
3080
+ "ARGS shows required/total. Modes: read-only \xB7 write \xB7 destructive."
3081
+ )
3082
+ );
3083
+ }
2430
3084
  }
2431
- console.log(formatHeader(`Available Tools (${tools.length}):`));
2432
- console.log("");
2433
- const tableData = tools.map((tool) => ({
2434
- name: source_default.bold(tool.name),
2435
- description: tool.description || source_default.gray("No description")
2436
- }));
2437
- console.log(
2438
- formatTable(tableData, [
2439
- { key: "name", header: "Tool", width: 25 },
2440
- { key: "description", header: "Description", width: 50 }
2441
- ])
2442
- );
2443
3085
  } catch (error) {
2444
3086
  console.error(formatError(`Failed to list tools: ${error.message}`));
2445
- process.exit(1);
3087
+ await cleanupAndExit(1);
2446
3088
  }
3089
+ await cleanupAndExit(0);
2447
3090
  }
2448
3091
  async function describeToolCommand(toolName, options) {
2449
3092
  try {
2450
3093
  const result = await getOrRestoreSession(options.session || null);
2451
- if (!result) return;
3094
+ if (!result) {
3095
+ await cleanupAndExit(1);
3096
+ }
2452
3097
  const { session } = result;
2453
3098
  const tools = session.tools;
2454
3099
  const tool = tools.find((t) => t.name === toolName);
@@ -2457,7 +3102,7 @@ async function describeToolCommand(toolName, options) {
2457
3102
  console.log("");
2458
3103
  console.log(formatInfo("Available tools:"));
2459
3104
  tools.forEach((t) => console.log(` \u2022 ${t.name}`));
2460
- return;
3105
+ await cleanupAndExit(1);
2461
3106
  }
2462
3107
  console.log(formatHeader(`Tool: ${tool.name}`));
2463
3108
  console.log("");
@@ -2471,41 +3116,54 @@ async function describeToolCommand(toolName, options) {
2471
3116
  }
2472
3117
  } catch (error) {
2473
3118
  console.error(formatError(`Failed to describe tool: ${error.message}`));
2474
- process.exit(1);
3119
+ await cleanupAndExit(1);
2475
3120
  }
3121
+ await cleanupAndExit(0);
2476
3122
  }
2477
- async function callToolCommand(toolName, argsJson, options) {
3123
+ async function callToolCommand(toolName, argsList, options) {
2478
3124
  try {
2479
3125
  const result = await getOrRestoreSession(options?.session || null);
2480
- if (!result) return;
3126
+ if (!result) {
3127
+ await cleanupAndExit(1);
3128
+ }
2481
3129
  const { session } = result;
3130
+ const tools = session.tools;
3131
+ const tool = tools.find((t) => t.name === toolName);
2482
3132
  let args = {};
2483
- if (argsJson) {
3133
+ if (argsList && argsList.length > 0) {
2484
3134
  try {
2485
- args = JSON.parse(argsJson);
3135
+ args = parseToolArgs(argsList, tool?.inputSchema);
2486
3136
  } catch (error) {
2487
- console.error(formatError("Invalid JSON arguments"));
2488
- return;
2489
- }
2490
- } else {
2491
- const tools = session.tools;
2492
- const tool = tools.find((t) => t.name === toolName);
2493
- if (tool?.inputSchema?.required && tool.inputSchema.required.length > 0) {
2494
- console.error(
2495
- formatError(
2496
- "This tool requires arguments. Provide them as a JSON string."
2497
- )
2498
- );
3137
+ console.error(formatError(error.message));
2499
3138
  console.log("");
2500
- console.log(formatInfo("Example:"));
3139
+ console.log(formatInfo("Usage:"));
2501
3140
  console.log(
2502
- ` npx mcp-use client tools call ${toolName} '{"param": "value"}'`
3141
+ ` npx mcp-use client tools call ${toolName} key=value [key2=value2 ...]`
2503
3142
  );
2504
- console.log("");
2505
- console.log(formatInfo("Tool schema:"));
2506
- console.log(formatSchema(tool.inputSchema));
2507
- return;
3143
+ console.log(
3144
+ ` npx mcp-use client tools call ${toolName} nested:='{"a":1}' # JSON value`
3145
+ );
3146
+ console.log(
3147
+ ` npx mcp-use client tools call ${toolName} '{"key":"value"}' # full JSON object`
3148
+ );
3149
+ if (tool?.inputSchema) {
3150
+ console.log("");
3151
+ console.log(formatInfo("Tool schema:"));
3152
+ console.log(formatSchema(tool.inputSchema));
3153
+ }
3154
+ await cleanupAndExit(1);
2508
3155
  }
3156
+ } else if (tool?.inputSchema?.required && tool.inputSchema.required.length > 0) {
3157
+ console.error(formatError("This tool requires arguments."));
3158
+ console.log("");
3159
+ console.log(formatInfo("Provide arguments as key=value pairs:"));
3160
+ console.log(
3161
+ ` npx mcp-use client tools call ${toolName} key=value [key2=value2 ...]`
3162
+ );
3163
+ console.log("");
3164
+ console.log(formatInfo("Tool schema:"));
3165
+ console.log(formatSchema(tool.inputSchema));
3166
+ await cleanupAndExit(1);
2509
3167
  }
2510
3168
  console.error(formatInfo(`Calling tool '${toolName}'...`));
2511
3169
  const callResult = await session.callTool(toolName, args, {
@@ -2516,49 +3174,66 @@ async function callToolCommand(toolName, argsJson, options) {
2516
3174
  } else {
2517
3175
  console.log(formatToolCall(callResult));
2518
3176
  }
3177
+ if (callResult.isError) {
3178
+ await cleanupAndExit(1);
3179
+ }
2519
3180
  } catch (error) {
2520
3181
  console.error(formatError(`Failed to call tool: ${error.message}`));
2521
- process.exit(1);
3182
+ if (error?.data !== void 0) {
3183
+ console.error(
3184
+ source_default.gray(
3185
+ typeof error.data === "string" ? error.data : formatJson(error.data)
3186
+ )
3187
+ );
3188
+ }
3189
+ await cleanupAndExit(1);
2522
3190
  }
3191
+ await cleanupAndExit(0);
2523
3192
  }
2524
3193
  async function listResourcesCommand(options) {
2525
3194
  try {
2526
3195
  const result = await getOrRestoreSession(options.session || null);
2527
- if (!result) return;
3196
+ if (!result) {
3197
+ await cleanupAndExit(1);
3198
+ }
2528
3199
  const { session } = result;
2529
3200
  const resourcesResult = await session.listAllResources();
2530
3201
  const resources = resourcesResult.resources;
2531
3202
  if (options.json) {
2532
3203
  console.log(formatJson(resources));
2533
- return;
2534
- }
2535
- if (resources.length === 0) {
2536
- console.log(formatInfo("No resources available"));
2537
- return;
3204
+ } else if (resources.length === 0) {
3205
+ if (isStdoutTty()) console.log(formatInfo("No resources available"));
3206
+ } else {
3207
+ const tty2 = isStdoutTty();
3208
+ if (tty2) {
3209
+ console.log(formatHeader(`Available Resources (${resources.length}):`));
3210
+ console.log("");
3211
+ }
3212
+ const tableData = resources.map((resource) => ({
3213
+ name: source_default.bold(resource.name || "(no name)"),
3214
+ type: resource.mimeType || source_default.gray("unknown"),
3215
+ uri: resource.uri
3216
+ }));
3217
+ console.log(
3218
+ formatTable(tableData, [
3219
+ { key: "name", header: "Name" },
3220
+ { key: "type", header: "Type" },
3221
+ { key: "uri", header: "URI", truncate: true }
3222
+ ])
3223
+ );
2538
3224
  }
2539
- console.log(formatHeader(`Available Resources (${resources.length}):`));
2540
- console.log("");
2541
- const tableData = resources.map((resource) => ({
2542
- uri: resource.uri,
2543
- name: resource.name || source_default.gray("(no name)"),
2544
- type: resource.mimeType || source_default.gray("unknown")
2545
- }));
2546
- console.log(
2547
- formatTable(tableData, [
2548
- { key: "uri", header: "URI", width: 40 },
2549
- { key: "name", header: "Name", width: 20 },
2550
- { key: "type", header: "Type", width: 15 }
2551
- ])
2552
- );
2553
3225
  } catch (error) {
2554
3226
  console.error(formatError(`Failed to list resources: ${error.message}`));
2555
- process.exit(1);
3227
+ await cleanupAndExit(1);
2556
3228
  }
3229
+ await cleanupAndExit(0);
2557
3230
  }
2558
3231
  async function readResourceCommand(uri, options) {
2559
3232
  try {
2560
3233
  const result = await getOrRestoreSession(options.session || null);
2561
- if (!result) return;
3234
+ if (!result) {
3235
+ await cleanupAndExit(1);
3236
+ }
2562
3237
  const { session } = result;
2563
3238
  console.error(formatInfo(`Reading resource: ${uri}`));
2564
3239
  const resource = await session.readResource(uri);
@@ -2569,13 +3244,16 @@ async function readResourceCommand(uri, options) {
2569
3244
  }
2570
3245
  } catch (error) {
2571
3246
  console.error(formatError(`Failed to read resource: ${error.message}`));
2572
- process.exit(1);
3247
+ await cleanupAndExit(1);
2573
3248
  }
3249
+ await cleanupAndExit(0);
2574
3250
  }
2575
3251
  async function subscribeResourceCommand(uri, options) {
2576
3252
  try {
2577
3253
  const result = await getOrRestoreSession(options.session || null);
2578
- if (!result) return;
3254
+ if (!result) {
3255
+ await cleanupAndExit(1);
3256
+ }
2579
3257
  const { session } = result;
2580
3258
  await session.subscribeToResource(uri);
2581
3259
  console.log(formatSuccess(`Subscribed to resource: ${uri}`));
@@ -2593,13 +3271,15 @@ async function subscribeResourceCommand(uri, options) {
2593
3271
  console.error(
2594
3272
  formatError(`Failed to subscribe to resource: ${error.message}`)
2595
3273
  );
2596
- process.exit(1);
3274
+ await cleanupAndExit(1);
2597
3275
  }
2598
3276
  }
2599
3277
  async function unsubscribeResourceCommand(uri, options) {
2600
3278
  try {
2601
3279
  const result = await getOrRestoreSession(options.session || null);
2602
- if (!result) return;
3280
+ if (!result) {
3281
+ await cleanupAndExit(1);
3282
+ }
2603
3283
  const { session } = result;
2604
3284
  await session.unsubscribeFromResource(uri);
2605
3285
  console.log(formatSuccess(`Unsubscribed from resource: ${uri}`));
@@ -2607,53 +3287,76 @@ async function unsubscribeResourceCommand(uri, options) {
2607
3287
  console.error(
2608
3288
  formatError(`Failed to unsubscribe from resource: ${error.message}`)
2609
3289
  );
2610
- process.exit(1);
3290
+ await cleanupAndExit(1);
2611
3291
  }
3292
+ await cleanupAndExit(0);
2612
3293
  }
2613
3294
  async function listPromptsCommand(options) {
2614
3295
  try {
2615
3296
  const result = await getOrRestoreSession(options.session || null);
2616
- if (!result) return;
3297
+ if (!result) {
3298
+ await cleanupAndExit(1);
3299
+ }
2617
3300
  const { session } = result;
2618
3301
  const promptsResult = await session.listPrompts();
2619
3302
  const prompts = promptsResult.prompts;
2620
3303
  if (options.json) {
2621
3304
  console.log(formatJson(prompts));
2622
- return;
2623
- }
2624
- if (prompts.length === 0) {
2625
- console.log(formatInfo("No prompts available"));
2626
- return;
3305
+ } else if (prompts.length === 0) {
3306
+ if (isStdoutTty()) console.log(formatInfo("No prompts available"));
3307
+ } else {
3308
+ const tty2 = isStdoutTty();
3309
+ if (tty2) {
3310
+ console.log(formatHeader(`Available Prompts (${prompts.length}):`));
3311
+ console.log("");
3312
+ }
3313
+ const tableData = prompts.map((prompt4) => {
3314
+ const args = prompt4.arguments ?? [];
3315
+ const reqCount = Array.isArray(args) ? args.filter((a) => a?.required).length : 0;
3316
+ const total = Array.isArray(args) ? args.length : 0;
3317
+ const argsCell = total === 0 ? source_default.gray("\u2014") : `${reqCount}/${total}`;
3318
+ return {
3319
+ name: source_default.bold(prompt4.name),
3320
+ args: argsCell,
3321
+ description: prompt4.description || source_default.gray("(no description)")
3322
+ };
3323
+ });
3324
+ console.log(
3325
+ formatTable(tableData, [
3326
+ { key: "name", header: "Prompt" },
3327
+ { key: "args", header: "Args" },
3328
+ { key: "description", header: "Description", truncate: true }
3329
+ ])
3330
+ );
2627
3331
  }
2628
- console.log(formatHeader(`Available Prompts (${prompts.length}):`));
2629
- console.log("");
2630
- const tableData = prompts.map((prompt4) => ({
2631
- name: source_default.bold(prompt4.name),
2632
- description: prompt4.description || source_default.gray("No description")
2633
- }));
2634
- console.log(
2635
- formatTable(tableData, [
2636
- { key: "name", header: "Prompt", width: 25 },
2637
- { key: "description", header: "Description", width: 50 }
2638
- ])
2639
- );
2640
3332
  } catch (error) {
2641
3333
  console.error(formatError(`Failed to list prompts: ${error.message}`));
2642
- process.exit(1);
3334
+ await cleanupAndExit(1);
2643
3335
  }
3336
+ await cleanupAndExit(0);
2644
3337
  }
2645
- async function getPromptCommand(promptName, argsJson, options) {
3338
+ async function getPromptCommand(promptName, argsList, options) {
2646
3339
  try {
2647
3340
  const result = await getOrRestoreSession(options?.session || null);
2648
- if (!result) return;
3341
+ if (!result) {
3342
+ await cleanupAndExit(1);
3343
+ }
2649
3344
  const { session } = result;
2650
3345
  let args = {};
2651
- if (argsJson) {
3346
+ if (argsList && argsList.length > 0) {
2652
3347
  try {
2653
- args = JSON.parse(argsJson);
3348
+ args = parsePromptArgs(argsList);
2654
3349
  } catch (error) {
2655
- console.error(formatError("Invalid JSON arguments"));
2656
- return;
3350
+ console.error(formatError(error.message));
3351
+ console.log("");
3352
+ console.log(formatInfo("Usage:"));
3353
+ console.log(
3354
+ ` npx mcp-use client prompts get ${promptName} key=value [key2=value2 ...]`
3355
+ );
3356
+ console.log(
3357
+ ` npx mcp-use client prompts get ${promptName} '{"key":"value"}' # full JSON object`
3358
+ );
3359
+ await cleanupAndExit(1);
2657
3360
  }
2658
3361
  }
2659
3362
  console.error(formatInfo(`Getting prompt '${promptName}'...`));
@@ -2675,8 +3378,9 @@ async function getPromptCommand(promptName, argsJson, options) {
2675
3378
  }
2676
3379
  } catch (error) {
2677
3380
  console.error(formatError(`Failed to get prompt: ${error.message}`));
2678
- process.exit(1);
3381
+ await cleanupAndExit(1);
2679
3382
  }
3383
+ await cleanupAndExit(0);
2680
3384
  }
2681
3385
  async function interactiveCommand(options) {
2682
3386
  try {
@@ -2711,7 +3415,7 @@ async function interactiveCommand(options) {
2711
3415
  source_default.gray(" exit, quit - Exit interactive mode")
2712
3416
  );
2713
3417
  console.log("");
2714
- const rl = (0, import_node_readline.createInterface)({
3418
+ const rl = (0, import_node_readline2.createInterface)({
2715
3419
  input: process.stdin,
2716
3420
  output: process.stdout,
2717
3421
  prompt: source_default.cyan("mcp> ")
@@ -2726,7 +3430,7 @@ async function interactiveCommand(options) {
2726
3430
  if (trimmed === "exit" || trimmed === "quit") {
2727
3431
  console.log(formatInfo("Goodbye!"));
2728
3432
  rl.close();
2729
- process.exit(0);
3433
+ await cleanupAndExit(0);
2730
3434
  }
2731
3435
  const parts = trimmed.split(" ");
2732
3436
  const scope = parts[0];
@@ -2850,23 +3554,29 @@ async function interactiveCommand(options) {
2850
3554
  }
2851
3555
  rl.prompt();
2852
3556
  });
2853
- rl.on("close", () => {
3557
+ rl.on("close", async () => {
2854
3558
  console.log("");
2855
3559
  console.log(formatInfo("Goodbye!"));
2856
- process.exit(0);
3560
+ await cleanupAndExit(0);
2857
3561
  });
2858
3562
  } catch (error) {
2859
3563
  console.error(
2860
3564
  formatError(`Failed to start interactive mode: ${error.message}`)
2861
3565
  );
2862
- process.exit(1);
3566
+ await cleanupAndExit(1);
2863
3567
  }
2864
3568
  }
2865
3569
  function createClientCommand() {
2866
3570
  const clientCommand = new import_commander.Command("client").description(
2867
3571
  "Interactive MCP client for terminal usage"
2868
3572
  );
2869
- clientCommand.command("connect <url>").description("Connect to an MCP server").option("--name <name>", "Session name").option("--stdio", "Use stdio connector instead of HTTP").option("--auth <token>", "Authentication token").action(connectCommand);
3573
+ clientCommand.command("connect <url>").description("Connect to an MCP server").option("--name <name>", "Session name").option("--stdio", "Use stdio connector instead of HTTP").option("--auth <token>", "Static Bearer token (skips OAuth)").option(
3574
+ "--no-oauth",
3575
+ "Don't auto-trigger OAuth on 401; fail with the 401 instead"
3576
+ ).option(
3577
+ "--auth-timeout <ms>",
3578
+ "OAuth loopback wait timeout in ms (default 300000)"
3579
+ ).action(connectCommand);
2870
3580
  clientCommand.command("disconnect [session]").description("Disconnect from a session").option("--all", "Disconnect all sessions").action(disconnectCommand);
2871
3581
  const sessionsCommand = new import_commander.Command("sessions").description(
2872
3582
  "Manage CLI sessions"
@@ -2878,7 +3588,9 @@ function createClientCommand() {
2878
3588
  "Interact with MCP tools"
2879
3589
  );
2880
3590
  toolsCommand.command("list").description("List available tools").option("--session <name>", "Use specific session").option("--json", "Output as JSON").action(listToolsCommand);
2881
- toolsCommand.command("call <name> [args]").description("Call a tool with arguments (JSON string)").option("--session <name>", "Use specific session").option("--timeout <ms>", "Request timeout in milliseconds", parseInt).option("--json", "Output as JSON").action(callToolCommand);
3591
+ toolsCommand.command("call <name> [args...]").description(
3592
+ "Call a tool. Args as key=value pairs (use key:=<json> for nested values, or pass a JSON object)"
3593
+ ).option("--session <name>", "Use specific session").option("--timeout <ms>", "Request timeout in milliseconds", parseInt).option("--json", "Output as JSON").action(callToolCommand);
2882
3594
  toolsCommand.command("describe <name>").description("Show tool details and schema").option("--session <name>", "Use specific session").action(describeToolCommand);
2883
3595
  clientCommand.addCommand(toolsCommand);
2884
3596
  const resourcesCommand = new import_commander.Command("resources").description(
@@ -2893,17 +3605,29 @@ function createClientCommand() {
2893
3605
  "Interact with MCP prompts"
2894
3606
  );
2895
3607
  promptsCommand.command("list").description("List available prompts").option("--session <name>", "Use specific session").option("--json", "Output as JSON").action(listPromptsCommand);
2896
- promptsCommand.command("get <name> [args]").description("Get a prompt with arguments (JSON string)").option("--session <name>", "Use specific session").option("--json", "Output as JSON").action(getPromptCommand);
3608
+ promptsCommand.command("get <name> [args...]").description(
3609
+ "Get a prompt. Args as key=value pairs (or pass a JSON object)"
3610
+ ).option("--session <name>", "Use specific session").option("--json", "Output as JSON").action(getPromptCommand);
2897
3611
  clientCommand.addCommand(promptsCommand);
2898
3612
  clientCommand.command("interactive").description("Start interactive REPL mode").option("--session <name>", "Use specific session").action(interactiveCommand);
3613
+ const authCommand = new import_commander.Command("auth").description(
3614
+ "Manage OAuth tokens for HTTP sessions"
3615
+ );
3616
+ authCommand.command("status [session]").description("Show OAuth token status for a session").action(authStatusCommand);
3617
+ authCommand.command("refresh [session]").description("Force-refresh the OAuth access token").action(authRefreshCommand);
3618
+ authCommand.command("logout [session]").description("Remove stored OAuth tokens for the session's URL").action(authLogoutCommand);
3619
+ clientCommand.addCommand(authCommand);
2899
3620
  return clientCommand;
2900
3621
  }
2901
3622
 
2902
3623
  // src/commands/deploy.ts
3624
+ init_cjs_shims();
2903
3625
  var import_node_fs7 = require("fs");
2904
3626
  var import_node_path5 = __toESM(require("path"), 1);
3627
+ init_open();
2905
3628
 
2906
3629
  // src/utils/git.ts
3630
+ init_cjs_shims();
2907
3631
  var import_node_child_process8 = require("child_process");
2908
3632
  var import_node_util7 = require("util");
2909
3633
  var execFileAsync5 = (0, import_node_util7.promisify)(import_node_child_process8.execFile);
@@ -3039,6 +3763,7 @@ function isGitHubUrl(url) {
3039
3763
  }
3040
3764
 
3041
3765
  // src/utils/cloud-urls.ts
3766
+ init_cjs_shims();
3042
3767
  var GATEWAY_DOMAIN = "run.mcp-use.com";
3043
3768
  function buildGatewayUrl(slugOrId) {
3044
3769
  return `https://${slugOrId}.${GATEWAY_DOMAIN}/mcp`;
@@ -3055,6 +3780,7 @@ function getMcpServerUrlForCloudServer(server) {
3055
3780
  }
3056
3781
 
3057
3782
  // src/utils/project-link.ts
3783
+ init_cjs_shims();
3058
3784
  var import_node_fs6 = require("fs");
3059
3785
  var import_node_path4 = __toESM(require("path"), 1);
3060
3786
  var MCP_USE_DIR = ".mcp-use";
@@ -4277,6 +5003,7 @@ async function deployCommand(options) {
4277
5003
  }
4278
5004
 
4279
5005
  // src/commands/deployments.ts
5006
+ init_cjs_shims();
4280
5007
  var import_commander2 = require("commander");
4281
5008
  async function prompt2(question) {
4282
5009
  const readline = await import("readline");
@@ -4705,9 +5432,11 @@ function createDeploymentsCommand() {
4705
5432
  }
4706
5433
 
4707
5434
  // src/commands/servers.ts
5435
+ init_cjs_shims();
4708
5436
  var import_commander4 = require("commander");
4709
5437
 
4710
5438
  // src/commands/env.ts
5439
+ init_cjs_shims();
4711
5440
  var import_commander3 = require("commander");
4712
5441
  var ALL_ENVS = ["production", "preview", "development"];
4713
5442
  function parseEnvironments(raw) {
@@ -5148,6 +5877,7 @@ function createServersCommand() {
5148
5877
  }
5149
5878
 
5150
5879
  // src/commands/org.ts
5880
+ init_cjs_shims();
5151
5881
  async function ensureLoggedIn() {
5152
5882
  if (!await isLoggedIn()) {
5153
5883
  console.log(source_default.yellow("\u26A0\uFE0F You are not logged in."));
@@ -5255,6 +5985,7 @@ async function orgCurrentCommand() {
5255
5985
  }
5256
5986
 
5257
5987
  // src/commands/skills.ts
5988
+ init_cjs_shims();
5258
5989
  var import_commander5 = require("commander");
5259
5990
  var import_node_fs8 = require("fs");
5260
5991
  var import_node_os5 = require("os");
@@ -5371,6 +6102,7 @@ function createSkillsCommand() {
5371
6102
  }
5372
6103
 
5373
6104
  // src/utils/next-shims.ts
6105
+ init_cjs_shims();
5374
6106
  var import_node_fs9 = require("fs");
5375
6107
  var import_node_path7 = __toESM(require("path"), 1);
5376
6108
  var import_node_url2 = require("url");
@@ -5471,6 +6203,7 @@ function quoteNodeOption(value) {
5471
6203
  }
5472
6204
 
5473
6205
  // src/utils/update-check.ts
6206
+ init_cjs_shims();
5474
6207
  var import_node_fs10 = require("fs");
5475
6208
  var import_promises6 = require("fs/promises");
5476
6209
  var import_node_module = require("module");