@agntn/tools 0.2.0 → 0.2.2

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/cli.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { Convert } from "./_chunks/libs/typebox.mjs";
1
+ import { Check } from "./_chunks/libs/typebox.mjs";
2
2
  import { ToolDefinitionError, ToolInputError, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText } from "./_chunks/src.mjs";
3
3
  import { readFileSync } from "node:fs";
4
4
  import { parseArgs } from "node:util";
@@ -8,6 +8,8 @@ const RESERVED_FLAGS = /* @__PURE__ */ new Set([
8
8
  "version",
9
9
  "json"
10
10
  ]);
11
+ const TEXT_KINDS = /* @__PURE__ */ new Set(["string", "enum"]);
12
+ const SHORT_FLAG = /^[a-z]$/i;
11
13
  const TYPE_KINDS = /* @__PURE__ */ new Map([
12
14
  ["boolean", "boolean"],
13
15
  ["integer", "number"],
@@ -34,13 +36,39 @@ function fieldKind(schema) {
34
36
  if ((Array.isArray(schema.anyOf) ? schema.anyOf : []).some((branch) => fieldKind(branch) === "json")) return "json";
35
37
  return TYPE_KINDS.get(schema.type) ?? "string";
36
38
  }
37
- function toolFields(tool) {
39
+ function textItems(schema) {
40
+ const { items } = schema;
41
+ if (schema.type !== "array" || typeof items !== "object" || items === null) return void 0;
42
+ if (Array.isArray(items)) return void 0;
43
+ return unionBranches(items).every(takesText) ? items : void 0;
44
+ }
45
+ function takesText(branch) {
46
+ if (branch.type === "string" || typeof branch.const === "string") return true;
47
+ return Array.isArray(branch.enum) && branch.enum.every((value) => typeof value === "string");
48
+ }
49
+ function cliHints(tool) {
50
+ const cli = tool.cli ?? {};
51
+ const rest = cli.rest === void 0 ? [] : [cli.rest];
52
+ const hints = {
53
+ positional: [...cli.positional ?? [], ...rest],
54
+ rest,
55
+ short: cli.short ?? {},
56
+ stdin: cli.stdin ?? []
57
+ };
38
58
  const properties = tool.input.properties;
39
- const positional = tool.cli?.positional ?? [];
40
- const stdin = tool.cli?.stdin ?? [];
41
- for (const key of [...positional, ...stdin]) if (!Object.hasOwn(properties, key)) throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);
59
+ for (const key of [
60
+ ...hints.positional,
61
+ ...Object.keys(hints.short),
62
+ ...hints.stdin
63
+ ]) if (!Object.hasOwn(properties, key)) throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);
64
+ const { positional } = hints;
42
65
  const repeated = positional.find((key, index) => positional.indexOf(key) !== index);
43
66
  if (repeated !== void 0) throw new ToolDefinitionError(`${tool.name}: cli hint lists positional ${repeated} twice`);
67
+ return hints;
68
+ }
69
+ function toolFields(tool) {
70
+ const properties = tool.input.properties;
71
+ const { positional, rest, short, stdin } = cliHints(tool);
44
72
  const keys = [...positional, ...Object.keys(properties).filter((key) => !positional.includes(key))];
45
73
  const required = tool.input.required ?? [];
46
74
  const flags = /* @__PURE__ */ new Set();
@@ -52,9 +80,13 @@ function toolFields(tool) {
52
80
  flag: flagName(key),
53
81
  kind: fieldKind(properties[key] ?? {}),
54
82
  positional: positional.includes(key),
83
+ rest: rest.includes(key),
84
+ restItems: rest.includes(key) ? textItems(properties[key] ?? {}) : void 0,
85
+ short: Object.hasOwn(short, key) ? short[key] : void 0,
55
86
  stdin: stdin.includes(key)
56
87
  };
57
88
  assertField(tool, field, !field.positional && flags.has(field.flag));
89
+ assertShort(tool, field);
58
90
  if (!field.positional) flags.add(field.flag);
59
91
  return field;
60
92
  });
@@ -71,7 +103,17 @@ function assertField(tool, field, taken) {
71
103
  if (!field.positional) assertFlag(tool, field);
72
104
  if (taken) throw new ToolDefinitionError(`${tool.name}: two properties take the flag --${field.flag}`);
73
105
  if (field.positional && field.kind === "boolean") throw new ToolDefinitionError(`${tool.name}: boolean property ${field.key} cannot be positional`);
106
+ assertTextHints(tool, field);
107
+ }
108
+ function assertTextHints(tool, field) {
74
109
  if (field.stdin && field.kind !== "string") throw new ToolDefinitionError(`${tool.name}: stdin property ${field.key} must be a string`);
110
+ if (field.rest && field.restItems === void 0 && !TEXT_KINDS.has(field.kind)) throw new ToolDefinitionError(`${tool.name}: rest property ${field.key} must be a string or an array of strings`);
111
+ }
112
+ function assertShort(tool, field) {
113
+ if (field.short === void 0) return;
114
+ if (field.positional) throw new ToolDefinitionError(`${tool.name}: positional property ${field.key} takes no short flag`);
115
+ if (!SHORT_FLAG.test(field.short)) throw new ToolDefinitionError(`${tool.name}: short flag ${JSON.stringify(field.short)} of ${field.key} must match ${SHORT_FLAG}`);
116
+ if (field.short === "h") throw new ToolDefinitionError(`${tool.name}: property ${field.key} takes -h, which asks for help`);
75
117
  }
76
118
  function assertRequiredPositionalsFirst(tool, fields) {
77
119
  const positional = fields.filter((field) => field.positional);
@@ -82,10 +124,15 @@ function assertRequiredPositionalsFirst(tool, fields) {
82
124
  function assertOneOptionPerSpelling(tool, fields) {
83
125
  const owners = /* @__PURE__ */ new Map();
84
126
  for (const field of fields.filter((each) => !each.positional)) {
85
- const negation = field.kind === "boolean" ? [`no-${field.flag}`] : [];
86
- for (const spelling of [field.flag, ...negation]) {
127
+ const negation = field.kind === "boolean" ? [`--no-${field.flag}`] : [];
128
+ const short = field.short === void 0 ? [] : [`-${field.short}`];
129
+ for (const spelling of [
130
+ `--${field.flag}`,
131
+ ...negation,
132
+ ...short
133
+ ]) {
87
134
  const owner = owners.get(spelling);
88
- if (owner !== void 0) throw new ToolDefinitionError(`${tool.name}: properties ${owner} and ${field.key} both answer to --${spelling}`);
135
+ if (owner !== void 0) throw new ToolDefinitionError(`${tool.name}: properties ${owner} and ${field.key} both answer to ${spelling}`);
89
136
  owners.set(spelling, field.key);
90
137
  }
91
138
  }
@@ -102,32 +149,38 @@ function valueHint(field) {
102
149
  if (field.kind === "enum") return field.schema.enum.join("|");
103
150
  return field.kind === "string" ? field.flag : field.kind;
104
151
  }
152
+ function optionSpelling(field) {
153
+ return field.kind === "boolean" ? `--[no-]${field.flag}` : `--${field.flag}=<${valueHint(field)}>`;
154
+ }
105
155
  function emptyRecord() {
106
156
  return Object.create(null);
107
157
  }
108
158
  function parseWords(rawArgs, fields, takesJson) {
109
159
  const entries = [...fields.filter((field) => !field.positional).map((field) => [field.flag, field]), ...takesJson ? [["json", "json"]] : []];
110
160
  const options = Object.fromEntries(entries);
161
+ const { args, origins, texts, refused } = takeDashedText(rawArgs, fields, options);
111
162
  const { tokens } = parseArgs({
112
- args: [...rawArgs],
113
- options: Object.fromEntries(Object.entries(options).map(([flag, field]) => [flag, { type: field === "json" || field.kind === "boolean" ? "boolean" : "string" }])),
163
+ args,
164
+ options: Object.fromEntries(Object.entries(options).map(([flag, field]) => [flag, field === "json" ? { type: "boolean" } : {
165
+ type: field.kind === "boolean" ? "boolean" : "string",
166
+ ...field.short === void 0 ? {} : { short: field.short }
167
+ }])),
114
168
  strict: false,
115
169
  allowPositionals: true,
116
170
  allowNegative: true,
117
171
  tokens: true
118
172
  });
119
173
  const values = emptyRecord();
120
- const errors = [];
121
- const positionals = [];
174
+ const errors = refused.map((word) => unknownOption(options, word));
122
175
  const flags = /* @__PURE__ */ new Set();
123
176
  for (const token of tokens) {
124
- if (token.kind === "positional") positionals.push(token.value);
125
177
  if (token.kind !== "option") continue;
126
- const read = readOption(options, token, rawArgs[token.index] ?? "", Object.keys(values));
178
+ const read = readOption(options, token, args[token.index] ?? "", Object.keys(values));
127
179
  if ("error" in read) errors.push(read.error);
128
180
  else if ("flag" in read) flags.add(read.flag);
129
181
  else values[read.key] = read.value;
130
182
  }
183
+ const positionals = inLineOrder(tokens, origins, texts);
131
184
  return {
132
185
  values: Object.assign(values, positionalValues(fields, positionals)),
133
186
  json: flags.has("json"),
@@ -135,14 +188,76 @@ function parseWords(rawArgs, fields, takesJson) {
135
188
  errors: [...new Set(errors.length > 0 ? errors : extraPositionals(fields, positionals))]
136
189
  };
137
190
  }
191
+ function takeDashedText(rawArgs, fields, options) {
192
+ const { dashed, plain } = scanWords(rawArgs, options);
193
+ const free = fields.filter((field) => field.positional).length - plain;
194
+ const taken = dashed.slice(0, Math.max(free, 0));
195
+ const skipped = new Set(dashed);
196
+ const origins = rawArgs.flatMap((_, index) => skipped.has(index) ? [] : [index]);
197
+ const word = (index) => rawArgs[index] ?? "";
198
+ return {
199
+ args: origins.map(word),
200
+ origins,
201
+ texts: taken.map((index) => [index, word(index)]),
202
+ refused: dashed.slice(taken.length).map(word)
203
+ };
204
+ }
205
+ function scanWords(rawArgs, options) {
206
+ const dashed = [];
207
+ let plain = 0;
208
+ for (let index = 0; index < rawArgs.length; index++) {
209
+ const word = rawArgs[index] ?? "";
210
+ if (word === "--") return {
211
+ dashed,
212
+ plain: plain + rawArgs.length - index - 1
213
+ };
214
+ const kind = wordKind(word, options);
215
+ if (kind === "plain") plain++;
216
+ else if (kind === "text") dashed.push(index);
217
+ else if (kind === "valued") index++;
218
+ }
219
+ return {
220
+ dashed,
221
+ plain
222
+ };
223
+ }
224
+ function wordKind(word, options) {
225
+ if (!word.startsWith("-") || word === "-") return "plain";
226
+ if (word === "-h") return "option";
227
+ const field = word.startsWith("--") ? longField(word.slice(2), options) : shortField(word, options);
228
+ if (field === void 0) return "text";
229
+ if (field === "option" || field.kind === "boolean" || word.includes("=")) return "option";
230
+ return "valued";
231
+ }
232
+ function inLineOrder(tokens, origins, texts) {
233
+ const read = tokens.flatMap((token) => token.kind === "positional" ? [[origins[token.index] ?? 0, token.value ?? ""]] : []);
234
+ return [...texts, ...read].toSorted(([a], [b]) => a - b).map(([, word]) => word);
235
+ }
236
+ function longField(spelled, options) {
237
+ const [name = ""] = spelled.split("=", 1);
238
+ if (name === "help") return "option";
239
+ const field = Object.hasOwn(options, name) ? options[name] : void 0;
240
+ if (field !== void 0) return field === "json" ? "option" : field;
241
+ return negatesBoolean(name, options) ? "option" : void 0;
242
+ }
243
+ function negatesBoolean(name, options) {
244
+ const flag = name.slice(3);
245
+ const field = name.startsWith("no-") && Object.hasOwn(options, flag) ? options[flag] : void 0;
246
+ return field !== void 0 && field !== "json" && field.kind === "boolean";
247
+ }
248
+ function shortField(word, options) {
249
+ return Object.values(options).find((field) => field !== "json" && field.short !== void 0 && `-${field.short}` === word);
250
+ }
138
251
  function positionalValues(fields, positionals) {
139
252
  const takes = fields.filter((field) => field.positional);
140
253
  return Object.assign(emptyRecord(), Object.fromEntries(takes.flatMap((field, index) => {
141
- const value = positionals[index];
142
- return value === void 0 ? [] : [[field.key, value]];
254
+ const words = field.rest ? positionals.slice(index) : positionals.slice(index, index + 1);
255
+ if (field.restItems !== void 0) return words.length > 0 || field.required ? [[field.key, words]] : [];
256
+ return words.length === 0 ? [] : [[field.key, words.join(" ")]];
143
257
  })));
144
258
  }
145
259
  function extraPositionals(fields, positionals) {
260
+ if (fields.some((field) => field.rest)) return [];
146
261
  const extra = positionals.length - fields.filter((field) => field.positional).length;
147
262
  if (extra <= 0) return [];
148
263
  return [`Invalid arguments: ${extra} unexpected positional argument${extra === 1 ? "" : "s"}`];
@@ -154,20 +269,25 @@ function optionField(options, token, word) {
154
269
  if (asksHelp(token, word)) return "help";
155
270
  const field = Object.hasOwn(options, token.name) ? options[token.name] : void 0;
156
271
  if (field === "json") return token.rawName === "--json" ? field : void 0;
157
- if (field === void 0 || token.rawName === `--${token.name}`) return field;
158
- return token.rawName === `--no-${token.name}` && field.kind === "boolean" ? field : void 0;
272
+ return field !== void 0 && spells(field, token, word) ? field : void 0;
273
+ }
274
+ function spells(field, token, word) {
275
+ if (token.rawName === `--${field.flag}`) return true;
276
+ if (field.short !== void 0 && token.rawName === `-${field.short}`) return word === token.rawName;
277
+ return field.kind === "boolean" && token.rawName === `--no-${field.flag}`;
278
+ }
279
+ function unknownOption(options, word) {
280
+ const flags = Object.entries(options).map(([flag, each]) => each === "json" || each.short === void 0 ? `--${flag}` : `--${flag} (-${each.short})`);
281
+ const takes = flags.length > 0 ? flags.join(", ") : "no options";
282
+ return `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}`;
159
283
  }
160
284
  function readOption(options, token, word, seen) {
161
285
  const field = optionField(options, token, word);
162
- if (field === void 0) {
163
- const flags = Object.keys(options).map((flag) => `--${flag}`);
164
- const takes = flags.length > 0 ? flags.join(", ") : "no options";
165
- return { error: `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}` };
166
- }
286
+ if (field === void 0) return { error: unknownOption(options, word) };
167
287
  if (field === "json" || field === "help") return token.inlineValue === true ? { error: `Invalid arguments: ${token.rawName} takes no value` } : { flag: field };
168
288
  const problem = optionProblem(field, token, seen.includes(field.key));
169
289
  if (problem !== void 0) return { error: `Invalid arguments: --${field.flag} ${problem}` };
170
- const value = field.kind === "boolean" ? token.rawName === `--${field.flag}` : token.value;
290
+ const value = field.kind === "boolean" ? token.rawName !== `--no-${field.flag}` : token.value;
171
291
  return {
172
292
  key: field.key,
173
293
  value: value ?? ""
@@ -189,19 +309,65 @@ function readStdin() {
189
309
  throw error;
190
310
  }
191
311
  }
312
+ const DECIMAL_INTEGER = /^[+-]?\d+$/;
313
+ const DECIMAL_NUMBER = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
314
+ function numberValue(integer, word) {
315
+ const value = Number(word);
316
+ if ((integer ? DECIMAL_INTEGER : DECIMAL_NUMBER).test(word) && Number.isFinite(value)) return { value };
317
+ return { error: integer ? "must be integer" : "must be number" };
318
+ }
319
+ const LITERAL_TYPES = /* @__PURE__ */ new Set([
320
+ "string",
321
+ "number",
322
+ "boolean"
323
+ ]);
324
+ const TYPE_LITERALS = /* @__PURE__ */ new Map([["null", [null]], ["boolean", [true, false]]]);
325
+ function literalValue(values, word) {
326
+ const spelled = (item) => (item === null || LITERAL_TYPES.has(typeof item)) && String(item) === word;
327
+ return values.some(spelled) ? { value: values.find(spelled) } : void 0;
328
+ }
329
+ function branchValue(branch, word) {
330
+ if (Object.hasOwn(branch, "const")) return literalValue([branch.const], word);
331
+ if (Array.isArray(branch.enum)) return literalValue(branch.enum, word);
332
+ const literals = TYPE_LITERALS.get(branch.type);
333
+ if (literals !== void 0) return literalValue(literals, word);
334
+ if (TYPE_KINDS.get(branch.type) !== "number") return void 0;
335
+ const read = numberValue(branch.type === "integer", word);
336
+ return "value" in read ? read : void 0;
337
+ }
338
+ function unionBranches(schema) {
339
+ const union = schema.anyOf ?? schema.oneOf ?? schema.allOf;
340
+ if (Array.isArray(union)) return union.flatMap(unionBranches);
341
+ if (!Array.isArray(schema.type)) return [schema];
342
+ return schema.type.map((type) => ({
343
+ ...schema,
344
+ type
345
+ }));
346
+ }
347
+ function wordValue(schema, word) {
348
+ const readings = [word, ...unionBranches(schema).flatMap((branch) => {
349
+ const read = branchValue(branch, word);
350
+ return read === void 0 ? [] : [read.value];
351
+ })];
352
+ const index = readings.findIndex((value) => Check(schema, value));
353
+ return index === -1 ? word : readings[index];
354
+ }
192
355
  function fieldValue(field, raw) {
193
356
  if (field.stdin && raw === "-") {
194
357
  const text = readStdin();
195
358
  return text === void 0 ? { error: "stdin is not UTF-8 text" } : { value: text };
196
359
  }
197
- if (field.kind !== "json" || typeof raw !== "string") return { value: raw };
360
+ if (typeof raw !== "string") return { value: raw };
361
+ if (field.kind === "number") return numberValue(field.schema.type === "integer", raw);
362
+ if (field.kind === "string") return { value: wordValue(field.schema, raw) };
363
+ if (field.kind !== "json") return { value: raw };
198
364
  try {
199
365
  return { value: JSON.parse(raw) };
200
366
  } catch {
201
367
  return { error: "must be JSON" };
202
368
  }
203
369
  }
204
- function toolInput(tool, fields, values) {
370
+ function toolInput(fields, values) {
205
371
  const input = emptyRecord();
206
372
  const fromStdin = fields.filter((field) => field.stdin && values[field.key] === "-");
207
373
  if (fromStdin.length > 1) throw new ToolInputError([`Invalid arguments: stdin can feed one argument, not ${fromStdin.map((field) => field.key).join(" and ")}`]);
@@ -209,12 +375,12 @@ function toolInput(tool, fields, values) {
209
375
  for (const field of fields) {
210
376
  const raw = values[field.key];
211
377
  if (raw === void 0) continue;
212
- const read = fieldValue(field, raw);
378
+ const read = typeof raw === "object" ? { value: raw.map((word) => wordValue(field.restItems ?? {}, word)) } : fieldValue(field, raw);
213
379
  if ("error" in read) errors.push(`Invalid arguments at /${field.key}: ${read.error}`);
214
380
  else input[field.key] = read.value;
215
381
  }
216
382
  if (errors.length > 0) throw new ToolInputError(errors);
217
- return Convert(tool.input, input);
383
+ return input;
218
384
  }
219
385
  function writeLine(stream, text) {
220
386
  process[stream].write(text.endsWith("\n") ? text : `${text}\n`);
@@ -232,6 +398,59 @@ function detailsJson(details) {
232
398
  return (JSON.stringify(details, (_key, value) => typeof value === "bigint" ? value.toString() : value, 2) ?? "null").replaceAll(JSON_FORGING, (character) => `\\u${(character.codePointAt(0) ?? 0).toString(16).padStart(4, "0")}`);
233
399
  }
234
400
  const JSON_FORGING = /[\u007F-\u009F\u061C\u200E\u200F\u2028\u2029\u202A-\u202E\u2066-\u206F]/g;
401
+ const GRAPHEMES = new Intl.Segmenter();
402
+ const WIDE = /^(?:\p{Extended_Pictographic}|[\u1100-\u115F\u231A\u231B\u2329\u232A\u2630-\u2637\u268A-\u268F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DFF\u4E00-\u9FFF\uA000-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6\u{16FE0}-\u{18DFF}\u{1AFF0}-\u{1B2FF}\u{1D15E}-\u{1D164}\u{1D1BB}-\u{1D1C0}\u{1D300}-\u{1D376}\u{1F000}-\u{1FAFF}\u{20000}-\u{3FFFD}])$/u;
403
+ const EMOJI = /^\p{RGI_Emoji}$/v;
404
+ const ZERO_WIDTH = /^[\p{Mn}\p{Me}]$/u;
405
+ function pointCells(point) {
406
+ if (WIDE.test(point)) return 2;
407
+ return ZERO_WIDTH.test(point) ? 0 : 1;
408
+ }
409
+ function graphemeCells(grapheme) {
410
+ let size = 0;
411
+ for (const point of grapheme.normalize("NFC")) size += pointCells(point);
412
+ return Math.max(EMOJI.test(grapheme) ? 2 : 1, size);
413
+ }
414
+ function fitLine(text, room) {
415
+ let fitted = "";
416
+ let used = 0;
417
+ for (const { segment } of GRAPHEMES.segment(text)) {
418
+ const size = graphemeCells(segment);
419
+ if (used + size > room) break;
420
+ fitted += segment;
421
+ used += size;
422
+ }
423
+ return {
424
+ text: fitted,
425
+ cells: used
426
+ };
427
+ }
428
+ function progressText(message, amount) {
429
+ const { progress, total } = amount ?? { progress: NaN };
430
+ if (!Number.isFinite(progress) || !Number.isFinite(total)) return message;
431
+ return `${message} (${progress}/${total})`.trim();
432
+ }
433
+ function progressLine() {
434
+ const stream = process.stderr;
435
+ if (stream.isTTY !== true) return {
436
+ context: {},
437
+ wipe() {}
438
+ };
439
+ let width = 0;
440
+ const wipe = () => {
441
+ if (width > 0) stream.write(`\r${" ".repeat(width)}\r`);
442
+ width = 0;
443
+ };
444
+ return {
445
+ context: { progress(message, amount) {
446
+ const line = fitLine(progressText(message, amount), Math.max(1, (stream.columns || 80) - 1));
447
+ wipe();
448
+ stream.write(line.text);
449
+ width = line.cells;
450
+ } },
451
+ wipe
452
+ };
453
+ }
235
454
  function toolCommand(tool) {
236
455
  const fields = toolFields(tool);
237
456
  const [summary = tool.title] = tool.description.split(/(?<=[.!?])\s/, 1);
@@ -240,14 +459,27 @@ function toolCommand(tool) {
240
459
  aliases: (tool.cli?.aliases ?? []).map((alias) => commandWord(tool.name, alias)),
241
460
  summary: tool.cli?.description ?? summary,
242
461
  fields,
243
- json: true,
462
+ json: tool.cli?.json !== false,
244
463
  async run(words) {
245
- const result = await invokeTool(tool, toolInput(tool, fields, words.values));
464
+ const host = {
465
+ cli: true,
466
+ json: words.json
467
+ };
468
+ const line = progressLine();
469
+ let result;
470
+ try {
471
+ result = await invokeTool(tool, toolInput(fields, words.values), {
472
+ ...line.context,
473
+ host
474
+ });
475
+ } finally {
476
+ line.wipe();
477
+ }
246
478
  if (result.isError === true) {
247
479
  writeLine("stderr", sanitizeText(resultText(result)));
248
480
  process.exitCode = 1;
249
481
  } else if (words.json) writeLine("stdout", detailsJson(result.details));
250
- else {
482
+ else if (result.content.length > 0) {
251
483
  writeLine("stdout", sanitizeText(resultText(result)));
252
484
  const images = result.content.filter((block) => block.type === "image").length;
253
485
  if (images > 0) writeLine("stderr", `(${images} image block(s) not printed)`);
@@ -264,7 +496,7 @@ function mcpCommand(options) {
264
496
  json: false,
265
497
  async run() {
266
498
  const [{ createMcpServer }, { StdioServerTransport }] = await Promise.all([import("./mcp.mjs"), import("@modelcontextprotocol/server/stdio")]);
267
- await createMcpServer(options, options.tools).connect(new StdioServerTransport());
499
+ await createMcpServer(typeof options.mcp === "object" ? options.mcp : options, options.tools).connect(new StdioServerTransport());
268
500
  }
269
501
  };
270
502
  }
@@ -275,7 +507,7 @@ function commandTools(options) {
275
507
  return [...listed, ...own.filter((command) => !listed.includes(command))];
276
508
  }
277
509
  function builtInMcp(options) {
278
- return options.mcp === true && !(options.commands ?? []).some((command) => commandName(command) === "mcp");
510
+ return options.mcp !== void 0 && options.mcp !== false && !(options.commands ?? []).some((command) => commandName(command) === "mcp");
279
511
  }
280
512
  function commandWords(options) {
281
513
  return [...commandTools(options).flatMap((tool) => [commandName(tool), ...tool.cli?.aliases ?? []]), ...builtInMcp(options) ? ["mcp"] : []];
@@ -346,11 +578,11 @@ function commandUsage(options, command) {
346
578
  const flags = command.fields.filter((field) => !field.positional);
347
579
  const takesOptions = flags.length > 0 || command.json;
348
580
  const words = positional.map((field) => {
349
- const name = field.flag.toUpperCase();
581
+ const name = `${field.flag.toUpperCase()}${field.rest ? "..." : ""}`;
350
582
  return field.required ? `<${name}>` : `[${name}]`;
351
583
  });
352
584
  const rows = [
353
- ...flags.map((field) => [field.kind === "boolean" ? `--[no-]${field.flag}` : `--${field.flag}=<${valueHint(field)}>`, fieldDescription(field)]),
585
+ ...flags.map((field) => [`${field.short === void 0 ? "" : `-${field.short}, `}${optionSpelling(field)}`, fieldDescription(field)]),
354
586
  ...command.json ? [["--json", "Print the details as JSON instead of the text"]] : [],
355
587
  ["-h, --help", "Show this help"]
356
588
  ];