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/_command.py ADDED
@@ -0,0 +1,426 @@
1
+ """Commands, their run context, results, middleware, and the transport-independent executor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextvars
7
+ import dataclasses
8
+ import inspect
9
+ import threading
10
+ import typing
11
+ from collections.abc import AsyncGenerator, Awaitable, Callable, Generator
12
+ from dataclasses import dataclass, field
13
+ from typing import TYPE_CHECKING, Any, Generic, Literal
14
+
15
+ from ._errors import CtaBlock, Error, unknown
16
+ from ._formatter import Format
17
+ from ._help import Example, Usage
18
+ from ._http import Request
19
+ from ._js import Json
20
+ from ._model import SchemaError, build, schema_of, to_json
21
+ from ._schema import Type
22
+
23
+ if TYPE_CHECKING:
24
+ from typing_extensions import TypeVar
25
+ else:
26
+ from typing import TypeVar as _TypeVar
27
+
28
+ def TypeVar(name: str, default: object = None) -> object: # noqa: N802
29
+ """Creates a type variable; defaults only matter to type checkers."""
30
+ return _TypeVar(name)
31
+
32
+
33
+ A = TypeVar("A", default=None)
34
+ O = TypeVar("O", default=None) # noqa: E741
35
+ E = TypeVar("E", default=None)
36
+ V = TypeVar("V", default=Any)
37
+ G = TypeVar("G", default=Any)
38
+ CE = TypeVar("CE", default=Any)
39
+
40
+ #: Where a command's output may appear: everywhere, or only to agents.
41
+ OutputPolicy = Literal["all", "agent-only"]
42
+
43
+
44
+ @dataclass
45
+ class Context(Generic[A, O, E, V, G]):
46
+ """The context a command handler receives.
47
+
48
+ Parameterize the handler's annotation with the schema classes it reads:
49
+ `Context[Args, Options, Env, Vars, Globals]`. Omitted input parameters default to `None` (no
50
+ input); omitted `Vars` and `Globals` are untyped.
51
+ """
52
+
53
+ agent: bool
54
+ """Whether the consumer is an agent (stdout is not a terminal)."""
55
+ args: A
56
+ """Positional arguments."""
57
+ display_name: str
58
+ """The binary name the user invoked."""
59
+ env: E
60
+ """Environment variables declared by the command."""
61
+ format: Format
62
+ """The resolved output format."""
63
+ format_explicit: bool
64
+ """Whether the user passed `--format` or `--json`."""
65
+ globals: G
66
+ """Global options: an instance of the CLI's `globals` class, or `None` without one."""
67
+ name: str
68
+ """The CLI name."""
69
+ options: O
70
+ """Named options."""
71
+ var: V
72
+ """Variables set by middleware: an instance of the CLI's `vars` class, or a `dict`."""
73
+ version: str | None
74
+ """The CLI version."""
75
+ request: Request | None = None
76
+ """The HTTP request, when the command runs over HTTP or HTTP MCP."""
77
+
78
+ def __class_getitem__(cls, params: object) -> Any:
79
+ """Fills omitted input parameters with `None`, and omitted state parameters with `Any`."""
80
+ padded = _pad(params, (None, None, None, Any, Any))
81
+ # `Generic` implements `__class_getitem__` at runtime only.
82
+ return super().__class_getitem__(padded) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownVariableType]
83
+
84
+
85
+ def _pad(params: object, fill: tuple[object, ...]) -> tuple[object, ...]:
86
+ """Fills omitted type parameters, which runtime `Generic` subscription requires."""
87
+ items = typing.cast("tuple[object, ...]", params if isinstance(params, tuple) else (params,))
88
+ return (*items, *fill[len(items) :])
89
+
90
+
91
+ @dataclass
92
+ class MiddlewareContext(Generic[V, CE, G]):
93
+ """The context middleware receives.
94
+
95
+ Parameterize the annotation with the CLI's classes: `MiddlewareContext[Vars, Env, Globals]`.
96
+ """
97
+
98
+ agent: bool
99
+ """Whether the consumer is an agent."""
100
+ command: str
101
+ """The resolved command path."""
102
+ display_name: str
103
+ """The binary name the user invoked."""
104
+ env: CE
105
+ """CLI-level environment variables: an instance of the CLI's `env` class, or `None`."""
106
+ format: Format
107
+ """The resolved output format."""
108
+ format_explicit: bool
109
+ """Whether the user passed `--format` or `--json`."""
110
+ globals: G
111
+ """Global options: an instance of the CLI's `globals` class, or `None` without one."""
112
+ name: str
113
+ """The CLI name."""
114
+ var: V
115
+ """Variables for downstream middleware and handlers: assign attributes, or keys of a `dict`."""
116
+ version: str | None
117
+ """The CLI version."""
118
+ request: Request | None = None
119
+ """The HTTP request, when the command runs over HTTP or HTTP MCP."""
120
+
121
+ def __class_getitem__(cls, params: object) -> Any:
122
+ """Fills omitted parameters with `Any`."""
123
+ padded = _pad(params, (Any, Any, Any))
124
+ return super().__class_getitem__(padded) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownVariableType]
125
+
126
+ def set(self, key: str, value: object) -> None:
127
+ """Sets a variable for downstream middleware and handlers, as `c.var.<key> = value` does."""
128
+ var: object = self.var
129
+ if isinstance(var, dict):
130
+ typing.cast("dict[str, object]", var)[key] = value
131
+ else:
132
+ setattr(var, key, value)
133
+
134
+
135
+ #: Runs the rest of the middleware chain and the command. `async def` middleware awaits it;
136
+ #: plain functions call it, and it returns once the rest of the chain has finished.
137
+ Next = Callable[[], Awaitable[None]]
138
+
139
+ #: Middleware: runs around command handlers in registration order. Raise `incur.Error` to fail.
140
+ #: Plain functions run in a worker thread, so their blocking `next()` cannot stall the event loop.
141
+ Middleware = Callable[[MiddlewareContext[Any, Any, Any], Next], Awaitable[None] | None]
142
+
143
+
144
+ @dataclass
145
+ class Outcome:
146
+ """Handler data with suggested next commands. Create it with `incur.ok`."""
147
+
148
+ data: object
149
+ """The data, or `None` for no data."""
150
+ cta: CtaBlock | None
151
+ """Suggested next commands."""
152
+
153
+
154
+ def ok(data: object = None, *, cta: CtaBlock | None = None) -> Outcome:
155
+ """Returns data with suggested next commands.
156
+
157
+ Return it from a handler. A streaming handler yields it last, or a generator returns it, to
158
+ attach suggestions after the stream; its data is ignored.
159
+ """
160
+ return Outcome(data, cta)
161
+
162
+
163
+ @dataclass
164
+ class ToolMeta:
165
+ """How a command appears as an MCP tool."""
166
+
167
+ name: str | None = None
168
+ description: str | None = None
169
+ annotations: dict[str, Json] | None = None
170
+ instructions: str | None = None
171
+
172
+
173
+ @dataclass
174
+ class Command:
175
+ """A registered command."""
176
+
177
+ handler: Callable[..., object] | None = None
178
+ aliases: list[str] = field(default_factory=list[str])
179
+ args: Type | None = None
180
+ destructive: bool = False
181
+ description: str | None = None
182
+ env: Type | None = None
183
+ examples: list[Example] = field(default_factory=list[Example])
184
+ format: Format | None = None
185
+ hint: str | None = None
186
+ middleware: list[Middleware] = field(default_factory=list[Middleware])
187
+ options: Type | None = None
188
+ output: Type | None = None
189
+ output_policy: OutputPolicy | None = None
190
+ usage: list[Usage] = field(default_factory=list[Usage])
191
+ mcp: ToolMeta | None = None
192
+ mcp_enabled: bool = True
193
+
194
+
195
+ def inputs(
196
+ fn: Callable[..., object], scope: dict[str, Any], state: tuple[type | None, type | None]
197
+ ) -> tuple[Type | None, Type | None, Type | None]:
198
+ """Reads the args, options, and env schemas from a handler's `Context[...]` annotation.
199
+
200
+ `state` holds the vars and globals classes of the registering CLI, which the annotation's
201
+ `Vars` and `Globals` must match when both name a class.
202
+ """
203
+ label = getattr(fn, "__qualname__", repr(fn))
204
+ params = list(inspect.signature(fn).parameters.values())
205
+ if len(params) != 1:
206
+ raise SchemaError(f"{label}: a handler takes exactly one parameter, the context")
207
+ hint = typing.get_type_hints(fn, localns=scope).get(params[0].name, Context)
208
+ if hint is Context:
209
+ return None, None, None
210
+ if typing.get_origin(hint) is not Context:
211
+ raise SchemaError(f"{label}: annotate the parameter as incur.Context[...]")
212
+ *schemas, vars_, globals_ = typing.get_args(hint)
213
+ for name, declared, expected in (("vars", vars_, state[0]), ("globals", globals_, state[1])):
214
+ # `Any` is a class too, from Python 3.11.
215
+ typed = isinstance(declared, type) and declared is not Any
216
+ if typed and expected is not None and declared is not expected:
217
+ raise SchemaError(
218
+ f"{label}: Context {name} must be {expected.__qualname__}, the CLI's {name} class"
219
+ )
220
+ found: list[Type | None] = []
221
+ for arg in schemas:
222
+ if arg is type(None):
223
+ found.append(None)
224
+ continue
225
+ ty = schema_of(arg) if isinstance(arg, type) else None
226
+ if ty is None:
227
+ raise SchemaError(f"{label}: Context parameters must be @incur.schema classes or None")
228
+ found.append(dataclasses.replace(ty, py=arg))
229
+ return found[0], found[1], found[2]
230
+
231
+
232
+ class Stream:
233
+ """The chunks a streaming handler yields, from a generator or an async generator.
234
+
235
+ Iteration ends at the first yielded `incur.ok(...)`, which becomes `final`, as does the
236
+ value a generator returns.
237
+ """
238
+
239
+ def __init__(
240
+ self, source: Generator[object, None, object] | AsyncGenerator[object, None]
241
+ ) -> None:
242
+ self.source = source
243
+ self.final: object = None
244
+ """The stream's result: an `Outcome` with suggestions, or `None`."""
245
+
246
+ def __aiter__(self) -> Stream:
247
+ return self
248
+
249
+ async def __anext__(self) -> object:
250
+ source = self.source
251
+ if isinstance(source, Generator):
252
+ try:
253
+ value = next(source)
254
+ except StopIteration as stop:
255
+ self.final = stop.value
256
+ raise StopAsyncIteration from None
257
+ else:
258
+ value = await anext(source)
259
+ if isinstance(value, Outcome):
260
+ self.final = value
261
+ if isinstance(source, Generator):
262
+ source.close()
263
+ else:
264
+ await source.aclose()
265
+ raise StopAsyncIteration
266
+ return value
267
+
268
+
269
+ @dataclass
270
+ class Success:
271
+ """The data of a command that succeeded, with its suggestions."""
272
+
273
+ data: Json
274
+ """The data as JSON, `None` for no data."""
275
+ cta: CtaBlock | None
276
+ """Suggested next commands."""
277
+
278
+
279
+ #: Parses a command's args, options, and env as JSON data. Raises `incur.Error` on bad input.
280
+ Parse = Callable[[], tuple[dict[str, Json], dict[str, Json], dict[str, Json]]]
281
+
282
+ #: Consumes a handler's stream: writes chunks to a terminal, a response, or a protocol message.
283
+ Sink = Callable[[Stream], Awaitable[None]]
284
+
285
+
286
+ async def execute(
287
+ command: Command,
288
+ context: MiddlewareContext[Any, Any, Any],
289
+ chain: list[Middleware],
290
+ parse: Parse,
291
+ sink: Sink,
292
+ ) -> Success | Error | None:
293
+ """Runs the middleware chain around a command, as every transport does.
294
+
295
+ Input parses inside the chain, after middleware has run. A stream goes to `sink` while
296
+ middleware waits in `next()`, and the result is then `None`. The outermost error wins.
297
+ """
298
+ result: Success | Error | None = Success(None, None)
299
+
300
+ async def last() -> None:
301
+ nonlocal result
302
+ try:
303
+ args, options, env = parse()
304
+ except Error as error:
305
+ result = error
306
+ return
307
+ result = await _invoke(command, context, args, options, env, sink)
308
+
309
+ failure = await run_chain(chain, context, last)
310
+ return result if failure is None else failure
311
+
312
+
313
+ async def _invoke(
314
+ command: Command,
315
+ c: MiddlewareContext[Any, Any, Any],
316
+ args: dict[str, Json],
317
+ options: dict[str, Json],
318
+ env: dict[str, Json],
319
+ sink: Sink,
320
+ ) -> Success | Error | None:
321
+ """Runs a handler, awaiting coroutines and passing streams to `sink`."""
322
+ handler = command.handler
323
+ assert handler is not None
324
+ cta: CtaBlock | None = None
325
+ try:
326
+ context = Context(
327
+ agent=c.agent,
328
+ args=build(command.args, args) if command.args else None,
329
+ display_name=c.display_name,
330
+ env=build(command.env, env) if command.env else None,
331
+ format=c.format,
332
+ format_explicit=c.format_explicit,
333
+ globals=c.globals,
334
+ name=c.name,
335
+ options=build(command.options, options) if command.options else None,
336
+ var=c.var,
337
+ version=c.version,
338
+ request=c.request,
339
+ )
340
+ result = handler(context)
341
+ if inspect.isawaitable(result):
342
+ result = await result
343
+ if inspect.isgenerator(result) or inspect.isasyncgen(result):
344
+ source = typing.cast(
345
+ "Generator[object, None, object] | AsyncGenerator[object, None]", result
346
+ )
347
+ await sink(Stream(source))
348
+ return None
349
+ if isinstance(result, Outcome):
350
+ cta = result.cta
351
+ result = result.data
352
+ return Success(to_json(result), cta)
353
+ except Error as error:
354
+ if error.cta is None and cta is not None:
355
+ error.cta = cta
356
+ return error
357
+ except Exception as error:
358
+ return unknown(str(error))
359
+
360
+
361
+ class _Done:
362
+ """The finished awaitable a plain-function middleware's `next()` returns."""
363
+
364
+ def __await__(self) -> Generator[None, None, None]:
365
+ yield from ()
366
+
367
+
368
+ async def run_chain(
369
+ chain: list[Middleware],
370
+ context: MiddlewareContext[Any, Any, Any],
371
+ last: Callable[[], Awaitable[None]],
372
+ ) -> Error | None:
373
+ """Runs a middleware chain around `last`. The outermost error wins."""
374
+ if not chain:
375
+ await last()
376
+ return None
377
+ first, rest = chain[0], chain[1:]
378
+ loop = asyncio.get_running_loop()
379
+ loop_thread = threading.get_ident()
380
+ inner: Error | None = None
381
+
382
+ async def run_rest() -> None:
383
+ nonlocal inner
384
+ inner = await run_chain(rest, context, last)
385
+
386
+ def call_next() -> Awaitable[None]:
387
+ if threading.get_ident() == loop_thread:
388
+ return run_rest()
389
+ # A plain function's `next()` blocks its worker thread until the chain has finished.
390
+ asyncio.run_coroutine_threadsafe(run_rest(), loop).result()
391
+ return _Done()
392
+
393
+ try:
394
+ if inspect.iscoroutinefunction(first):
395
+ returned = first(context, call_next)
396
+ else:
397
+ returned = await _in_thread(lambda: first(context, call_next))
398
+ if inspect.isawaitable(returned):
399
+ await returned
400
+ except Error as error:
401
+ return error
402
+ except Exception as error:
403
+ return unknown(str(error))
404
+ return inner
405
+
406
+
407
+ async def _in_thread(fn: Callable[[], object]) -> object:
408
+ """Runs a blocking function in a new thread and returns its result.
409
+
410
+ Each call gets its own thread: nested middleware blocks one thread per level, which could
411
+ exhaust a fixed pool.
412
+ """
413
+ loop = asyncio.get_running_loop()
414
+ done: asyncio.Future[object] = loop.create_future()
415
+ context = contextvars.copy_context()
416
+
417
+ def target() -> None:
418
+ try:
419
+ value = context.run(fn)
420
+ except BaseException as error:
421
+ loop.call_soon_threadsafe(done.set_exception, error)
422
+ else:
423
+ loop.call_soon_threadsafe(done.set_result, value)
424
+
425
+ threading.Thread(target=target, daemon=True).start()
426
+ return await done
incur/_completions.py ADDED
@@ -0,0 +1,170 @@
1
+ """Dynamic shell completions for bash, fish, nushell, and zsh."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from . import _js
8
+ from ._js import Json
9
+ from ._schema import Field, Type
10
+
11
+ #: Every shell, in help order.
12
+ SHELLS = ("bash", "fish", "nushell", "zsh")
13
+
14
+
15
+ @dataclass
16
+ class Candidate:
17
+ """A completion candidate."""
18
+
19
+ value: str
20
+ description: str | None = None
21
+ no_space: bool = False
22
+
23
+
24
+ @dataclass
25
+ class Node:
26
+ """A command tree node: a group with subcommands, or a command with options."""
27
+
28
+ description: str | None
29
+ options: Type | None
30
+ group: bool
31
+ commands: list[tuple[str, Node, bool]]
32
+
33
+
34
+ def register(shell: str, name: str) -> str:
35
+ """Generates the shell hook that calls back into the binary at every tab press."""
36
+ ident = "".join(ch if (ch.isascii() and ch.isalnum()) or ch == "_" else "_" for ch in name)
37
+ if shell == "bash":
38
+ return f"""_incur_complete_{ident}() {{
39
+ local IFS=$'\\013'
40
+ local _COMPLETE_INDEX=${{COMP_CWORD}}
41
+ local _completions
42
+ _completions=( $(
43
+ export COMPLETE="bash"
44
+ export _COMPLETE_INDEX="$_COMPLETE_INDEX"
45
+ "{name}" -- "${{COMP_WORDS[@]}}"
46
+ ) )
47
+ if [[ $? != 0 ]]; then
48
+ unset COMPREPLY
49
+ return
50
+ fi
51
+ local _nospace=false
52
+ COMPREPLY=()
53
+ for _c in "${{_completions[@]}}"; do
54
+ if [[ "$_c" == *$'\\001' ]]; then
55
+ _nospace=true
56
+ COMPREPLY+=("${{_c%$'\\001'}}")
57
+ else
58
+ COMPREPLY+=("$_c")
59
+ fi
60
+ done
61
+ if [[ $_nospace == true ]]; then
62
+ compopt -o nospace
63
+ fi
64
+ }}
65
+ complete -o default -o bashdefault -o nosort -F _incur_complete_{ident} {name}"""
66
+ if shell == "zsh":
67
+ return f"""#compdef {name}
68
+ _incur_complete_{ident}() {{
69
+ local completions=("${{(@f)$(
70
+ export _COMPLETE_INDEX=$(( CURRENT - 1 ))
71
+ export COMPLETE="zsh"
72
+ "{name}" -- "${{words[@]}}" 2>/dev/null
73
+ )}}")
74
+ if [[ -n $completions ]]; then
75
+ _describe 'values' completions -S ''
76
+ fi
77
+ }}
78
+ compdef _incur_complete_{ident} {name}"""
79
+ if shell == "fish":
80
+ return (
81
+ f"complete --keep-order --exclusive --command {name} \\\n"
82
+ f' --arguments "(COMPLETE=fish {name} -- (commandline --current-process '
83
+ '--tokenize --cut-at-cursor) (commandline --current-token))"'
84
+ )
85
+ return f"""# External completer for {name}
86
+ # Add to $env.config.completions.external.completer or use in a dispatch completer.
87
+ let _incur_complete_{ident} = {{|spans|
88
+ COMPLETE=nushell {name} -- ...$spans | from json
89
+ }}"""
90
+
91
+
92
+ def _option_field(token: str, options: Type) -> Field | None:
93
+ """Resolves a flag token to its option field."""
94
+ if token.startswith("--"):
95
+ raw = token[2:]
96
+ found = next((f for f in options.fields if _js.to_kebab(f.name) == raw), None)
97
+ return found or next((f for f in options.fields if f.name == raw), None)
98
+ if token.startswith("-") and _js.utf16_len(token) == 2:
99
+ return next((f for f in options.fields if f.alias == token[1]), None)
100
+ return None
101
+
102
+
103
+ def _flags(candidates: list[Candidate], options: Type, current: str) -> None:
104
+ """Suggests the option flags of a schema that match the current word."""
105
+ flags = [(f"--{_js.to_kebab(f.name)}", f) for f in options.fields]
106
+ flags += [(f"-{f.alias}", f) for f in options.fields if f.alias is not None]
107
+ for flag, f in flags:
108
+ if flag.startswith(current) and not any(c.value == flag for c in candidates):
109
+ candidates.append(Candidate(flag, f.ty.description))
110
+
111
+
112
+ def _values(candidates: list[Candidate], prev: str, options: Type, current: str) -> bool:
113
+ """Suggests enum values. Returns whether the option takes a value."""
114
+ f = _option_field(prev, options)
115
+ if f is None:
116
+ return False
117
+ if f.ty.kind == "enum":
118
+ candidates.extend(Candidate(v) for v in f.ty.values if v.startswith(current))
119
+ return True
120
+ return not f.ty.is_flag()
121
+
122
+
123
+ def complete(root: Node, argv: list[str], index: int, globals_: Type | None) -> list[Candidate]:
124
+ """Computes completion candidates for the word at `index`."""
125
+ current = argv[index] if index < len(argv) else ""
126
+ scope = root
127
+ for token in argv[:index]:
128
+ if token.startswith("-"):
129
+ continue
130
+ # Tokens after a command are its arguments.
131
+ if not scope.group:
132
+ break
133
+ scope = next((node for name, node, _ in scope.commands if name == token), scope)
134
+ leaf = scope.options
135
+ candidates: list[Candidate] = []
136
+ if current.startswith("-"):
137
+ for options in (leaf, globals_):
138
+ if options is not None:
139
+ _flags(candidates, options, current)
140
+ return candidates
141
+ if 0 < index <= len(argv) and argv[index - 1].startswith("-"):
142
+ for options in (leaf, globals_):
143
+ if options is not None and _values(candidates, argv[index - 1], options, current):
144
+ return candidates
145
+ for name, node, alias in scope.commands:
146
+ if not alias and name.startswith(current):
147
+ candidates.append(Candidate(name, node.description, node.group))
148
+ return candidates
149
+
150
+
151
+ def format_candidates(shell: str, candidates: list[Candidate]) -> str:
152
+ """Formats candidates for a shell."""
153
+ if shell == "bash":
154
+ return "\x0b".join(c.value + ("\x01" if c.no_space else "") for c in candidates)
155
+ if shell == "zsh":
156
+ return "\n".join(
157
+ c.value.replace(":", "\\:") + (f":{c.description}" if c.description else "")
158
+ for c in candidates
159
+ )
160
+ if shell == "fish":
161
+ return "\n".join(
162
+ c.value + (f"\t{c.description}" if c.description else "") for c in candidates
163
+ )
164
+ records: list[Json] = []
165
+ for c in candidates:
166
+ record: dict[str, Json] = {"value": c.value}
167
+ if c.description:
168
+ record["description"] = c.description
169
+ records.append(record)
170
+ return _js.stringify(records)