toolmenu 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/explain.js CHANGED
@@ -28,6 +28,7 @@ export class Trace {
28
28
  stderrTail = [];
29
29
  stderrLines = 0;
30
30
  stderrPartial = '';
31
+ ownWarning = false;
31
32
  send(method) {
32
33
  this.sent.push({ method, at: Date.now() });
33
34
  }
@@ -64,6 +65,16 @@ export class Trace {
64
65
  const text = clean(line, 240);
65
66
  if (!text)
66
67
  return;
68
+ // Node 22 warns about NODE_USE_ENV_PROXY, which toolmenu sets for stdio servers
69
+ // behind a proxy (connect.ts): toolmenu's doing, not the server's words.
70
+ if (/^\(node:\d+\) \[UNDICI-EHPA\] Warning: EnvHttpProxyAgent is experimental/.test(text)) {
71
+ this.ownWarning = true;
72
+ return;
73
+ }
74
+ const hint = this.ownWarning && text.startsWith('(Use `node --trace-warnings');
75
+ this.ownWarning = false;
76
+ if (hint)
77
+ return;
67
78
  this.stderrLines++;
68
79
  this.stderrTail.push(text);
69
80
  if (this.stderrTail.length > STDERR_LINES)
@@ -164,7 +175,10 @@ const HELP_ROW = /^[ \t]*(?:[a-z][\w.-]*(?: [a-z][\w-]*)?(?: [[<][^\]>]*[\]>])*|
164
175
  /** Help output, even when the "Usage:" line scrolled out of the stderr kept: three table rows or more. */
165
176
  const helpRows = (text) => text.split('\n').filter((l) => HELP_ROW.test(l)).length >= 3;
166
177
  // The subcommands that usually start the MCP server, most specific first.
167
- const SUBCOMMANDS = ['mcp start', 'mcp serve', 'server start', 'mcp', 'stdio', 'serve', 'server', 'start'];
178
+ const SUBCOMMANDS = ['mcp start', 'mcp serve', 'server start', 'mcp', 'stdio', 'serve', 'server', 'start', 'run'];
179
+ // A CLI that names its commands when it gets none: "Unknown command: undefined. Expected
180
+ // 'init' or 'run'." (@cloudflare/mcp-server-cloudflare 0.2.0).
181
+ const EXPECTED_COMMANDS = /\b(?:unknown|invalid|missing|no) (?:sub)?command\b[^\n]*?\bexpected:?\s+((?:["'`][a-z][\w-]*["'`](?:,?\s*(?:or\s+)?)?)+)/i;
168
182
  // An HTTP server's address in its log: "MCP server listening on http://localhost:3001/mcp",
169
183
  // "StreamableHTTP endpoint available at http://127.0.0.1:3333/mcp".
170
184
  const HTTP_URL = /\b(?:listening|available|running|serving|started)\b[^\n]{0,60}?(https?:\/\/[^\s"'<>]+)/gi;
@@ -202,6 +216,10 @@ function offeredSubcommand(text) {
202
216
  for (const m of text.matchAll(/\{([^{}\n]*)\}/g))
203
217
  for (const w of m[1].split(','))
204
218
  offered.add(w.trim());
219
+ const expected = EXPECTED_COMMANDS.exec(text);
220
+ if (expected)
221
+ for (const m of expected[1].matchAll(/["'`]([a-z][\w-]*)["'`]/g))
222
+ offered.add(m[1]);
205
223
  let inUsage = false;
206
224
  for (const line of text.split('\n')) {
207
225
  if (!line.trim()) {
@@ -236,7 +254,7 @@ export function startupHint(trace, command, { exited = true } = {}) {
236
254
  const where = url ?? `http://localhost:${port}/mcp`;
237
255
  return `The server started an HTTP server (${where}) instead of talking on its stdin and stdout. Start it in stdio mode (${flag ? `its output mentions ${flag}` : 'often --stdio or --transport stdio'}), or run toolmenu against the address while the server runs: toolmenu snapshot ${where}`;
238
256
  }
239
- if (exited && (USAGE.some((re) => re.test(text)) || helpRows(text))) {
257
+ if (exited && (USAGE.some((re) => re.test(text)) || helpRows(text) || EXPECTED_COMMANDS.test(text))) {
240
258
  const sub = offeredSubcommand(text);
241
259
  return `The command printed its usage and exited: it wants a subcommand or an argument it wasn't given. ${sub ? `Its usage lists “${sub}”: try ${command} ${sub}` : 'Its usage (above) or its docs say what starts the MCP server: add that after the command.'}`;
242
260
  }
@@ -460,6 +478,28 @@ function rejectedCredentials(stderrText) {
460
478
  return REJECTED.exec(stderrText)?.[0];
461
479
  }
462
480
  const REJECTED_NEXT = "Check the API key or token the server was given (--env, or its config): it's likely wrong, expired or for another account. This is a reading of the server's log, not certain: read its stderr above.";
481
+ /**
482
+ * A proxy this machine sets that Node's built-in fetch ignores: it reads HTTPS_PROXY
483
+ * only with NODE_USE_ENV_PROXY=1 (Node 22.21 and later). Behind such a proxy, every
484
+ * host looks like it doesn't resolve.
485
+ */
486
+ export function ignoredProxy(env = process.env, host) {
487
+ if (env.NODE_USE_ENV_PROXY === '1')
488
+ return undefined;
489
+ // A host NO_PROXY exempts goes direct either way: its DNS failure is its own.
490
+ const exempt = (env.NO_PROXY ?? env.no_proxy ?? '').split(',').map((h) => h.trim().replace(/^\*?\./, '').toLowerCase()).filter(Boolean);
491
+ if (host && exempt.some((h) => h === '*' || host.toLowerCase() === h || host.toLowerCase().endsWith(`.${h}`)))
492
+ return undefined;
493
+ return ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy'].find((k) => env[k]);
494
+ }
495
+ /** What to do about an ignored proxy, for this Node. */
496
+ export function proxyAdvice(proxy, version = process.versions.node) {
497
+ const [major, minor] = version.split('.').map(Number);
498
+ const supported = major > 22 || (major === 22 && minor >= 21);
499
+ return supported
500
+ ? `This machine sets ${proxy}, but Node's fetch only goes through it with NODE_USE_ENV_PROXY=1: rerun as NODE_USE_ENV_PROXY=1 toolmenu ….`
501
+ : `This machine sets ${proxy}, but Node's fetch doesn't go through it, and Node ${version} can't be told to: Node 22.21 or later reads it with NODE_USE_ENV_PROXY=1.`;
502
+ }
463
503
  function firstLine(text) {
464
504
  return clean(text.split('\n')[0], 300);
465
505
  }
@@ -477,9 +517,19 @@ function explainHttp(error, trace, context, target) {
477
517
  const innermost = chain.at(-1);
478
518
  // The network, before any HTTP answer.
479
519
  if (code === 'ENOTFOUND' || code === 'EAI_AGAIN') {
480
- return new ConnectError(code === 'ENOTFOUND' ? `Couldn't find ${host}: the name doesn't resolve (DNS: ENOTFOUND).` : `Couldn't look up ${host}: DNS failed for now (EAI_AGAIN).`, [['url', target.url], ['stage', first]], code === 'ENOTFOUND'
481
- ? "Check the host name for typos. If it's right, the server may have moved or shut down: look up its current URL in its docs or registry entry."
482
- : 'Check this machine\'s network and DNS, then retry.', stage, { cause: error });
520
+ const proxy = ignoredProxy(process.env, host);
521
+ return new ConnectError(code === 'ENOTFOUND' ? `Couldn't find ${host}: the name doesn't resolve (DNS: ENOTFOUND).` : `Couldn't look up ${host}: DNS failed for now (EAI_AGAIN).`, [['url', target.url], ['stage', first], ...(proxy ? [['proxy', `${proxy} is set, but Node's fetch doesn't use it`]] : [])], proxy
522
+ ? proxyAdvice(proxy)
523
+ : code === 'ENOTFOUND'
524
+ ? "Check the host name for typos. If it's right, the server may have moved or shut down: look up its current URL in its docs or registry entry."
525
+ : 'Check this machine\'s network and DNS, then retry.', stage, { cause: error });
526
+ }
527
+ // A proxy that won't open the tunnel (undici: "Proxy response (502) !== 200 when HTTP Tunneling").
528
+ const tunnel = chain.map((e) => /Proxy response \((\d+)\) !== 200 when HTTP Tunneling/.exec(e.message)).find(Boolean);
529
+ if (tunnel) {
530
+ return new ConnectError(`The proxy couldn't open a connection to ${host}: it answered the tunnel request with HTTP ${tunnel[1]}.`, [['url', target.url], ['stage', first]], tunnel[1] === '403' || tunnel[1] === '407'
531
+ ? `The proxy refused ${host}: check what HTTPS_PROXY's policy allows, or run from a machine that can reach it directly.`
532
+ : `The proxy couldn't reach ${host} (often: the host is down or doesn't answer). Check that the server is up, e.g. curl -I ${target.url}, then retry.`, stage, { cause: error });
483
533
  }
484
534
  if (code === 'ECONNREFUSED') {
485
535
  return new ConnectError(`Nothing is listening at ${host}:${port}: the connection was refused (ECONNREFUSED).`, [['url', target.url], ['stage', first]], `Start the server, or check the host and port${url.port ? '' : ` (no port in the URL means ${port})`}.`, stage, { cause: error });
@@ -1,4 +1,4 @@
1
- export type FailureClass = 'auth' | 'environment' | 'network' | 'not-found' | 'client' | 'invalid-arguments' | 'other';
1
+ export type FailureClass = 'auth' | 'payment' | 'environment' | 'network' | 'not-found' | 'client' | 'invalid-arguments' | 'other';
2
2
  /** Failures of the setup (credentials, this machine, the network), not of the server. */
3
3
  export declare const SETUP_FAILURES: Set<FailureClass>;
4
4
  /**
@@ -73,3 +73,14 @@ export declare function setupFailureAdvice(classes: Iterable<FailureClass>, tran
73
73
  fix: string;
74
74
  confidence: 'unsure';
75
75
  };
76
+ /**
77
+ * A result not marked isError whose content is an HTTP auth error in structured form:
78
+ * the API the tool calls said 401 or 403 and the server passed the body on as an
79
+ * answer. Notion's server returns `{"status":401,"object":"error","code":"unauthorized"}`
80
+ * as a plain result. Only a JSON object whose own status or code says so counts, not
81
+ * "401" anywhere in the data. Says what it saw, or undefined.
82
+ */
83
+ export declare function deniedAnswer(result: {
84
+ content?: unknown;
85
+ structuredContent?: unknown;
86
+ }): string | undefined;
package/dist/failures.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * as a finding.
6
6
  */
7
7
  /** Failures of the setup (credentials, this machine, the network), not of the server. */
8
- export const SETUP_FAILURES = new Set(['auth', 'environment', 'network', 'not-found', 'client']);
8
+ export const SETUP_FAILURES = new Set(['auth', 'payment', 'environment', 'network', 'not-found', 'client']);
9
9
  // A tool that asks the client for something toolmenu doesn't offer: "Cannot request
10
10
  // input 'roots' (roots/list): the request's client capabilities do not declare the
11
11
  // required capability" (server-everything's get-roots-list), sampling, elicitation.
@@ -22,6 +22,11 @@ const ENVIRONMENT = /could not find [^.]{0,40}executable|is not found at \/|\bno
22
22
  // Netlify" (Netlify), "The API key you provided was rejected" (Pinecone), "Admin
23
23
  // auth is missing", "Runtime credentials are missing" (securenow). Not a bare
24
24
  // "token": plenty of errors mention one.
25
+ // Hosted servers ask the user to sign in in their own words: "Sign in to Ideal (or create
26
+ // your creator account) to continue", "Connect your Novamris account to read its saved chart".
27
+ const SIGN_IN = /\bsign in to\b|\blog ?in to (?:continue|use)\b|\bconnect your [\w .'-]{1,40}? account\b/i;
28
+ // A paid tool: "Payment required: $0.50 over MPP" (a hosted server), HTTP 402, no credits left.
29
+ const PAYMENT = /\bpayment required\b|\b(?:HTTP|status(?: code)?) 402\b|\binsufficient (?:credits?|balance|funds)\b/i;
25
30
  const AUTH = /\b(?:auth|authentication|credentials?|api[ _-]?key|access token)\b (?:is |are )?missing\b|\bno (?:authentication|auth|credentials?|api[ _-]?keys?|access tokens?|auth tokens?) (?:was |were )?(?:found|provided|configured|set|given)\b|\b(401|403)\b|unauthori[sz]ed|unauth(enticated|error)|forbidden|bad credentials|authori[sz]ation expired|re-?authori[sz]e|not authenticated|not logged (?:in|into)\b(?! to the browser)|authentication (token|failed|required|error)|(invalid|expired|revoked) (api[ _-]?key|access token|token|credentials)|(token|api[ _-]?key|credentials) (is |are )?(not valid|invalid|expired)|(api[ _-]?key|access token|credentials)\b[^.]{0,30}\b(was|were|is|are) (rejected|refused|revoked)|valid (access )?token/i;
26
31
  const NETWORK = /\b(ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|EHOSTUNREACH)\b|socket hang up|getaddrinfo|network error/i;
27
32
  // "Either 'page_id' OR both 'title' and 'space_key' must be provided" (Atlassian),
@@ -164,7 +169,9 @@ export function classifyFailure(text, options = {}) {
164
169
  return 'client';
165
170
  if (ENVIRONMENT.test(text))
166
171
  return 'environment';
167
- if (AUTH.test(text))
172
+ if (PAYMENT.test(text))
173
+ return 'payment';
174
+ if (AUTH.test(text) || SIGN_IN.test(text))
168
175
  return 'auth';
169
176
  if (NETWORK.test(text))
170
177
  return 'network';
@@ -176,6 +183,7 @@ export function classifyFailure(text, options = {}) {
176
183
  }
177
184
  export const FAILURE_LABELS = {
178
185
  auth: 'authentication',
186
+ payment: 'payment (a paid tool)',
179
187
  environment: 'something missing on this machine',
180
188
  network: 'the network',
181
189
  'not-found': 'a 404 on a call that named nothing (usually the account or site behind the credentials)',
@@ -194,6 +202,8 @@ export function setupFailureAdvice(classes, transport) {
194
202
  const steps = [];
195
203
  if (set.has('auth') || set.has('not-found'))
196
204
  steps.push(`If the errors are about credentials, rerun with real ones (${credentials}); a test account is enough.`);
205
+ if (set.has('payment'))
206
+ steps.push('If a tool asks for payment, it can\'t be checked without paying: leave it out of the scenario, or run with an account that has credit.');
197
207
  if (set.has('environment'))
198
208
  steps.push('If something is missing on this machine (a browser, a binary, a module), install it where the server runs, or run the server in its own container image.');
199
209
  if (set.has('client'))
@@ -202,3 +212,45 @@ export function setupFailureAdvice(classes, transport) {
202
212
  steps.push('If the server calls an upstream API, check this machine can reach it (DNS, proxy, firewall).');
203
213
  return { fix: steps.join(' ') || 'Check the quoted errors: they came from before the tool ran.', confidence: 'unsure' };
204
214
  }
215
+ const DENIED_CODES = /^(?:unauthori[sz]ed|unauthenticated|forbidden|invalid_auth|invalid_token|not_authed|authentication_(?:required|failed)|permission_denied)$/i;
216
+ /**
217
+ * A result not marked isError whose content is an HTTP auth error in structured form:
218
+ * the API the tool calls said 401 or 403 and the server passed the body on as an
219
+ * answer. Notion's server returns `{"status":401,"object":"error","code":"unauthorized"}`
220
+ * as a plain result. Only a JSON object whose own status or code says so counts, not
221
+ * "401" anywhere in the data. Says what it saw, or undefined.
222
+ */
223
+ export function deniedAnswer(result) {
224
+ // (A tool that fetches a URL is skipped by the caller: its answer is the page's.)
225
+ const objects = [result.structuredContent];
226
+ for (const c of Array.isArray(result.content) ? result.content : []) {
227
+ const text = c && typeof c === 'object' && 'text' in c && typeof c.text === 'string' ? c.text.trim() : '';
228
+ if (!text.startsWith('{'))
229
+ continue;
230
+ try {
231
+ objects.push(JSON.parse(text));
232
+ }
233
+ catch {
234
+ // not JSON
235
+ }
236
+ }
237
+ for (const o of objects) {
238
+ if (!o || typeof o !== 'object' || Array.isArray(o))
239
+ continue;
240
+ for (const v of [o, o.error]) {
241
+ if (!v || typeof v !== 'object' || Array.isArray(v))
242
+ continue;
243
+ const r = v;
244
+ const status = [r.status, r.statusCode, r.status_code, r.code].find((x) => x === 401 || x === 403 || x === '401' || x === '403');
245
+ const code = [r.code, r.error, r.type].find((x) => typeof x === 'string' && DENIED_CODES.test(x));
246
+ // A status alone may be what the tool was asked to fetch ({"status":403,"body":…});
247
+ // with it, the object has to say it's an error.
248
+ const isError = v !== o || r.object === 'error' || ![undefined, null, false, '', 0].includes(r.error) || typeof r.message === 'string';
249
+ if (code === undefined && (status === undefined || !isError))
250
+ continue;
251
+ const message = typeof r.message === 'string' ? `: ${r.message}` : '';
252
+ return `${status !== undefined ? `HTTP ${status}` : String(code)}${message}`;
253
+ }
254
+ }
255
+ return undefined;
256
+ }
package/dist/help.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const COMMANDS: readonly ['init', 'snapshot', 'diff', 'session', 'history', 'auth'];
1
+ export declare const COMMANDS: readonly ['init', 'snapshot', 'diff', 'session', 'history', 'auth', 'scan', 'explain'];
2
2
  export type Command = (typeof COMMANDS)[number];
3
3
  /** `toolmenu --help`: what toolmenu is and which command to reach for. */
4
4
  export declare function overview(): string;
package/dist/help.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * codes. Option names and behaviour live in cli.ts; this file only describes them.
5
5
  */
6
6
  import { VERSION } from './version.js';
7
- export const COMMANDS = ['init', 'snapshot', 'diff', 'session', 'history', 'auth'];
7
+ export const COMMANDS = ['init', 'snapshot', 'diff', 'session', 'history', 'auth', 'scan', 'explain'];
8
8
  /** Every option, once: its spelling and what it does (continuation lines are indented by the renderer). */
9
9
  const OPTIONS = {
10
10
  out: ['--out <path>', ['where to write the menu (default: menu.json)']],
@@ -30,6 +30,7 @@ const OPTIONS = {
30
30
  plan: ['--plan', ['print the steps without connecting or running anything']],
31
31
  init: ['--init', ["write a starter scenario from the server's menu (to --scenario,", 'default scenario.yml; never overwrites)']],
32
32
  auto: ['--auto', ['build the steps from the menu: every read-only tool whose required', 'arguments the schema can fill (const, default, examples, enum, type),', 'then the first call again']],
33
+ 'create-handles': ['--create-handles', ['with --auto on 2026-07-28, call the tool that creates a session, basket or cart', '(a write, so only with this flag; never one marked destructiveHint) and give', 'the tools that take it back the handle it returned']],
33
34
  'open-world': ['--open-world', ['with --auto, also call read-only tools marked openWorldHint: true', '(web search, fetch, scraping): they may cost API credits']],
34
35
  'max-calls': ['--max-calls <n>', ['with --auto, at most n calls in all, the tools unlocks bring', 'included (default: 20, plus --max-calls-per-unlock for each unlock value)']],
35
36
  'max-calls-per-unlock': ['--max-calls-per-unlock <n>', ['with --auto, at most n calls for the tools each unlock value', 'brings (default: 5), so every toolset gets some']],
@@ -52,6 +53,9 @@ const OPTIONS = {
52
53
  'init-out': ['--out <path>', ['where to write the baseline menu (default: menu.json)']],
53
54
  'with-session': ['--with-session', ['the workflow also runs session --auto (calls read-only tools)']],
54
55
  port: ['--port <n>', ['loopback port for the login redirect (default: 33418)']],
56
+ concurrency: ['--concurrency <n>', ['servers checked at a time (default: 4)']],
57
+ 'out-dir': ['--out-dir <dir>', ["write each server's menu file there, as <name>.json (default: none)"]],
58
+ 'no-browser': ['--no-browser', ["don't open a browser: print the login URL, open it on any device, and paste", 'back the address the browser ends on (over SSH, in a container, on a remote box)']],
55
59
  scope: ['--scope <scopes>', ["scopes to ask for (default: the server's)"]],
56
60
  'client-id': ['--client-id <id>', ['a pre-registered client, for servers without dynamic registration']],
57
61
  'client-secret': ['--client-secret <s>', ['its secret, if it has one']],
@@ -110,7 +114,7 @@ const HELP = {
110
114
  'prompt cache, a different menu in a fresh process.',
111
115
  SERVER_NOTE,
112
116
  ],
113
- own: ['scenario', 'auto', 'init', 'plan', 'value', 'values-file', 'assume-read-only', 'open-world', 'max-calls', 'max-calls-per-unlock', 'save-scenario', 'union-out', 'elicitation'],
117
+ own: ['scenario', 'auto', 'init', 'plan', 'value', 'values-file', 'assume-read-only', 'open-world', 'create-handles', 'max-calls', 'max-calls-per-unlock', 'save-scenario', 'union-out', 'elicitation'],
114
118
  shared: ['config', 'format', 'json', 'fail-on', 'header', 'env', 'no-auth', 'protocol', 'timeout', 'processes'],
115
119
  examples: [
116
120
  'toolmenu session --auto -- node dist/index.js',
@@ -144,7 +148,7 @@ const HELP = {
144
148
  'snapshot and session then use them for that URL (--no-auth to skip).',
145
149
  'Stored in $TOOLMENU_AUTH_DIR, else $XDG_CONFIG_HOME/toolmenu/auth, else ~/.config/toolmenu/auth.',
146
150
  ],
147
- own: ['port', 'scope', 'client-id', 'client-secret'],
151
+ own: ['port', 'no-browser', 'scope', 'client-id', 'client-secret'],
148
152
  shared: [],
149
153
  examples: [
150
154
  'toolmenu auth login https://example.com/mcp',
@@ -153,6 +157,33 @@ const HELP = {
153
157
  ],
154
158
  exits: ['0 done (logout of a URL with no login is not an error)', '2 the login failed, or bad usage'],
155
159
  },
160
+ scan: {
161
+ summary: 'snapshot every server in an MCP client config or a list, side by side',
162
+ usage: ['toolmenu scan [options] <list>'],
163
+ about: [
164
+ 'The list is an MCP client config (Claude Desktop, Claude Code .mcp.json, Cursor,',
165
+ 'VS Code: the mcpServers or servers object, ${VAR} filled from the environment), or a',
166
+ 'text file with one server per line: a URL or a command, optionally "name<TAB>" first.',
167
+ 'Runs snapshot on each (nothing written unless --out-dir). A server that could not be',
168
+ 'started or read is a row that says why, and makes the exit code 2: it was not checked.',
169
+ ],
170
+ own: ['concurrency', 'out-dir'],
171
+ shared: ['config', 'format', 'json', 'fail-on', 'protocol', 'timeout', 'processes'],
172
+ examples: ['toolmenu scan ~/Library/Application\\ Support/Claude/claude_desktop_config.json', 'toolmenu scan .mcp.json --format markdown', 'toolmenu scan servers.txt --concurrency 8 --out-dir menus'],
173
+ exits: ['0 every server checked, no findings at or above --fail-on', '1 findings at or above --fail-on', "2 a server wasn't checked (couldn't start, couldn't connect, a variable not set), or bad usage"],
174
+ },
175
+ explain: {
176
+ summary: 'say what a rule checks, its default level and how to change it',
177
+ usage: ['toolmenu explain <rule>', 'toolmenu explain'],
178
+ about: [
179
+ 'The rule as a finding names it (naming/vague-id), or the part after the slash (vague-id).',
180
+ 'Without a rule, lists every rule by the command that reports it. Offline.',
181
+ ],
182
+ own: [],
183
+ shared: ['format', 'json'],
184
+ examples: ['toolmenu explain naming/vague-id', 'toolmenu explain handle-lifetime', 'toolmenu explain --json diff/param-required'],
185
+ exits: ['0 explained', "2 no such rule (the closest ones are named), or bad usage"],
186
+ },
156
187
  };
157
188
  function optionLines(keys) {
158
189
  const width = Math.max(...keys.map((k) => OPTIONS[k][0].length)) + 2;
package/dist/options.d.ts CHANGED
@@ -2,6 +2,12 @@ export declare const CLI_OPTIONS: {
2
2
  readonly out: {
3
3
  readonly type: 'string';
4
4
  };
5
+ readonly 'out-dir': {
6
+ readonly type: 'string';
7
+ };
8
+ readonly concurrency: {
9
+ readonly type: 'string';
10
+ };
5
11
  readonly 'no-write': {
6
12
  readonly type: 'boolean';
7
13
  };
@@ -53,6 +59,9 @@ export declare const CLI_OPTIONS: {
53
59
  readonly port: {
54
60
  readonly type: 'string';
55
61
  };
62
+ readonly 'no-browser': {
63
+ readonly type: 'boolean';
64
+ };
56
65
  readonly scope: {
57
66
  readonly type: 'string';
58
67
  };
@@ -114,6 +123,9 @@ export declare const CLI_OPTIONS: {
114
123
  readonly auto: {
115
124
  readonly type: 'boolean';
116
125
  };
126
+ readonly 'create-handles': {
127
+ readonly type: 'boolean';
128
+ };
117
129
  readonly 'with-session': {
118
130
  readonly type: 'boolean';
119
131
  };
package/dist/options.js CHANGED
@@ -4,6 +4,8 @@
4
4
  */
5
5
  export const CLI_OPTIONS = {
6
6
  out: { type: 'string' },
7
+ 'out-dir': { type: 'string' },
8
+ concurrency: { type: 'string' },
7
9
  'no-write': { type: 'boolean' },
8
10
  routes: { type: 'string' },
9
11
  config: { type: 'string' },
@@ -20,6 +22,7 @@ export const CLI_OPTIONS = {
20
22
  elicitation: { type: 'string' },
21
23
  'no-auth': { type: 'boolean' },
22
24
  port: { type: 'string' },
25
+ 'no-browser': { type: 'boolean' },
23
26
  scope: { type: 'string' },
24
27
  'client-id': { type: 'string' },
25
28
  'client-secret': { type: 'string' },
@@ -40,6 +43,7 @@ export const CLI_OPTIONS = {
40
43
  init: { type: 'boolean' },
41
44
  'union-out': { type: 'string' },
42
45
  auto: { type: 'boolean' },
46
+ 'create-handles': { type: 'boolean' },
43
47
  'with-session': { type: 'boolean' },
44
48
  catalog: { type: 'boolean' },
45
49
  'open-world': { type: 'boolean' },
package/dist/report.d.ts CHANGED
@@ -6,7 +6,10 @@ import { type Finding, type Menu, type Severity } from './types.js';
6
6
  export type Format = 'text' | 'json' | 'github' | 'markdown';
7
7
  export declare function counts(findings: Finding[]): Record<Severity, number>;
8
8
  export declare function formatSnapshot(menu: Menu, findings: Finding[], format: Format, outPath?: string, cost?: ClientCost, notOffered?: string[]): string;
9
+ export declare function findingLines(findings: Finding[]): string[];
10
+ export declare function githubLines(findings: Finding[]): string[];
9
11
  export declare function formatDiff(d: DiffResult, beforeTools: number, afterTools: number, format: Format): string;
10
12
  export declare function formatHistory(h: HistoryResult, format: Format, outDir: string, csvPath?: string): string;
11
13
  export declare function formatSession(s: SessionResult, format: Format): string;
12
14
  export declare function formatPlan(scenario: Scenario, name: string): string;
15
+ export declare function mdFindings(findings: Finding[]): string[];
package/dist/report.js CHANGED
@@ -87,7 +87,7 @@ export function formatSnapshot(menu, findings, format, outPath, cost, notOffered
87
87
  function mdBreakdown(menu) {
88
88
  return breakdownMarkdown(breakdown(menu), menu.tools.length);
89
89
  }
90
- function findingLines(findings) {
90
+ export function findingLines(findings) {
91
91
  const lines = [];
92
92
  for (const f of findings) {
93
93
  lines.push(`${LABEL[f.severity]} ${f.rule}${unsureMark(f)}`);
@@ -106,7 +106,7 @@ function summaryLine(findings) {
106
106
  const mark = c.error ? '✗' : c.warn ? '!' : '✓';
107
107
  return `${mark} ${plural(c.error, 'error')}, ${plural(c.warn, 'warning')}, ${c.info} info`;
108
108
  }
109
- function githubLines(findings) {
109
+ export function githubLines(findings) {
110
110
  return findings.map((f) => {
111
111
  const level = f.severity === 'error' ? 'error' : f.severity === 'warn' ? 'warning' : 'notice';
112
112
  const body = [f.message, ...(f.detail ?? []), ...(f.fix ? [`→ Next: ${f.fix}`] : [])].join('\n').replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
@@ -534,7 +534,7 @@ function stepPrefix(f, prefix) {
534
534
  function mdCell(text) {
535
535
  return text.replace(/\|/g, '\\|').replace(/\n/g, ' ');
536
536
  }
537
- function mdFindings(findings) {
537
+ export function mdFindings(findings) {
538
538
  if (findings.length === 0)
539
539
  return ['No findings.'];
540
540
  const row = (f) => `| ${f.severity === 'error' ? '**error**' : f.severity} | \`${f.rule}\`${f.confidence === 'unsure' ? ' · _unsure_' : ''} | ${mdCell([f.message, ...(f.detail ?? [])].join(' · '))}${f.fix ? `<br>**→ Next:** ${mdCell(f.fix)}` : ''} |`;
@@ -0,0 +1,26 @@
1
+ export interface RuleDoc {
2
+ command: string;
3
+ severity: string;
4
+ text: string;
5
+ }
6
+ export declare function ruleDocs(): Record<string, RuleDoc>;
7
+ /**
8
+ * The rule a name means: the id itself, or the part after the slash when only one
9
+ * rule ends that way (vague-id → naming/vague-id). Otherwise the ids close to it.
10
+ */
11
+ export declare function findRule(name: string): {
12
+ id: string;
13
+ } | {
14
+ near: string[];
15
+ };
16
+ export interface Explained extends RuleDoc {
17
+ rule: string;
18
+ /** diff rules: what the change means for semver. */
19
+ class?: string;
20
+ /** Menu rules: the protocol version the rule applies from. */
21
+ since?: string;
22
+ }
23
+ export declare function explain(id: string): Explained;
24
+ export declare function formatExplained(e: Explained): string;
25
+ /** `toolmenu explain` with no rule: every id, by command. */
26
+ export declare function listRules(): string;
@@ -0,0 +1,88 @@
1
+ /*
2
+ * `toolmenu explain <rule>`: one entry of docs/RULES.md, which the build copies to
3
+ * dist/rule-docs.json (docs/ isn't in the npm package).
4
+ */
5
+ import { readFileSync } from 'node:fs';
6
+ import { DIFF_RULES } from './diff.js';
7
+ import { MENU_RULES } from './rules/index.js';
8
+ import { editDistance } from './words.js';
9
+ let cache;
10
+ export function ruleDocs() {
11
+ cache ??= JSON.parse(readFileSync(new URL('./rule-docs.json', import.meta.url), 'utf8'));
12
+ return cache;
13
+ }
14
+ /** Markdown out of a table cell, for a terminal: `code` and **bold** as plain words. */
15
+ function plain(text) {
16
+ return text.replace(/\*\*([^*]+)\*\*/g, '$1').replace(/`([^`]+)`/g, '$1');
17
+ }
18
+ function wrap(text, width, indent) {
19
+ const lines = [];
20
+ let line = '';
21
+ for (const word of text.split(/\s+/)) {
22
+ if (line && line.length + 1 + word.length > width) {
23
+ lines.push(indent + line);
24
+ line = word;
25
+ }
26
+ else
27
+ line = line ? `${line} ${word}` : word;
28
+ }
29
+ if (line)
30
+ lines.push(indent + line);
31
+ return lines;
32
+ }
33
+ /**
34
+ * The rule a name means: the id itself, or the part after the slash when only one
35
+ * rule ends that way (vague-id → naming/vague-id). Otherwise the ids close to it.
36
+ */
37
+ export function findRule(name) {
38
+ const docs = ruleDocs();
39
+ const wanted = name.trim().toLowerCase();
40
+ if (Object.hasOwn(docs, wanted))
41
+ return { id: wanted };
42
+ const ids = Object.keys(docs);
43
+ const tail = ids.filter((id) => id.split('/')[1] === wanted);
44
+ if (tail.length === 1)
45
+ return { id: tail[0] };
46
+ if (tail.length > 1)
47
+ return { near: tail };
48
+ const scored = ids
49
+ .map((id) => ({ id, d: Math.min(editDistance(wanted, id), editDistance(wanted, id.split('/')[1]) + (wanted.includes('/') ? 99 : 0)) }))
50
+ .filter((x) => x.d <= Math.max(2, Math.floor(wanted.length / 4)));
51
+ const contains = ids.filter((id) => wanted.length >= 3 && id.includes(wanted));
52
+ const near = [...new Set([...scored.sort((a, b) => a.d - b.d).map((x) => x.id), ...contains])];
53
+ return { near: near.slice(0, 5) };
54
+ }
55
+ export function explain(id) {
56
+ const doc = ruleDocs()[id];
57
+ const menu = MENU_RULES.find((r) => r.id === id);
58
+ const diff = Object.hasOwn(DIFF_RULES, id) ? DIFF_RULES[id] : undefined;
59
+ return {
60
+ rule: id,
61
+ ...doc,
62
+ severity: doc.severity.replace(/ \((?:breaking|minor|notice)\)$/, ''),
63
+ ...(diff?.class ? { class: diff.class } : {}),
64
+ ...(menu?.since ? { since: menu.since } : {}),
65
+ };
66
+ }
67
+ export function formatExplained(e) {
68
+ return [
69
+ `${e.rule} (${e.command}, ${e.severity}${e.class ? `, ${e.class}` : ''})`,
70
+ '',
71
+ ...wrap(plain(e.text), 86, ' '),
72
+ ...(e.since ? ['', ` Checked on servers that speak ${e.since} or later.`] : []),
73
+ '',
74
+ ` Change its level, or turn it off, in toolmenu.config.json:`,
75
+ ` { "rules": { "${e.rule}": "off" } } (or "error", "warn", "info")`,
76
+ '',
77
+ ].join('\n');
78
+ }
79
+ /** `toolmenu explain` with no rule: every id, by command. */
80
+ export function listRules() {
81
+ const by = new Map();
82
+ for (const [id, doc] of Object.entries(ruleDocs()))
83
+ by.set(doc.command, [...(by.get(doc.command) ?? []), id]);
84
+ const out = ['Rules, by the command that reports them. toolmenu explain <rule> says what one checks.', ''];
85
+ for (const [command, ids] of by)
86
+ out.push(`${command}:`, ...wrap(ids.join(' '), 86, ' '), '');
87
+ return out.join('\n');
88
+ }