incur-cli 0.10.0__py3-none-any.whl

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.
incur/_cli.py ADDED
@@ -0,0 +1,2139 @@
1
+ """CLI definition, command routing, and the `serve` loop."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import inspect
8
+ import io
9
+ import math
10
+ import os
11
+ import sys
12
+ import time
13
+ import typing
14
+ from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence
15
+ from dataclasses import dataclass, field, replace
16
+ from typing import Any, Literal, NoReturn, Protocol, TextIO, TypeVar
17
+
18
+ from . import (
19
+ _completions,
20
+ _filter,
21
+ _gateway,
22
+ _js,
23
+ _mcpsource,
24
+ _parser,
25
+ _pm,
26
+ _serve_http,
27
+ _skill,
28
+ _syncmcp,
29
+ _tokens,
30
+ )
31
+ from ._command import (
32
+ Command,
33
+ Middleware,
34
+ MiddlewareContext,
35
+ Outcome,
36
+ OutputPolicy,
37
+ Stream,
38
+ Success,
39
+ execute,
40
+ inputs,
41
+ run_chain,
42
+ )
43
+ from ._errors import (
44
+ Error,
45
+ FormattedCta,
46
+ FormattedCtaBlock,
47
+ format_cta,
48
+ human_error,
49
+ unknown,
50
+ )
51
+ from ._filter import MISSING, Missing
52
+ from ._formatter import FORMATS, Format, format_value
53
+ from ._help import Entry as HelpEntry
54
+ from ._help import Example, Usage, format_command, format_root
55
+ from ._help import Options as HelpOptions
56
+ from ._http import FetchHandler, Request, RequestSource, Response, asgi, call
57
+ from ._js import Json
58
+ from ._mcp import HttpHandler, McpOptions, McpTool, serve_stdio
59
+ from ._mcp import Server as McpServer
60
+ from ._model import SchemaError, build, caller_locals, to_json, type_of
61
+ from ._openapi import OpenapiConfig, OpenapiSource
62
+ from ._openapi import commands as openapi_commands
63
+ from ._openapi import resolve as openapi_resolve
64
+ from ._schema import Field, Type, json_schema, object_type
65
+ from ._sync import Options as SyncOptions
66
+ from ._sync import Sync, has_installed_skills, list_skills, read_hash
67
+ from ._sync import sync as sync_skills
68
+ from ._tree import (
69
+ Alias,
70
+ BannerMode,
71
+ Entry,
72
+ Gateway,
73
+ GatewayHit,
74
+ Group,
75
+ GroupHelp,
76
+ NotFound,
77
+ Resolution,
78
+ Resolved,
79
+ Spec,
80
+ help_entries,
81
+ once,
82
+ resolve,
83
+ suggest,
84
+ target,
85
+ )
86
+ from ._update import Options as UpdateOptions
87
+ from ._update import Update
88
+ from ._update import check as check_update
89
+ from ._update import install as install_update
90
+ from ._update import refresh as refresh_update
91
+
92
+ _F = TypeVar("_F", bound=Callable[..., object])
93
+
94
+
95
+ class Writer(Protocol):
96
+ """A text stream, such as `sys.stdout` or `io.StringIO`."""
97
+
98
+ def write(self, text: str, /) -> int:
99
+ """Writes text."""
100
+ ...
101
+
102
+
103
+ @dataclass
104
+ class Config:
105
+ """Config-file option defaults.
106
+
107
+ A config file is a JSON object: `{"commands": {"<name>": {"options": {...}}}}`, nested by
108
+ command path, with root command options at the top level.
109
+ """
110
+
111
+ flag: str | None = None
112
+ """Global flag that names a config file, such as `config` for `--config <path>`."""
113
+ files: list[str] = field(default_factory=list[str])
114
+ """Ordered search paths. The first existing file wins. Defaults to `<cli>.json`."""
115
+ loader: Callable[[str | None], object | Awaitable[object]] | None = None
116
+ """Custom loader, called with the resolved path or `None`. Returns an object or `None`.
117
+
118
+ It may be an `async def` function."""
119
+
120
+
121
+ class Cli:
122
+ """A CLI: a router of commands, optionally with its own root command.
123
+
124
+ >>> import incur
125
+ >>> cli = incur.Cli("my-cli", description="My CLI", update=False)
126
+ >>> @cli.command("status", description="Show repo status")
127
+ ... def status(c: incur.Context) -> dict[str, bool]:
128
+ ... return {"clean": True}
129
+ >>> cli.serve_with(["status"], stdout=sys.stdout)
130
+ clean: true
131
+ 0
132
+
133
+ Handlers and middleware may be `async def` functions, and streaming handlers async
134
+ generators. `serve()` runs the event loop; `await cli.serve_async()` and `await cli.run(...)`
135
+ run inside one that is already running. `await cli.fetch(request)` and the ASGI application
136
+ `cli.asgi` serve the same commands over HTTP.
137
+ """
138
+
139
+ def __init__(
140
+ self,
141
+ name: str,
142
+ *,
143
+ description: str | None = None,
144
+ version: str | None = None,
145
+ aliases: Sequence[str] = (),
146
+ banner: Callable[[], str | Awaitable[str | None] | None] | None = None,
147
+ banner_mode: BannerMode = "all",
148
+ config: Config | None = None,
149
+ env: type | None = None,
150
+ fetch: FetchHandler | None = None,
151
+ format: Format | None = None,
152
+ globals: type | None = None,
153
+ mcp: McpOptions | Literal[False] | None = None,
154
+ openapi: OpenapiSource | None = None,
155
+ openapi_config: OpenapiConfig | None = None,
156
+ output_policy: OutputPolicy | None = None,
157
+ package: str | None = None,
158
+ sync: Sync | bool = True,
159
+ update: Update | bool = True,
160
+ vars: type | Mapping[str, Any] | None = None,
161
+ ) -> None:
162
+ """Creates a CLI.
163
+
164
+ Args:
165
+ name: The CLI name, shown in help and used as the default binary name.
166
+ description: What the CLI does.
167
+ version: Version printed by `--version`.
168
+ aliases: Alternative binary names. Completions register every name.
169
+ banner: Renders text shown above root help. It may be an `async def` function.
170
+ banner_mode: Who sees the banner.
171
+ config: Enables config-file option defaults.
172
+ env: A schema class of CLI-level environment variables, parsed before middleware.
173
+ Middleware reads an instance as `c.env`.
174
+ fetch: A fetch handler, or a hosted source from `incur.from_request`, that runs when
175
+ no command matches: arguments become a curl-style HTTP request.
176
+ format: The default output format.
177
+ globals: A schema class of global options available to every command. Middleware and
178
+ handlers read an instance as `c.globals`.
179
+ mcp: MCP server and registration settings. `False` hides the CLI's commands from MCP
180
+ clients when it is mounted as a group.
181
+ openapi: An OpenAPI document, or its URL, that generates root commands calling
182
+ `fetch`.
183
+ openapi_config: How OpenAPI commands are generated.
184
+ output_policy: The default output policy, inherited by every command.
185
+ package: The npm package that runs the CLI, when it differs from the name.
186
+ sync: Settings of the built-in `skills add` command, or `False` to disable skills.
187
+ update: Settings of update checks and `--update`, or `False` to disable both.
188
+ vars: Variables that middleware sets for handlers: a class whose fields all have
189
+ defaults, such as an `@incur.schema` class, instantiated for every run as
190
+ `c.var`; or a mapping of defaults, copied into a `dict`.
191
+
192
+ Raises:
193
+ SchemaError: When a global option collides with a built-in flag.
194
+ """
195
+ self.name = name
196
+ """The CLI name."""
197
+ spec = Spec(name)
198
+ self._spec = spec
199
+ spec.description = description
200
+ spec.version = version
201
+ spec.aliases = list(aliases)
202
+ spec.banner = banner
203
+ spec.banner_mode = banner_mode
204
+ spec.config = config
205
+ spec.env = type_of(env, f"{name} env") if env is not None else None
206
+ spec.format = format
207
+ spec.update = None if update is False else Update() if update is True else update
208
+ spec.globals = self._check_globals(type_of(globals, f"{name} globals")) if globals else None
209
+ spec.output_policy = output_policy
210
+ spec.sync = None if sync is False else Sync() if sync is True else sync
211
+ spec.vars = vars if isinstance(vars, type) else dict(vars or {})
212
+ spec.mcp = mcp or None
213
+ spec.mcp_enabled = mcp is not False
214
+ spec.package = package
215
+ spec.root_fetch = fetch
216
+ if fetch is not None and openapi is not None:
217
+ spec.pending.append(self._openapi(fetch, openapi, openapi_config, None, spec.commands))
218
+ self._mcp_http = HttpHandler(spec)
219
+
220
+ def _check_globals(self, schema: Type) -> Type:
221
+ """Rejects global options that collide with built-in flags."""
222
+ builtins = [
223
+ "fullOutput",
224
+ "format",
225
+ "json",
226
+ "llms",
227
+ "llmsFull",
228
+ "mcp",
229
+ "help",
230
+ "incurBinaryApply",
231
+ "incurUpdateCheck",
232
+ *(["update"] if self._spec.update is not None else []),
233
+ "version",
234
+ "schema",
235
+ "filterOutput",
236
+ "tokenLimit",
237
+ "tokenOffset",
238
+ "tokenCount",
239
+ ]
240
+ flag = self._spec.config.flag if self._spec.config else None
241
+ if flag:
242
+ builtins += [flag, f"no{flag[0].upper()}{flag[1:]}"]
243
+ for f in schema.fields:
244
+ if f.name in builtins:
245
+ raise SchemaError(
246
+ f"Global option '{f.name}' conflicts with a built-in flag. "
247
+ "Choose a different name."
248
+ )
249
+ if f.alias == "h":
250
+ raise SchemaError(
251
+ f"Global alias '-h' for '{f.name}' conflicts with a built-in short flag. "
252
+ "Choose a different alias."
253
+ )
254
+ return schema
255
+
256
+ def command(
257
+ self,
258
+ name: str,
259
+ *,
260
+ description: str | None = None,
261
+ aliases: Sequence[str] = (),
262
+ destructive: bool = False,
263
+ examples: Sequence[Example] = (),
264
+ format: Format | None = None,
265
+ hint: str | None = None,
266
+ mcp: McpTool | Literal[False] | None = None,
267
+ middleware: Sequence[Middleware] = (),
268
+ output: object = None,
269
+ output_policy: OutputPolicy | None = None,
270
+ usage: Sequence[Usage] = (),
271
+ ) -> Callable[[_F], _F]:
272
+ """Registers the decorated function as a command handler.
273
+
274
+ The handler, a plain or `async def` function, takes one parameter annotated
275
+ `incur.Context[Args, Options, Env, Vars, Globals]`, whose schema classes declare the
276
+ command's input. It returns data or `incur.ok(...)`, or is a generator or async generator
277
+ that streams chunks, and raises `incur.Error` to fail.
278
+
279
+ Args:
280
+ name: The command name.
281
+ description: What the command does.
282
+ aliases: Alternative names, such as `ext` for `extension`.
283
+ destructive: Marks the command as destructive in generated agent skills.
284
+ examples: Usage examples shown in help and manifests.
285
+ format: The default output format.
286
+ hint: Guidance shown after examples.
287
+ mcp: How the command appears as an MCP tool, or `False` to hide it from MCP.
288
+ middleware: Middleware that runs after CLI and group middleware.
289
+ output: The output type: a schema class, `str`, `Any`, and so on.
290
+ output_policy: Where the output may appear.
291
+ usage: Alternative usage lines.
292
+ """
293
+ # Annotations may name classes local to the declaring function.
294
+ scope = caller_locals()
295
+
296
+ def register(fn: _F) -> _F:
297
+ command = self._make_command(
298
+ fn,
299
+ scope,
300
+ description=description,
301
+ aliases=list(aliases),
302
+ destructive=destructive,
303
+ examples=list(examples),
304
+ format=format,
305
+ hint=hint,
306
+ middleware=list(middleware),
307
+ output=type_of(output, f"{name} output") if output is not None else None,
308
+ output_policy=output_policy,
309
+ usage=list(usage),
310
+ mcp=mcp.meta() if mcp else None,
311
+ mcp_enabled=mcp is not False,
312
+ )
313
+ for alias in command.aliases:
314
+ self._spec.commands[alias] = Alias(command)
315
+ self._spec.commands[name] = command
316
+ return fn
317
+
318
+ return register
319
+
320
+ def gateway(
321
+ self,
322
+ name: str,
323
+ fetch: FetchHandler,
324
+ *,
325
+ description: str | None = None,
326
+ base_path: str | None = None,
327
+ openapi: OpenapiSource | None = None,
328
+ openapi_config: OpenapiConfig | None = None,
329
+ output_policy: OutputPolicy | None = None,
330
+ mcp: bool = True,
331
+ ) -> Cli:
332
+ """Adds a command that forwards to a fetch handler. Returns this CLI.
333
+
334
+ Arguments after the command become a curl-style HTTP request: path segments, `--key value`
335
+ query parameters, `-X` for the method, `-H "Name: value"` headers, and `-d` for a body.
336
+ With `openapi`, the command is instead a group of typed commands, one per operation.
337
+
338
+ Args:
339
+ name: The command name.
340
+ fetch: An `async def` fetch handler, such as an ASGI-free in-process app, or a hosted
341
+ source from `incur.from_request`.
342
+ description: What the command does.
343
+ base_path: A path prepended to every request path.
344
+ openapi: An OpenAPI document, or its URL, relative to a hosted source's URL.
345
+ openapi_config: How OpenAPI commands are generated.
346
+ output_policy: Where the output may appear.
347
+ mcp: Whether generated OpenAPI commands are MCP tools.
348
+ """
349
+ if openapi is None:
350
+ self._spec.commands[name] = Gateway(fetch, description, base_path, output_policy)
351
+ return self
352
+ group = Group({}, description, output_policy=output_policy, mcp=mcp)
353
+ load = self._openapi(fetch, openapi, openapi_config, base_path, group.commands)
354
+
355
+ async def mount() -> None:
356
+ await load()
357
+ self._spec.commands[name] = group
358
+
359
+ self._spec.pending.append(mount)
360
+ return self
361
+
362
+ def mcp_source(
363
+ self,
364
+ name: str,
365
+ url: str,
366
+ *,
367
+ fetch: FetchHandler | None = None,
368
+ headers: Mapping[str, str] | None = None,
369
+ description: str | None = None,
370
+ output_policy: OutputPolicy | None = None,
371
+ ) -> Cli:
372
+ """Adds a group of commands that call the tools of a remote MCP server. Returns this CLI.
373
+
374
+ The server is reached over streamable HTTP when the group is first used, and its tools
375
+ become commands, whether it lists them directly or through progressive discovery.
376
+
377
+ Args:
378
+ name: The group name.
379
+ url: The server's streamable-HTTP endpoint.
380
+ fetch: Sends the MCP requests, such as another CLI's `fetch`. Defaults to the
381
+ network.
382
+ headers: Headers sent with every MCP request.
383
+ description: What the group does.
384
+ output_policy: Where the output may appear.
385
+ """
386
+ group = Group({}, description, output_policy=output_policy)
387
+ self._spec.commands[name] = group
388
+
389
+ async def load() -> None:
390
+ source = _mcpsource.Source(url, fetch, dict(headers or {}))
391
+ group.commands.update(await _mcpsource.commands(source))
392
+
393
+ self._spec.lazy[name] = once(load)
394
+ return self
395
+
396
+ def _openapi(
397
+ self,
398
+ fetch: FetchHandler,
399
+ source: OpenapiSource,
400
+ config: OpenapiConfig | None,
401
+ base_path: str | None,
402
+ into: dict[str, Entry],
403
+ ) -> Callable[[], Awaitable[None]]:
404
+ async def load() -> None:
405
+ base = fetch.url if isinstance(fetch, RequestSource) else None
406
+ spec = await openapi_resolve(source, base)
407
+ into.update(openapi_commands(spec, fetch, config, base_path))
408
+
409
+ return load
410
+
411
+ def root(
412
+ self,
413
+ *,
414
+ description: str | None = None,
415
+ examples: Sequence[Example] = (),
416
+ format: Format | None = None,
417
+ hint: str | None = None,
418
+ output: object = None,
419
+ usage: Sequence[Usage] = (),
420
+ ) -> Callable[[_F], _F]:
421
+ """Registers the decorated function as the root command, run when no subcommand matches.
422
+
423
+ Takes the same handler and options as `command`. The description defaults to the CLI's.
424
+ """
425
+ scope = caller_locals()
426
+
427
+ def register(fn: _F) -> _F:
428
+ self._spec.root = self._make_command(
429
+ fn,
430
+ scope,
431
+ description=description,
432
+ examples=list(examples),
433
+ format=format,
434
+ hint=hint,
435
+ output=type_of(output, f"{self.name} output") if output is not None else None,
436
+ usage=list(usage),
437
+ )
438
+ return fn
439
+
440
+ return register
441
+
442
+ def group(self, cli: Cli) -> Cli:
443
+ """Mounts another CLI as a command group. Returns this CLI."""
444
+ sub = cli._spec
445
+ root = sub.root_command()
446
+ entry: Entry
447
+ if root is not None and not sub.commands:
448
+ # A CLI without subcommands mounts as a command, keeping its aliases.
449
+ entry = replace(root, aliases=list(sub.aliases))
450
+ for alias in entry.aliases:
451
+ self._spec.commands[alias] = Alias(entry)
452
+ else:
453
+ entry = Group(
454
+ sub.commands,
455
+ sub.description,
456
+ sub.middleware,
457
+ sub.output_policy,
458
+ root,
459
+ sub.mcp_enabled,
460
+ )
461
+ # Mounted CLIs resolve their deferred groups up front.
462
+ if sub.pending or sub.lazy:
463
+ self._spec.pending.append(sub.load)
464
+ self._spec.commands[cli.name] = entry
465
+ return self
466
+
467
+ def _make_command(
468
+ self, fn: Callable[..., object], scope: dict[str, Any], **settings: Any
469
+ ) -> Command:
470
+ spec = self._spec
471
+ state = (
472
+ spec.vars if isinstance(spec.vars, type) else None,
473
+ spec.globals.py if spec.globals else None,
474
+ )
475
+ args, options, env = inputs(fn, scope, state)
476
+ return Command(handler=fn, args=args, options=options, env=env, **settings)
477
+
478
+ def use(self, middleware: Middleware) -> Middleware:
479
+ """Adds middleware, which runs around every command in registration order.
480
+
481
+ Usable as a decorator. Middleware takes the context and `next`, and calls `next()` to
482
+ run the rest of the chain: `async def` middleware awaits it, and a plain function, which
483
+ runs in a worker thread, calls it.
484
+ """
485
+ self._spec.middleware.append(middleware)
486
+ return middleware
487
+
488
+ async def fetch(self, request: Request) -> Response:
489
+ """Serves an HTTP request: runs the command its path names, or speaks MCP at `/mcp`.
490
+
491
+ `GET /users/list?limit=5` runs `users list` with options from the query; other methods
492
+ read options from a JSON body. `/openapi.json` describes the commands as an OpenAPI
493
+ document, and `/.well-known/agent-skills/index.json` lists their agent skills.
494
+ """
495
+ await self._spec.load()
496
+ return await _serve_http.handle(self._spec, request, self._mcp_http)
497
+
498
+ @property
499
+ def asgi(self) -> Any:
500
+ """The CLI as an ASGI 3 application, serving the same routes as `fetch`.
501
+
502
+ Run it with any ASGI server, such as `uvicorn module:cli.asgi`.
503
+ """
504
+ return asgi(self.fetch)
505
+
506
+ def serve(self) -> NoReturn:
507
+ """Runs the CLI with the process arguments, environment, and streams, then exits.
508
+
509
+ Runs the event loop with `asyncio.run`. Inside a running loop, await `serve_async`.
510
+ """
511
+ raise SystemExit(asyncio.run(self.serve_async()))
512
+
513
+ async def serve_async(self) -> int:
514
+ """Runs the CLI with the process arguments, environment, and streams.
515
+
516
+ Returns the exit code.
517
+ """
518
+ display = os.path.basename(sys.argv[0]) if sys.argv else None
519
+ code = await self._serve(
520
+ sys.argv[1:],
521
+ dict(os.environ),
522
+ sys.stdout,
523
+ sys.stderr,
524
+ sys.stdin,
525
+ sys.stdout.isatty(),
526
+ display,
527
+ )
528
+ sys.stdout.flush()
529
+ return code
530
+
531
+ async def run(
532
+ self,
533
+ argv: Sequence[str],
534
+ *,
535
+ env: Mapping[str, str] | None = None,
536
+ stdout: Writer | None = None,
537
+ stderr: Writer | None = None,
538
+ stdin: TextIO | None = None,
539
+ tty: bool = False,
540
+ ) -> int:
541
+ """Runs the CLI with explicit arguments and I/O inside a running event loop.
542
+
543
+ Returns the exit code. Takes the same arguments as `serve_with`.
544
+ """
545
+ return await self._serve(
546
+ list(argv),
547
+ dict(env or {}),
548
+ stdout or _Null(),
549
+ stderr or _Null(),
550
+ stdin or io.StringIO(),
551
+ tty,
552
+ None,
553
+ )
554
+
555
+ def serve_with(
556
+ self,
557
+ argv: Sequence[str],
558
+ *,
559
+ env: Mapping[str, str] | None = None,
560
+ stdout: Writer | None = None,
561
+ stderr: Writer | None = None,
562
+ stdin: TextIO | None = None,
563
+ tty: bool = False,
564
+ ) -> int:
565
+ """Runs the CLI with explicit arguments and I/O. Returns the exit code.
566
+
567
+ Runs the event loop with `asyncio.run`. Inside a running loop, await `run`.
568
+
569
+ Args:
570
+ argv: Arguments after the binary name.
571
+ env: Environment variables. Defaults to none. Agent, skill, and update paths
572
+ resolve from its `HOME` and `XDG_*` variables.
573
+ stdout: Receives output. Defaults to discarding it.
574
+ stderr: Receives warnings. Defaults to discarding them.
575
+ stdin: Input of `--mcp`. Defaults to empty input.
576
+ tty: Whether stdout is a terminal, which selects human output.
577
+ """
578
+ return asyncio.run(
579
+ self.run(argv, env=env, stdout=stdout, stderr=stderr, stdin=stdin, tty=tty)
580
+ )
581
+
582
+ async def _serve(
583
+ self,
584
+ argv: list[str],
585
+ env: dict[str, str],
586
+ stdout: Writer,
587
+ stderr: Writer,
588
+ stdin: TextIO,
589
+ tty: bool,
590
+ bin_name: str | None,
591
+ ) -> int:
592
+ spec = self._spec
593
+ await spec.load_pending()
594
+ display = bin_name if bin_name in (self.name, *spec.aliases) else self.name
595
+ run = _Run(spec, display or self.name, env, stdout, stderr, stdin, tty)
596
+ await run.serve(argv)
597
+ return run.exit
598
+
599
+
600
+ class _Null:
601
+ """A writer that discards text."""
602
+
603
+ def write(self, text: str, /) -> int:
604
+ return len(text)
605
+
606
+
607
+ @dataclass
608
+ class _Flags:
609
+ """Built-in flags extracted from argv."""
610
+
611
+ config_disabled: bool = False
612
+ config_path: str | None = None
613
+ filter_output: str | None = None
614
+ format: Format = "toon"
615
+ format_explicit: bool = False
616
+ full_output: bool = False
617
+ help: bool = False
618
+ llms: bool = False
619
+ llms_full: bool = False
620
+ mcp: bool = False
621
+ rest: list[str] = field(default_factory=list[str])
622
+ schema: bool = False
623
+ token_count: bool = False
624
+ token_limit: float | None = None
625
+ token_offset: float | None = None
626
+ update: bool = False
627
+ update_check: bool = False
628
+ version: bool = False
629
+
630
+
631
+ #: The hidden flag of detached update checks.
632
+ UPDATE_CHECK_FLAG = "--incur-update-check"
633
+
634
+
635
+ def _extract_flags(argv: list[str], config_flag: str | None, update: bool = True) -> _Flags:
636
+ """Extracts built-in flags from argv."""
637
+ flags = _Flags()
638
+ i = 0
639
+ while i < len(argv):
640
+ token = argv[i]
641
+ nxt = argv[i + 1] if i + 1 < len(argv) and argv[i + 1] else None
642
+ if token == "--full-output":
643
+ flags.full_output = True
644
+ elif token == "--llms":
645
+ flags.llms = True
646
+ elif token == "--llms-full":
647
+ flags.llms_full = True
648
+ elif token == "--mcp":
649
+ flags.mcp = True
650
+ elif token in ("--help", "-h"):
651
+ flags.help = True
652
+ elif token == "--update" and update:
653
+ flags.update = True
654
+ elif token == UPDATE_CHECK_FLAG:
655
+ flags.update_check = True
656
+ elif token == "--version" and (nxt is None or nxt.startswith("-")):
657
+ # A following value belongs to a command-local `--version` option.
658
+ flags.version = True
659
+ elif token == "--schema":
660
+ flags.schema = True
661
+ elif token == "--json":
662
+ flags.format = "json"
663
+ flags.format_explicit = True
664
+ elif token == "--format" and nxt is not None:
665
+ if nxt not in FORMATS:
666
+ raise unknown(
667
+ f'Invalid format: "{nxt}". Expected one of: toon, json, yaml, md, jsonl'
668
+ )
669
+ flags.format = nxt
670
+ flags.format_explicit = True
671
+ i += 1
672
+ elif token == "--filter-output" and nxt is not None:
673
+ flags.filter_output = nxt
674
+ i += 1
675
+ elif token in ("--token-limit", "--token-offset") and nxt is not None:
676
+ value = _js.to_number(nxt)
677
+ if not math.isfinite(value) or not _js.trim(nxt):
678
+ raise unknown(f'Invalid value for {token}: "{nxt}"')
679
+ if token == "--token-limit":
680
+ flags.token_limit = value
681
+ else:
682
+ flags.token_offset = value
683
+ i += 1
684
+ elif token == "--token-count":
685
+ flags.token_count = True
686
+ elif config_flag is not None and token == f"--{config_flag}":
687
+ if i + 1 >= len(argv):
688
+ raise unknown(f"Missing value for flag: --{config_flag}")
689
+ flags.config_path = argv[i + 1]
690
+ flags.config_disabled = False
691
+ i += 1
692
+ elif config_flag is not None and token.startswith(f"--{config_flag}="):
693
+ value = token[len(config_flag) + 3 :]
694
+ if not value:
695
+ raise unknown(f"Missing value for flag: --{config_flag}")
696
+ flags.config_path = value
697
+ flags.config_disabled = False
698
+ elif config_flag is not None and token == f"--no-{config_flag}":
699
+ flags.config_path = None
700
+ flags.config_disabled = True
701
+ else:
702
+ flags.rest.append(token)
703
+ i += 1
704
+ return flags
705
+
706
+
707
+ def _manifest_entry(path: str, command: Command, full: bool) -> dict[str, Json]:
708
+ out: dict[str, Json] = {"name": path}
709
+ if command.description:
710
+ out["description"] = command.description
711
+ if not full:
712
+ return out
713
+ schema: dict[str, Json] = {}
714
+ for key, ty in (
715
+ ("args", command.args),
716
+ ("env", command.env),
717
+ ("options", command.options),
718
+ ("output", command.output),
719
+ ):
720
+ if ty is not None:
721
+ schema[key] = json_schema(ty)
722
+ if schema:
723
+ out["schema"] = schema
724
+ if command.examples:
725
+ examples: list[Json] = []
726
+ for example in _skill.prefixed_examples(command.examples, path):
727
+ item: dict[str, Json] = {"command": example.command}
728
+ if example.description is not None:
729
+ item["description"] = example.description
730
+ examples.append(item)
731
+ out["examples"] = examples
732
+ return out
733
+
734
+
735
+ def _manifest_commands(
736
+ commands: dict[str, Entry], prefix: list[str], full: bool
737
+ ) -> list[dict[str, Json]]:
738
+ out: list[dict[str, Json]] = []
739
+ for name, entry in commands.items():
740
+ path = [*prefix, name]
741
+ joined = " ".join(path)
742
+ if isinstance(entry, Command):
743
+ out.append(_manifest_entry(joined, entry, full))
744
+ elif isinstance(entry, Gateway):
745
+ item: dict[str, Json] = {"name": joined}
746
+ if entry.description:
747
+ item["description"] = entry.description
748
+ out.append(item)
749
+ elif isinstance(entry, Group):
750
+ if entry.root is not None:
751
+ out.append(_manifest_entry(joined, entry.root, full))
752
+ out += _manifest_commands(entry.commands, path, full)
753
+ return out
754
+
755
+
756
+ #: Built-in subcommands: built-in name, subcommand name, description, aliases.
757
+ _BUILTIN_SUBCOMMANDS: tuple[tuple[str, str, str, tuple[str, ...]], ...] = (
758
+ ("mcp", "add", "Register as MCP server", ()),
759
+ ("mcp", "doctor", "Validate MCP server startup and tool listing", ()),
760
+ ("skills", "add", "Sync skill files to agents", ()),
761
+ ("skills", "list", "List skills", ("ls",)),
762
+ )
763
+
764
+ #: Built-in command descriptions.
765
+ _BUILTINS = (
766
+ ("completions", "Generate shell completion script"),
767
+ ("mcp", "Register as MCP server"),
768
+ ("skills", "Sync skill files to agents"),
769
+ )
770
+
771
+
772
+ def _find_builtin(token: str) -> str | None:
773
+ """Resolves a token to a built-in command name."""
774
+ return {"completions": "completions", "mcp": "mcp", "skills": "skills", "skill": "skills"}.get(
775
+ token
776
+ )
777
+
778
+
779
+ def _string_type(description: str) -> Type:
780
+ return Type("string", optional=True, description=description)
781
+
782
+
783
+ @dataclass
784
+ class _Output:
785
+ """Output settings resolved for a command."""
786
+
787
+ flags: _Flags
788
+ format: Format
789
+ human: bool
790
+ filter: list[list[_filter.Segment]] | None
791
+ render: bool
792
+
793
+
794
+ class _Run:
795
+ """The per-invocation serve state."""
796
+
797
+ def __init__(
798
+ self,
799
+ cli: Spec,
800
+ display_name: str,
801
+ env: dict[str, str],
802
+ stdout: Writer,
803
+ stderr: Writer,
804
+ stdin: TextIO,
805
+ tty: bool,
806
+ ) -> None:
807
+ self.cli = cli
808
+ self.display_name = display_name
809
+ self.env_map = env
810
+ self.stdout = stdout
811
+ self.stderr = stderr
812
+ self.stdin = stdin
813
+ self.tty = tty
814
+ self.root = cli.root_command()
815
+ self.exit = 0
816
+ self.start = time.monotonic()
817
+ self.notice: FormattedCtaBlock | None = None
818
+
819
+ def write(self, text: str) -> None:
820
+ self.stdout.write(text)
821
+
822
+ def writeln(self, text: str) -> None:
823
+ self.write(text if text.endswith("\n") else text + "\n")
824
+
825
+ def env(self, key: str) -> str | None:
826
+ return self.env_map.get(key)
827
+
828
+ def duration(self) -> str:
829
+ return f"{int((time.monotonic() - self.start) * 1000)}ms"
830
+
831
+ def config_flag(self) -> str | None:
832
+ config = self.cli.config
833
+ return config.flag if config else None
834
+
835
+ def help_options(self, **overrides: Any) -> HelpOptions:
836
+ base = HelpOptions(
837
+ config_flag=self.config_flag(),
838
+ globals=self.cli.globals,
839
+ hide_skills=not self.cli.sync,
840
+ hide_update=self.cli.update is None,
841
+ )
842
+ return replace(base, **overrides)
843
+
844
+ def early_error(self, error: Error, human: bool, fmt: Format) -> None:
845
+ """Reports an error before a command resolves."""
846
+ self.writeln(human_error(error) if human else format_value(error.to_json(), fmt))
847
+ self.exit = 1
848
+
849
+ async def banner(self, human: bool, show_help: bool) -> None:
850
+ render = self.cli.banner
851
+ if render is None or show_help:
852
+ return
853
+ mode = self.cli.banner_mode
854
+ if mode == "all" or (mode == "human") == human:
855
+ text = render()
856
+ if inspect.isawaitable(text):
857
+ text = await text
858
+ if text:
859
+ self.writeln(text)
860
+
861
+ def root_help(self, globals_: bool = True) -> str:
862
+ cli = self.cli
863
+ return format_root(
864
+ cli.name,
865
+ self.help_options(
866
+ aliases=cli.aliases,
867
+ commands=help_entries(cli.commands),
868
+ description=cli.description,
869
+ globals=cli.globals if globals_ else None,
870
+ root=True,
871
+ version=cli.version,
872
+ ),
873
+ )
874
+
875
+ def group_help(self, group: GroupHelp, **overrides: Any) -> str:
876
+ return format_root(
877
+ f"{self.cli.name} {group.path}",
878
+ self.help_options(
879
+ commands=help_entries(group.commands), description=group.description, **overrides
880
+ ),
881
+ )
882
+
883
+ async def serve(self, argv: list[str]) -> None:
884
+ cli = self.cli
885
+ shell = self.env("COMPLETE")
886
+ if shell is not None:
887
+ await self.complete(shell, argv)
888
+ return
889
+ try:
890
+ flags = _extract_flags(argv, self.config_flag(), cli.update is not None)
891
+ except Error as error:
892
+ self.early_error(error, self.tty, "toon")
893
+ return
894
+ human = self.tty and not flags.format_explicit
895
+
896
+ filtered = flags.rest
897
+ globals_schema = cli.globals
898
+ if globals_schema is not None:
899
+ try:
900
+ filtered = _parser.parse_globals(flags.rest, globals_schema, None, known=True)[1]
901
+ except Error as error:
902
+ self.early_error(error, human, flags.format)
903
+ return
904
+
905
+ # Deferred groups load only when this invocation can reach them.
906
+ first = filtered[0] if filtered else None
907
+ reaches_all = (
908
+ flags.mcp
909
+ or ((flags.llms or flags.llms_full) and first is None)
910
+ or first == cli.name
911
+ or (first is not None and _find_builtin(first) is not None)
912
+ )
913
+ if reaches_all:
914
+ await cli.load()
915
+ elif first is not None:
916
+ await cli.load(first)
917
+
918
+ if flags.update_check:
919
+ if cli.update is not None:
920
+ with contextlib.suppress(Exception):
921
+ await refresh_update(cli.name, self.update_options(), self.env_map)
922
+ return
923
+ # --help takes precedence over --update.
924
+ if flags.update and not flags.help:
925
+ await self.install_update(human, flags)
926
+ return
927
+
928
+ if flags.mcp:
929
+ await serve_stdio(cli, self.env_map, self.stdin, typing.cast("TextIO", self.stdout))
930
+ return
931
+
932
+ skills_cta = await self.skills_notice(flags, filtered)
933
+
934
+ if flags.llms or flags.llms_full:
935
+ self.llms(flags, filtered)
936
+ return
937
+
938
+ def builtin_index(builtin: str) -> int | None:
939
+ if filtered and _find_builtin(filtered[0]) == builtin:
940
+ return 0
941
+ if (
942
+ len(filtered) > 1
943
+ and filtered[0] == cli.name
944
+ and _find_builtin(filtered[1]) == builtin
945
+ ):
946
+ return 1
947
+ return None
948
+
949
+ index = builtin_index("completions")
950
+ if index is not None:
951
+ shell_name = filtered[index + 1] if index + 1 < len(filtered) else None
952
+ if shell_name is None or flags.help:
953
+ self.completions_help()
954
+ elif shell_name in _completions.SHELLS:
955
+ self.writeln(self.register_scripts(shell_name))
956
+ else:
957
+ error = Error(
958
+ "INVALID_SHELL",
959
+ f"Unknown shell '{shell_name}'. Supported: bash, fish, nushell, zsh",
960
+ )
961
+ self.writeln(human_error(error))
962
+ self.exit = 1
963
+ return
964
+
965
+ for builtin in ("skills", "mcp"):
966
+ if builtin == "skills" and not cli.sync:
967
+ continue
968
+ index = builtin_index(builtin)
969
+ if index is not None:
970
+ await self.builtin(builtin, filtered, index, argv, flags, human)
971
+ return
972
+
973
+ version = cli.version
974
+ if flags.version and not flags.help and version is not None:
975
+ self.writeln(version)
976
+ return
977
+
978
+ root = self.root
979
+ if not filtered:
980
+ required = (
981
+ root is not None
982
+ and root.args is not None
983
+ and any(not f.ty.is_optional() for f in root.args.fields)
984
+ )
985
+ if root is not None and human and required:
986
+ await self.banner(human, flags.help)
987
+ commands = help_entries(cli.commands)
988
+ options = self.command_help(root, cli.aliases, version, commands, True)
989
+ self.writeln(format_command(cli.name, options))
990
+ return
991
+ if root is None and cli.root_fetch is None:
992
+ await self.banner(human, flags.help)
993
+ self.writeln(self.root_help())
994
+ return
995
+
996
+ resolved: Resolution
997
+ if root is not None and not filtered:
998
+ resolved = Resolved(root, None, [], None, cli.name, [])
999
+ elif cli.root_fetch is not None and not filtered:
1000
+ resolved = GatewayHit(Gateway(cli.root_fetch, cli.description), [], None, cli.name, [])
1001
+ else:
1002
+ resolved = resolve(cli.commands, filtered)
1003
+
1004
+ if flags.help and isinstance(resolved, GatewayHit):
1005
+ if resolved.path == cli.name and cli.commands:
1006
+ self.writeln(self.root_help(globals_=False))
1007
+ else:
1008
+ name = cli.name if resolved.path == cli.name else f"{cli.name} {resolved.path}"
1009
+ self.writeln(_gateway.help_text(name, resolved.gateway.description))
1010
+ return
1011
+ if flags.help:
1012
+ self.help(resolved)
1013
+ return
1014
+ if flags.schema:
1015
+ self.schema(resolved, flags)
1016
+ return
1017
+ if isinstance(resolved, GroupHelp):
1018
+ self.writeln(self.group_help(resolved, hide_skills=False, hide_update=False))
1019
+ return
1020
+
1021
+ update_cta: FormattedCtaBlock | None = None
1022
+ if human and cli.update is not None:
1023
+ available = check_update(cli.name, self.update_options(), self.env_map)
1024
+ if available is not None:
1025
+ update_cta = FormattedCtaBlock(
1026
+ [
1027
+ FormattedCta(
1028
+ f"{self.display_name} --update",
1029
+ f"upgrade from {available.current} to {available.latest}",
1030
+ )
1031
+ ],
1032
+ f"Update available for {available.name}:",
1033
+ )
1034
+ notices = [block for block in (skills_cta, update_cta) if block is not None]
1035
+ if notices:
1036
+ self.notice = FormattedCtaBlock(
1037
+ [c for block in notices for c in block.commands], notices[0].description
1038
+ )
1039
+
1040
+ command_format = resolved.command.format if isinstance(resolved, Resolved) else None
1041
+ fmt = flags.format if flags.format_explicit else command_format or cli.format or "toon"
1042
+
1043
+ # A token that is not a typo of a known command falls back to the root fetch or command.
1044
+ # A token starting with `/` is a request path, never a mistyped command.
1045
+ if (
1046
+ isinstance(resolved, NotFound)
1047
+ and not resolved.path
1048
+ and (root is not None or cli.root_fetch is not None)
1049
+ ):
1050
+ candidates = [*resolved.commands, *self.builtin_names()]
1051
+ if resolved.error.startswith("/") or suggest(resolved.error, candidates) is None:
1052
+ if cli.root_fetch is not None:
1053
+ gateway = Gateway(cli.root_fetch, cli.description)
1054
+ resolved = GatewayHit(gateway, [], None, cli.name, list(filtered))
1055
+ else:
1056
+ assert root is not None
1057
+ resolved = Resolved(root, None, [], None, cli.name, list(filtered))
1058
+
1059
+ if isinstance(resolved, (Resolved, GatewayHit)):
1060
+ policy = resolved.output_policy or cli.output_policy
1061
+ else:
1062
+ policy = cli.output_policy
1063
+ output = _Output(
1064
+ flags=flags,
1065
+ format=fmt,
1066
+ human=human,
1067
+ filter=_filter.parse(flags.filter_output) if flags.filter_output is not None else None,
1068
+ render=not (human and policy == "agent-only"),
1069
+ )
1070
+
1071
+ if isinstance(resolved, NotFound):
1072
+ self.not_found(resolved.error, resolved.path, resolved.commands, argv, output)
1073
+ elif isinstance(resolved, GatewayHit):
1074
+ await self.forward(resolved, filtered, output)
1075
+ else:
1076
+ await self.execute(resolved, filtered, output)
1077
+
1078
+ def update_options(self) -> UpdateOptions:
1079
+ """The update settings of this run."""
1080
+ update = self.cli.update
1081
+ assert update is not None
1082
+ return UpdateOptions(update, self.cli.version)
1083
+
1084
+ async def install_update(self, human: bool, flags: _Flags) -> None:
1085
+ """Handles `--update`, which is only a flag when updates are enabled."""
1086
+ cli = self.cli
1087
+ try:
1088
+ result = await install_update(cli.name, self.update_options(), self.env_map)
1089
+ except Exception as error:
1090
+ failure = Error("UPDATE_FAILED", str(error))
1091
+ if human:
1092
+ self.writeln(human_error(failure))
1093
+ else:
1094
+ self.writeln(format_value(failure.to_json(), flags.format))
1095
+ self.exit = 1
1096
+ return
1097
+ if human:
1098
+ deferred = result.get("deferred") is True
1099
+ lines = [
1100
+ f"\u2713 Update staged for {result['name']}"
1101
+ if deferred
1102
+ else f"\u2713 Updated {result['name']}"
1103
+ ]
1104
+ if "command" in result:
1105
+ lines.append(f" {result['command']}")
1106
+ if deferred:
1107
+ lines.append(" Installation will finish after this process exits.")
1108
+ self.writeln("\n".join(lines))
1109
+ else:
1110
+ self.writeln(format_value(result, flags.format))
1111
+
1112
+ async def skills_notice(self, flags: _Flags, filtered: list[str]) -> FormattedCtaBlock | None:
1113
+ """Suggests `skills add` when installed skills are out of date."""
1114
+ cli = self.cli
1115
+ if (
1116
+ cli.sync is None
1117
+ or flags.llms
1118
+ or flags.llms_full
1119
+ or flags.schema
1120
+ or flags.help
1121
+ or flags.update
1122
+ or flags.update_check
1123
+ or flags.version
1124
+ ):
1125
+ return None
1126
+ for index in (0, 1):
1127
+ if index == 1 and (not filtered or filtered[0] != cli.name):
1128
+ break
1129
+ if len(filtered) > index and _find_builtin(filtered[index]) in ("skills", "mcp"):
1130
+ return None
1131
+ env = self.env_map
1132
+ stored = read_hash(cli.name, env)
1133
+ if stored is None or not has_installed_skills(cli.name, env, cli.sync.cwd):
1134
+ return None
1135
+ # The stored hash covers every command, deferred groups included.
1136
+ await cli.load()
1137
+ infos, _ = self.skill_infos()
1138
+ if _skill.hash_commands(infos) == stored:
1139
+ return None
1140
+ runner = (env.get("npm_config_user_agent") or env.get("npm_execpath")) and (
1141
+ cli.package is not None or _syncmcp.is_package_name(cli.name)
1142
+ )
1143
+ if runner:
1144
+ specifier = _syncmcp.package_specifier(cli.name, cli.package, cli.version)
1145
+ command = f"{_pm.runner(env)} {specifier} skills add"
1146
+ else:
1147
+ command = f"{self.display_name} skills add"
1148
+ return FormattedCtaBlock(
1149
+ [FormattedCta(command, "sync outdated skills")], "Skills are out of date:"
1150
+ )
1151
+
1152
+ def builtin_names(self) -> list[str]:
1153
+ """Names of built-in commands, without skills when the integration is disabled."""
1154
+ return [n for n, _ in _BUILTINS if self.cli.sync or n != "skills"]
1155
+
1156
+ def register_scripts(self, shell: str) -> str:
1157
+ names = [self.cli.name, *self.cli.aliases]
1158
+ return "\n".join(_completions.register(shell, name) for name in names)
1159
+
1160
+ def command_help(
1161
+ self,
1162
+ command: Command,
1163
+ aliases: list[str],
1164
+ version: str | None,
1165
+ commands: list[HelpEntry] | None,
1166
+ root: bool,
1167
+ ) -> HelpOptions:
1168
+ return self.help_options(
1169
+ aliases=aliases,
1170
+ args=command.args,
1171
+ commands=commands or None,
1172
+ description=command.description,
1173
+ env=command.env,
1174
+ env_source=self.env,
1175
+ examples=command.examples or None,
1176
+ hint=command.hint,
1177
+ options=command.options,
1178
+ root=root,
1179
+ usage=command.usage,
1180
+ version=version,
1181
+ )
1182
+
1183
+ def help(self, resolved: Resolution) -> None:
1184
+ cli = self.cli
1185
+ assert not isinstance(resolved, GatewayHit)
1186
+ if isinstance(resolved, GroupHelp):
1187
+ text = self.group_help(resolved)
1188
+ elif isinstance(resolved, NotFound):
1189
+ entries = help_entries(cli.commands)
1190
+ if self.root is not None and entries:
1191
+ options = self.command_help(
1192
+ self.root,
1193
+ cli.aliases,
1194
+ cli.version,
1195
+ entries,
1196
+ True,
1197
+ )
1198
+ text = format_command(cli.name, options)
1199
+ else:
1200
+ text = self.root_help()
1201
+ else:
1202
+ command = resolved.command
1203
+ is_root = resolved.path == cli.name
1204
+ name = cli.name if is_root else f"{cli.name} {resolved.path}"
1205
+ if resolved.commands:
1206
+ entries = help_entries(resolved.commands)
1207
+ elif is_root:
1208
+ entries = help_entries(cli.commands)
1209
+ else:
1210
+ entries = []
1211
+ aliases = cli.aliases if is_root else command.aliases
1212
+ version = cli.version if is_root else None
1213
+ text = format_command(
1214
+ name, self.command_help(command, aliases, version, entries, is_root)
1215
+ )
1216
+ self.writeln(text)
1217
+
1218
+ def schema(self, resolved: Resolution, flags: _Flags) -> None:
1219
+ cli = self.cli
1220
+ if isinstance(resolved, GroupHelp):
1221
+ self.writeln(self.group_help(resolved, hide_skills=False))
1222
+ elif isinstance(resolved, GatewayHit):
1223
+ self.writeln("--schema is not supported for fetch commands.")
1224
+ self.exit = 1
1225
+ elif isinstance(resolved, NotFound):
1226
+ parent = f"{cli.name} {resolved.path}" if resolved.path else cli.name
1227
+ suggestion = suggest(resolved.error, resolved.commands)
1228
+ did_you_mean = f" Did you mean '{suggestion}'?" if suggestion else ""
1229
+ self.writeln(
1230
+ f"Error: '{resolved.error}' is not a command for '{parent}'.{did_you_mean}"
1231
+ )
1232
+ self.exit = 1
1233
+ else:
1234
+ command = resolved.command
1235
+ fmt: Format = flags.format if flags.format_explicit else "toon"
1236
+ out: dict[str, Json] = {}
1237
+ for key, ty in (
1238
+ ("args", command.args),
1239
+ ("env", command.env),
1240
+ ("options", command.options),
1241
+ ("output", command.output),
1242
+ ("globals", cli.globals),
1243
+ ):
1244
+ if ty is not None:
1245
+ out[key] = json_schema(ty)
1246
+ self.writeln(format_value(out, fmt))
1247
+
1248
+ def llms(self, flags: _Flags, filtered: list[str]) -> None:
1249
+ cli = self.cli
1250
+ commands: dict[str, Entry] = cli.commands
1251
+ prefix: list[str] = []
1252
+ description = cli.description
1253
+ root = self.root
1254
+ for token in filtered:
1255
+ entry = commands.get(token)
1256
+ if entry is None:
1257
+ break
1258
+ if isinstance(entry, Group):
1259
+ commands = entry.commands
1260
+ description = entry.description
1261
+ root = entry.root
1262
+ prefix.append(token)
1263
+ else:
1264
+ commands = {token: target(entry) or entry}
1265
+ root = None
1266
+ break
1267
+ if not prefix:
1268
+ root = self.root
1269
+ scoped = " ".join([cli.name, *prefix])
1270
+ if not flags.format_explicit or flags.format == "md":
1271
+ groups: dict[str, str] = {}
1272
+ infos = _skill.collect(commands, [], groups, root)
1273
+ if flags.llms_full:
1274
+ text = _skill.generate(scoped, infos, groups)
1275
+ else:
1276
+ text = _skill.index(scoped, infos, description)
1277
+ self.writeln(text)
1278
+ return
1279
+ full = flags.llms_full
1280
+ entries = _manifest_commands(commands, prefix, full)
1281
+ if root is not None and prefix:
1282
+ entries.append(_manifest_entry(" ".join(prefix), root, full))
1283
+ entries.sort(key=lambda e: _js.locale_key(str(e["name"])))
1284
+ manifest: dict[str, Json] = {"version": "incur.v1", "commands": [*entries]}
1285
+ if cli.globals is not None:
1286
+ manifest["globals"] = json_schema(cli.globals)
1287
+ self.writeln(format_value(manifest, flags.format))
1288
+
1289
+ def completions_help(self) -> None:
1290
+ name = self.cli.name
1291
+ rows = [
1292
+ ("bash", f'eval "$({name} completions bash)"', "# add to ~/.bashrc"),
1293
+ ("fish", f"{name} completions fish | source", "# add to ~/.config/fish/config.fish"),
1294
+ ("nushell", f"see `{name} completions nushell`", "# add to config.nu"),
1295
+ ("zsh", f'eval "$({name} completions zsh)"', "# add to ~/.zshrc"),
1296
+ ]
1297
+ width = max(_js.utf16_len(r[1]) for r in rows)
1298
+ hint = "\n".join(
1299
+ [
1300
+ "Setup:",
1301
+ *(
1302
+ f" {shell:<7} {command}{' ' * (width - _js.utf16_len(command))} {comment}"
1303
+ for shell, command, comment in rows
1304
+ ),
1305
+ ]
1306
+ )
1307
+ args = object_type(
1308
+ [
1309
+ Field(
1310
+ "shell",
1311
+ Type(
1312
+ "enum",
1313
+ values=list(_completions.SHELLS),
1314
+ description="Shell to generate completions for",
1315
+ ),
1316
+ )
1317
+ ]
1318
+ )
1319
+ text = format_command(
1320
+ f"{name} completions",
1321
+ HelpOptions(
1322
+ args=args,
1323
+ description="Generate shell completion script",
1324
+ hide_global_options=True,
1325
+ hint=hint,
1326
+ ),
1327
+ )
1328
+ self.writeln(text)
1329
+
1330
+ async def builtin(
1331
+ self,
1332
+ builtin: str,
1333
+ filtered: list[str],
1334
+ index: int,
1335
+ argv: list[str],
1336
+ flags: _Flags,
1337
+ human: bool,
1338
+ ) -> None:
1339
+ """Handles `skills` and `mcp`."""
1340
+ name = self.cli.name
1341
+ subs = [s for s in _BUILTIN_SUBCOMMANDS if s[0] == builtin]
1342
+ if index + 1 >= len(filtered):
1343
+ entries = [HelpEntry(s[1], s[2]) for s in subs]
1344
+ description = next(d for n, d in _BUILTINS if n == builtin)
1345
+ text = format_root(
1346
+ f"{name} {builtin}",
1347
+ HelpOptions(
1348
+ aliases=["skill"] if builtin == "skills" else [],
1349
+ commands=entries,
1350
+ description=description,
1351
+ ),
1352
+ )
1353
+ self.writeln(text)
1354
+ return
1355
+ sub = filtered[index + 1]
1356
+ found = next((s for s in subs if s[1] == sub or sub in s[3]), None)
1357
+ if found is None:
1358
+ candidates = [value for s in subs for value in (s[1], *s[3])]
1359
+ suggestion = suggest(sub, candidates)
1360
+ did_you_mean = f" Did you mean '{suggestion}'?" if suggestion else ""
1361
+ message = f"'{sub}' is not a command for '{name} {builtin}'.{did_you_mean}"
1362
+ commands: list[FormattedCta] = []
1363
+ if suggestion is not None:
1364
+ corrected = " ".join(suggestion if t == sub else t for t in argv)
1365
+ commands.append(FormattedCta(f"{name} {corrected}"))
1366
+ commands.append(FormattedCta(f"{name} {builtin} --help", "see all available commands"))
1367
+ cta = FormattedCtaBlock.of(commands)
1368
+ error = Error("COMMAND_NOT_FOUND", message)
1369
+ if human:
1370
+ self.writeln(human_error(error))
1371
+ self.writeln(cta.human())
1372
+ else:
1373
+ value: dict[str, Json] = {
1374
+ "code": error.code,
1375
+ "message": error.message,
1376
+ "cta": cta.to_json(),
1377
+ }
1378
+ self.writeln(format_value(value, "toon"))
1379
+ self.exit = 1
1380
+ return
1381
+ if flags.help:
1382
+ options: Type | None = None
1383
+ if found[:2] == ("mcp", "add"):
1384
+ options = object_type(
1385
+ [
1386
+ Field(
1387
+ "agent",
1388
+ _string_type("Target a specific agent (e.g. claude-code, cursor)"),
1389
+ ),
1390
+ Field(
1391
+ "command",
1392
+ _string_type(
1393
+ 'Override the command agents will run (e.g. "pnpm my-cli --mcp")'
1394
+ ),
1395
+ alias="c",
1396
+ ),
1397
+ Field(
1398
+ "noGlobal",
1399
+ Type(
1400
+ "boolean",
1401
+ optional=True,
1402
+ description="Install to project instead of globally",
1403
+ ),
1404
+ ),
1405
+ ]
1406
+ )
1407
+ elif found[:2] == ("skills", "add"):
1408
+ options = object_type(
1409
+ [
1410
+ Field(
1411
+ "depth",
1412
+ Type(
1413
+ "number",
1414
+ optional=True,
1415
+ description="Grouping depth for skill files (default: 1)",
1416
+ ),
1417
+ ),
1418
+ Field(
1419
+ "noGlobal",
1420
+ Type(
1421
+ "boolean",
1422
+ optional=True,
1423
+ description="Install to project instead of globally",
1424
+ ),
1425
+ ),
1426
+ ]
1427
+ )
1428
+ text = format_command(
1429
+ f"{name} {builtin} {found[1]}",
1430
+ HelpOptions(
1431
+ aliases=list(found[3]),
1432
+ description=found[2],
1433
+ hide_global_options=True,
1434
+ options=options,
1435
+ ),
1436
+ )
1437
+ self.writeln(text)
1438
+ return
1439
+ rest = filtered[index + 2 :]
1440
+ fmt: Format = flags.format if flags.format_explicit else "toon"
1441
+ if found[:2] == ("skills", "list"):
1442
+ await self.skills_list(fmt)
1443
+ elif found[:2] == ("skills", "add"):
1444
+ await self.skills_add(rest, flags, fmt)
1445
+ elif found[:2] == ("mcp", "doctor"):
1446
+ report = await self.mcp_doctor()
1447
+ self.writeln(format_value(report, fmt))
1448
+ if report["ok"] is not True:
1449
+ self.exit = 1
1450
+ else:
1451
+ await self.mcp_add(rest, flags, fmt)
1452
+
1453
+ def sync_options(self) -> SyncOptions:
1454
+ cli = self.cli
1455
+ sync = cli.sync
1456
+ assert sync is not None
1457
+ return SyncOptions(
1458
+ env=self.env_map,
1459
+ cwd=sync.cwd,
1460
+ depth=sync.depth,
1461
+ description=cli.description,
1462
+ include=list(sync.include),
1463
+ )
1464
+
1465
+ def skill_infos(self) -> tuple[list[_skill.CommandInfo], dict[str, str]]:
1466
+ """The commands that skill files describe, and group descriptions."""
1467
+ cli = self.cli
1468
+ groups: dict[str, str] = {cli.name: cli.description} if cli.description else {}
1469
+ return _skill.collect(cli.commands, [], groups, self.root), groups
1470
+
1471
+ async def skills_list(self, fmt: Format) -> None:
1472
+ """Handles `skills list`."""
1473
+ cli = self.cli
1474
+ try:
1475
+ infos, groups = self.skill_infos()
1476
+ skills = await list_skills(cli.name, infos, groups, self.sync_options())
1477
+ except Exception as error:
1478
+ failure: dict[str, Json] = {"code": "LIST_SKILLS_FAILED", "message": str(error)}
1479
+ self.writeln(format_value(failure, fmt))
1480
+ self.exit = 1
1481
+ return
1482
+ if not skills:
1483
+ self.writeln("No skills found.")
1484
+ return
1485
+ width = max(_js.utf16_len(s.name) for s in skills)
1486
+ lines: list[str] = []
1487
+ for s in skills:
1488
+ icon = "\u2713" if s.installed else "\u2717"
1489
+ pad = " " * (width - _js.utf16_len(s.name))
1490
+ lines.append(
1491
+ f" {icon} {s.name}" + (f"{pad} {s.description}" if s.description else "")
1492
+ )
1493
+ installed = sum(1 for s in skills if s.installed)
1494
+ plural = "" if len(skills) == 1 else "s"
1495
+ lines += ["", f"{len(skills)} skill{plural} ({installed} installed)"]
1496
+ self.writeln("\n".join(lines))
1497
+
1498
+ async def skills_add(self, rest: list[str], flags: _Flags, fmt: Format) -> None:
1499
+ """Handles `skills add`."""
1500
+ cli = self.cli
1501
+ sync = cli.sync
1502
+ assert sync is not None
1503
+ options = self.sync_options()
1504
+ if "--depth" in rest:
1505
+ at = rest.index("--depth") + 1
1506
+ options.depth = _js.to_number(rest[at]) if at < len(rest) else math.nan
1507
+ else:
1508
+ eq = next((t for t in rest if t.startswith("--depth=")), None)
1509
+ if eq is not None:
1510
+ options.depth = _js.to_number(eq.split("=")[1])
1511
+ options.global_ = False if "--no-global" in rest else None
1512
+ self.write("Syncing...")
1513
+ try:
1514
+ infos, groups = self.skill_infos()
1515
+ result = await sync_skills(cli.name, infos, groups, options)
1516
+ except Exception as error:
1517
+ failure: dict[str, Json] = {"code": "SYNC_SKILLS_FAILED", "message": str(error)}
1518
+ self.writeln(format_value(failure, fmt))
1519
+ self.exit = 1
1520
+ return
1521
+ self.write("\r\x1b[K")
1522
+ width = max((_js.utf16_len(s.name) for s in result.skills), default=0)
1523
+ lines: list[str] = []
1524
+ for s in result.skills:
1525
+ pad = " " * (width - _js.utf16_len(s.name))
1526
+ lines.append(
1527
+ f" \u2713 {s.name}" + (f"{pad} {s.description}" if s.description else "")
1528
+ )
1529
+ plural = "" if len(result.skills) == 1 else "s"
1530
+ lines += ["", f"{len(result.skills)} skill{plural} synced"]
1531
+ if sync.body:
1532
+ lines += ["", sync.body]
1533
+ if sync.suggestions:
1534
+ lines += ["", f"Your agent can now use {cli.name}. Try asking:"]
1535
+ lines += [f' "{s}"' for s in sync.suggestions]
1536
+ lines += ["", f"Run `{cli.name} --help` to see the full command reference."]
1537
+ self.writeln("\n".join(lines))
1538
+ if flags.full_output or flags.format_explicit:
1539
+ out: dict[str, Json] = {"skills": list(result.paths)}
1540
+ if sync.body:
1541
+ out["body"] = sync.body
1542
+ if flags.full_output and result.agents:
1543
+ out["agents"] = list(result.agents)
1544
+ self.writeln(format_value(out, fmt))
1545
+
1546
+ async def mcp_doctor(self) -> dict[str, Json]:
1547
+ """Handles `mcp doctor`: lists the tools a direct MCP server exposes."""
1548
+ report: dict[str, Json] = {"ok": False, "toolCount": 0, "tools": [], "warnings": []}
1549
+ try:
1550
+ server = McpServer(self.cli, self.env_map, direct=True)
1551
+ except Exception as error:
1552
+ report["errors"] = [{"code": "MCP_SERVER_FAILED", "message": str(error)}]
1553
+ return report
1554
+ listed = _js.as_list(server.list_tools()["tools"])
1555
+ tools: list[Json] = []
1556
+ for tool in listed:
1557
+ item = _js.as_object(tool)
1558
+ entry: dict[str, Json] = {"name": item["name"]}
1559
+ if "description" in item:
1560
+ entry["description"] = item["description"]
1561
+ tools.append(entry)
1562
+ report.update(ok=True, toolCount=len(tools), tools=tools, errors=[])
1563
+ if not tools:
1564
+ report["warnings"] = ["No MCP tools exposed."]
1565
+ return report
1566
+
1567
+ async def mcp_add(self, rest: list[str], flags: _Flags, fmt: Format) -> None:
1568
+ """Handles `mcp add`."""
1569
+ cli = self.cli
1570
+ options = cli.mcp or McpOptions()
1571
+ command = options.command
1572
+ agents = list(options.agents)
1573
+ i = 0
1574
+ while i < len(rest):
1575
+ if rest[i] in ("--command", "-c") and i + 1 < len(rest) and rest[i + 1]:
1576
+ command = rest[i + 1]
1577
+ i += 1
1578
+ elif rest[i] == "--agent" and i + 1 < len(rest) and rest[i + 1]:
1579
+ agents.append(rest[i + 1])
1580
+ i += 1
1581
+ i += 1
1582
+ name = options.name or cli.name
1583
+ self.write("Registering MCP server...")
1584
+ try:
1585
+ result = await _syncmcp.register(
1586
+ name,
1587
+ _syncmcp.Options(
1588
+ env=self.env_map,
1589
+ cli=None if name == cli.name else cli.name,
1590
+ command=command,
1591
+ global_="--no-global" not in rest,
1592
+ agents=agents,
1593
+ package=cli.package,
1594
+ version=cli.version if cli.package is not None else None,
1595
+ ),
1596
+ )
1597
+ except Exception as error:
1598
+ failure: dict[str, Json] = {"code": "MCP_ADD_FAILED", "message": str(error)}
1599
+ self.writeln(format_value(failure, fmt))
1600
+ self.exit = 1
1601
+ return
1602
+ self.write("\r\x1b[K")
1603
+ lines = [f"\u2713 Registered {name} as MCP server"]
1604
+ if result.agents:
1605
+ lines.append(f" Agents: {', '.join(result.agents)}")
1606
+ lines += ["", f"Agents can now use {name} tools."]
1607
+ suggestions = cli.sync.suggestions if cli.sync else []
1608
+ if suggestions:
1609
+ lines += ["", "Try asking:", *(f' "{s}"' for s in suggestions)]
1610
+ self.writeln("\n".join(lines))
1611
+ if flags.full_output or flags.format_explicit:
1612
+ out: dict[str, Json] = {
1613
+ "name": name,
1614
+ "command": result.command,
1615
+ "agents": list(result.agents),
1616
+ }
1617
+ self.writeln(format_value(out, fmt))
1618
+
1619
+ async def complete(self, shell: str, argv: list[str]) -> None:
1620
+ """Answers a shell completion request."""
1621
+ cli = self.cli
1622
+ if shell not in _completions.SHELLS:
1623
+ return
1624
+ words = argv[argv.index("--") + 1 :] if "--" in argv else argv
1625
+ if not words:
1626
+ self.write(self.register_scripts(shell))
1627
+ return
1628
+ # The index is a JavaScript number: shells may send anything, and `slice` and element
1629
+ # reads interpret it as JavaScript does.
1630
+ raw_index = self.env("_COMPLETE_INDEX")
1631
+ index = float(len(words) - 1) if raw_index is None else _js.to_number(raw_index)
1632
+ cut = _js.relative_index(index, len(words))
1633
+ before: list[str] | None
1634
+ try:
1635
+ before = _extract_flags(words[:cut], self.config_flag()).rest
1636
+ if _js.element(words, index - 1) == "--version":
1637
+ before.append("--version")
1638
+ globals_schema = cli.globals
1639
+ if globals_schema is not None:
1640
+ before = _parser.parse_globals(before, globals_schema)[1]
1641
+ except Error:
1642
+ before = None
1643
+ # Groups named before the cursor load so their commands complete.
1644
+ for word in before if before is not None else words[:cut]:
1645
+ await cli.load(word)
1646
+ if before is not None:
1647
+ words_in = [*before, *words[cut:]]
1648
+ at = len(before)
1649
+ else:
1650
+ words_in = list(words)
1651
+ at = cut
1652
+ tree = _tree(cli.commands, self.root, None)
1653
+ candidates = _completions.complete(tree, words_in, at, cli.globals)
1654
+ current = _js.element(words, index) or ""
1655
+ non_flags = [w for w in before if not w.startswith("-")] if before is not None else None
1656
+ if non_flags is not None and len(non_flags) <= 1:
1657
+ for name, description in _BUILTINS:
1658
+ if name == "skills" and not cli.sync:
1659
+ continue
1660
+ if name.startswith(current) and not any(c.value == name for c in candidates):
1661
+ candidates.append(
1662
+ _completions.Candidate(name, description, name != "completions")
1663
+ )
1664
+ elif non_flags is not None and len(non_flags) == 2:
1665
+ builtin = _find_builtin(non_flags[1])
1666
+ if builtin is not None and builtin != "completions" and builtin in self.builtin_names():
1667
+ for sub in _BUILTIN_SUBCOMMANDS:
1668
+ if sub[0] != builtin:
1669
+ continue
1670
+ for value in (sub[1], *sub[3]):
1671
+ if value.startswith(current) and not any(
1672
+ c.value == value for c in candidates
1673
+ ):
1674
+ candidates.append(_completions.Candidate(value, sub[2]))
1675
+ out = _completions.format_candidates(shell, candidates)
1676
+ if out:
1677
+ self.write(out)
1678
+
1679
+ def not_found(
1680
+ self,
1681
+ error: str,
1682
+ path: str,
1683
+ commands: dict[str, Entry],
1684
+ argv: list[str],
1685
+ output: _Output,
1686
+ ) -> None:
1687
+ cli = self.cli
1688
+ parent = f"{cli.name} {path}" if path else cli.name
1689
+ candidates = list(commands)
1690
+ if not path:
1691
+ candidates += self.builtin_names()
1692
+ suggestion = suggest(error, candidates)
1693
+ did_you_mean = f" Did you mean '{suggestion}'?" if suggestion else ""
1694
+ message = f"'{error}' is not a command for '{parent}'.{did_you_mean}"
1695
+ ctas: list[FormattedCta] = []
1696
+ if suggestion is not None:
1697
+ corrected = " ".join(suggestion if t == error else t for t in argv)
1698
+ ctas.append(FormattedCta(f"{cli.name} {corrected}"))
1699
+ ctas.append(FormattedCta(f"{parent} --help", "see all available commands"))
1700
+ cta = FormattedCtaBlock.of(ctas)
1701
+ failure = Error("COMMAND_NOT_FOUND", message)
1702
+ if output.human and not output.flags.full_output:
1703
+ self.writeln(human_error(failure))
1704
+ self.writeln(self.with_notice(cta).human())
1705
+ else:
1706
+ self.write_output(output, False, failure.to_json(), error, cta)
1707
+ self.exit = 1
1708
+
1709
+ @typing.overload
1710
+ def with_notice(self, cta: FormattedCtaBlock) -> FormattedCtaBlock: ...
1711
+
1712
+ @typing.overload
1713
+ def with_notice(self, cta: FormattedCtaBlock | None) -> FormattedCtaBlock | None: ...
1714
+
1715
+ def with_notice(self, cta: FormattedCtaBlock | None) -> FormattedCtaBlock | None:
1716
+ """Appends framework notices, such as an available update, to suggestions."""
1717
+ notice = self.notice
1718
+ if notice is None:
1719
+ return cta
1720
+ if cta is None:
1721
+ return notice
1722
+ return FormattedCtaBlock([*cta.commands, *notice.commands], cta.description)
1723
+
1724
+ @staticmethod
1725
+ def truncate(flags: _Flags, text: str) -> tuple[str, bool, float | None]:
1726
+ """Truncates text to the requested token window."""
1727
+ if flags.token_limit is None and flags.token_offset is None:
1728
+ return text, False, None
1729
+ total = float(_tokens.estimate(text))
1730
+ offset = flags.token_offset or 0.0
1731
+ end = total if flags.token_limit is None else offset + flags.token_limit
1732
+ if offset == 0 and end >= total:
1733
+ return text, False, None
1734
+ sliced = _tokens.slice_tokens(text, offset, end)
1735
+ actual_end = min(end, total)
1736
+ nxt = actual_end if actual_end < total else None
1737
+ note = (
1738
+ f"[truncated: showing tokens {_js.number_to_string(offset)}\u2013"
1739
+ f"{_js.number_to_string(actual_end)} of {_js.number_to_string(total)}]"
1740
+ )
1741
+ return f"{sliced}\n{note}", True, nxt
1742
+
1743
+ def write_output(
1744
+ self,
1745
+ output: _Output,
1746
+ ok: bool,
1747
+ body: _filter.Filtered,
1748
+ command: str,
1749
+ cta: FormattedCtaBlock | None,
1750
+ ) -> None:
1751
+ """Writes a command result. `body` is `MISSING` for no data."""
1752
+ flags = output.flags
1753
+ fmt = output.format
1754
+ cta = self.with_notice(cta)
1755
+ if output.filter is not None and ok and not isinstance(body, Missing):
1756
+ body = _filter.apply(body, output.filter)
1757
+ text = "" if isinstance(body, Missing) else format_value(body, fmt)
1758
+ if flags.token_count:
1759
+ self.writeln(str(_tokens.estimate(text)))
1760
+ return
1761
+ if output.human and not flags.full_output:
1762
+ if ok:
1763
+ if not isinstance(body, Missing) and body is not None and output.render:
1764
+ self.writeln(self.truncate(flags, text)[0])
1765
+ else:
1766
+ assert isinstance(body, dict)
1767
+ hint = body.get("hint")
1768
+ error = Error(
1769
+ str(body["code"]),
1770
+ str(body["message"]),
1771
+ hint=hint if isinstance(hint, str) else None,
1772
+ )
1773
+ self.writeln(human_error(error))
1774
+ if cta is not None:
1775
+ self.writeln(cta.human())
1776
+ return
1777
+ meta: dict[str, Json] = {"command": command, "duration": self.duration()}
1778
+ if cta is not None:
1779
+ meta["cta"] = cta.to_json()
1780
+ key = "data" if ok else "error"
1781
+ envelope: dict[str, Json] = {"ok": ok}
1782
+ if flags.full_output:
1783
+ truncated, done, nxt = self.truncate(flags, text)
1784
+ if done:
1785
+ if nxt is not None:
1786
+ meta["nextOffset"] = nxt
1787
+ envelope[key] = truncated
1788
+ elif not isinstance(body, Missing):
1789
+ envelope[key] = body
1790
+ envelope["meta"] = meta
1791
+ self.writeln(format_value(envelope, fmt))
1792
+ return
1793
+ if cta is None:
1794
+ if text:
1795
+ self.writeln(self.truncate(flags, text)[0])
1796
+ return
1797
+ if isinstance(body, dict):
1798
+ payload: dict[str, Json] = {**body, "cta": cta.to_json()}
1799
+ else:
1800
+ payload = {} if isinstance(body, Missing) else {"data": body}
1801
+ payload["cta"] = cta.to_json()
1802
+ self.writeln(self.truncate(flags, format_value(payload, fmt))[0])
1803
+
1804
+ def write_failure(self, output: _Output, error: Error, command: str) -> None:
1805
+ cta = format_cta(self.display_name, error.cta)
1806
+ self.write_output(output, False, error.to_json(), command, cta)
1807
+ self.exit = error.exit_code if error.exit_code is not None else 1
1808
+
1809
+ def deprecations(self, argv: list[str], options: Type | None) -> None:
1810
+ """Writes warnings for deprecated flags."""
1811
+ if options is None:
1812
+ return
1813
+ deprecated = [(_js.to_kebab(f.name), f.alias) for f in options.fields if f.ty.deprecated]
1814
+ known = {kebab for kebab, _ in deprecated}
1815
+ for token in argv:
1816
+ if token.startswith("--"):
1817
+ stripped = token[2:].split("=")[0]
1818
+ raw = stripped
1819
+ if stripped.startswith("no-") and stripped not in known:
1820
+ raw = stripped[3:]
1821
+ if raw in known:
1822
+ self.stderr.write(f"Warning: --{raw} is deprecated\n")
1823
+ elif len(token) >= 2 and token.startswith("-"):
1824
+ for ch in token[1:]:
1825
+ kebab = next((k for k, alias in deprecated if alias == ch), None)
1826
+ if kebab is not None:
1827
+ self.stderr.write(f"Warning: --{kebab} is deprecated\n")
1828
+
1829
+ async def config_defaults(self, path: str, flags: _Flags) -> dict[str, Json] | None:
1830
+ """Loads config-file defaults for a command path."""
1831
+ cli = self.cli
1832
+ config = cli.config
1833
+ if config is None or flags.config_disabled:
1834
+ return None
1835
+
1836
+ def resolve_path(p: str) -> str:
1837
+ if p == "~" or p.startswith("~/"):
1838
+ rest = p[1:].lstrip("/")
1839
+ home = self.env("HOME") or ""
1840
+ return os.path.join(home, rest) if rest else home
1841
+ return os.path.join(os.getcwd(), p)
1842
+
1843
+ target: str | None
1844
+ if flags.config_path is not None:
1845
+ target = resolve_path(flags.config_path)
1846
+ else:
1847
+ files = config.files or [f"{cli.name}.json"]
1848
+ target = next((p for p in map(resolve_path, files) if _exists(p)), None)
1849
+
1850
+ parsed: object
1851
+ if config.loader is not None:
1852
+ try:
1853
+ parsed = config.loader(target)
1854
+ if inspect.isawaitable(parsed):
1855
+ parsed = await parsed
1856
+ except Error:
1857
+ raise
1858
+ except Exception as error:
1859
+ raise unknown(str(error)) from error
1860
+ if parsed is None:
1861
+ return None
1862
+ if not isinstance(parsed, dict):
1863
+ raise unknown("Config loader must return a plain object or undefined")
1864
+ else:
1865
+ if target is None:
1866
+ return None
1867
+ try:
1868
+ with open(target, "rb") as file:
1869
+ raw = file.read().decode("utf-8", "replace")
1870
+ except FileNotFoundError:
1871
+ # Search paths only resolve to existing files, so a missing file was named by flag.
1872
+ raise unknown(f"Config file not found: {target}") from None
1873
+ except OSError as error:
1874
+ # TypeScript reports Node's `fs` message here, whose wording varies by version.
1875
+ raise unknown(error.strerror or str(error)) from None
1876
+ details = _js.json_parse_error(raw)
1877
+ if details is not None:
1878
+ raise unknown(f"Invalid JSON config file: {target}\n\nDetails: {details}")
1879
+ parsed = _js.parse_json(raw)
1880
+ if not isinstance(parsed, dict):
1881
+ raise unknown(f"Invalid config file: expected a top-level object in {target}")
1882
+ node: Json = typing.cast("dict[str, Json]", parsed)
1883
+ for segment in [] if path == cli.name else path.split(" "):
1884
+ section = node.get("commands") if isinstance(node, dict) else None
1885
+ if not isinstance(section, dict) or segment not in section:
1886
+ return None
1887
+ node = section[segment]
1888
+ if not isinstance(node, dict):
1889
+ raise unknown(f"Invalid config section for '{path}': expected an object")
1890
+ options = node.get("options")
1891
+ if options is None or options == {}:
1892
+ return None
1893
+ if not isinstance(options, dict):
1894
+ raise unknown(f"Invalid config 'options' for '{path}': expected an object")
1895
+ return dict(options)
1896
+
1897
+ async def execute(self, resolved: Resolved, filtered: list[str], output: _Output) -> None:
1898
+ """Parses input, runs middleware and the handler, and writes the result."""
1899
+ cli = self.cli
1900
+ command = resolved.command
1901
+ path = resolved.path
1902
+ depth = len(filtered) - len(resolved.rest)
1903
+ globals_: dict[str, Json] = {}
1904
+ argv = output.flags.rest
1905
+ globals_schema = cli.globals
1906
+ if globals_schema is not None:
1907
+ try:
1908
+ globals_, argv = _parser.parse_globals(
1909
+ output.flags.rest, globals_schema, command.options, known=True, validate=True
1910
+ )
1911
+ except Error as error:
1912
+ self.early_error(error, output.human, output.flags.format)
1913
+ return
1914
+ argv = argv[depth:]
1915
+ if output.human:
1916
+ self.deprecations(argv, command.options)
1917
+ try:
1918
+ defaults = await self.config_defaults(path, output.flags)
1919
+ except Error as error:
1920
+ self.write_failure(output, error, path)
1921
+ return
1922
+
1923
+ context = self.context(path, output, globals_)
1924
+
1925
+ def parse() -> tuple[dict[str, Json], dict[str, Json], dict[str, Json]]:
1926
+ args, options = _parser.parse(argv, command.args, command.options, defaults)
1927
+ env = _parser.parse_env(command.env, self.env) if command.env else {}
1928
+ return args, options, env
1929
+
1930
+ async def sink(chunks: Stream) -> None:
1931
+ await self.stream(chunks, path, output)
1932
+
1933
+ result: Success | Error | None
1934
+ try:
1935
+ if cli.env is not None:
1936
+ context.env = build(cli.env, _parser.parse_env(cli.env, self.env))
1937
+ except Error as error:
1938
+ result = error
1939
+ else:
1940
+ chain = [*cli.middleware, *resolved.middleware, *command.middleware]
1941
+ result = await execute(command, context, chain, parse, sink)
1942
+ if result is None:
1943
+ return
1944
+ if isinstance(result, Error):
1945
+ if output.human and not output.flags.format_explicit and result.field_errors:
1946
+ self.validation_help(command, path, result)
1947
+ else:
1948
+ self.write_failure(output, result, path)
1949
+ return
1950
+ data = MISSING if result.data is None else result.data
1951
+ self.write_output(output, True, data, path, format_cta(self.display_name, result.cta))
1952
+
1953
+ def context(
1954
+ self, path: str, output: _Output, globals_: dict[str, Json]
1955
+ ) -> MiddlewareContext[Any, Any, Any]:
1956
+ """Creates the middleware context of a run."""
1957
+ cli = self.cli
1958
+ return MiddlewareContext[Any, Any, Any](
1959
+ agent=not output.human,
1960
+ command=path,
1961
+ display_name=self.display_name,
1962
+ env=None,
1963
+ format=output.format,
1964
+ format_explicit=output.flags.format_explicit,
1965
+ globals=build(cli.globals, globals_) if cli.globals else None,
1966
+ name=cli.name,
1967
+ var=cli.vars_instance(),
1968
+ version=cli.version,
1969
+ )
1970
+
1971
+ async def forward(self, hit: GatewayHit, filtered: list[str], output: _Output) -> None:
1972
+ """Runs a fetch gateway: sends argv as an HTTP request and writes the response."""
1973
+ cli = self.cli
1974
+ path = hit.path
1975
+ depth = len(filtered) - len(hit.rest)
1976
+ globals_: dict[str, Json] = {}
1977
+ argv = output.flags.rest
1978
+ if cli.globals is not None:
1979
+ try:
1980
+ globals_, argv = _parser.parse_globals(
1981
+ output.flags.rest, cli.globals, None, known=True, validate=True
1982
+ )
1983
+ except Error as error:
1984
+ self.early_error(error, output.human, output.flags.format)
1985
+ return
1986
+ argv = argv[depth:]
1987
+
1988
+ async def send() -> None:
1989
+ data = _gateway.parse_argv(argv)
1990
+ if hit.gateway.base_path:
1991
+ data.path = hit.gateway.base_path + data.path
1992
+ response = await call(hit.gateway.fetch, _gateway.build_request(data))
1993
+ if _gateway.is_streaming(response):
1994
+ await self.stream(_gateway.stream(response), path, output, cli.name)
1995
+ return
1996
+ body = await _gateway.read(response)
1997
+ if response.ok:
1998
+ self.write_output(output, True, body, path, None)
1999
+ return
2000
+ code, message = _gateway.error_of(body, response.status)
2001
+ self.write_output(output, False, {"code": code, "message": message}, path, None)
2002
+ self.exit = 1
2003
+
2004
+ try:
2005
+ context = self.context(path, output, globals_)
2006
+ if cli.env is not None:
2007
+ context.env = build(cli.env, _parser.parse_env(cli.env, self.env))
2008
+ chain = [*cli.middleware, *hit.middleware]
2009
+ failure = await run_chain(chain, context, send) if chain else await send()
2010
+ except Error as error:
2011
+ failure = error
2012
+ except Exception as error:
2013
+ failure = unknown(str(error))
2014
+ if failure is not None:
2015
+ self.write_failure(output, failure, path)
2016
+
2017
+ def validation_help(self, command: Command, path: str, error: Error) -> None:
2018
+ """Writes human validation errors followed by command help."""
2019
+ cli = self.cli
2020
+ lines: list[str] = []
2021
+ for f in error.field_errors or []:
2022
+ head, *tail = f.path.split(".")
2023
+ suffix = "." + ".".join(tail) if tail else ""
2024
+ if command.options is not None and command.options.field(head) is not None:
2025
+ kind, label = "option", f"--{_js.to_kebab(head)}{suffix}"
2026
+ elif command.env is not None and command.env.field(head) is not None:
2027
+ kind, label = "environment variable", f"{head}{suffix}"
2028
+ else:
2029
+ kind, label = "argument", f"<{f.path}>"
2030
+ if f.missing:
2031
+ lines.append(f"Error: missing required {kind} {label}")
2032
+ elif kind == "environment variable":
2033
+ lines.append(f"Error: invalid value for environment variable {label}: {f.message}")
2034
+ else:
2035
+ lines.append(f"Error: invalid value for {label}: {f.message}")
2036
+ lines += ["See below for usage.", ""]
2037
+ name = cli.name if path == cli.name else f"{cli.name} {path}"
2038
+ lines.append(
2039
+ format_command(
2040
+ name,
2041
+ HelpOptions(
2042
+ args=command.args,
2043
+ config_flag=self.config_flag(),
2044
+ description=command.description,
2045
+ env=command.env,
2046
+ env_source=self.env,
2047
+ examples=command.examples or None,
2048
+ hint=command.hint,
2049
+ options=command.options,
2050
+ usage=command.usage,
2051
+ ),
2052
+ )
2053
+ )
2054
+ self.writeln("\n".join(lines))
2055
+ self.exit = 1
2056
+
2057
+ async def stream(
2058
+ self,
2059
+ chunks: Stream | AsyncIterator[Json],
2060
+ path: str,
2061
+ output: _Output,
2062
+ name: str | None = None,
2063
+ ) -> None:
2064
+ """Writes a streamed result."""
2065
+ jsonl = output.format == "jsonl"
2066
+ incremental = jsonl or (not output.flags.format_explicit and output.format == "toon")
2067
+ name = name or self.display_name
2068
+
2069
+ def fail(error: Error) -> None:
2070
+ cta = format_cta(name, error.cta)
2071
+ if jsonl:
2072
+ record: dict[str, Json] = {"type": "error", "ok": False, "error": error.to_json()}
2073
+ if cta is not None:
2074
+ record["meta"] = {"cta": cta.to_json()}
2075
+ self.writeln(_js.stringify(record))
2076
+ elif incremental:
2077
+ self.writeln(human_error(error))
2078
+ if cta is not None:
2079
+ self.writeln(cta.human())
2080
+ else:
2081
+ self.write_output(output, False, error.to_json(), path, cta)
2082
+ self.exit = error.exit_code if error.exit_code is not None else 1
2083
+
2084
+ buffered: list[Json] = []
2085
+ try:
2086
+ async for chunk in chunks:
2087
+ value = to_json(chunk)
2088
+ if jsonl:
2089
+ self.writeln(_js.stringify({"type": "chunk", "data": value}))
2090
+ elif incremental:
2091
+ if output.render:
2092
+ text = format_value(value, output.format)
2093
+ self.writeln(self.truncate(output.flags, text)[0])
2094
+ else:
2095
+ buffered.append(value)
2096
+ except Error as error:
2097
+ fail(error)
2098
+ return
2099
+ except Exception as error:
2100
+ fail(unknown(str(error)))
2101
+ return
2102
+ final = chunks.final if isinstance(chunks, Stream) else None
2103
+ cta = format_cta(name, final.cta if isinstance(final, Outcome) else None)
2104
+ if jsonl:
2105
+ meta: dict[str, Json] = {"command": path, "duration": self.duration()}
2106
+ if cta is not None:
2107
+ meta["cta"] = cta.to_json()
2108
+ self.writeln(_js.stringify({"type": "done", "ok": True, "meta": meta}))
2109
+ elif incremental:
2110
+ if cta is not None:
2111
+ self.writeln(cta.human())
2112
+ else:
2113
+ self.write_output(output, True, buffered, path, cta)
2114
+
2115
+
2116
+ def _exists(path: str) -> bool:
2117
+ """Whether a path opens for reading, as a search path must."""
2118
+ try:
2119
+ os.close(os.open(path, os.O_RDONLY))
2120
+ except OSError:
2121
+ return False
2122
+ return True
2123
+
2124
+
2125
+ def _tree(
2126
+ commands: dict[str, Entry], root: Command | None, description: str | None
2127
+ ) -> _completions.Node:
2128
+ """Builds the completion tree of a command group."""
2129
+ nodes: list[tuple[str, _completions.Node, bool]] = []
2130
+ for name, entry in commands.items():
2131
+ if isinstance(entry, Group):
2132
+ node = _tree(entry.commands, entry.root, entry.description)
2133
+ else:
2134
+ command = target(entry)
2135
+ assert command is not None
2136
+ node = _completions.Node(command.description, command.options, False, [])
2137
+ nodes.append((name, node, isinstance(entry, Alias)))
2138
+ options = root.options if root is not None else None
2139
+ return _completions.Node(description, options, True, nodes)