ekl-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.
Files changed (75) hide show
  1. ekl_cli/__init__.py +2 -0
  2. ekl_cli/bridge.py +160 -0
  3. ekl_cli/client.py +232 -0
  4. ekl_cli/clients/.agents/plugins/marketplace.json +20 -0
  5. ekl_cli/clients/.claude-plugin/marketplace.json +16 -0
  6. ekl_cli/clients/README.md +3 -0
  7. ekl_cli/clients/claude-code/.claude-plugin/plugin.json +14 -0
  8. ekl_cli/clients/claude-code/.mcp.json +10 -0
  9. ekl_cli/clients/claude-code/commands/check.md +11 -0
  10. ekl_cli/clients/claude-code/commands/deploy.md +49 -0
  11. ekl_cli/clients/claude-code/commands/status.md +10 -0
  12. ekl_cli/clients/claude-code/skills/agent-behaviour/SKILL.md +112 -0
  13. ekl_cli/clients/claude-code/skills/agent-config-in-repo/SKILL.md +92 -0
  14. ekl_cli/clients/claude-code/skills/connect-mcp-server/SKILL.md +296 -0
  15. ekl_cli/clients/claude-code/skills/operate-agent/SKILL.md +54 -0
  16. ekl_cli/clients/claude-code/skills/plan-with-the-network/SKILL.md +60 -0
  17. ekl_cli/clients/codex/mcp.json +11 -0
  18. ekl_cli/clients/codex/plugin.json +8 -0
  19. ekl_cli/clients/codex/skills/agent-behaviour/SKILL.md +112 -0
  20. ekl_cli/clients/codex/skills/agent-config-in-repo/SKILL.md +92 -0
  21. ekl_cli/clients/codex/skills/connect-mcp-server/SKILL.md +296 -0
  22. ekl_cli/clients/codex/skills/operate-agent/SKILL.md +54 -0
  23. ekl_cli/clients/codex/skills/plan-with-the-network/SKILL.md +60 -0
  24. ekl_cli/clients/cursor/.cursor-plugin/plugin.json +8 -0
  25. ekl_cli/clients/cursor/commands/check.md +11 -0
  26. ekl_cli/clients/cursor/commands/deploy.md +49 -0
  27. ekl_cli/clients/cursor/commands/status.md +10 -0
  28. ekl_cli/clients/cursor/mcp.json +10 -0
  29. ekl_cli/clients/cursor/rules/eukollab.mdc +81 -0
  30. ekl_cli/clients/cursor/skills/agent-behaviour/SKILL.md +112 -0
  31. ekl_cli/clients/cursor/skills/agent-config-in-repo/SKILL.md +92 -0
  32. ekl_cli/clients/cursor/skills/connect-mcp-server/SKILL.md +296 -0
  33. ekl_cli/clients/cursor/skills/operate-agent/SKILL.md +54 -0
  34. ekl_cli/clients/cursor/skills/plan-with-the-network/SKILL.md +60 -0
  35. ekl_cli/clients/gemini/GEMINI.md +76 -0
  36. ekl_cli/clients/gemini/gemini-extension.json +14 -0
  37. ekl_cli/clients/generic/AGENTS.md +76 -0
  38. ekl_cli/clients/generic/mcp.json +10 -0
  39. ekl_cli/clients/vscode/instructions/eukollab.instructions.md +80 -0
  40. ekl_cli/clients/vscode/mcp.json +11 -0
  41. ekl_cli/command_help.py +223 -0
  42. ekl_cli/declarations.py +492 -0
  43. ekl_cli/deploy.py +432 -0
  44. ekl_cli/deploy_command.py +556 -0
  45. ekl_cli/derive.py +217 -0
  46. ekl_cli/design.py +339 -0
  47. ekl_cli/finder.py +695 -0
  48. ekl_cli/icon.py +102 -0
  49. ekl_cli/install.py +185 -0
  50. ekl_cli/lifecycle.py +357 -0
  51. ekl_cli/main.py +643 -0
  52. ekl_cli/mcp.py +279 -0
  53. ekl_cli/messages.py +245 -0
  54. ekl_cli/onboard.py +1040 -0
  55. ekl_cli/participation.py +247 -0
  56. ekl_cli/project.py +211 -0
  57. ekl_cli/prompt.py +176 -0
  58. ekl_cli/py.typed +0 -0
  59. ekl_cli/release_root.json +9 -0
  60. ekl_cli/release_trust.py +376 -0
  61. ekl_cli/repair.py +266 -0
  62. ekl_cli/schema.py +117 -0
  63. ekl_cli/setup.py +326 -0
  64. ekl_cli/supervise.py +162 -0
  65. ekl_cli/templates/python/eukollab-agent.md.tmpl +202 -0
  66. ekl_cli/templates/python/eukollab_callbacks.py.tmpl +509 -0
  67. ekl_cli/templates/versions.json +3 -0
  68. ekl_cli/ui.py +158 -0
  69. ekl_cli/versions.py +402 -0
  70. ekl_cli-0.10.0.dist-info/METADATA +72 -0
  71. ekl_cli-0.10.0.dist-info/RECORD +75 -0
  72. ekl_cli-0.10.0.dist-info/WHEEL +5 -0
  73. ekl_cli-0.10.0.dist-info/entry_points.txt +2 -0
  74. ekl_cli-0.10.0.dist-info/licenses/LICENSE +10 -0
  75. ekl_cli-0.10.0.dist-info/top_level.txt +1 -0
ekl_cli/finder.py ADDED
@@ -0,0 +1,695 @@
1
+ # Copyright © 2026 EuKreate, Inc. All rights reserved.
2
+ """The example finder: a working example call for every offered service, found the way an assistant uses the same
3
+ server.
4
+
5
+ An assistant succeeds with an MCP server because it reads every tool's description, calls other tools for the values
6
+ a tool needs ("area_ref: From list_supported_areas"), passes the value a description offers ("or 'US'"), reuses what
7
+ earlier answers gave (a search's listing_ref, an address) and follows what errors say. The finder does the same,
8
+ within a budget, from the publisher's machine: the current example if the finder set it, the schema's own values,
9
+ values the field's description quotes, values taken from a tool that the target's description or an error names,
10
+ values from what the server answered for other services, and, when nothing names a source, a placeholder call only to
11
+ read the error. For a service still without an example, it then asks EuKollab, when signed in, for candidate inputs
12
+ from the tool's name, description, schema and the errors it got (never the server's address): the network screens
13
+ each tool first and proposes values only for one it plainly allows. It accepts only an example the target actually
14
+ ran on, whoever proposed it. Planning beyond that is the coding-agent skill's job, under the same rules.
15
+
16
+ The safety rules live in `callable_as`: only read-only tools are called, as the target or as a helper; an external
17
+ action only as the target, only with its dry-run argument declared and set; a tool whose class is not settled never.
18
+ """
19
+
20
+ import json
21
+ import re
22
+ import time
23
+ from collections.abc import Callable
24
+ from collections.abc import Set as AbstractSet
25
+ from dataclasses import dataclass, field
26
+ from typing import Any, Protocol
27
+
28
+ from ekl_cli import schema
29
+ from ekl_cli.derive import schema_candidates
30
+ from ekl_cli.mcp import ToolCall
31
+
32
+ MAX_CALLS = 8
33
+ PLACEHOLDER_SOURCE = "a made-up value, to read the tool's error"
34
+ NETWORK_SOURCE = "a value EuKollab proposed"
35
+ # What the finder sends about one tool's errors: the reasons it showed the publisher, already redacted.
36
+ ERRORS_SENT = 8
37
+ CALL_SECONDS = 15.0
38
+ SERVICE_SECONDS = 90.0
39
+ PLACEHOLDERS: dict[str, Any] = {
40
+ "string": "example",
41
+ "integer": 1,
42
+ "number": 1,
43
+ "boolean": False,
44
+ "array": [],
45
+ "object": {},
46
+ }
47
+
48
+ SECRET_QUERY = re.compile(r"([?&](?:key|token|code|secret|api_key|apikey|access_token)=)[^&\s'\"#]+", re.IGNORECASE)
49
+ BEARER = re.compile(r"(Bearer\s+)[A-Za-z0-9._~+/=-]+", re.IGNORECASE)
50
+ KEY_LIKE = re.compile(r"\b(ekl[a-z]_)[A-Za-z0-9_-]{8,}")
51
+ # A path segment that looks like a secret token, as servers protected by a secret URL use: long, and mixing letter
52
+ # cases or letters and digits. Ordinary path words ("mcp", "ekl", "agent-tools") are left alone.
53
+ PATH_SEGMENT = re.compile(r"/([A-Za-z0-9_-]{16,})(?=[/?#\s'\":,;)\]]|$)")
54
+ QUOTED = re.compile(r"'([^'\n]{1,40})'|\"([^\"\n]{1,40})\"|`([^`\n]{1,40})`")
55
+ SENTENCE = re.compile(r"(?<=[.!?])\s+")
56
+ # Above this maxLength a text field is prose, written for the call, never borrowed from another key of an answer.
57
+ PROSE_CHARS = 200
58
+ # A quoted word that names something in the interface rather than giving a value: snake_case, or one lowercase word.
59
+ IDENTIFIER = re.compile(r"[a-z][a-z0-9_]*")
60
+ # Passed with an address the result gives beside it: "10284 E Underwood Rd" alone matches several homes.
61
+ LOCALITY = ("city", "state", "postal_code", "zip", "zip_code")
62
+
63
+
64
+ def _secret_looking(segment: str) -> bool:
65
+ kinds = sum(bool(re.search(p, segment)) for p in ("[a-z]", "[A-Z]", "[0-9]"))
66
+ return kinds >= 2 and bool(re.search("[A-Z0-9]", segment))
67
+
68
+
69
+ def redact(text: str) -> str:
70
+ """Query secrets, bearer tokens, EuKollab keys and secret-looking path segments removed from anything shown: the
71
+ server's address may carry its own token, and errors quote it."""
72
+ text = PATH_SEGMENT.sub(lambda m: "/…" if _secret_looking(m.group(1)) else m.group(0), text)
73
+ return KEY_LIKE.sub(r"\1…", BEARER.sub(r"\1…", SECRET_QUERY.sub(r"\1redacted", text)))
74
+
75
+
76
+ class Server(Protocol):
77
+ """What the finder needs of a server: one tool call (McpReader, or a fake in tests)."""
78
+
79
+ def call(self, tool: str, arguments: dict[str, Any], timeout: float) -> ToolCall: ...
80
+
81
+
82
+ # The network's example proposals (POST /v1/owner/examples/propose): what it answered, or {"note": why there is none}.
83
+ Proposer = Callable[[list[dict[str, Any]]], dict[str, Any]]
84
+
85
+
86
+ @dataclass
87
+ class Attempt:
88
+ """One call the finder made, to the target or a helper tool, and where its arguments came from (`source`)."""
89
+
90
+ tool: str
91
+ arguments: dict[str, Any]
92
+ ok: bool
93
+ reason: str
94
+ data: Any
95
+ source: str
96
+
97
+
98
+ @dataclass
99
+ class Outcome:
100
+ """What the finder concluded for one service: found (with the example and its helpers), failed, skipped (not
101
+ tried, and why) or yours (the publisher's example, left alone)."""
102
+
103
+ tool: str
104
+ status: str
105
+ reason: str
106
+ example: dict[str, Any] | None = None
107
+ helpers: list[str] = field(default_factory=list)
108
+ tried: list[dict[str, str]] = field(default_factory=list)
109
+ # For a service left without an example: the example call to write, with the tool's own field names.
110
+ fix: dict[str, Any] = field(default_factory=dict)
111
+ # The network's screening would hold this service ({category, reason}): it proposed nothing for it.
112
+ held: dict[str, str] | None = None
113
+ # Why the network proposed nothing, when it was asked.
114
+ note: str = ""
115
+
116
+ def as_dict(self) -> dict[str, Any]:
117
+ return {
118
+ "tool": self.tool,
119
+ "status": self.status,
120
+ "reason": self.reason,
121
+ "example": self.example,
122
+ "helpers": self.helpers,
123
+ "tried": self.tried,
124
+ "fix": self.fix,
125
+ "held": self.held,
126
+ "note": self.note,
127
+ }
128
+
129
+
130
+ def _brief(value: dict[str, Any]) -> str:
131
+ text = json.dumps(value, ensure_ascii=False, separators=(", ", ": "))
132
+ return text if len(text) <= 120 else text[:117] + "…"
133
+
134
+
135
+ def _values_for(data: Any, field_name: str) -> list[Any]:
136
+ """Values of `field_name` anywhere in a tool's result, first found first: a listing tool's area_ref values, a
137
+ search result's address. Without that key, a key ending in it (display_address for address). Only scalars are
138
+ taken; an address keeps the city, state and postal code beside it."""
139
+ return _walk(data, field_name, lambda key: key == field_name) or _walk(
140
+ data, field_name, lambda key: key.endswith("_" + field_name)
141
+ )
142
+
143
+
144
+ def _walk(data: Any, field_name: str, matches: Callable[[str], bool]) -> list[Any]:
145
+ found: list[Any] = []
146
+
147
+ def walk(node: Any) -> None:
148
+ if len(found) >= 5:
149
+ return
150
+ if isinstance(node, dict):
151
+ for key, value in node.items():
152
+ if matches(str(key)) and isinstance(value, str | int | float | bool):
153
+ taken = _with_locality(node, value) if "address" in field_name else value
154
+ if taken not in found:
155
+ found.append(taken)
156
+ for value in node.values():
157
+ walk(value)
158
+ elif isinstance(node, list):
159
+ for item in node[:20]:
160
+ walk(item)
161
+
162
+ walk(data)
163
+ return found
164
+
165
+
166
+ def _with_locality(node: dict[str, Any], address: Any) -> Any:
167
+ if not isinstance(address, str):
168
+ return address
169
+ parts = [str(node[k]) for k in LOCALITY if isinstance(node.get(k), str | int) and str(node[k]) not in address]
170
+ return ", ".join([address, *parts])
171
+
172
+
173
+ def _kind(prop: dict[str, Any]) -> str:
174
+ """A field's JSON type, ignoring null: `string | null` and `anyOf: [string, null]` are strings."""
175
+ kind = prop.get("type")
176
+ if isinstance(kind, list):
177
+ return next((str(k) for k in kind if k != "null"), "string")
178
+ if kind:
179
+ return str(kind)
180
+ options = [o for o in prop.get("anyOf") or prop.get("oneOf") or [] if isinstance(o, dict)]
181
+ return next((_kind(o) for o in options if o.get("type") != "null"), "")
182
+
183
+
184
+ def _field_values(data: Any, field_name: str, prop: dict[str, Any]) -> list[Any]:
185
+ """Values one field can take from a tool's result. A list field takes one item of its singular
186
+ (listing_refs takes [listing_ref])."""
187
+ if _kind(prop) == "array":
188
+ singular = field_name[:-1] if field_name.endswith("s") else field_name
189
+ return [[v] for v in _values_for(data, singular)]
190
+ return _values_for(data, field_name)
191
+
192
+
193
+ def _quoted(text: str) -> list[str]:
194
+ return [next(g for g in m.groups() if g) for m in QUOTED.finditer(text or "")]
195
+
196
+
197
+ def _mentioned(text: str, names: list[str]) -> list[str]:
198
+ return [n for n in names if re.search(rf"\b{re.escape(n)}\b", text or "")]
199
+
200
+
201
+ def _placeholder(tool: dict[str, Any]) -> dict[str, Any]:
202
+ """A first call with a made-up value for each required field, only to learn from the tool's error."""
203
+ input_schema = tool.get("inputSchema") or {}
204
+ props = input_schema.get("properties") or {}
205
+ filled: dict[str, Any] = {}
206
+ for name in input_schema.get("required") or []:
207
+ kind = (props.get(name) or {}).get("type")
208
+ kind = next((k for k in kind if k != "null"), "string") if isinstance(kind, list) else kind or "string"
209
+ filled[name] = PLACEHOLDERS.get(kind, "example")
210
+ return filled
211
+
212
+
213
+ def callable_as(tool: dict[str, Any], cap: dict[str, Any] | None) -> tuple[bool, bool, str]:
214
+ """(may be called as a helper, may be called as the target, why not) for one tool of the server. A tool the
215
+ configuration doesn't describe is judged by its own annotations."""
216
+ if cap is None:
217
+ read_only = (tool.get("annotations") or {}).get("readOnlyHint") is True
218
+ return read_only, False, "" if read_only else "it isn't marked read-only"
219
+ kind = cap.get("class")
220
+ if cap.get("needs_confirmation"):
221
+ return False, False, "its class isn't settled yet: it may change things or reach outside"
222
+ if kind == "read_only":
223
+ return True, True, ""
224
+ if kind == "external_action":
225
+ if (cap.get("effects") or {}).get("dry_run_argument"):
226
+ return False, True, ""
227
+ return False, False, "it acts outside and declares no dry-run argument"
228
+ return False, False, f"it is marked {str(kind).replace('_', ' ')}, and only read-only tools are called"
229
+
230
+
231
+ def origin_of(cap: dict[str, Any]) -> str | None:
232
+ """Who set the service's example: None when it has none. An example without an origin is the publisher's."""
233
+ example = cap.get("example")
234
+ if not isinstance(example, dict):
235
+ return None
236
+ return str(example.get("origin") or "publisher")
237
+
238
+
239
+ class Search:
240
+ """One service's search: its budget, and what was tried."""
241
+
242
+ def __init__(self, target: dict[str, Any], cap: dict[str, Any], clock: Callable[[], float]):
243
+ self.target, self.cap, self.clock = target, cap, clock
244
+ self.started = clock()
245
+ self.attempts: list[Attempt] = []
246
+ # Tools whose earlier answers supplied the values being tried, without being called again.
247
+ self.borrowed: set[str] = set()
248
+
249
+ def remaining(self) -> float:
250
+ return SERVICE_SECONDS - (self.clock() - self.started)
251
+
252
+ @property
253
+ def spent(self) -> bool:
254
+ return len(self.attempts) >= MAX_CALLS or self.remaining() <= 0
255
+
256
+ def helpers_used(self) -> list[str]:
257
+ return sorted({a.tool for a in self.attempts if a.ok and a.tool != self.target["name"]} | self.borrowed)
258
+
259
+ def texts(self) -> list[str]:
260
+ props = (self.target.get("inputSchema") or {}).get("properties") or {}
261
+ texts = [str(self.target.get("description") or ""), *(str(p.get("description") or "") for p in props.values())]
262
+ return texts + [a.reason for a in self.attempts if a.tool == self.target["name"]]
263
+
264
+
265
+ class Finder:
266
+ """Finds example calls for the offered services of one agent.json on one server."""
267
+
268
+ def __init__(
269
+ self,
270
+ server: Server,
271
+ tools: list[dict[str, Any]],
272
+ agent_file: dict[str, Any],
273
+ clock: Callable[[], float] = time.monotonic,
274
+ proposer: Proposer | None = None,
275
+ ):
276
+ self.server, self.clock, self.proposer = server, clock, proposer
277
+ self.tools = {str(t.get("name")): t for t in tools if t.get("name")}
278
+ self.caps = {str(c.get("tool")): c for c in agent_file.get("capabilities") or []}
279
+ self.rights = {name: callable_as(tool, self.caps.get(name)) for name, tool in self.tools.items()}
280
+ # Every answer the server gave so far, for every service's search: an assistant passes a search's listing_ref
281
+ # or address on to the next tool without being told where it comes from.
282
+ self.answers: list[tuple[str, Any]] = []
283
+ self.found: dict[str, dict[str, Any]] = {}
284
+
285
+ def find_all(self) -> list[Outcome]:
286
+ offered = [cap for cap in self.caps.values() if cap.get("offered", True) is not False]
287
+ outcomes = {str(cap.get("tool")): self.find(cap) for cap in offered}
288
+ # A service whose values only a later service's answers supply gets a second try once those are in.
289
+ for cap in offered:
290
+ first = outcomes[str(cap.get("tool"))]
291
+ if first.status == "failed":
292
+ again = self.find(cap, answers_only=True)
293
+ if again.status == "found":
294
+ outcomes[first.tool] = again
295
+ else:
296
+ first.tried += again.tried
297
+ if self.proposer is not None:
298
+ self._proposed(outcomes)
299
+ return list(outcomes.values())
300
+
301
+ def _proposed(self, outcomes: dict[str, Outcome]) -> None:
302
+ """The services still without an example, tried with the inputs EuKollab proposes for them: one request for
303
+ all of them, then each candidate on the server under the same rules and a budget of its own."""
304
+ waiting = [o for o in outcomes.values() if o.status == "failed"]
305
+ if not waiting or self.proposer is None:
306
+ return
307
+ tools = [self._described(o) for o in waiting]
308
+ answer = self.proposer(tools)
309
+ proposals = answer.get("proposals") or {}
310
+ held = answer.get("held") or {}
311
+ note = str(answer.get("note") or "")
312
+ if not note and answer.get("screened") is False:
313
+ note = "EuKollab proposed nothing: its model didn't answer; try again later with ekl sync"
314
+ for outcome in waiting:
315
+ if isinstance(held.get(outcome.tool), dict):
316
+ outcome.held = {k: str(v) for k, v in held[outcome.tool].items() if k in ("category", "reason")}
317
+ continue
318
+ candidates = [c for c in proposals.get(outcome.tool) or [] if isinstance(c, dict)]
319
+ if not candidates:
320
+ outcome.note = note or "EuKollab had no values to propose for it"
321
+ continue
322
+ search = Search(self.tools[outcome.tool], self.caps[outcome.tool], self.clock)
323
+ if any(self._try(search, candidate, NETWORK_SOURCE) for candidate in candidates):
324
+ outcomes[outcome.tool] = self._found(outcome.tool, search)
325
+ else:
326
+ outcome.tried += self._tried(search)
327
+
328
+ def _described(self, outcome: Outcome) -> dict[str, Any]:
329
+ """What the network receives about one tool: its own words and the errors already shown, never the server's
330
+ address or headers."""
331
+ tool = self.tools[outcome.tool]
332
+ errors = [t["reason"] for t in outcome.tried if t["tool"] == outcome.tool and t["reason"] != "answered"]
333
+ return {
334
+ "name": outcome.tool,
335
+ "description": str(tool.get("description") or "")[:4000],
336
+ "input_schema": tool.get("inputSchema") or {},
337
+ "errors": [e[:300] for e in errors[-ERRORS_SENT:]],
338
+ }
339
+
340
+ def _found(self, name: str, search: Search) -> Outcome:
341
+ # As called: an external action's example keeps its dry-run argument set.
342
+ found = next(a.arguments for a in reversed(search.attempts) if a.ok and a.tool == name)
343
+ self.found[name] = found
344
+ via = search.helpers_used()
345
+ source = next(a.source for a in reversed(search.attempts) if a.ok and a.tool == name)
346
+ reason = "found and tried on your server" + (f", using {', '.join(via)}" if via else "")
347
+ if source == NETWORK_SOURCE:
348
+ reason += ", from a value EuKollab proposed"
349
+ return Outcome(name, "found", reason, found, via, self._tried(search))
350
+
351
+ def find(self, cap: dict[str, Any], answers_only: bool = False) -> Outcome:
352
+ name = str(cap.get("tool"))
353
+ if origin_of(cap) == "publisher":
354
+ return Outcome(name, "yours", "you wrote this example; the finder leaves it alone")
355
+ target = self.tools.get(name)
356
+ if target is None:
357
+ return Outcome(name, "skipped", "not tried: your server lists no tool of this name")
358
+ if not self.rights[name][1]:
359
+ return Outcome(name, "skipped", f"not tried: {self.rights[name][2]}")
360
+ search = Search(target, cap, self.clock)
361
+ found = self._from_answers(search) if answers_only else self._search(search)
362
+ tried = self._tried(search)
363
+ if found is not None:
364
+ return self._found(name, search)
365
+ fix = _example_to_write(target)
366
+ if not search.attempts:
367
+ return Outcome(
368
+ name,
369
+ "failed",
370
+ "nothing gave values to try: its input schema has no examples or defaults, and neither its "
371
+ "description nor another tool's answer names any",
372
+ fix=fix,
373
+ )
374
+ count = sum(1 for a in search.attempts if a.tool == name)
375
+ spent = " (the budget ran out)" if search.spent else ""
376
+ reason = (
377
+ f"{name} was never called: nothing gave a value for {', '.join(fix) or 'its fields'}{spent}"
378
+ if not count
379
+ else f"{name} refused every value tried ({count} call{'s' if count != 1 else ''}{spent})"
380
+ )
381
+ return Outcome(
382
+ name,
383
+ "failed",
384
+ reason,
385
+ tried=tried,
386
+ fix=fix,
387
+ )
388
+
389
+ # --- the strategies, cheapest first, stopping at the first example the tool runs on ---------------------------
390
+
391
+ def _search(self, search: Search) -> dict[str, Any] | None:
392
+ current = (search.cap.get("example") or {}).get("input")
393
+ if isinstance(current, dict) and self._try(search, current, "the current example"):
394
+ return dict(current)
395
+ candidates = schema_candidates(search.target.get("inputSchema") or {})
396
+ for candidate in candidates:
397
+ if self._try(search, candidate, "your schema"):
398
+ return candidate
399
+ quoted = self._quoted_candidates(search.target)
400
+ for candidate in quoted:
401
+ if self._try(search, candidate, "a value your description gives"):
402
+ return candidate
403
+ if not candidates and not quoted and not self._references(search) and not self._answered_fields(search):
404
+ # Nothing names where values come from: one made-up call, as an assistant's first try, so the tool's
405
+ # error can say (for example "Call list_supported_areas and pass an area_ref"). Never accepted.
406
+ self._call(search, search.target["name"], _placeholder(search.target), PLACEHOLDER_SOURCE)
407
+ found = self._follow_references(search)
408
+ return found if found is not None else self._from_answers(search)
409
+
410
+ @staticmethod
411
+ def _quoted_candidates(target: dict[str, Any]) -> list[dict[str, Any]]:
412
+ """Values the description quotes for the required string fields the schema leaves open ("A ZIP, city,
413
+ county, two-letter state, or 'US'"): the field's own description, then the target's sentences naming it."""
414
+ input_schema = target.get("inputSchema") or {}
415
+ props = input_schema.get("properties") or {}
416
+ base = (schema_candidates(input_schema) or [{}])[0]
417
+ missing = [n for n in input_schema.get("required") or [] if n not in base]
418
+ values: dict[str, list[str]] = {}
419
+ described = str(target.get("description") or "")
420
+ for name in missing:
421
+ prop = props.get(name) or {}
422
+ if _kind(prop) != "string":
423
+ return []
424
+ naming = [s for s in SENTENCE.split(described) if re.search(rf"\b{name}\b", s)]
425
+ values[name] = [v for text in [str(prop.get("description") or ""), *naming] for v in _quoted(text)]
426
+ if not values[name] and len(missing) == 1:
427
+ # One open text field, and the description gives examples of what goes in it without naming the
428
+ # field ("a region such as 'the East Bay'"): an assistant would try those. Identifiers it quotes
429
+ # (field and tool names) are not values.
430
+ values[name] = [v for v in _quoted(described) if " " in v or not IDENTIFIER.fullmatch(v)]
431
+ if not values[name]:
432
+ return []
433
+ sets: list[dict[str, Any]] = []
434
+ for i in range(3 if values else 0):
435
+ chosen = {**base, **{k: v[min(i, len(v) - 1)] for k, v in values.items()}}
436
+ if chosen not in sets:
437
+ sets.append(chosen)
438
+ return sets
439
+
440
+ def _answered_fields(self, search: Search) -> bool:
441
+ """Whether any earlier answer has a value for one of the target's fields."""
442
+ props = (search.target.get("inputSchema") or {}).get("properties") or {}
443
+ return any(
444
+ _field_values(data, n, p or {})
445
+ for tool, data in self.answers
446
+ if tool != search.target["name"]
447
+ for n, p in props.items()
448
+ )
449
+
450
+ def _from_answers(self, search: Search) -> dict[str, Any] | None:
451
+ """Values from what the server answered for other services: the required fields together, or, with none
452
+ required, each field alone, as for "pass exactly one of address or listing_ref"."""
453
+ input_schema = search.target.get("inputSchema") or {}
454
+ props = input_schema.get("properties") or {}
455
+ base = (schema_candidates(input_schema) or [{}])[0]
456
+ required = [n for n in input_schema.get("required") or [] if n not in base]
457
+ groups = [required] if required else [[n] for n in props if n not in base]
458
+ for fields in groups:
459
+ values: dict[str, list[tuple[Any, str]]] = {}
460
+ for name in fields:
461
+ values[name] = [
462
+ (value, tool)
463
+ for tool, data in self.answers
464
+ if tool != search.target["name"]
465
+ for value in _field_values(data, name, props.get(name) or {})
466
+ ]
467
+ if not fields or not all(values.values()):
468
+ continue
469
+ for i in range(3):
470
+ if search.spent:
471
+ return None
472
+ chosen = {k: v[min(i, len(v) - 1)] for k, v in values.items()}
473
+ candidate = {**base, **{k: value for k, (value, _) in chosen.items()}}
474
+ search.borrowed = {tool for _, tool in chosen.values()}
475
+ if self._try(search, candidate, f"a value from {', '.join(sorted(search.borrowed))}"):
476
+ return candidate
477
+ search.borrowed = set()
478
+ return None
479
+
480
+ def _references(self, search: Search) -> list[str]:
481
+ """Helper tools the target's description, its fields' descriptions or its errors name, in order."""
482
+ helpers = [n for n, (helper, _, _) in self.rights.items() if helper and n != search.target["name"]]
483
+ named: list[str] = []
484
+ for text in search.texts():
485
+ named += [n for n in _mentioned(text, helpers) if n not in named]
486
+ return named
487
+
488
+ def _follow_references(self, search: Search) -> dict[str, Any] | None:
489
+ """Values from another tool that the target's text names, as an assistant would read "From X" or an error
490
+ saying "Call X and use one of the values it returns"."""
491
+ input_schema = search.target.get("inputSchema") or {}
492
+ props = input_schema.get("properties") or {}
493
+ required = list(input_schema.get("required") or [])
494
+ tried: set[str] = set()
495
+ for name in self._references(search):
496
+ if name in tried or search.spent:
497
+ continue
498
+ tried.add(name)
499
+ # A helper that needs values itself is called with the example found for it, as an assistant chains
500
+ # list_supported_areas, then search_active_listings, then the tool it wanted.
501
+ candidates = schema_candidates(self.tools[name].get("inputSchema") or {})
502
+ arguments = candidates[0] if candidates else self.found.get(name)
503
+ if arguments is None:
504
+ continue
505
+ answer = self._call(search, name, arguments, f"looked up with {name}")
506
+ if answer is None or not answer.ok:
507
+ continue
508
+ wanted = required or [p for p, d in props.items() if name in str(d.get("description") or "")]
509
+ base = (schema_candidates(input_schema) or [{}])[0]
510
+ # A long free-text field (a request in someone's own words) is never filled with a value borrowed from
511
+ # another key: it would run, but tell other agents nothing about how to call it.
512
+ prose = {n for n in wanted if int((props.get(n) or {}).get("maxLength") or 0) > PROSE_CHARS}
513
+ for value_set in self._combinations(answer.data, wanted, " ".join(search.texts()), prose):
514
+ if search.spent:
515
+ break
516
+ candidate = {**base, **value_set}
517
+ if self._try(search, candidate, f"a value from {name}"):
518
+ return candidate
519
+ return None
520
+
521
+ @staticmethod
522
+ def _combinations(
523
+ data: Any, wanted: list[str], said: str, prose: AbstractSet[str] = frozenset()
524
+ ) -> list[dict[str, Any]]:
525
+ """Up to three candidate value sets from a helper's result: the first value of each wanted field, then the
526
+ next ones. A field the result doesn't name takes the values of a key the target's text names instead ("pass
527
+ an area_ref as scope")."""
528
+ values = {name: _values_for(data, name) for name in wanted}
529
+ missing = [n for n, v in values.items() if not v]
530
+ if len(missing) == 1 and missing[0] not in prose:
531
+ for key in re.findall(r"[A-Za-z_][A-Za-z0-9_]*", said):
532
+ named = _values_for(data, key) if key not in wanted else []
533
+ # A status word ("matched") names a state, not a value for another field.
534
+ named = [v for v in named if not (isinstance(v, str) and IDENTIFIER.fullmatch(v))]
535
+ if named:
536
+ values[missing[0]] = named
537
+ break
538
+ found = {k: v for k, v in values.items() if v}
539
+ if not found:
540
+ return []
541
+ sets: list[dict[str, Any]] = []
542
+ for i in range(3):
543
+ chosen = {k: v[min(i, len(v) - 1)] for k, v in found.items()}
544
+ if chosen not in sets:
545
+ sets.append(chosen)
546
+ return sets
547
+
548
+ # --- calls -----------------------------------------------------------------------------------------------------
549
+
550
+ def _try(self, search: Search, candidate: dict[str, Any], source: str) -> bool:
551
+ name = search.target["name"]
552
+ if search.spent or any(a.tool == name and a.arguments == candidate for a in search.attempts):
553
+ return False
554
+ answer = self._call(search, name, candidate, source)
555
+ return answer is not None and answer.ok
556
+
557
+ def _call(self, search: Search, tool: str, arguments: dict[str, Any], source: str) -> Attempt | None:
558
+ """One call within the rules and the budget, judged as a validation call would be: it completes, the tool
559
+ doesn't say it failed, and the result fits the output schema where one exists."""
560
+ helper, target, _ = self.rights.get(tool, (False, False, ""))
561
+ as_target = tool == search.target["name"]
562
+ if search.spent or not (helper or (as_target and target)):
563
+ return None
564
+ dry_run = (search.cap.get("effects") or {}).get("dry_run_argument") if as_target else None
565
+ if as_target and search.cap.get("class") == "external_action":
566
+ if not dry_run:
567
+ return None
568
+ arguments = {**arguments, str(dry_run): True}
569
+ answer = self.server.call(tool, arguments, min(CALL_SECONDS, max(search.remaining(), 0.1)))
570
+ reason = ""
571
+ if answer.error:
572
+ reason = answer.error
573
+ elif answer.is_error:
574
+ reason = f"the tool answered with an error: {answer.text[:300] or 'no reason given'}"
575
+ else:
576
+ output_schema = (search.cap.get("output_schema") if as_target else None) or self.tools[tool].get(
577
+ "outputSchema"
578
+ )
579
+ if output_schema:
580
+ if answer.data is None:
581
+ reason = "the tool answered without the structured result its output schema declares"
582
+ elif problems := schema.errors(answer.data, output_schema):
583
+ reason = f"the result doesn't match the tool's output schema: {problems[0][:160]}"
584
+ data = answer.data
585
+ if data is None and answer.text:
586
+ try:
587
+ data = json.loads(answer.text)
588
+ except json.JSONDecodeError:
589
+ data = None
590
+ attempt = Attempt(tool, arguments, not reason, redact(reason), data, source)
591
+ search.attempts.append(attempt)
592
+ if attempt.ok and data is not None:
593
+ self.answers.append((tool, data))
594
+ return attempt
595
+
596
+ def check(self, cap: dict[str, Any]) -> Outcome:
597
+ """One try of the service's current example, under the same rules: what `ekl check` reports."""
598
+ name = str(cap.get("tool"))
599
+ example = (cap.get("example") or {}).get("input")
600
+ if not isinstance(example, dict):
601
+ return Outcome(name, "skipped", "no example: listed as not sample-tested, and check 9 skips it")
602
+ target = self.tools.get(name)
603
+ if target is None:
604
+ return Outcome(name, "skipped", "not tried: your server lists no tool of this name")
605
+ if not self.rights[name][1]:
606
+ return Outcome(name, "skipped", f"not tried: {self.rights[name][2]}")
607
+ search = Search(target, cap, self.clock)
608
+ answer = self._call(search, name, example, "the example")
609
+ if answer is not None and answer.ok:
610
+ return Outcome(name, "ok", "the example ran on your server", example)
611
+ return Outcome(name, "failed", answer.reason if answer else "not tried", example, tried=self._tried(search))
612
+
613
+ def _tried(self, search: Search) -> list[dict[str, str]]:
614
+ return [
615
+ {"tool": a.tool, "input": redact(_brief(a.arguments)), "source": a.source, "reason": _tried_reason(a)}
616
+ for a in search.attempts
617
+ ]
618
+
619
+
620
+ def _tried_reason(attempt: Attempt) -> str:
621
+ """What came of one call, in words that say whether it counts."""
622
+ if attempt.reason:
623
+ return attempt.reason
624
+ if attempt.source == PLACEHOLDER_SOURCE:
625
+ return "it answered, but a made-up value is never kept as an example"
626
+ return "answered"
627
+
628
+
629
+ def apply(agent_file: dict[str, Any], outcomes: list[Outcome]) -> int:
630
+ """Write found examples into agent.json, only where the finder may: a service with no example, or one set from
631
+ the schema or by the finder. Returns how many were written."""
632
+ found = {o.tool: o for o in outcomes if o.status == "found" and o.example is not None}
633
+ written = 0
634
+ for cap in agent_file.get("capabilities") or []:
635
+ outcome = found.get(str(cap.get("tool")))
636
+ if outcome is None or origin_of(cap) == "publisher" or outcome.example is None:
637
+ continue
638
+ before = cap.get("example") or {}
639
+ kept = {k: v for k, v in before.items() if k not in {"input", "origin", "helpers"}}
640
+ # Trying the current example again uses no helper; the helpers that first supplied its values still did.
641
+ same = before.get("input") == outcome.example and before.get("origin") == "found"
642
+ helpers = outcome.helpers or (list(before.get("helpers") or []) if same else [])
643
+ cap["example"] = {"input": outcome.example, "origin": "found", "helpers": helpers, **kept}
644
+ written += 1
645
+ return written
646
+
647
+
648
+ def _example_to_write(target: dict[str, Any]) -> dict[str, Any]:
649
+ """The example input to write for a tool, with its own field names: the required ones, or with none required,
650
+ the first field (as for "pass exactly one of")."""
651
+ props = (target.get("inputSchema") or {}).get("properties") or {}
652
+ required = list((target.get("inputSchema") or {}).get("required") or [])
653
+ names = required or list(props)[:1]
654
+ # Strings show "…" for the publisher to replace; other kinds a value of the right type.
655
+ return {
656
+ n: "…" if _kind(props.get(n) or {}) == "string" else PLACEHOLDERS.get(_kind(props.get(n) or {})) for n in names
657
+ }
658
+
659
+
660
+ def report(outcomes: list[Outcome]) -> str:
661
+ """Per service, one line: ✓ with the example that ran, or ! with why there is none, what was tried and how to
662
+ write one. A service without an example is still offered, so it is never an error."""
663
+ from ekl_cli import ui # noqa: PLC0415 - ui reads the client, which the finder's callers already import
664
+
665
+ width = max((len(o.tool) for o in outcomes), default=0)
666
+ lines = []
667
+ for o in outcomes:
668
+ if o.status == "failed":
669
+ lines.append(f" {ui.paint(ui.WARN, ui.YELLOW)} {o.tool.ljust(width)} no example: {o.reason}")
670
+ elif o.status == "skipped":
671
+ # Not tried is neither a pass nor a problem.
672
+ lines.append(f" {ui.dim(ui.DOT)} {o.tool.ljust(width)} {ui.dim(o.reason)}")
673
+ else:
674
+ shown = _brief(o.example) if o.example is not None else o.reason
675
+ lines.append(f" {ui.paint(ui.OK, ui.GREEN)} {o.tool.ljust(width)} {ui.dim(shown)}")
676
+ indent = " " * (width + 6)
677
+ if o.status not in {"found", "yours"}:
678
+ lines += [f"{indent}tried {t['tool']} {t['input']}: {t['reason']}" for t in o.tried]
679
+ if o.held:
680
+ lines += [
681
+ f"{indent}EuKollab's screening would hold it ({o.held.get('category', 'other')}): "
682
+ f"{o.held.get('reason', '')}",
683
+ f"{indent}A person at EuKollab reviews it once the agent announces itself; it isn't listed before.",
684
+ ]
685
+ elif o.note:
686
+ lines.append(f"{indent}{o.note}")
687
+ if o.status == "failed":
688
+ snippet = json.dumps({"tools": {o.tool: {"example": {"input": o.fix}}}}, ensure_ascii=False)
689
+ lines += [
690
+ f"{indent}Fix: in eukollab.json, with values your server accepts, then ekl sync:",
691
+ f"{indent} {snippet}",
692
+ ]
693
+ if any(o.status == "failed" for o in outcomes):
694
+ lines.append(ui.dim(" A service without a working example is still offered, only not sample-tested."))
695
+ return "\n".join(lines) or " No offered services."