mcp-dispatch 0.1.1__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.
- mcp_dispatch/__init__.py +59 -0
- mcp_dispatch/__main__.py +3 -0
- mcp_dispatch/agent_instructions/host.md +102 -0
- mcp_dispatch/agent_instructions/plugin.md +222 -0
- mcp_dispatch/check.py +310 -0
- mcp_dispatch/cli.py +276 -0
- mcp_dispatch/command.py +121 -0
- mcp_dispatch/dispatch.py +208 -0
- mcp_dispatch/docs.py +100 -0
- mcp_dispatch/errors.py +32 -0
- mcp_dispatch/lenient.py +172 -0
- mcp_dispatch/mcp_tools.py +195 -0
- mcp_dispatch/py.typed +0 -0
- mcp_dispatch/registry.py +972 -0
- mcp_dispatch/skills.py +533 -0
- mcp_dispatch/tags.py +173 -0
- mcp_dispatch/trials.py +380 -0
- mcp_dispatch-0.1.1.dist-info/METADATA +86 -0
- mcp_dispatch-0.1.1.dist-info/RECORD +22 -0
- mcp_dispatch-0.1.1.dist-info/WHEEL +4 -0
- mcp_dispatch-0.1.1.dist-info/entry_points.txt +2 -0
- mcp_dispatch-0.1.1.dist-info/licenses/LICENSE +21 -0
mcp_dispatch/registry.py
ADDED
|
@@ -0,0 +1,972 @@
|
|
|
1
|
+
"""The dispatcher: a path names a package and an action; the call is made by
|
|
2
|
+
reflection.
|
|
3
|
+
|
|
4
|
+
The tools are the host's: it hands the registry its list (tags.py), and an
|
|
5
|
+
action is tagged with the name of one of them. A tag that names a tool the
|
|
6
|
+
host does not have stops the start, as does any plugin that cannot be loaded.
|
|
7
|
+
|
|
8
|
+
``resolve(tool, arguments)`` takes what arrived on one of the tools. The
|
|
9
|
+
reserved key ``path`` says where the call goes; every other key is a flat
|
|
10
|
+
argument of the action. A path that ends in ``?`` is answered with help
|
|
11
|
+
generated from the signatures and docstrings, on any tool, and calls nothing.
|
|
12
|
+
Otherwise the arguments are checked against the action's type hints and the
|
|
13
|
+
call is handed back, bound, for the caller to run inside its transaction.
|
|
14
|
+
|
|
15
|
+
Several calls can come in one: ``{"calls": [{...}, {...}]}`` holds n full
|
|
16
|
+
calls for the same tool. ``batch`` takes them apart and ``report`` puts their
|
|
17
|
+
answers together; each is resolved and run as if it had come alone, so no
|
|
18
|
+
action deals with lists of calls.
|
|
19
|
+
|
|
20
|
+
There is one search, the tool ``search``, which the dispatcher brings itself
|
|
21
|
+
and which takes no path: ``t`` names one kind and the call goes to the
|
|
22
|
+
package that finds that kind; without ``t`` every package is asked whose
|
|
23
|
+
search takes the arguments given. Several kinds are several calls. Short
|
|
24
|
+
argument names (``t``, ``q``) are the only names: there are no aliases.
|
|
25
|
+
|
|
26
|
+
JSON that arrives as text (a list of calls, a list argument) is read with
|
|
27
|
+
the usual slips repaired (lenient.py), and the answer says what was repaired.
|
|
28
|
+
|
|
29
|
+
Plugins are found through a Python entry point group that the host names:
|
|
30
|
+
the entry point's name is the package, the first part of the path, and its
|
|
31
|
+
value is the plugin class. The dispatcher reflects the tagged methods and the
|
|
32
|
+
skills itself; a plugin makes no register call.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import inspect
|
|
38
|
+
import json
|
|
39
|
+
import math
|
|
40
|
+
import re
|
|
41
|
+
import typing
|
|
42
|
+
from collections.abc import Callable, Iterator, Mapping, Sequence
|
|
43
|
+
from dataclasses import dataclass
|
|
44
|
+
from importlib.metadata import entry_points
|
|
45
|
+
from pathlib import Path
|
|
46
|
+
from typing import Any, Literal
|
|
47
|
+
|
|
48
|
+
from pydantic import TypeAdapter, ValidationError
|
|
49
|
+
|
|
50
|
+
from mcp_dispatch import lenient
|
|
51
|
+
from mcp_dispatch import skills as skill_files
|
|
52
|
+
from mcp_dispatch.docs import Doc, parse
|
|
53
|
+
from mcp_dispatch.errors import BAD_INPUT, NOT_FOUND, DispatchError, PluginError
|
|
54
|
+
from mcp_dispatch.skills import Skill
|
|
55
|
+
from mcp_dispatch.tags import (
|
|
56
|
+
SEARCH,
|
|
57
|
+
SEARCH_DESCRIPTION,
|
|
58
|
+
TAG_ATTR,
|
|
59
|
+
Plugin,
|
|
60
|
+
Tag,
|
|
61
|
+
Tool,
|
|
62
|
+
standard_tools,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
#: the entry point group plugins are found under unless the host names its own
|
|
66
|
+
GROUP = "mcp_dispatch.plugins"
|
|
67
|
+
PATH_KEY = "path"
|
|
68
|
+
CALLS_KEY = "calls"
|
|
69
|
+
#: the keys of a call that are the dispatcher's own, never an action's argument
|
|
70
|
+
RESERVED = (PATH_KEY, CALLS_KEY)
|
|
71
|
+
MAX_CALLS = 20 # in one batch
|
|
72
|
+
SEARCH_PATH = SEARCH # what the search is called in help; no package may take it
|
|
73
|
+
KIND_KEY = "t" # the kind a search is for
|
|
74
|
+
SKILL_PACKAGE = "skill"
|
|
75
|
+
|
|
76
|
+
_NAME_RE = re.compile(r"^[a-z][a-z0-9_-]*$")
|
|
77
|
+
|
|
78
|
+
#: where a registry reads skills from when it is not told (see Registry). The
|
|
79
|
+
#: command line switches it to "files" while it checks or updates.
|
|
80
|
+
default_skills_from: Literal["index", "files"] = "index"
|
|
81
|
+
_REQUIRED: Any = inspect.Parameter.empty
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class Param:
|
|
86
|
+
name: str
|
|
87
|
+
adapter: TypeAdapter[Any]
|
|
88
|
+
#: as it is written in JSON, which is how help, a hint and the contract
|
|
89
|
+
#: show it; _REQUIRED when the parameter has none
|
|
90
|
+
default: Any
|
|
91
|
+
text: str # its line of the docstring's Args section
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def required(self) -> bool:
|
|
95
|
+
return self.default is _REQUIRED
|
|
96
|
+
|
|
97
|
+
def type_text(self) -> str:
|
|
98
|
+
return _type_text(self.adapter.json_schema())
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True)
|
|
102
|
+
class Action:
|
|
103
|
+
package: str
|
|
104
|
+
name: str
|
|
105
|
+
tool: str # the name of the tool it is called through
|
|
106
|
+
kinds: tuple[str, ...]
|
|
107
|
+
fn: Callable[..., Any]
|
|
108
|
+
params: tuple[Param, ...]
|
|
109
|
+
doc: Doc
|
|
110
|
+
search: bool = False
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def path(self) -> str:
|
|
114
|
+
return SEARCH_PATH if self.search else f"{self.package}/{self.name}"
|
|
115
|
+
|
|
116
|
+
def signature(self) -> str:
|
|
117
|
+
parts = [
|
|
118
|
+
p.name if p.required else f"{p.name}={json.dumps(p.default)}"
|
|
119
|
+
for p in self.params
|
|
120
|
+
]
|
|
121
|
+
return f"{self.path}({', '.join(parts)})"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True)
|
|
125
|
+
class Package:
|
|
126
|
+
name: str
|
|
127
|
+
plugin: Plugin
|
|
128
|
+
doc: Doc
|
|
129
|
+
actions: dict[str, Action]
|
|
130
|
+
search: Action | None = None # its part of the one search
|
|
131
|
+
skills_dir: Path | None = None # where its skill files are, if it has any
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@dataclass(frozen=True)
|
|
135
|
+
class Help:
|
|
136
|
+
"""The answer to a path that ends in ``?``: nothing was called."""
|
|
137
|
+
|
|
138
|
+
text: str
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@dataclass(frozen=True)
|
|
142
|
+
class Bound:
|
|
143
|
+
"""A checked call, not yet made."""
|
|
144
|
+
|
|
145
|
+
registry: Registry
|
|
146
|
+
action: Action
|
|
147
|
+
params: dict[str, Any]
|
|
148
|
+
#: what was repaired to read an argument sent as JSON text
|
|
149
|
+
repairs: tuple[str, ...] = ()
|
|
150
|
+
#: a search of several packages: the others, asked after this one
|
|
151
|
+
others: tuple[Bound, ...] = ()
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def tool(self) -> Tool:
|
|
155
|
+
return self.registry.tools[self.action.tool]
|
|
156
|
+
|
|
157
|
+
def run(self, call: Any) -> str:
|
|
158
|
+
"""Make the call. ``call`` is the host's: whatever its actions need
|
|
159
|
+
about this one call (a connection, who is calling). The dispatcher
|
|
160
|
+
passes it on as the action's first argument and never looks inside."""
|
|
161
|
+
if not self.others:
|
|
162
|
+
return self._answer(call)
|
|
163
|
+
return "\n\n".join(
|
|
164
|
+
f"[{one.action.package}]\n{one._answer(call)}"
|
|
165
|
+
for one in (self, *self.others)
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def _answer(self, call: Any) -> str:
|
|
169
|
+
answer = self.action.fn(call, **self.params)
|
|
170
|
+
if not isinstance(answer, str):
|
|
171
|
+
raise TypeError(f"{self.action.path} returned {type(answer).__name__}")
|
|
172
|
+
return answer
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@dataclass(frozen=True)
|
|
176
|
+
class Batch:
|
|
177
|
+
"""Several calls that came in one."""
|
|
178
|
+
|
|
179
|
+
calls: list[Mapping[str, Any]]
|
|
180
|
+
repairs: tuple[str, ...] = ()
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _type_text(schema: Mapping[str, Any]) -> str:
|
|
184
|
+
"""A parameter's type in a few words, from its JSON schema."""
|
|
185
|
+
if "enum" in schema:
|
|
186
|
+
return "one of " + ", ".join(json.dumps(v) for v in schema["enum"])
|
|
187
|
+
if "const" in schema:
|
|
188
|
+
return json.dumps(schema["const"])
|
|
189
|
+
if "anyOf" in schema:
|
|
190
|
+
options = [_type_text(s) for s in schema["anyOf"] if s.get("type") != "null"]
|
|
191
|
+
return " or ".join(dict.fromkeys(options))
|
|
192
|
+
kind = schema.get("type", "any")
|
|
193
|
+
if kind == "array":
|
|
194
|
+
return f"list of {_type_text(schema.get('items', {}))}"
|
|
195
|
+
bounds = [
|
|
196
|
+
f"{word} {schema[key]}"
|
|
197
|
+
for key, word in (
|
|
198
|
+
("minimum", "at least"),
|
|
199
|
+
("maximum", "at most"),
|
|
200
|
+
("exclusiveMinimum", "more than"),
|
|
201
|
+
("exclusiveMaximum", "less than"),
|
|
202
|
+
)
|
|
203
|
+
if key in schema
|
|
204
|
+
]
|
|
205
|
+
return f"{kind}, {', '.join(bounds)}" if bounds else str(kind)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _not_finite(value: Any) -> bool:
|
|
209
|
+
"""Whether a default holds inf or nan, which JSON cannot say."""
|
|
210
|
+
if isinstance(value, float):
|
|
211
|
+
return not math.isfinite(value)
|
|
212
|
+
if isinstance(value, Mapping):
|
|
213
|
+
return any(map(_not_finite, value.values()))
|
|
214
|
+
return isinstance(value, (list, tuple, set, frozenset)) and any(
|
|
215
|
+
map(_not_finite, value)
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _json_default(where: str, p: inspect.Parameter, adapter: TypeAdapter[Any]) -> Any:
|
|
220
|
+
"""A parameter's default as it is written in JSON: an enum's value, a
|
|
221
|
+
date's text. One that has no such form stops the start."""
|
|
222
|
+
if p.default is _REQUIRED:
|
|
223
|
+
return _REQUIRED
|
|
224
|
+
try:
|
|
225
|
+
if _not_finite(p.default):
|
|
226
|
+
raise ValueError("inf and nan are not JSON")
|
|
227
|
+
shown = adapter.dump_python(p.default, mode="json", warnings=False)
|
|
228
|
+
json.dumps(shown, allow_nan=False)
|
|
229
|
+
except Exception as exc:
|
|
230
|
+
raise TypeError(
|
|
231
|
+
f"{where}: the default of {p.name}, {p.default!r}, cannot be written"
|
|
232
|
+
" as JSON"
|
|
233
|
+
) from exc
|
|
234
|
+
return shown
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _reflect(package: str, name: str, fn: Callable[..., Any], tag: Tag) -> Action:
|
|
238
|
+
"""An action from a bound method: its parameters after the call context."""
|
|
239
|
+
where = f"{package}/{name}"
|
|
240
|
+
if inspect.iscoroutinefunction(fn) or inspect.isasyncgenfunction(fn):
|
|
241
|
+
raise TypeError(
|
|
242
|
+
f"{where} is `async def`; an action is a plain `def` that returns text"
|
|
243
|
+
)
|
|
244
|
+
if inspect.isgeneratorfunction(fn):
|
|
245
|
+
raise TypeError(
|
|
246
|
+
f"{where} has a `yield`; an action is a plain `def` that returns text"
|
|
247
|
+
)
|
|
248
|
+
declared = list(inspect.signature(fn).parameters.values())
|
|
249
|
+
if not declared:
|
|
250
|
+
raise TypeError(f"{where} takes no call context: def {name}(self, call, ...)")
|
|
251
|
+
hints = typing.get_type_hints(fn, include_extras=True)
|
|
252
|
+
doc = parse(fn.__doc__)
|
|
253
|
+
params = []
|
|
254
|
+
for p in declared[1:]:
|
|
255
|
+
if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD, p.POSITIONAL_ONLY):
|
|
256
|
+
raise TypeError(f"{where}: {p.name} must be a named parameter")
|
|
257
|
+
if p.name in RESERVED:
|
|
258
|
+
raise TypeError(f"{where}: no parameter may be called {p.name!r}")
|
|
259
|
+
if p.name not in hints:
|
|
260
|
+
raise TypeError(f"{where}: {p.name} needs a type hint")
|
|
261
|
+
adapter = TypeAdapter(hints[p.name])
|
|
262
|
+
default = _json_default(where, p, adapter)
|
|
263
|
+
params.append(Param(p.name, adapter, default, doc.args.get(p.name, "")))
|
|
264
|
+
return Action(
|
|
265
|
+
package, name, tag.tool, tag.kinds, fn, tuple(params), doc, search=tag.search
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class Registry:
|
|
270
|
+
"""The host's tools, the packages installed here, their actions and their
|
|
271
|
+
skills.
|
|
272
|
+
|
|
273
|
+
``tools`` is the host's list, in the order a client sees them; left out,
|
|
274
|
+
the standard set (``standard_tools()``). The ``search`` tool is added to
|
|
275
|
+
it: ``search`` replaces what a client is told about it. The skill package
|
|
276
|
+
is registered at once, its two actions under the first tool that only
|
|
277
|
+
reads.
|
|
278
|
+
|
|
279
|
+
``skills_from`` says where a plugin's skills are read from: ``"index"``,
|
|
280
|
+
the generated ``skills/index.json``, which a running host uses and which
|
|
281
|
+
must be there and name the files that are there; or ``"files"``, the
|
|
282
|
+
headers of the skill files themselves, which the check and the updater
|
|
283
|
+
use. With ``"files"`` a skill that cannot be read is left out and what is
|
|
284
|
+
wrong with it is kept in ``skill_problems``.
|
|
285
|
+
"""
|
|
286
|
+
|
|
287
|
+
def __init__(
|
|
288
|
+
self,
|
|
289
|
+
tools: Sequence[Tool] | None = None,
|
|
290
|
+
*,
|
|
291
|
+
search: str | None = None,
|
|
292
|
+
skills_from: Literal["index", "files"] | None = None,
|
|
293
|
+
) -> None:
|
|
294
|
+
if skills_from not in (None, "index", "files"):
|
|
295
|
+
raise ValueError(f'skills_from is "index" or "files", not {skills_from!r}')
|
|
296
|
+
self.skills_from = skills_from or default_skills_from
|
|
297
|
+
self.skill_problems: list[str] = []
|
|
298
|
+
self.tools: dict[str, Tool] = {}
|
|
299
|
+
for tool in standard_tools() if tools is None else tools:
|
|
300
|
+
if not _NAME_RE.match(tool.name):
|
|
301
|
+
raise ValueError(f"a tool name is lower case, a-z 0-9 _ -: {tool!r}")
|
|
302
|
+
if tool.name == SEARCH:
|
|
303
|
+
raise ValueError(
|
|
304
|
+
f"{SEARCH!r} is the dispatcher's own tool; a host does not"
|
|
305
|
+
" list it (its description: Registry(..., search=...))"
|
|
306
|
+
)
|
|
307
|
+
if tool.name in self.tools:
|
|
308
|
+
raise ValueError(f"the tool {tool.name!r} is listed twice")
|
|
309
|
+
self.tools[tool.name] = tool
|
|
310
|
+
reading = [t.name for t in self.tools.values() if not t.writes]
|
|
311
|
+
if not reading:
|
|
312
|
+
raise ValueError(
|
|
313
|
+
"a host needs one tool that only reads (Tool(..., writes=False)):"
|
|
314
|
+
" the skills are read through it"
|
|
315
|
+
)
|
|
316
|
+
#: the first tool that only reads
|
|
317
|
+
self.read_tool = reading[0]
|
|
318
|
+
self.tools[SEARCH] = Tool(SEARCH, search or SEARCH_DESCRIPTION, writes=False)
|
|
319
|
+
self.packages: dict[str, Package] = {}
|
|
320
|
+
self.skills: dict[str, Skill] = {}
|
|
321
|
+
self.register(SKILL_PACKAGE, skill_files.skills_plugin(self.read_tool))
|
|
322
|
+
|
|
323
|
+
@property
|
|
324
|
+
def host_tools(self) -> list[Tool]:
|
|
325
|
+
"""The tools an action can be tagged with: all but the search."""
|
|
326
|
+
return [t for t in self.tools.values() if t.name != SEARCH]
|
|
327
|
+
|
|
328
|
+
def example_calls(self, text: str) -> Iterator[tuple[str, dict[str, Any]]]:
|
|
329
|
+
"""Every ``<tool> {json}`` in a text, for this host's tools."""
|
|
330
|
+
return skill_files.example_calls(text, tuple(self.tools))
|
|
331
|
+
|
|
332
|
+
# ------------------------------------------------------------ registration
|
|
333
|
+
|
|
334
|
+
def register(self, name: str, plugin_cls: type[Plugin]) -> Package:
|
|
335
|
+
"""Reflect a plugin class under ``name``, the first part of its paths."""
|
|
336
|
+
if not _NAME_RE.match(name):
|
|
337
|
+
raise ValueError(f"a package name is lower case, a-z 0-9 _ -: {name!r}")
|
|
338
|
+
if name in self.packages:
|
|
339
|
+
raise ValueError(f"package {name!r} is registered already")
|
|
340
|
+
if name == SEARCH_PATH:
|
|
341
|
+
raise ValueError(f"{SEARCH_PATH!r} is the search, not a package")
|
|
342
|
+
if not (isinstance(plugin_cls, type) and issubclass(plugin_cls, Plugin)):
|
|
343
|
+
raise TypeError(f"package {name!r}: {plugin_cls!r} is not a Plugin class")
|
|
344
|
+
plugin = plugin_cls()
|
|
345
|
+
plugin.registry = self
|
|
346
|
+
actions = {}
|
|
347
|
+
search: Action | None = None
|
|
348
|
+
for attr, member in inspect.getmembers(plugin, callable):
|
|
349
|
+
tag = getattr(member, TAG_ATTR, None)
|
|
350
|
+
if not isinstance(tag, Tag):
|
|
351
|
+
continue
|
|
352
|
+
if not tag.search and (tag.tool not in self.tools or tag.tool == SEARCH):
|
|
353
|
+
raise ValueError(
|
|
354
|
+
f"{name}/{attr} is tagged for the tool {tag.tool!r}, which this"
|
|
355
|
+
" host does not have; its tools are "
|
|
356
|
+
+ ", ".join(t.name for t in self.host_tools)
|
|
357
|
+
)
|
|
358
|
+
if not tag.search:
|
|
359
|
+
actions[attr] = _reflect(name, attr, member, tag)
|
|
360
|
+
elif search is None:
|
|
361
|
+
search = _reflect(name, attr, member, tag)
|
|
362
|
+
else:
|
|
363
|
+
raise TypeError(f"package {name!r} has two searches; it gets one")
|
|
364
|
+
directory = plugin_cls.skills_dir()
|
|
365
|
+
package = Package(
|
|
366
|
+
name, plugin, parse(plugin_cls.__doc__), actions, search, directory
|
|
367
|
+
)
|
|
368
|
+
found: list[Skill] = []
|
|
369
|
+
if directory is not None and self.skills_from == "files":
|
|
370
|
+
found, problems = skill_files.scan(name, directory, tuple(self.tools))
|
|
371
|
+
self.skill_problems += problems
|
|
372
|
+
elif directory is not None:
|
|
373
|
+
found = skill_files.load_index(name, directory)
|
|
374
|
+
for skill in found:
|
|
375
|
+
if skill.name in self.skills:
|
|
376
|
+
raise ValueError(
|
|
377
|
+
f"package {name!r}: a skill called {skill.name!r} exists already"
|
|
378
|
+
f" (from {self.skills[skill.name].package!r})"
|
|
379
|
+
)
|
|
380
|
+
self.packages[name] = package
|
|
381
|
+
self.skills.update({skill.name: skill for skill in found})
|
|
382
|
+
return package
|
|
383
|
+
|
|
384
|
+
def load_entry_points(self, group: str = GROUP) -> None:
|
|
385
|
+
"""Register every plugin installed under ``group``. One that cannot be
|
|
386
|
+
loaded stops the start: a host that came up without it would answer
|
|
387
|
+
"not installed here" to calls that worked the day before."""
|
|
388
|
+
for ep in sorted(entry_points(group=group), key=lambda e: e.name):
|
|
389
|
+
try:
|
|
390
|
+
plugin_cls = ep.load()
|
|
391
|
+
known = self.packages.get(ep.name)
|
|
392
|
+
if known is not None and type(known.plugin) is plugin_cls:
|
|
393
|
+
continue # found before: looking twice adds nothing
|
|
394
|
+
self.register(ep.name, plugin_cls)
|
|
395
|
+
except Exception as exc:
|
|
396
|
+
raise PluginError(
|
|
397
|
+
f"the plugin {ep.name!r} ({ep.value}) cannot be loaded: {exc}"
|
|
398
|
+
) from exc
|
|
399
|
+
|
|
400
|
+
# ------------------------------------------------------------------ lookup
|
|
401
|
+
|
|
402
|
+
def shown(self) -> list[Package]:
|
|
403
|
+
"""The packages by name; the skill package only where a plugin ships
|
|
404
|
+
a skill."""
|
|
405
|
+
return [
|
|
406
|
+
p
|
|
407
|
+
for p in sorted_by_name(self.packages)
|
|
408
|
+
if p.name != SKILL_PACKAGE or self.skills
|
|
409
|
+
]
|
|
410
|
+
|
|
411
|
+
def package(self, name: str) -> Package:
|
|
412
|
+
found = self.packages.get(name)
|
|
413
|
+
if found is None:
|
|
414
|
+
shown = ", ".join(p.name for p in self.shown())
|
|
415
|
+
raise DispatchError(
|
|
416
|
+
NOT_FOUND,
|
|
417
|
+
f"no package {name!r} is installed here",
|
|
418
|
+
hint=f"installed: {shown}" if shown else None,
|
|
419
|
+
)
|
|
420
|
+
return found
|
|
421
|
+
|
|
422
|
+
def action(self, package: str, name: str) -> Action:
|
|
423
|
+
found = self.package(package).actions.get(name)
|
|
424
|
+
if found is None:
|
|
425
|
+
raise DispatchError(
|
|
426
|
+
NOT_FOUND,
|
|
427
|
+
f"{package} has no action {name!r}",
|
|
428
|
+
hint=f'the path "{package}/?" lists its actions',
|
|
429
|
+
)
|
|
430
|
+
return found
|
|
431
|
+
|
|
432
|
+
def actions(self) -> list[Action]:
|
|
433
|
+
return [a for p in self.packages.values() for a in p.actions.values()]
|
|
434
|
+
|
|
435
|
+
def searchers(self) -> list[Action]:
|
|
436
|
+
"""Each package's part of the search: those that take any kind first,
|
|
437
|
+
then by package name. The skill package takes part only when there is a
|
|
438
|
+
skill to find."""
|
|
439
|
+
found = [
|
|
440
|
+
p.search
|
|
441
|
+
for p in self.packages.values()
|
|
442
|
+
if p.search is not None
|
|
443
|
+
# the skills are asked only where a plugin ships some
|
|
444
|
+
and (p.name != SKILL_PACKAGE or self.skills)
|
|
445
|
+
]
|
|
446
|
+
return sorted(found, key=lambda a: (bool(a.kinds), a.package))
|
|
447
|
+
|
|
448
|
+
def contract(self) -> dict[str, Any]:
|
|
449
|
+
"""What a caller depends on, as plain data: every path with its tool
|
|
450
|
+
and, in order, its arguments with their JSON schema and default.
|
|
451
|
+
A host pins it in a file and regenerates that after a deliberate
|
|
452
|
+
change."""
|
|
453
|
+
|
|
454
|
+
def one(action: Action) -> dict[str, Any]:
|
|
455
|
+
return {
|
|
456
|
+
"tool": action.tool,
|
|
457
|
+
"kinds": list(action.kinds),
|
|
458
|
+
"arguments": {
|
|
459
|
+
p.name: {
|
|
460
|
+
"schema": p.adapter.json_schema(),
|
|
461
|
+
**({} if p.required else {"default": p.default}),
|
|
462
|
+
}
|
|
463
|
+
for p in action.params
|
|
464
|
+
},
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
out = {a.path: one(a) for a in sorted(self.actions(), key=lambda a: a.path)}
|
|
468
|
+
out[SEARCH_PATH] = {a.package: one(a) for a in self.searchers()}
|
|
469
|
+
return out
|
|
470
|
+
|
|
471
|
+
def used_by(self, path: str) -> list[str]:
|
|
472
|
+
"""The skills whose example calls name this path."""
|
|
473
|
+
return [s.name for s in self.skills.values() if path in s.uses]
|
|
474
|
+
|
|
475
|
+
def best_skills(self, q: str, limit: int = 2) -> list[Skill]:
|
|
476
|
+
"""The skills that fit a task said in plain words, best first: for a
|
|
477
|
+
host that wants to hand an assistant the one or two it will need."""
|
|
478
|
+
return skill_files.rank(self.skills.values(), q)[: max(0, limit)]
|
|
479
|
+
|
|
480
|
+
# ---------------------------------------------------------------- the call
|
|
481
|
+
|
|
482
|
+
def batch(self, arguments: Mapping[str, Any], tool: str = "") -> Batch | None:
|
|
483
|
+
"""The calls of ``{"calls": [...]}``, each to be resolved as if it had
|
|
484
|
+
come alone; ``None`` when the arguments are one call. The list, or a
|
|
485
|
+
call in it, may come as JSON text. ``tool`` is the tool they came on:
|
|
486
|
+
a refusal shows the form of that tool's calls (a search has no path)."""
|
|
487
|
+
if CALLS_KEY not in arguments:
|
|
488
|
+
return None
|
|
489
|
+
if tool == SEARCH:
|
|
490
|
+
own, first = '"q"', '"q": "<words>"'
|
|
491
|
+
else:
|
|
492
|
+
own, first = f'"{PATH_KEY}"', f'"{PATH_KEY}": "<package>/<action>"'
|
|
493
|
+
form = f'{{"{CALLS_KEY}": [{{{first}, ...}}, ...]}}'
|
|
494
|
+
if len(arguments) > 1:
|
|
495
|
+
raise DispatchError(
|
|
496
|
+
BAD_INPUT,
|
|
497
|
+
f'"{CALLS_KEY}" stands alone: each call inside it has its own'
|
|
498
|
+
f" {own} and arguments",
|
|
499
|
+
hint=form,
|
|
500
|
+
)
|
|
501
|
+
calls = arguments[CALLS_KEY]
|
|
502
|
+
repairs: list[str] = []
|
|
503
|
+
|
|
504
|
+
def read(text: str, what: str) -> Any:
|
|
505
|
+
try:
|
|
506
|
+
value, repaired = lenient.loads(text)
|
|
507
|
+
except ValueError as exc:
|
|
508
|
+
raise DispatchError(
|
|
509
|
+
BAD_INPUT, f"{what} is not JSON: {exc}", hint=form
|
|
510
|
+
) from exc
|
|
511
|
+
if repaired:
|
|
512
|
+
repairs.append(f"{what} ({', '.join(repaired)})")
|
|
513
|
+
return value
|
|
514
|
+
|
|
515
|
+
if isinstance(calls, str):
|
|
516
|
+
calls = read(calls, f'"{CALLS_KEY}"')
|
|
517
|
+
if isinstance(calls, list):
|
|
518
|
+
calls = [
|
|
519
|
+
read(one, f"call {n}") if isinstance(one, str) else one
|
|
520
|
+
for n, one in enumerate(calls, 1)
|
|
521
|
+
]
|
|
522
|
+
if (
|
|
523
|
+
not isinstance(calls, list)
|
|
524
|
+
or not calls
|
|
525
|
+
or not all(isinstance(one, Mapping) for one in calls)
|
|
526
|
+
):
|
|
527
|
+
raise DispatchError(
|
|
528
|
+
BAD_INPUT, f'"{CALLS_KEY}" is a list of one or more calls', hint=form
|
|
529
|
+
)
|
|
530
|
+
if len(calls) > MAX_CALLS:
|
|
531
|
+
raise DispatchError(
|
|
532
|
+
BAD_INPUT,
|
|
533
|
+
f"{len(calls)} calls in one; the limit is {MAX_CALLS}",
|
|
534
|
+
hint="nothing was done; send them in smaller lists",
|
|
535
|
+
)
|
|
536
|
+
return Batch(calls, tuple(repairs))
|
|
537
|
+
|
|
538
|
+
def resolve(self, tool: str, arguments: Mapping[str, Any]) -> Help | Bound:
|
|
539
|
+
"""What a call on ``tool`` asks for: help, or a checked call to run."""
|
|
540
|
+
args = dict(arguments)
|
|
541
|
+
if CALLS_KEY in args:
|
|
542
|
+
raise DispatchError(
|
|
543
|
+
BAD_INPUT,
|
|
544
|
+
f'a call inside "{CALLS_KEY}" is one call: it cannot hold'
|
|
545
|
+
f' "{CALLS_KEY}" itself',
|
|
546
|
+
)
|
|
547
|
+
if tool not in self.tools:
|
|
548
|
+
raise ValueError(f"this host has no tool {tool!r}")
|
|
549
|
+
path = args.pop(PATH_KEY, None)
|
|
550
|
+
if tool == SEARCH:
|
|
551
|
+
return self._on_search(path, args)
|
|
552
|
+
if not isinstance(path, str) or not path.strip():
|
|
553
|
+
raise DispatchError(
|
|
554
|
+
BAD_INPUT,
|
|
555
|
+
'a call needs a "path": "<package>/<action>"',
|
|
556
|
+
hint='the path "?" lists what is installed',
|
|
557
|
+
)
|
|
558
|
+
path = path.strip()
|
|
559
|
+
if path.endswith("?"):
|
|
560
|
+
return Help(self.help(path[:-1]))
|
|
561
|
+
if path == SEARCH_PATH:
|
|
562
|
+
raise DispatchError(
|
|
563
|
+
BAD_INPUT,
|
|
564
|
+
f"the search is a tool of its own, `{SEARCH}`, not a path of `{tool}`",
|
|
565
|
+
hint="nothing was done; send "
|
|
566
|
+
+ f"{SEARCH} {json.dumps(args, ensure_ascii=False)}",
|
|
567
|
+
)
|
|
568
|
+
parts = path.split("/")
|
|
569
|
+
if len(parts) != 2 or not all(parts):
|
|
570
|
+
raise DispatchError(
|
|
571
|
+
BAD_INPUT,
|
|
572
|
+
f'a path is "<package>/<action>", not {path!r}',
|
|
573
|
+
hint='the path "?" lists what is installed',
|
|
574
|
+
)
|
|
575
|
+
action = self.action(parts[0], parts[1])
|
|
576
|
+
self._through(tool, action.path, action.tool)
|
|
577
|
+
return self.bind(action, args)
|
|
578
|
+
|
|
579
|
+
def _on_search(self, path: Any, args: dict[str, Any]) -> Help | Bound:
|
|
580
|
+
"""A call on the search tool. It takes no path: the one use of a path
|
|
581
|
+
there is help. An action's path is told which tool it goes through."""
|
|
582
|
+
if path is None:
|
|
583
|
+
return self._resolve_search(args)
|
|
584
|
+
text = path.strip() if isinstance(path, str) else ""
|
|
585
|
+
if text.endswith("?"):
|
|
586
|
+
return Help(self.help(text[:-1]))
|
|
587
|
+
package, _, name = text.partition("/")
|
|
588
|
+
found = self.packages.get(package)
|
|
589
|
+
action = found.actions.get(name) if found is not None else None
|
|
590
|
+
if action is not None:
|
|
591
|
+
self._through(SEARCH, action.path, action.tool)
|
|
592
|
+
send = args or {"q": "<words>"}
|
|
593
|
+
raise DispatchError(
|
|
594
|
+
BAD_INPUT,
|
|
595
|
+
f"the `{SEARCH}` tool takes no path",
|
|
596
|
+
hint="nothing was done; send "
|
|
597
|
+
+ f"{SEARCH} {json.dumps(send, ensure_ascii=False)}",
|
|
598
|
+
)
|
|
599
|
+
|
|
600
|
+
def _through(self, tool: str, path: str, right: str) -> None:
|
|
601
|
+
if tool != right:
|
|
602
|
+
raise DispatchError(
|
|
603
|
+
BAD_INPUT,
|
|
604
|
+
f"{path} goes through the `{right}` tool, not `{tool}`",
|
|
605
|
+
hint=f"nothing was done; send the same call with `{right}`",
|
|
606
|
+
)
|
|
607
|
+
|
|
608
|
+
def _resolve_search(self, args: dict[str, Any]) -> Bound:
|
|
609
|
+
"""The one search: to the package that finds the kind ``t``, or,
|
|
610
|
+
without ``t``, to every package whose search takes these arguments."""
|
|
611
|
+
searchers = self.searchers()
|
|
612
|
+
kind = args.get(KIND_KEY)
|
|
613
|
+
if kind is None:
|
|
614
|
+
if not searchers:
|
|
615
|
+
raise DispatchError(NOT_FOUND, "nothing installed here can be searched")
|
|
616
|
+
bound, refusal = [], None
|
|
617
|
+
for action in searchers:
|
|
618
|
+
try:
|
|
619
|
+
bound.append(self.bind_search(action, args))
|
|
620
|
+
except DispatchError as exc:
|
|
621
|
+
refusal = refusal or exc
|
|
622
|
+
bound = self._unasked_skills(bound, args.get("q"))
|
|
623
|
+
if not bound and refusal is not None:
|
|
624
|
+
raise refusal
|
|
625
|
+
else:
|
|
626
|
+
if not isinstance(kind, str) or not kind.strip():
|
|
627
|
+
raise DispatchError(
|
|
628
|
+
BAD_INPUT,
|
|
629
|
+
f'`{KIND_KEY}` is one kind, e.g. "note"',
|
|
630
|
+
hint="for several kinds send several calls: "
|
|
631
|
+
+ self._several_kinds(searchers),
|
|
632
|
+
)
|
|
633
|
+
key = kind.strip().lower()
|
|
634
|
+
rest = {k: v for k, v in args.items() if k != KIND_KEY}
|
|
635
|
+
if key in ("*", "all", "any"):
|
|
636
|
+
# every kind is the search without `t`: said with the
|
|
637
|
+
# caller's own arguments, so that the retry asks the same
|
|
638
|
+
raise DispatchError(
|
|
639
|
+
BAD_INPUT,
|
|
640
|
+
f"`{KIND_KEY}` names one kind; without it every kind is searched",
|
|
641
|
+
hint="nothing was done; send "
|
|
642
|
+
+ f"{SEARCH} {json.dumps(rest, ensure_ascii=False)}",
|
|
643
|
+
)
|
|
644
|
+
if "," in key:
|
|
645
|
+
several = [
|
|
646
|
+
{**rest, KIND_KEY: one.strip()}
|
|
647
|
+
for one in kind.split(",")
|
|
648
|
+
if one.strip()
|
|
649
|
+
]
|
|
650
|
+
raise DispatchError(
|
|
651
|
+
BAD_INPUT,
|
|
652
|
+
f"`{KIND_KEY}` names one kind, not several",
|
|
653
|
+
hint="nothing was done; send one call for each kind: "
|
|
654
|
+
+ f"{SEARCH} "
|
|
655
|
+
+ json.dumps({CALLS_KEY: several}, ensure_ascii=False),
|
|
656
|
+
)
|
|
657
|
+
# a kind that a package names is that package's, also the skills'
|
|
658
|
+
# where no plugin ships one: the answer is then that there are none
|
|
659
|
+
named = [
|
|
660
|
+
p.search
|
|
661
|
+
for p in sorted_by_name(self.packages)
|
|
662
|
+
if p.search is not None and key in p.search.kinds
|
|
663
|
+
]
|
|
664
|
+
if len(named) > 1 and not self.skills:
|
|
665
|
+
# a plugin finds this kind itself: the built-in package has
|
|
666
|
+
# nothing to add where no skill file is installed
|
|
667
|
+
named = [a for a in named if a.package != SKILL_PACKAGE]
|
|
668
|
+
chosen = named or [a for a in searchers if not a.kinds]
|
|
669
|
+
if not chosen:
|
|
670
|
+
kinds = [k for a in searchers for k in a.kinds]
|
|
671
|
+
raise DispatchError(
|
|
672
|
+
NOT_FOUND,
|
|
673
|
+
f"nothing installed here finds the kind {kind!r}",
|
|
674
|
+
hint="kinds: " + ", ".join(kinds) if kinds else None,
|
|
675
|
+
)
|
|
676
|
+
bound = [self.bind_search(action, args) for action in chosen]
|
|
677
|
+
return Bound(
|
|
678
|
+
self,
|
|
679
|
+
bound[0].action,
|
|
680
|
+
bound[0].params,
|
|
681
|
+
tuple(r for one in bound for r in one.repairs),
|
|
682
|
+
tuple(bound[1:]),
|
|
683
|
+
)
|
|
684
|
+
|
|
685
|
+
def _unasked_skills(self, bound: list[Bound], q: Any) -> list[Bound]:
|
|
686
|
+
"""The skills' part in a search that names no kind. Beside the
|
|
687
|
+
answers of other packages the guides are named only when one fits
|
|
688
|
+
the task well, and say nothing otherwise; where they alone answer,
|
|
689
|
+
the search is one for guides."""
|
|
690
|
+
skills = [b for b in bound if b.action.package == SKILL_PACKAGE]
|
|
691
|
+
if not skills:
|
|
692
|
+
return bound
|
|
693
|
+
if len(bound) == 1:
|
|
694
|
+
skills[0].params[KIND_KEY] = skill_files.KIND
|
|
695
|
+
elif not skill_files.fits(
|
|
696
|
+
self.skills.values(), q if isinstance(q, str) else ""
|
|
697
|
+
):
|
|
698
|
+
return [b for b in bound if b.action.package != SKILL_PACKAGE]
|
|
699
|
+
return bound
|
|
700
|
+
|
|
701
|
+
def bind_search(self, action: Action, args: Mapping[str, Any]) -> Bound:
|
|
702
|
+
"""``t`` chose the package; it is passed on only to a search that
|
|
703
|
+
filters by it."""
|
|
704
|
+
if KIND_KEY not in {p.name for p in action.params}:
|
|
705
|
+
args = {k: v for k, v in args.items() if k != KIND_KEY}
|
|
706
|
+
return self.bind(action, args)
|
|
707
|
+
|
|
708
|
+
def bind(self, action: Action, args: Mapping[str, Any]) -> Bound:
|
|
709
|
+
"""The call with its arguments as the action's type hints want them,
|
|
710
|
+
or ``BadInput`` naming every argument that is unknown, missing or of
|
|
711
|
+
the wrong type."""
|
|
712
|
+
known = {p.name: p for p in action.params}
|
|
713
|
+
problems = [f"unknown argument `{name}`" for name in args if name not in known]
|
|
714
|
+
out: dict[str, Any] = {}
|
|
715
|
+
repairs = []
|
|
716
|
+
for p in action.params:
|
|
717
|
+
if p.name not in args:
|
|
718
|
+
if p.required:
|
|
719
|
+
problems.append(f"`{p.name}` is missing")
|
|
720
|
+
continue
|
|
721
|
+
try:
|
|
722
|
+
out[p.name], repaired = _validate(p, args[p.name])
|
|
723
|
+
if repaired:
|
|
724
|
+
repairs.append(f"`{p.name}` ({', '.join(repaired)})")
|
|
725
|
+
except ValidationError as exc:
|
|
726
|
+
first = exc.errors(include_url=False)[0]
|
|
727
|
+
problems.append(f"`{p.name}`: {first['msg']} ({p.type_text()})")
|
|
728
|
+
if problems:
|
|
729
|
+
raise DispatchError(
|
|
730
|
+
BAD_INPUT,
|
|
731
|
+
f"{action.path}: " + "; ".join(problems),
|
|
732
|
+
hint=f'{action.signature()}; the path "{action.path}?" explains them',
|
|
733
|
+
)
|
|
734
|
+
return Bound(self, action, out, tuple(repairs))
|
|
735
|
+
|
|
736
|
+
# -------------------------------------------------------------------- help
|
|
737
|
+
|
|
738
|
+
def help(self, path: str) -> str:
|
|
739
|
+
"""Help for a path without its question mark: everything installed,
|
|
740
|
+
one package, one action, or one parameter of an action."""
|
|
741
|
+
parts = [part for part in path.strip().split("/") if part]
|
|
742
|
+
if not parts:
|
|
743
|
+
return self._help_root()
|
|
744
|
+
if parts[0] == SEARCH_PATH and len(parts) <= 2:
|
|
745
|
+
return self._help_search(parts[1] if len(parts) == 2 else None)
|
|
746
|
+
if len(parts) == 1:
|
|
747
|
+
return self._help_package(self.package(parts[0]))
|
|
748
|
+
action = self.action(parts[0], parts[1])
|
|
749
|
+
if len(parts) == 2:
|
|
750
|
+
return self._help_action(action)
|
|
751
|
+
if len(parts) == 3:
|
|
752
|
+
for p in action.params:
|
|
753
|
+
if p.name == parts[2]:
|
|
754
|
+
return f"{action.path}/{p.name} {_param_text(p)}"
|
|
755
|
+
raise DispatchError(
|
|
756
|
+
NOT_FOUND,
|
|
757
|
+
f"{action.path} has no argument {parts[2]!r}",
|
|
758
|
+
hint=action.signature(),
|
|
759
|
+
)
|
|
760
|
+
raise DispatchError(
|
|
761
|
+
BAD_INPUT,
|
|
762
|
+
f"help goes as deep as <package>/<action>/<argument>?, not {path!r}",
|
|
763
|
+
)
|
|
764
|
+
|
|
765
|
+
def _help_root(self) -> str:
|
|
766
|
+
shown = self.shown()
|
|
767
|
+
lines = [
|
|
768
|
+
"Packages installed here:" if shown else "No package is installed here."
|
|
769
|
+
]
|
|
770
|
+
lines += [f"- {p.name}: {p.doc.summary}" for p in shown]
|
|
771
|
+
if self.searchers():
|
|
772
|
+
lines.append(
|
|
773
|
+
f'Search: the `{SEARCH}` tool searches all of them, {SEARCH} {{"q":'
|
|
774
|
+
f' "<words>"}}; the path "{SEARCH_PATH}?" shows its arguments.'
|
|
775
|
+
)
|
|
776
|
+
lines += [
|
|
777
|
+
"",
|
|
778
|
+
'A call is one tool and one JSON object: "path" is "<package>/<action>",'
|
|
779
|
+
" every other key is an argument of that action.",
|
|
780
|
+
"Tools: "
|
|
781
|
+
+ ", ".join(f"`{t.name}` ({_does(t)})" for t in self.host_tools)
|
|
782
|
+
+ f". Each action goes through one of them. `{SEARCH}` takes no path.",
|
|
783
|
+
f'Several calls at once: {{"{CALLS_KEY}": [{{...}}, {{...}}]}} holds up to'
|
|
784
|
+
f" {MAX_CALLS} calls for one tool. Each runs on its own and all are"
|
|
785
|
+
" answered together.",
|
|
786
|
+
'next: "<package>/?" lists a package\'s actions; "<package>/<action>?"'
|
|
787
|
+
" shows its arguments. A path ending in ? runs nothing.",
|
|
788
|
+
]
|
|
789
|
+
return "\n".join(lines)
|
|
790
|
+
|
|
791
|
+
def _help_package(self, package: Package) -> str:
|
|
792
|
+
lines = [f"{package.name}: {package.doc.summary}"]
|
|
793
|
+
for tool in self.host_tools:
|
|
794
|
+
found = [a for a in sorted_by_name(package.actions) if a.tool == tool.name]
|
|
795
|
+
if found:
|
|
796
|
+
lines.append(f"through `{tool.name}`:")
|
|
797
|
+
lines += [f"- {a.path}: {a.doc.summary}" for a in found]
|
|
798
|
+
if package.search is not None and package.search in self.searchers():
|
|
799
|
+
kinds = ", ".join(package.search.kinds) or "any kind"
|
|
800
|
+
lines.append(f"found through the `{SEARCH}` tool: {kinds}")
|
|
801
|
+
own = [s.name for s in self.skills.values() if s.package == package.name]
|
|
802
|
+
if own:
|
|
803
|
+
lines.append("skills: " + ", ".join(own))
|
|
804
|
+
lines.append(f'next: "{package.name}/<action>?" shows an action\'s arguments')
|
|
805
|
+
return "\n".join(lines)
|
|
806
|
+
|
|
807
|
+
def _help_search(self, param: str | None) -> str:
|
|
808
|
+
searchers = self.searchers()
|
|
809
|
+
if not searchers:
|
|
810
|
+
raise DispatchError(NOT_FOUND, "nothing installed here can be searched")
|
|
811
|
+
if param is not None:
|
|
812
|
+
lines = [
|
|
813
|
+
f"{SEARCH_PATH}/{p.name} for {a.package} {_param_text(p)}"
|
|
814
|
+
for a in searchers
|
|
815
|
+
for p in a.params
|
|
816
|
+
if p.name == param
|
|
817
|
+
]
|
|
818
|
+
if param == KIND_KEY:
|
|
819
|
+
lines.insert(0, self._kinds_line(searchers))
|
|
820
|
+
if not lines:
|
|
821
|
+
raise DispatchError(
|
|
822
|
+
NOT_FOUND,
|
|
823
|
+
f"{SEARCH_PATH} has no argument {param!r}",
|
|
824
|
+
hint="; ".join(a.signature() for a in searchers),
|
|
825
|
+
)
|
|
826
|
+
return "\n".join(lines)
|
|
827
|
+
lines = [
|
|
828
|
+
f"{SEARCH_PATH} (a tool of its own, it takes no path): one search over"
|
|
829
|
+
f" everything installed. `{KIND_KEY}` names one kind and the package that"
|
|
830
|
+
f" finds it answers; without `{KIND_KEY}` every package answers whose"
|
|
831
|
+
" search takes the arguments given.",
|
|
832
|
+
self._kinds_line(searchers),
|
|
833
|
+
"For several kinds send several calls: " + self._several_kinds(searchers),
|
|
834
|
+
]
|
|
835
|
+
for action in searchers:
|
|
836
|
+
lines.append(f"[{action.package}] {action.doc.summary}")
|
|
837
|
+
lines += self._action_lines(action)
|
|
838
|
+
return "\n".join(lines)
|
|
839
|
+
|
|
840
|
+
def _several_kinds(self, searchers: list[Action]) -> str:
|
|
841
|
+
"""Two kinds in one call, as it is sent: with kinds that are found
|
|
842
|
+
here where a package names some, with blanks where none does."""
|
|
843
|
+
kinds = [kind for a in searchers for kind in a.kinds][:2]
|
|
844
|
+
kinds += ["<kind>", "<another kind>"][len(kinds) :]
|
|
845
|
+
calls = [{"q": "<words>", KIND_KEY: kind} for kind in kinds]
|
|
846
|
+
return f"{SEARCH} " + json.dumps({CALLS_KEY: calls}, ensure_ascii=False)
|
|
847
|
+
|
|
848
|
+
def _kinds_line(self, searchers: list[Action]) -> str:
|
|
849
|
+
return "Kinds: " + "; ".join(
|
|
850
|
+
f"{', '.join(a.kinds) if a.kinds else 'any other'} ({a.package})"
|
|
851
|
+
for a in sorted(searchers, key=lambda a: (not a.kinds, a.package))
|
|
852
|
+
)
|
|
853
|
+
|
|
854
|
+
def _help_action(self, action: Action) -> str:
|
|
855
|
+
lines = [f"{action.path} (tool: {action.tool}): {action.doc.summary}"]
|
|
856
|
+
return "\n".join(lines + self._action_lines(action))
|
|
857
|
+
|
|
858
|
+
def _action_lines(self, action: Action) -> list[str]:
|
|
859
|
+
lines = []
|
|
860
|
+
if action.doc.body:
|
|
861
|
+
lines.append(action.doc.body)
|
|
862
|
+
if action.kinds and not action.search:
|
|
863
|
+
lines.append("Works on: " + ", ".join(action.kinds))
|
|
864
|
+
if action.params:
|
|
865
|
+
lines.append("Arguments:")
|
|
866
|
+
lines += [_param_line(p) for p in action.params]
|
|
867
|
+
else:
|
|
868
|
+
lines.append("Arguments: none")
|
|
869
|
+
if action.doc.returns:
|
|
870
|
+
lines.append(f"Returns: {action.doc.returns}")
|
|
871
|
+
if action.doc.example:
|
|
872
|
+
lines.append(f"Example: {action.doc.example}")
|
|
873
|
+
used = self.used_by(action.path)
|
|
874
|
+
if used and not action.search:
|
|
875
|
+
lines.append("Skills that use it: " + ", ".join(used))
|
|
876
|
+
return lines
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
def label(arguments: Mapping[str, Any], tool: str = "") -> str:
|
|
880
|
+
"""What a call of a batch is called in the report: its path, and on the
|
|
881
|
+
search tool, which takes none, the search."""
|
|
882
|
+
path = arguments.get(PATH_KEY)
|
|
883
|
+
if isinstance(path, str) and path.strip():
|
|
884
|
+
return path.strip()
|
|
885
|
+
return SEARCH_PATH if tool == SEARCH else "(no path)"
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
def _does(tool: Tool) -> str:
|
|
889
|
+
"""What a tool's actions do, in a word or three, from how it is marked."""
|
|
890
|
+
if not tool.writes:
|
|
891
|
+
return "reads"
|
|
892
|
+
return "cannot be undone" if tool.destructive else "writes"
|
|
893
|
+
|
|
894
|
+
|
|
895
|
+
def report(answers: list[tuple[str, str]]) -> str:
|
|
896
|
+
"""The answers of a batch as one text: (label, answer) in the order sent."""
|
|
897
|
+
lost = [n for n, (_, text) in enumerate(answers, 1) if failed(text)]
|
|
898
|
+
many = "1 call" if len(answers) == 1 else f"{len(answers)} calls, each on its own"
|
|
899
|
+
head = f"{many}: {len(answers) - len(lost)} ok"
|
|
900
|
+
if lost:
|
|
901
|
+
head += f", {len(lost)} failed ({', '.join(map(str, lost))})."
|
|
902
|
+
if len(answers) > 1:
|
|
903
|
+
head += " A failed call did not stop or undo the others."
|
|
904
|
+
else:
|
|
905
|
+
head += "."
|
|
906
|
+
parts = [head]
|
|
907
|
+
parts += [f"[{n}] {name}\n{text}" for n, (name, text) in enumerate(answers, 1)]
|
|
908
|
+
return "\n\n".join(parts)
|
|
909
|
+
|
|
910
|
+
|
|
911
|
+
def failed(answer: str) -> bool:
|
|
912
|
+
"""Whether an answer is a refusal; what was repaired may stand before it."""
|
|
913
|
+
if answer.startswith(_REPAIRED):
|
|
914
|
+
answer = answer.partition("\n")[2]
|
|
915
|
+
return answer.startswith("[error:")
|
|
916
|
+
|
|
917
|
+
|
|
918
|
+
_REPAIRED = "note: JSON sent as text was repaired: "
|
|
919
|
+
|
|
920
|
+
|
|
921
|
+
def repaired(repairs: tuple[str, ...], answer: str) -> str:
|
|
922
|
+
"""An answer led by what was repaired to read the call, if anything was."""
|
|
923
|
+
if not repairs:
|
|
924
|
+
return answer
|
|
925
|
+
return (
|
|
926
|
+
f"{_REPAIRED}{'; '.join(repairs)}."
|
|
927
|
+
" Check that the call below did what you meant.\n" + answer
|
|
928
|
+
)
|
|
929
|
+
|
|
930
|
+
|
|
931
|
+
def sorted_by_name(things: Mapping[str, Any]) -> list[Any]:
|
|
932
|
+
return [things[name] for name in sorted(things)]
|
|
933
|
+
|
|
934
|
+
|
|
935
|
+
def _param_text(p: Param) -> str:
|
|
936
|
+
need = "required" if p.required else f"default {json.dumps(p.default)}"
|
|
937
|
+
return f"({p.type_text()}; {need}): {p.text}".rstrip()
|
|
938
|
+
|
|
939
|
+
|
|
940
|
+
def _param_line(p: Param) -> str:
|
|
941
|
+
return f"- {p.name} {_param_text(p)}"
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
def _validate(p: Param, value: Any) -> tuple[Any, tuple[str, ...]]:
|
|
945
|
+
"""The value as the hint wants it, and what was repaired to read it."""
|
|
946
|
+
try:
|
|
947
|
+
return p.adapter.validate_python(value), ()
|
|
948
|
+
except ValidationError:
|
|
949
|
+
# A list or an object sent as its JSON text, perhaps not quite JSON.
|
|
950
|
+
if not (isinstance(value, str) and value.lstrip()[:1] in ("[", "{")):
|
|
951
|
+
raise
|
|
952
|
+
try:
|
|
953
|
+
parsed, repairs = lenient.loads(value)
|
|
954
|
+
except ValueError:
|
|
955
|
+
pass
|
|
956
|
+
else:
|
|
957
|
+
return p.adapter.validate_python(parsed), repairs
|
|
958
|
+
raise
|
|
959
|
+
|
|
960
|
+
|
|
961
|
+
def build_registry(
|
|
962
|
+
tools: Sequence[Tool] | None = None,
|
|
963
|
+
*,
|
|
964
|
+
search: str | None = None,
|
|
965
|
+
group: str = GROUP,
|
|
966
|
+
skills_from: Literal["index", "files"] | None = None,
|
|
967
|
+
) -> Registry:
|
|
968
|
+
"""The registry of a running host: its tools and every plugin installed
|
|
969
|
+
under its entry point group."""
|
|
970
|
+
registry = Registry(tools, search=search, skills_from=skills_from)
|
|
971
|
+
registry.load_entry_points(group)
|
|
972
|
+
return registry
|