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/__init__.py +62 -0
- incur/_cli.py +2139 -0
- incur/_command.py +426 -0
- incur/_completions.py +170 -0
- incur/_errors.py +234 -0
- incur/_filter.py +173 -0
- incur/_formatter.py +112 -0
- incur/_gateway.py +173 -0
- incur/_help.py +260 -0
- incur/_http.py +389 -0
- incur/_js.py +467 -0
- incur/_jsonschema.py +320 -0
- incur/_mcp.py +872 -0
- incur/_mcpsource.py +226 -0
- incur/_model.py +348 -0
- incur/_openapi.py +640 -0
- incur/_parser.py +347 -0
- incur/_pm.py +49 -0
- incur/_schema.py +555 -0
- incur/_serve_http.py +236 -0
- incur/_skill.py +355 -0
- incur/_sync.py +403 -0
- incur/_syncmcp.py +188 -0
- incur/_tokens.py +130 -0
- incur/_toon.py +202 -0
- incur/_tree.py +273 -0
- incur/_update.py +373 -0
- incur/_yaml.py +651 -0
- incur/py.typed +0 -0
- incur_cli-0.10.0.dist-info/METADATA +376 -0
- incur_cli-0.10.0.dist-info/RECORD +32 -0
- incur_cli-0.10.0.dist-info/WHEEL +4 -0
incur/_serve_http.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""The CLI as an HTTP handler: commands, MCP over HTTP, and OpenAPI and skills discovery."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
import urllib.parse
|
|
9
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from . import _js, _parser, _skill, _yaml
|
|
13
|
+
from ._command import Command, Middleware, Stream, execute
|
|
14
|
+
from ._errors import Error, format_cta, unknown
|
|
15
|
+
from ._http import Request, Response, call, origin, search_params
|
|
16
|
+
from ._js import Json
|
|
17
|
+
from ._mcp import spec_context
|
|
18
|
+
from ._model import build, to_json
|
|
19
|
+
from ._openapi import from_cli as openapi_from_cli
|
|
20
|
+
from ._tree import GatewayHit, GroupHelp, NotFound, Spec, resolve, suggest
|
|
21
|
+
|
|
22
|
+
_CACHE = {"cache-control": "public, max-age=300"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _duration(start: float) -> str:
|
|
26
|
+
return f"{round((time.monotonic() - start) * 1000)}ms"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _failure(code: str, message: str, command: str, start: float, status: int) -> Response:
|
|
30
|
+
body: dict[str, Json] = {
|
|
31
|
+
"ok": False,
|
|
32
|
+
"error": {"code": code, "message": message},
|
|
33
|
+
"meta": {"command": command, "duration": _duration(start)},
|
|
34
|
+
}
|
|
35
|
+
return Response.json(body, status=status)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def handle(
|
|
39
|
+
spec: Spec, request: Request, mcp: Callable[[Request], Awaitable[Response]]
|
|
40
|
+
) -> Response:
|
|
41
|
+
"""Answers an HTTP request for a CLI."""
|
|
42
|
+
start = time.monotonic()
|
|
43
|
+
path = urllib.parse.urlsplit(request.url).path
|
|
44
|
+
segments = [s for s in path.split("/") if s]
|
|
45
|
+
|
|
46
|
+
if request.method == "GET" and _is_openapi(segments):
|
|
47
|
+
document = openapi_from_cli(spec)
|
|
48
|
+
if segments[0] in ("openapi.yml", "openapi.yaml"):
|
|
49
|
+
headers = {"content-type": "application/yaml", **_CACHE}
|
|
50
|
+
return Response(_yaml.stringify(document), headers=headers)
|
|
51
|
+
return Response(
|
|
52
|
+
_js.stringify(document), headers={"content-type": "application/json", **_CACHE}
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
if segments == ["mcp"]:
|
|
56
|
+
return await mcp(request)
|
|
57
|
+
|
|
58
|
+
if (
|
|
59
|
+
len(segments) >= 3
|
|
60
|
+
and segments[0] == ".well-known"
|
|
61
|
+
and segments[1] in ("agent-skills", "skills")
|
|
62
|
+
and request.method == "GET"
|
|
63
|
+
):
|
|
64
|
+
groups: dict[str, str] = {}
|
|
65
|
+
infos = _skill.collect(spec.commands, [], groups, spec.root_command())
|
|
66
|
+
files = _skill.split(spec.name, infos, 1, groups)
|
|
67
|
+
if segments[2] == "index.json" and len(segments) == 3:
|
|
68
|
+
listed = [(f.dir or spec.name, f.description, f.content) for f in files]
|
|
69
|
+
if segments[1] == "agent-skills":
|
|
70
|
+
index: dict[str, Json] = _skill.discovery(origin(request.url), listed)
|
|
71
|
+
else:
|
|
72
|
+
skills: list[Json] = [
|
|
73
|
+
{"name": name, "description": description, "files": ["SKILL.md"]}
|
|
74
|
+
for name, description, _ in listed
|
|
75
|
+
]
|
|
76
|
+
index = {"skills": skills}
|
|
77
|
+
return Response(
|
|
78
|
+
_js.stringify(index), headers={"content-type": "application/json", **_CACHE}
|
|
79
|
+
)
|
|
80
|
+
if len(segments) == 4 and segments[3] == "SKILL.md":
|
|
81
|
+
found = next((f for f in files if (f.dir or spec.name) == segments[2]), None)
|
|
82
|
+
if found is not None:
|
|
83
|
+
return Response(found.content, headers={"content-type": "text/markdown", **_CACHE})
|
|
84
|
+
return Response("Not Found", status=404)
|
|
85
|
+
|
|
86
|
+
inputs: dict[str, Json] = {}
|
|
87
|
+
if request.method == "GET":
|
|
88
|
+
inputs = dict(search_params(urllib.parse.urlsplit(request.url).query))
|
|
89
|
+
elif "application/json" in (request.headers.get("content-type") or ""):
|
|
90
|
+
text = request.text()
|
|
91
|
+
if _js.json_parse_error(text) is None:
|
|
92
|
+
inputs = _js.as_object(_js.parse_json(text))
|
|
93
|
+
|
|
94
|
+
if not segments:
|
|
95
|
+
root = spec.root_command()
|
|
96
|
+
if root is None:
|
|
97
|
+
return _failure("COMMAND_NOT_FOUND", "No root command defined.", "/", start, 404)
|
|
98
|
+
return await _run(spec, spec.name, root, [], [], inputs, request, start)
|
|
99
|
+
|
|
100
|
+
resolved = resolve(spec.commands, segments)
|
|
101
|
+
if isinstance(resolved, NotFound):
|
|
102
|
+
parent = f"{spec.name} {resolved.path}" if resolved.path else spec.name
|
|
103
|
+
suggestion = suggest(resolved.error, resolved.commands)
|
|
104
|
+
did_you_mean = f" Did you mean '{suggestion}'?" if suggestion else ""
|
|
105
|
+
message = f"'{resolved.error}' is not a command for '{parent}'.{did_you_mean}"
|
|
106
|
+
return _failure("COMMAND_NOT_FOUND", message, resolved.error, start, 404)
|
|
107
|
+
if isinstance(resolved, GroupHelp):
|
|
108
|
+
message = f"'{resolved.path}' is a command group. Specify a subcommand."
|
|
109
|
+
return _failure("COMMAND_NOT_FOUND", message, resolved.path, start, 404)
|
|
110
|
+
if isinstance(resolved, GatewayHit):
|
|
111
|
+
return await call(resolved.gateway.fetch, request)
|
|
112
|
+
return await _run(
|
|
113
|
+
spec,
|
|
114
|
+
resolved.path,
|
|
115
|
+
resolved.command,
|
|
116
|
+
resolved.rest,
|
|
117
|
+
resolved.middleware,
|
|
118
|
+
inputs,
|
|
119
|
+
request,
|
|
120
|
+
start,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _is_openapi(segments: list[str]) -> bool:
|
|
125
|
+
if len(segments) == 1:
|
|
126
|
+
return segments[0] in ("openapi.json", "openapi.yml", "openapi.yaml")
|
|
127
|
+
return segments == [".well-known", "openapi.json"]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
async def _run(
|
|
131
|
+
spec: Spec,
|
|
132
|
+
path: str,
|
|
133
|
+
command: Command,
|
|
134
|
+
rest: list[str],
|
|
135
|
+
middleware: list[Middleware],
|
|
136
|
+
inputs: dict[str, Json],
|
|
137
|
+
request: Request,
|
|
138
|
+
start: float,
|
|
139
|
+
) -> Response:
|
|
140
|
+
"""Runs a command for an HTTP request and renders its JSON or NDJSON response."""
|
|
141
|
+
globals_: dict[str, Json] = {}
|
|
142
|
+
options = inputs
|
|
143
|
+
if spec.globals is not None:
|
|
144
|
+
keys = {f.name for f in spec.globals.fields}
|
|
145
|
+
raw = {k: v for k, v in inputs.items() if k in keys}
|
|
146
|
+
options = {k: v for k, v in inputs.items() if k not in keys}
|
|
147
|
+
try:
|
|
148
|
+
globals_ = _parser.check(spec.globals, raw)
|
|
149
|
+
except Error as error:
|
|
150
|
+
messages = [f.message for f in error.field_errors or []]
|
|
151
|
+
message = "; ".join(messages) or "Validation failed"
|
|
152
|
+
return _failure("VALIDATION_ERROR", message, path, start, 400)
|
|
153
|
+
|
|
154
|
+
name = spec.name
|
|
155
|
+
context = spec_context(spec, path, globals_, request)
|
|
156
|
+
environ = os.environ
|
|
157
|
+
|
|
158
|
+
def parse() -> tuple[dict[str, Json], dict[str, Json], dict[str, Json]]:
|
|
159
|
+
args = _parser.parse(rest, command.args, None, None)[0]
|
|
160
|
+
return (
|
|
161
|
+
args,
|
|
162
|
+
_parser.check(command.options, options) if command.options else {},
|
|
163
|
+
_parser.parse_env(command.env, environ.get) if command.env else {},
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
def meta(cta: Any = None) -> dict[str, Json]:
|
|
167
|
+
out: dict[str, Json] = {"command": path, "duration": _duration(start)}
|
|
168
|
+
if cta is not None:
|
|
169
|
+
out["cta"] = cta.to_json()
|
|
170
|
+
return out
|
|
171
|
+
|
|
172
|
+
def error_record(error: Error) -> bytes:
|
|
173
|
+
record: dict[str, Json] = {
|
|
174
|
+
"type": "error",
|
|
175
|
+
"ok": False,
|
|
176
|
+
"error": error.to_json(),
|
|
177
|
+
"meta": meta(format_cta(name, error.cta)),
|
|
178
|
+
}
|
|
179
|
+
return (_js.stringify(record) + "\n").encode()
|
|
180
|
+
|
|
181
|
+
loop = asyncio.get_running_loop()
|
|
182
|
+
handoff: asyncio.Future[Stream] = loop.create_future()
|
|
183
|
+
finished = asyncio.Event()
|
|
184
|
+
|
|
185
|
+
async def sink(chunks: Stream) -> None:
|
|
186
|
+
handoff.set_result(chunks)
|
|
187
|
+
await finished.wait()
|
|
188
|
+
|
|
189
|
+
async def run() -> Any:
|
|
190
|
+
try:
|
|
191
|
+
if spec.env is not None:
|
|
192
|
+
context.env = build(spec.env, _parser.parse_env(spec.env, environ.get))
|
|
193
|
+
except Error as error:
|
|
194
|
+
return error
|
|
195
|
+
chain = [*spec.middleware, *middleware, *command.middleware]
|
|
196
|
+
return await execute(command, context, chain, parse, sink)
|
|
197
|
+
|
|
198
|
+
task = asyncio.ensure_future(run())
|
|
199
|
+
await asyncio.wait({task, handoff}, return_when=asyncio.FIRST_COMPLETED)
|
|
200
|
+
if handoff.done():
|
|
201
|
+
chunks = handoff.result()
|
|
202
|
+
|
|
203
|
+
async def records() -> AsyncIterator[bytes]:
|
|
204
|
+
try:
|
|
205
|
+
async for chunk in chunks:
|
|
206
|
+
record = {"type": "chunk", "data": to_json(chunk)}
|
|
207
|
+
yield (_js.stringify(record) + "\n").encode()
|
|
208
|
+
except Error as error:
|
|
209
|
+
yield error_record(error)
|
|
210
|
+
return
|
|
211
|
+
except Exception as error:
|
|
212
|
+
yield error_record(unknown(str(error)))
|
|
213
|
+
return
|
|
214
|
+
finally:
|
|
215
|
+
finished.set()
|
|
216
|
+
await task
|
|
217
|
+
final = chunks.final
|
|
218
|
+
done: dict[str, Json] = {
|
|
219
|
+
"type": "done",
|
|
220
|
+
"ok": True,
|
|
221
|
+
"meta": meta(format_cta(name, getattr(final, "cta", None))),
|
|
222
|
+
}
|
|
223
|
+
yield (_js.stringify(done) + "\n").encode()
|
|
224
|
+
|
|
225
|
+
return Response(records(), headers={"content-type": "application/x-ndjson"})
|
|
226
|
+
|
|
227
|
+
result = task.result()
|
|
228
|
+
if isinstance(result, Error):
|
|
229
|
+
body = {"ok": False, "error": result.to_json(), "meta": meta(format_cta(name, result.cta))}
|
|
230
|
+
status = 400 if result.code == "VALIDATION_ERROR" else 500
|
|
231
|
+
return Response.json(body, status=status)
|
|
232
|
+
body: dict[str, Json] = {"ok": True}
|
|
233
|
+
if result.data is not None:
|
|
234
|
+
body["data"] = result.data
|
|
235
|
+
body["meta"] = meta(format_cta(name, result.cta))
|
|
236
|
+
return Response.json(body)
|
incur/_skill.py
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
"""Markdown command manifests for `--llms` and `--llms-full`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import re
|
|
7
|
+
import typing
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
|
|
10
|
+
from . import _js, _yaml
|
|
11
|
+
from ._command import Command
|
|
12
|
+
from ._help import Example
|
|
13
|
+
from ._js import Json
|
|
14
|
+
from ._schema import Type, json_schema
|
|
15
|
+
from ._tree import Entry, Gateway, Group
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class CommandInfo:
|
|
20
|
+
"""A command described in a manifest."""
|
|
21
|
+
|
|
22
|
+
name: str | None
|
|
23
|
+
args: Type | None = None
|
|
24
|
+
description: str | None = None
|
|
25
|
+
env: Type | None = None
|
|
26
|
+
examples: list[Example] = field(default_factory=list[Example])
|
|
27
|
+
hint: str | None = None
|
|
28
|
+
options: Type | None = None
|
|
29
|
+
output: Type | None = None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
#: The hint of fetch gateways in agent skills.
|
|
33
|
+
GATEWAY_HINT = "Fetch gateway. Pass path segments and curl-style flags (-X, -H, -d, --key value)."
|
|
34
|
+
|
|
35
|
+
#: The hint appended to destructive commands in agent skills.
|
|
36
|
+
DESTRUCTIVE_HINT = "Confirm with the user before executing this destructive command."
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _is_destructive(command: Command) -> bool:
|
|
40
|
+
annotations = command.mcp.annotations if command.mcp and command.mcp_enabled else None
|
|
41
|
+
return command.destructive or (annotations or {}).get("destructiveHint") is True
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _hint_with_destructive(command: Command) -> str | None:
|
|
45
|
+
if not _is_destructive(command):
|
|
46
|
+
return command.hint
|
|
47
|
+
if not command.hint:
|
|
48
|
+
return DESTRUCTIVE_HINT
|
|
49
|
+
if DESTRUCTIVE_HINT in command.hint:
|
|
50
|
+
return command.hint
|
|
51
|
+
return f"{command.hint} {DESTRUCTIVE_HINT}"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def prefixed_examples(examples: list[Example], name: str) -> list[Example]:
|
|
55
|
+
"""Prefixes examples with a command path."""
|
|
56
|
+
return [Example(f"{name} {e.command}" if e.command else name, e.description) for e in examples]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _command_info(name: str | None, command: Command) -> CommandInfo:
|
|
60
|
+
examples = prefixed_examples(command.examples, name) if name else list(command.examples)
|
|
61
|
+
return CommandInfo(
|
|
62
|
+
name=name,
|
|
63
|
+
args=command.args,
|
|
64
|
+
description=command.description,
|
|
65
|
+
env=command.env,
|
|
66
|
+
examples=examples,
|
|
67
|
+
hint=_hint_with_destructive(command),
|
|
68
|
+
options=command.options,
|
|
69
|
+
output=command.output,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def collect(
|
|
74
|
+
commands: dict[str, Entry],
|
|
75
|
+
prefix: list[str],
|
|
76
|
+
groups: dict[str, str],
|
|
77
|
+
root: Command | None,
|
|
78
|
+
) -> list[CommandInfo]:
|
|
79
|
+
"""Collects the commands that skill files and Markdown manifests describe, sorted by name.
|
|
80
|
+
|
|
81
|
+
`groups` receives the descriptions of groups along the way.
|
|
82
|
+
"""
|
|
83
|
+
out: list[CommandInfo] = []
|
|
84
|
+
if root is not None:
|
|
85
|
+
out.append(_command_info(None, root))
|
|
86
|
+
for name, entry in commands.items():
|
|
87
|
+
path = [*prefix, name]
|
|
88
|
+
joined = " ".join(path)
|
|
89
|
+
if isinstance(entry, Command):
|
|
90
|
+
out.append(_command_info(joined, entry))
|
|
91
|
+
elif isinstance(entry, Gateway):
|
|
92
|
+
out.append(CommandInfo(name=joined, description=entry.description, hint=GATEWAY_HINT))
|
|
93
|
+
elif isinstance(entry, Group):
|
|
94
|
+
if entry.description is not None:
|
|
95
|
+
groups[joined] = entry.description
|
|
96
|
+
if entry.root is not None:
|
|
97
|
+
out.append(_command_info(joined, entry.root))
|
|
98
|
+
out += collect(entry.commands, path, groups, None)
|
|
99
|
+
out.sort(key=lambda info: _js.locale_key(info.name or ""))
|
|
100
|
+
return out
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _type_name(ty: Type) -> str:
|
|
104
|
+
"""Returns the JSON Schema type name, mapping `integer` to `number`."""
|
|
105
|
+
return {"integer": "number", "enum": "string"}.get(ty.kind, ty.kind)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _required(ty: Type) -> str:
|
|
109
|
+
return "no" if ty.is_optional() else "yes"
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _signature(cli: str, cmd: CommandInfo) -> str:
|
|
113
|
+
base = cli if cmd.name is None else f"{cli} {cmd.name}"
|
|
114
|
+
if cmd.args is None:
|
|
115
|
+
return base
|
|
116
|
+
names: list[str] = []
|
|
117
|
+
for f in cmd.args.fields:
|
|
118
|
+
label = f"{f.name}..." if f.ty.kind == "array" else f.name
|
|
119
|
+
names.append(f"[{label}]" if f.ty.is_optional() else f"<{label}>")
|
|
120
|
+
return f"{base} {' '.join(names)}"
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def index(name: str, commands: list[CommandInfo], description: str | None) -> str:
|
|
124
|
+
"""Generates the compact command index `--llms` prints."""
|
|
125
|
+
lines = [f"# {name}"]
|
|
126
|
+
if description:
|
|
127
|
+
lines += ["", description]
|
|
128
|
+
lines += ["", "| Command | Description |", "|---------|-------------|"]
|
|
129
|
+
for cmd in commands:
|
|
130
|
+
lines.append(f"| `{_signature(name, cmd)}` | {cmd.description or ''} |")
|
|
131
|
+
lines += [
|
|
132
|
+
"",
|
|
133
|
+
f"Run `{name} --llms-full` for full manifest. "
|
|
134
|
+
f"Run `{name} <command> --schema` for argument details.",
|
|
135
|
+
]
|
|
136
|
+
return "\n".join(lines)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def generate(name: str, commands: list[CommandInfo], groups: dict[str, str]) -> str:
|
|
140
|
+
"""Generates the full Markdown manifest `--llms-full` prints."""
|
|
141
|
+
if not groups:
|
|
142
|
+
return "\n\n".join(_body(name, cmd, 1) for cmd in commands)
|
|
143
|
+
sections = [f"# {name}"]
|
|
144
|
+
last: str | None = None
|
|
145
|
+
for cmd in commands:
|
|
146
|
+
segment = cmd.name.split(" ")[0] if cmd.name else ""
|
|
147
|
+
if last != segment:
|
|
148
|
+
last = segment
|
|
149
|
+
if segment:
|
|
150
|
+
description = groups.get(segment)
|
|
151
|
+
heading = f"## {name} {segment}"
|
|
152
|
+
sections.append(f"{heading}\n\n{description}" if description else heading)
|
|
153
|
+
sections.append(_body(name, cmd, 3 if segment else 2))
|
|
154
|
+
return "\n\n".join(sections)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _body(cli: str, cmd: CommandInfo, level: int) -> str:
|
|
158
|
+
full = cli if cmd.name is None else f"{cli} {cmd.name}"
|
|
159
|
+
heading = f"{'#' * level} {full}"
|
|
160
|
+
if cmd.description:
|
|
161
|
+
heading += f"\n\n{cmd.description}"
|
|
162
|
+
sections = [heading]
|
|
163
|
+
sub = "#" * (level + 1)
|
|
164
|
+
|
|
165
|
+
if cmd.args is not None:
|
|
166
|
+
rows = [
|
|
167
|
+
f"| `{f.name}` | `{_type_name(f.ty)}` | {_required(f.ty)} | {f.ty.description or ''} |"
|
|
168
|
+
for f in cmd.args.fields
|
|
169
|
+
]
|
|
170
|
+
sections.append(
|
|
171
|
+
f"{sub} Arguments\n\n| Name | Type | Required | Description |\n"
|
|
172
|
+
"|------|------|----------|-------------|\n" + "\n".join(rows)
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
if cmd.env is not None:
|
|
176
|
+
rows = [
|
|
177
|
+
f"| `{f.name}` | `{_type_name(f.ty)}` | {_required(f.ty)} | "
|
|
178
|
+
f"{_default_cell(f.ty)} | {f.ty.description or ''} |"
|
|
179
|
+
for f in cmd.env.fields
|
|
180
|
+
]
|
|
181
|
+
sections.append(
|
|
182
|
+
f"{sub} Environment Variables\n\n| Name | Type | Required | Default | Description |\n"
|
|
183
|
+
"|------|------|----------|---------|-------------|\n" + "\n".join(rows)
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
if cmd.options is not None:
|
|
187
|
+
rows: list[str] = []
|
|
188
|
+
for f in cmd.options.fields:
|
|
189
|
+
raw = f.ty.description or ""
|
|
190
|
+
description = f"**Deprecated.** {raw}" if f.ty.deprecated else raw
|
|
191
|
+
rows.append(
|
|
192
|
+
f"| `--{f.name}` | `{_type_name(f.ty)}` | {_default_cell(f.ty)} | {description} |"
|
|
193
|
+
)
|
|
194
|
+
sections.append(
|
|
195
|
+
f"{sub} Options\n\n| Flag | Type | Default | Description |\n"
|
|
196
|
+
"|------|------|---------|-------------|\n" + "\n".join(rows)
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
if cmd.output is not None:
|
|
200
|
+
table = _schema_table(cmd.output, "")
|
|
201
|
+
if table is None:
|
|
202
|
+
sections.append(f"{sub} Output\n\nType: `{_type_name(cmd.output)}`")
|
|
203
|
+
else:
|
|
204
|
+
sections.append(f"{sub} Output\n\n{table}")
|
|
205
|
+
|
|
206
|
+
if cmd.examples:
|
|
207
|
+
lines = [
|
|
208
|
+
(f"# {e.description}\n" if e.description else "") + f"{cli} {e.command}"
|
|
209
|
+
for e in cmd.examples
|
|
210
|
+
]
|
|
211
|
+
sections.append(f"{sub} Examples\n\n```sh\n" + "\n\n".join(lines) + "\n```")
|
|
212
|
+
|
|
213
|
+
if cmd.hint:
|
|
214
|
+
sections.append(f"> {cmd.hint}")
|
|
215
|
+
return "\n\n".join(sections)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _default_cell(ty: Type) -> str:
|
|
219
|
+
text = "" if ty.default is None else _js.to_string(ty.default)
|
|
220
|
+
return f"`{text}`" if text else ""
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _schema_table(ty: Type, prefix: str) -> str | None:
|
|
224
|
+
"""Renders an object schema as a Markdown table, expanding nested objects."""
|
|
225
|
+
if ty.kind != "object" or not ty.fields:
|
|
226
|
+
return None
|
|
227
|
+
rows: list[str] = []
|
|
228
|
+
for f in ty.fields:
|
|
229
|
+
name = f"{prefix}.{f.name}" if prefix else f.name
|
|
230
|
+
rows.append(
|
|
231
|
+
f"| `{name}` | `{_type_name(f.ty)}` | {_required(f.ty)} | {f.ty.description or ''} |"
|
|
232
|
+
)
|
|
233
|
+
nested = None
|
|
234
|
+
if f.ty.kind == "object":
|
|
235
|
+
nested = _schema_table(f.ty, name)
|
|
236
|
+
elif f.ty.items is not None:
|
|
237
|
+
nested = _schema_table(f.ty.items, f"{name}[]")
|
|
238
|
+
if nested is not None:
|
|
239
|
+
rows += nested.split("\n")[2:]
|
|
240
|
+
return (
|
|
241
|
+
"| Field | Type | Required | Description |\n"
|
|
242
|
+
"|-------|------|----------|-------------|\n" + "\n".join(rows)
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
@dataclass
|
|
247
|
+
class File:
|
|
248
|
+
"""A generated skill file: its directory, `SKILL.md` contents, and description."""
|
|
249
|
+
|
|
250
|
+
dir: str
|
|
251
|
+
content: str
|
|
252
|
+
description: str
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def slugify(value: str) -> str:
|
|
256
|
+
"""Converts text to a lowercase slug, such as `My Tool` to `my-tool`."""
|
|
257
|
+
slug = re.sub("[^a-z0-9-]+", "-", value.lower())
|
|
258
|
+
return re.sub("^-|-$", "", re.sub("-{2,}", "-", slug))
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def split(
|
|
262
|
+
name: str, commands: list[CommandInfo], depth: float, groups: dict[str, str]
|
|
263
|
+
) -> list[File]:
|
|
264
|
+
"""Splits commands into skill files, grouped by their first `depth` name segments.
|
|
265
|
+
|
|
266
|
+
`depth` bounds a JavaScript `slice`, as `--depth` parses it: fractions truncate, negative
|
|
267
|
+
values count from the end, and `NaN` takes no segments.
|
|
268
|
+
"""
|
|
269
|
+
if depth == 0:
|
|
270
|
+
return [_group(name, name, commands, groups, name, "")]
|
|
271
|
+
|
|
272
|
+
def head(cmd: str) -> list[str]:
|
|
273
|
+
segments = cmd.split(" ")
|
|
274
|
+
return segments[: _js.relative_index(depth, len(segments))]
|
|
275
|
+
|
|
276
|
+
buckets: dict[str, list[CommandInfo]] = {}
|
|
277
|
+
for cmd in commands:
|
|
278
|
+
key = slugify(name) if not cmd.name else "-".join(head(cmd.name))
|
|
279
|
+
buckets.setdefault(key, []).append(cmd)
|
|
280
|
+
files: list[File] = []
|
|
281
|
+
for key in sorted(buckets, key=_js.locale_key):
|
|
282
|
+
cmds = buckets[key]
|
|
283
|
+
first = cmds[0]
|
|
284
|
+
prefix = " ".join(head(first.name)) if first.name else ""
|
|
285
|
+
title = f"{name} {prefix}" if prefix else name
|
|
286
|
+
files.append(_group(name, title, cmds, groups, prefix or None, key))
|
|
287
|
+
return files
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _group(
|
|
291
|
+
cli: str,
|
|
292
|
+
title: str,
|
|
293
|
+
cmds: list[CommandInfo],
|
|
294
|
+
groups: dict[str, str],
|
|
295
|
+
prefix: str | None,
|
|
296
|
+
directory: str,
|
|
297
|
+
) -> File:
|
|
298
|
+
"""Renders a skill file: frontmatter, then command bodies."""
|
|
299
|
+
described = groups.get(prefix) if prefix else None
|
|
300
|
+
fallback = cmds[0].description if len(cmds) == 1 and cmds[0].description else None
|
|
301
|
+
desc = described if described is not None else fallback
|
|
302
|
+
usage = f"Run `{title} --help` for usage details."
|
|
303
|
+
description = f"{desc.removesuffix('.')}. {usage}" if desc else usage
|
|
304
|
+
frontmatter = {
|
|
305
|
+
"name": slugify(title),
|
|
306
|
+
"description": description,
|
|
307
|
+
"requires_bin": cli,
|
|
308
|
+
"command": title,
|
|
309
|
+
}
|
|
310
|
+
meta = _yaml.stringify(typing.cast("Json", frontmatter), line_width=0).rstrip()
|
|
311
|
+
body = "\n\n---\n\n".join(_body(cli, cmd, 1) for cmd in cmds)
|
|
312
|
+
return File(directory, f"---\n{meta}\n---\n\n{body}", description)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def hash_commands(commands: list[CommandInfo]) -> str:
|
|
316
|
+
"""Hashes the command structure, to detect when installed skills are out of date."""
|
|
317
|
+
data: list[Json] = []
|
|
318
|
+
for cmd in commands:
|
|
319
|
+
entry: dict[str, Json] = {}
|
|
320
|
+
if cmd.name is not None:
|
|
321
|
+
entry["name"] = cmd.name
|
|
322
|
+
if cmd.description is not None:
|
|
323
|
+
entry["description"] = cmd.description
|
|
324
|
+
if cmd.hint is not None:
|
|
325
|
+
entry["hint"] = cmd.hint
|
|
326
|
+
for key, ty in (
|
|
327
|
+
("args", cmd.args),
|
|
328
|
+
("env", cmd.env),
|
|
329
|
+
("options", cmd.options),
|
|
330
|
+
("output", cmd.output),
|
|
331
|
+
):
|
|
332
|
+
if ty is not None:
|
|
333
|
+
entry[key] = json_schema(ty)
|
|
334
|
+
data.append(entry)
|
|
335
|
+
return hashlib.sha256(_js.stringify(data).encode()).hexdigest()[:16]
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def discovery(origin: str, files: list[tuple[str, str, str]]) -> dict[str, Json]:
|
|
339
|
+
"""Builds the Agent Skills discovery index (v0.2.0) of `(name, description, content)`."""
|
|
340
|
+
skills: list[Json] = []
|
|
341
|
+
for name, description, content in files:
|
|
342
|
+
digest = hashlib.sha256(content.encode()).hexdigest()
|
|
343
|
+
skills.append(
|
|
344
|
+
{
|
|
345
|
+
"name": name,
|
|
346
|
+
"type": "skill-md",
|
|
347
|
+
"description": description,
|
|
348
|
+
"url": f"{origin}/.well-known/agent-skills/{name}/SKILL.md",
|
|
349
|
+
"digest": f"sha256:{digest}",
|
|
350
|
+
}
|
|
351
|
+
)
|
|
352
|
+
return {
|
|
353
|
+
"$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json",
|
|
354
|
+
"skills": skills,
|
|
355
|
+
}
|