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.
- ekl_cli/__init__.py +2 -0
- ekl_cli/bridge.py +160 -0
- ekl_cli/client.py +232 -0
- ekl_cli/clients/.agents/plugins/marketplace.json +20 -0
- ekl_cli/clients/.claude-plugin/marketplace.json +16 -0
- ekl_cli/clients/README.md +3 -0
- ekl_cli/clients/claude-code/.claude-plugin/plugin.json +14 -0
- ekl_cli/clients/claude-code/.mcp.json +10 -0
- ekl_cli/clients/claude-code/commands/check.md +11 -0
- ekl_cli/clients/claude-code/commands/deploy.md +49 -0
- ekl_cli/clients/claude-code/commands/status.md +10 -0
- ekl_cli/clients/claude-code/skills/agent-behaviour/SKILL.md +112 -0
- ekl_cli/clients/claude-code/skills/agent-config-in-repo/SKILL.md +92 -0
- ekl_cli/clients/claude-code/skills/connect-mcp-server/SKILL.md +296 -0
- ekl_cli/clients/claude-code/skills/operate-agent/SKILL.md +54 -0
- ekl_cli/clients/claude-code/skills/plan-with-the-network/SKILL.md +60 -0
- ekl_cli/clients/codex/mcp.json +11 -0
- ekl_cli/clients/codex/plugin.json +8 -0
- ekl_cli/clients/codex/skills/agent-behaviour/SKILL.md +112 -0
- ekl_cli/clients/codex/skills/agent-config-in-repo/SKILL.md +92 -0
- ekl_cli/clients/codex/skills/connect-mcp-server/SKILL.md +296 -0
- ekl_cli/clients/codex/skills/operate-agent/SKILL.md +54 -0
- ekl_cli/clients/codex/skills/plan-with-the-network/SKILL.md +60 -0
- ekl_cli/clients/cursor/.cursor-plugin/plugin.json +8 -0
- ekl_cli/clients/cursor/commands/check.md +11 -0
- ekl_cli/clients/cursor/commands/deploy.md +49 -0
- ekl_cli/clients/cursor/commands/status.md +10 -0
- ekl_cli/clients/cursor/mcp.json +10 -0
- ekl_cli/clients/cursor/rules/eukollab.mdc +81 -0
- ekl_cli/clients/cursor/skills/agent-behaviour/SKILL.md +112 -0
- ekl_cli/clients/cursor/skills/agent-config-in-repo/SKILL.md +92 -0
- ekl_cli/clients/cursor/skills/connect-mcp-server/SKILL.md +296 -0
- ekl_cli/clients/cursor/skills/operate-agent/SKILL.md +54 -0
- ekl_cli/clients/cursor/skills/plan-with-the-network/SKILL.md +60 -0
- ekl_cli/clients/gemini/GEMINI.md +76 -0
- ekl_cli/clients/gemini/gemini-extension.json +14 -0
- ekl_cli/clients/generic/AGENTS.md +76 -0
- ekl_cli/clients/generic/mcp.json +10 -0
- ekl_cli/clients/vscode/instructions/eukollab.instructions.md +80 -0
- ekl_cli/clients/vscode/mcp.json +11 -0
- ekl_cli/command_help.py +223 -0
- ekl_cli/declarations.py +492 -0
- ekl_cli/deploy.py +432 -0
- ekl_cli/deploy_command.py +556 -0
- ekl_cli/derive.py +217 -0
- ekl_cli/design.py +339 -0
- ekl_cli/finder.py +695 -0
- ekl_cli/icon.py +102 -0
- ekl_cli/install.py +185 -0
- ekl_cli/lifecycle.py +357 -0
- ekl_cli/main.py +643 -0
- ekl_cli/mcp.py +279 -0
- ekl_cli/messages.py +245 -0
- ekl_cli/onboard.py +1040 -0
- ekl_cli/participation.py +247 -0
- ekl_cli/project.py +211 -0
- ekl_cli/prompt.py +176 -0
- ekl_cli/py.typed +0 -0
- ekl_cli/release_root.json +9 -0
- ekl_cli/release_trust.py +376 -0
- ekl_cli/repair.py +266 -0
- ekl_cli/schema.py +117 -0
- ekl_cli/setup.py +326 -0
- ekl_cli/supervise.py +162 -0
- ekl_cli/templates/python/eukollab-agent.md.tmpl +202 -0
- ekl_cli/templates/python/eukollab_callbacks.py.tmpl +509 -0
- ekl_cli/templates/versions.json +3 -0
- ekl_cli/ui.py +158 -0
- ekl_cli/versions.py +402 -0
- ekl_cli-0.10.0.dist-info/METADATA +72 -0
- ekl_cli-0.10.0.dist-info/RECORD +75 -0
- ekl_cli-0.10.0.dist-info/WHEEL +5 -0
- ekl_cli-0.10.0.dist-info/entry_points.txt +2 -0
- ekl_cli-0.10.0.dist-info/licenses/LICENSE +10 -0
- ekl_cli-0.10.0.dist-info/top_level.txt +1 -0
ekl_cli/derive.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
# Copyright © 2026 EuKreate, Inc. All rights reserved.
|
|
2
|
+
"""agent.json from what an MCP server says about itself and what eukollab.json declares.
|
|
3
|
+
|
|
4
|
+
`ekl add` reads the server on the publisher's machine and writes the whole configuration from MCP's standard fields
|
|
5
|
+
(its information, tools, schemas and annotations), the settings in eukollab.json and the network's defaults. Nothing
|
|
6
|
+
EuKollab-specific is read from the server. The network never reads the server; it checks what the connector
|
|
7
|
+
announces.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
FORMAT = "1.0"
|
|
14
|
+
# Where eukollab.json's declarations travel with the server's information and each tool (declarations.merged): keys
|
|
15
|
+
# of ekl's own, never read from the server.
|
|
16
|
+
DECLARED = "eukollab"
|
|
17
|
+
# Agent-wide declarations: those that describe the profile, and those that are top-level fields of agent.json.
|
|
18
|
+
PROFILE_FIELDS = ("display_name", "purpose", "interests", "languages", "logo", "website")
|
|
19
|
+
TOP_FIELDS = ("mode", "execution_mode", "data_declared", "terms")
|
|
20
|
+
DAILY_FREE_CALLS = 200
|
|
21
|
+
MAX_CAPABILITIES = 50
|
|
22
|
+
HANDLE_WORD = re.compile(r"[^a-z0-9]+")
|
|
23
|
+
# Tool names the network keeps for itself, never the publisher's services.
|
|
24
|
+
RESERVED_PREFIX = "ekl_"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def first_sentences(text: str, limit: int) -> str:
|
|
28
|
+
"""As many whole sentences of a description as fit the limit: tool descriptions written for assistants are often
|
|
29
|
+
long, and a summary cut mid-sentence reads badly."""
|
|
30
|
+
text = " ".join(text.split())
|
|
31
|
+
if len(text) <= limit:
|
|
32
|
+
return text
|
|
33
|
+
sentences = re.split(r"(?<=[.!?])\s+", text)
|
|
34
|
+
kept = ""
|
|
35
|
+
for sentence in sentences:
|
|
36
|
+
if len(kept) + len(sentence) + 1 > limit:
|
|
37
|
+
break
|
|
38
|
+
kept = f"{kept} {sentence}".strip()
|
|
39
|
+
return kept or text[: limit - 1].rsplit(" ", 1)[0] + "…"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _declared_value(prop: dict[str, Any]) -> tuple[bool, Any]:
|
|
43
|
+
"""A value the schema itself offers for one field: an example, a default, the first allowed value or a constant.
|
|
44
|
+
"A list or nothing" fields (anyOf with null) are read through their non-null choice."""
|
|
45
|
+
choices = [prop, *[o for o in prop.get("anyOf") or prop.get("oneOf") or [] if isinstance(o, dict)]]
|
|
46
|
+
for choice in choices:
|
|
47
|
+
for key in ("examples", "default", "enum", "const"):
|
|
48
|
+
value = choice.get(key)
|
|
49
|
+
if value is None or value == []:
|
|
50
|
+
continue
|
|
51
|
+
# examples and enum are lists of values; a default or a constant is the value itself.
|
|
52
|
+
return True, value[0] if key in {"examples", "enum"} and isinstance(value, list) else value
|
|
53
|
+
return False, None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _from_schema(schema: dict[str, Any], *, optional: bool) -> dict[str, Any]:
|
|
57
|
+
props = schema.get("properties") or {}
|
|
58
|
+
names = list(schema.get("required") or [])
|
|
59
|
+
if optional:
|
|
60
|
+
names += [n for n in props if n not in names]
|
|
61
|
+
example: dict[str, Any] = {}
|
|
62
|
+
for name in names:
|
|
63
|
+
found, value = _declared_value(props.get(name) or {})
|
|
64
|
+
if found and value is not None:
|
|
65
|
+
example[name] = value
|
|
66
|
+
return example
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def schema_candidates(schema: dict[str, Any]) -> list[dict[str, Any]]:
|
|
70
|
+
"""Example calls built only from what the input schema declares, fullest first. A candidate that misses a
|
|
71
|
+
required field is not offered: the tool would refuse it."""
|
|
72
|
+
required = set(schema.get("required") or [])
|
|
73
|
+
found = []
|
|
74
|
+
for candidate in (_from_schema(schema, optional=True), _from_schema(schema, optional=False)):
|
|
75
|
+
if required <= set(candidate) and candidate not in found:
|
|
76
|
+
found.append(candidate)
|
|
77
|
+
return found
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def suggest_handle(name: str) -> str:
|
|
81
|
+
"""A handle from the server's name, for the publisher to keep or change: @ and 2 to 31 of [a-z0-9-]. The network
|
|
82
|
+
makes it unique when the key is registered."""
|
|
83
|
+
words = HANDLE_WORD.sub("-", name.lower()).strip("-")[:31].strip("-")
|
|
84
|
+
return "@" + (words if len(words) >= 2 else "my-agent")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def class_of(annotations: dict[str, Any]) -> tuple[str, bool]:
|
|
88
|
+
"""The class a tool's MCP annotations suggest, and whether the publisher must settle it before it is offered.
|
|
89
|
+
Hints are not proof: a tool is a transformation only when the server says explicitly that it neither destroys nor
|
|
90
|
+
reaches outside; a tool that says nothing is unknown and waits for the publisher."""
|
|
91
|
+
if annotations.get("readOnlyHint") is True:
|
|
92
|
+
return "read_only", False
|
|
93
|
+
if annotations.get("destructiveHint") is False and annotations.get("openWorldHint") is False:
|
|
94
|
+
return "transformation", False
|
|
95
|
+
return "transformation", True
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def contradicts(declared_class: str, annotations: dict[str, Any]) -> bool:
|
|
99
|
+
"""A declared side_effect_class the tool's MCP annotations contradict: read only while readOnlyHint is false, or
|
|
100
|
+
read only or transformation while the tool says it destroys or reaches outside."""
|
|
101
|
+
if declared_class == "read_only" and annotations.get("readOnlyHint") is False:
|
|
102
|
+
return True
|
|
103
|
+
acts = annotations.get("destructiveHint") is True or annotations.get("openWorldHint") is True
|
|
104
|
+
return declared_class in ("read_only", "transformation") and acts
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _example_call(schema: dict[str, Any]) -> dict[str, Any] | None:
|
|
108
|
+
"""The schema's own values as the example call, fullest first, when they supply every required field. An empty
|
|
109
|
+
call is kept only for a tool that takes no inputs: for any other it says nothing, and a tool with rules its schema
|
|
110
|
+
can't express (such as "exactly one of") would refuse it at check 9."""
|
|
111
|
+
takes_inputs = bool(schema.get("properties"))
|
|
112
|
+
for candidate in schema_candidates(schema):
|
|
113
|
+
if candidate or not takes_inputs:
|
|
114
|
+
return {"input": candidate, "origin": "schema"}
|
|
115
|
+
return None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def about(text: str, tool_names: list[str]) -> str:
|
|
119
|
+
"""The opening sentences that say what the server is. A server's instructions go on to tell an assistant which tool
|
|
120
|
+
to call when; that is guidance for a client, and may name tools that are not offered, so it stops there."""
|
|
121
|
+
sentences = re.split(r"(?<=[.!?])\s+", " ".join(text.split()))
|
|
122
|
+
named = re.compile(r"\b(" + "|".join(re.escape(n) for n in tool_names) + r")\b") if tool_names else None
|
|
123
|
+
kept = []
|
|
124
|
+
for sentence in sentences:
|
|
125
|
+
if named and named.search(sentence):
|
|
126
|
+
break
|
|
127
|
+
kept.append(sentence)
|
|
128
|
+
return " ".join(kept)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def profile(server: dict[str, Any], tools: list[dict[str, Any]]) -> dict[str, Any]:
|
|
132
|
+
name = str(server.get("title") or server.get("name") or "").strip()
|
|
133
|
+
described = str(server.get("description") or server.get("instructions") or "")
|
|
134
|
+
purpose = first_sentences(about(described, [str(t.get("name")) for t in tools if t.get("name")]), 500)
|
|
135
|
+
if len(purpose) < 10:
|
|
136
|
+
listed = ", ".join(str(t.get("title") or t.get("name")) for t in tools[:5])
|
|
137
|
+
purpose = f"{name or 'This agent'} offers {listed}." if listed else f"{name or 'This agent'} on the network."
|
|
138
|
+
icons = [i for i in server.get("icons") or [] if str(i.get("src", "")).startswith("https://")]
|
|
139
|
+
return {
|
|
140
|
+
"handle": suggest_handle(name or "my agent"),
|
|
141
|
+
"display_name": (name or "My agent")[:80],
|
|
142
|
+
"purpose": purpose[:500],
|
|
143
|
+
"interests": [],
|
|
144
|
+
"languages": ["en"],
|
|
145
|
+
"logo": str(icons[0]["src"]) if icons else None,
|
|
146
|
+
"website": str(server["website_url"]) if str(server.get("website_url") or "").startswith("https://") else None,
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def service_declaration(tool: dict[str, Any]) -> dict[str, Any]:
|
|
151
|
+
"""What eukollab.json declares about a tool's service, if anything."""
|
|
152
|
+
declared = tool.get(DECLARED)
|
|
153
|
+
return dict(declared) if isinstance(declared, dict) else {}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def capability(tool: dict[str, Any]) -> dict[str, Any]:
|
|
157
|
+
"""One service for one tool: its declaration first, then what the tool says, then the defaults of 13.12."""
|
|
158
|
+
name = str(tool.get("name", ""))
|
|
159
|
+
cap_class, settle = class_of(tool.get("annotations") or {})
|
|
160
|
+
description = first_sentences(str(tool.get("description") or ""), 300)
|
|
161
|
+
cap: dict[str, Any] = {
|
|
162
|
+
"tool": name,
|
|
163
|
+
"name": str(tool.get("title") or name.replace("_", " ").capitalize())[:80],
|
|
164
|
+
"summary": description if len(description) >= 10 else f"Calls the {name} tool.",
|
|
165
|
+
"category": "general",
|
|
166
|
+
"limitations": "None stated.",
|
|
167
|
+
"class": cap_class,
|
|
168
|
+
"offered": not settle,
|
|
169
|
+
"needs_confirmation": settle,
|
|
170
|
+
}
|
|
171
|
+
example = _example_call(tool.get("inputSchema") or {})
|
|
172
|
+
if example is not None:
|
|
173
|
+
cap["example"] = example
|
|
174
|
+
declared = service_declaration(tool)
|
|
175
|
+
declared.pop("tool", None)
|
|
176
|
+
# "needs_confirmation": false beside a class is the publisher confirming it against contrary annotations.
|
|
177
|
+
confirmed = declared.pop("needs_confirmation", None) is False
|
|
178
|
+
if "class" in declared:
|
|
179
|
+
# A declared class is the publisher's statement of what the tool does: it settles the service, unless the
|
|
180
|
+
# tool's own annotations contradict it, which waits for the publisher's confirmation (spec 5.6).
|
|
181
|
+
disagree = not confirmed and contradicts(str(declared["class"]), tool.get("annotations") or {})
|
|
182
|
+
cap["needs_confirmation"], cap["offered"] = disagree, not disagree
|
|
183
|
+
if isinstance(declared.get("example"), dict):
|
|
184
|
+
declared["example"] = {"origin": "publisher", **declared["example"]}
|
|
185
|
+
return cap | declared
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def derive(
|
|
189
|
+
server: dict[str, Any], tools: list[dict[str, Any]], *, endpoint: str, upstream: str | None = None
|
|
190
|
+
) -> dict[str, Any]:
|
|
191
|
+
"""The whole configuration from what the server says about itself. `endpoint` is the adapter's public MCP
|
|
192
|
+
endpoint; `upstream`, for the connector, is how it reaches the server (normally ${NAME}, as the address may hold
|
|
193
|
+
the server's own token)."""
|
|
194
|
+
capabilities = [
|
|
195
|
+
capability(t)
|
|
196
|
+
for t in tools[:MAX_CAPABILITIES]
|
|
197
|
+
if t.get("name") and not str(t["name"]).startswith(RESERVED_PREFIX)
|
|
198
|
+
]
|
|
199
|
+
content: dict[str, Any] = {
|
|
200
|
+
"ekl": FORMAT,
|
|
201
|
+
"mode": "service_provider",
|
|
202
|
+
"execution_mode": "storage_free",
|
|
203
|
+
"agent": profile(server, tools),
|
|
204
|
+
"adapter": {"endpoint": endpoint},
|
|
205
|
+
"data_declared": False,
|
|
206
|
+
"defaults": {"plans": [{"type": "free", "daily_limit": DAILY_FREE_CALLS}]},
|
|
207
|
+
"capabilities": capabilities,
|
|
208
|
+
}
|
|
209
|
+
if upstream is not None:
|
|
210
|
+
content["upstream"] = {"mcp_url": upstream}
|
|
211
|
+
declared = server.get(DECLARED)
|
|
212
|
+
if isinstance(declared, dict):
|
|
213
|
+
content["agent"] |= {k: declared[k] for k in PROFILE_FIELDS if k in declared}
|
|
214
|
+
content |= {k: declared[k] for k in TOP_FIELDS if k in declared}
|
|
215
|
+
if isinstance(declared.get("defaults"), dict):
|
|
216
|
+
content["defaults"] = content["defaults"] | declared["defaults"]
|
|
217
|
+
return content
|
ekl_cli/design.py
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
# Copyright © 2026 EuKreate, Inc. All rights reserved.
|
|
2
|
+
"""Designing with other agents: `ekl find`, `ekl show` and `ekl try`, and the plan: the services the agent plans to
|
|
3
|
+
use, declared in eukollab.json as `uses`, which `ekl sync` and the deploy's sync step write into agent.json with, for a
|
|
4
|
+
preferred service, the version and schema digests the network gives for it, and `ekl check` watches.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import json
|
|
9
|
+
import urllib.parse
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from ekl_cli import declarations
|
|
14
|
+
from ekl_cli.client import CliError, OwnerApi
|
|
15
|
+
|
|
16
|
+
# What agent.json records of a preferred service, which the network watches the plan against.
|
|
17
|
+
WATCHED = ("version", "input_schema_sha256", "output_schema_sha256")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _service(ref: str) -> tuple[str, str]:
|
|
21
|
+
handle, _, name = ref.partition("/")
|
|
22
|
+
if not handle.startswith("@") or not name:
|
|
23
|
+
raise CliError("EKL-601", ref=ref)
|
|
24
|
+
return handle, name
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# --- the plan: `uses` in eukollab.json ---------------------------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def apply_plan(content: dict[str, Any], root: Path, api: OwnerApi | None = None) -> None:
|
|
31
|
+
"""Set `uses` in agent.json from eukollab.json, or drop it when the file declares none, so a removed need goes
|
|
32
|
+
too. A preferred service gets its version and schema digests from the network when ekl is signed in; otherwise,
|
|
33
|
+
or when the network can't say, it keeps what agent.json recorded for the same service, so a sync offline writes
|
|
34
|
+
the same file."""
|
|
35
|
+
planned = declarations.uses(root)
|
|
36
|
+
if not planned:
|
|
37
|
+
content.pop("uses", None)
|
|
38
|
+
return
|
|
39
|
+
before = {str(u.get("prefer")): u for u in content.get("uses") or [] if isinstance(u, dict) and u.get("prefer")}
|
|
40
|
+
for use in planned:
|
|
41
|
+
prefer = use.get("prefer")
|
|
42
|
+
if not prefer:
|
|
43
|
+
continue
|
|
44
|
+
live: dict[str, Any] = {}
|
|
45
|
+
if api is not None:
|
|
46
|
+
try:
|
|
47
|
+
live = _show(api, *_service(str(prefer))).get("service") or {}
|
|
48
|
+
except CliError:
|
|
49
|
+
live = {}
|
|
50
|
+
known = live or before.get(str(prefer)) or {}
|
|
51
|
+
use |= {key: known[key] for key in WATCHED if known.get(key)}
|
|
52
|
+
content["uses"] = planned
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def check_uses(api: OwnerApi, content: dict[str, Any]) -> tuple[list[dict[str, Any]], list[str]]:
|
|
56
|
+
"""Each planned service that prefers one: whether it is still listed and still matches the digests agent.json
|
|
57
|
+
recorded for it."""
|
|
58
|
+
found, lines = [], []
|
|
59
|
+
for use in content.get("uses") or []:
|
|
60
|
+
ref = str(use.get("prefer") or "")
|
|
61
|
+
if not ref:
|
|
62
|
+
continue
|
|
63
|
+
handle, name = _service(ref)
|
|
64
|
+
try:
|
|
65
|
+
live = _show(api, handle, name).get("service") or {}
|
|
66
|
+
except CliError as exc:
|
|
67
|
+
problem = f"no longer listed for you: {exc}"
|
|
68
|
+
else:
|
|
69
|
+
stale = [
|
|
70
|
+
side
|
|
71
|
+
for side in ("input", "output")
|
|
72
|
+
if (recorded := use.get(f"{side}_schema_sha256")) and recorded != live.get(f"{side}_schema_sha256")
|
|
73
|
+
]
|
|
74
|
+
problem = (
|
|
75
|
+
f"its {' and '.join(stale)} schema changed since the plan was written; look again with "
|
|
76
|
+
f"ekl show {handle} {name}, then ekl sync"
|
|
77
|
+
if stale
|
|
78
|
+
else ""
|
|
79
|
+
)
|
|
80
|
+
found.append({"need": use.get("need"), "service": ref, "problem": problem or None})
|
|
81
|
+
if problem:
|
|
82
|
+
lines.append(f" {ref} ({use.get('need')}): {problem}")
|
|
83
|
+
return found, lines
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# --- commands ----------------------------------------------------------------------------------------------------
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _narrowing(args: argparse.Namespace) -> dict[str, Any]:
|
|
90
|
+
chosen = {
|
|
91
|
+
"max_price": args.max_price,
|
|
92
|
+
"no_retention": args.no_retention or None,
|
|
93
|
+
"no_training": args.no_training or None,
|
|
94
|
+
"region": args.region,
|
|
95
|
+
"free": args.free or None,
|
|
96
|
+
}
|
|
97
|
+
return {k: v for k, v in chosen.items() if v is not None}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _price(item: dict[str, Any]) -> str:
|
|
101
|
+
"""The service's price as its first paid plan states it."""
|
|
102
|
+
paid = [p for p in item.get("plans") or [] if p.get("type") != "free"]
|
|
103
|
+
return plan_text(paid[0]) if paid else "free"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def plan_text(plan: dict[str, Any]) -> str:
|
|
107
|
+
"""A plan as people read it: free, a price per call for a pack of one call, else the pack's price and calls."""
|
|
108
|
+
if plan.get("type") == "free":
|
|
109
|
+
return "free" + (f", {plan['daily_limit']} calls a day" if plan.get("daily_limit") else "")
|
|
110
|
+
money = _money(plan.get("price"), plan.get("currency") or "USD")
|
|
111
|
+
calls = plan.get("calls") or 1
|
|
112
|
+
return f"{money}/call" if calls == 1 else f"{money} / {calls} calls"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _money(value: Any, currency: str) -> str:
|
|
116
|
+
text = str(value if value is not None else "0")
|
|
117
|
+
if "." in text:
|
|
118
|
+
whole, cents = text.split(".", 1)
|
|
119
|
+
text = whole if not cents.strip("0") else f"{whole}.{cents.rstrip('0').ljust(2, '0')}"
|
|
120
|
+
return f"${text}" if currency == "USD" else f"{text} {currency}"
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def cmd_find(api: OwnerApi, args: argparse.Namespace) -> Any:
|
|
124
|
+
if args.watching:
|
|
125
|
+
watches = api.request("GET", "/network/watches")["watches"]
|
|
126
|
+
rows = [[w["watch_id"], w["query"], w["expires_at"][:10]] for w in watches]
|
|
127
|
+
return watches, _table(rows, ["WATCH", "QUERY", "ENDS"]) if rows else "no watched searches"
|
|
128
|
+
if args.unwatch:
|
|
129
|
+
api.request("DELETE", f"/network/watches/{urllib.parse.quote(args.unwatch)}")
|
|
130
|
+
return {"removed": args.unwatch}, f"stopped watching {args.unwatch}"
|
|
131
|
+
if not args.query:
|
|
132
|
+
raise CliError("EKL-602")
|
|
133
|
+
if args.watch:
|
|
134
|
+
saved = api.request("POST", "/network/watches", {"q": args.query} | _narrowing(args))
|
|
135
|
+
return saved, (
|
|
136
|
+
f"watching “{saved['query']}” until {saved['expires_at'][:10]}: the people who configure "
|
|
137
|
+
f"agents are emailed when a matching service is listed (remove it with: ekl find --unwatch "
|
|
138
|
+
f"{saved['watch_id']})"
|
|
139
|
+
)
|
|
140
|
+
query = urllib.parse.urlencode({"q": args.query, "limit": args.limit} | _narrowing(args))
|
|
141
|
+
items = api.request("GET", f"/network/services?{query}")["items"]
|
|
142
|
+
if not items:
|
|
143
|
+
return items, f'nothing listed fits yet; to hear when something does: ekl find "{args.query}" --watch'
|
|
144
|
+
rows = [
|
|
145
|
+
[
|
|
146
|
+
i["service"],
|
|
147
|
+
str(i.get("name") or i.get("summary", ""))[:40],
|
|
148
|
+
_price(i),
|
|
149
|
+
"keeps nothing" if i.get("data_retention") == "none" else str(i.get("data_retention") or "?"),
|
|
150
|
+
"sample-tested" if "sample_executed" in (i.get("labels") or {}) else "—",
|
|
151
|
+
f"{(i.get('evidence') or {}).get('useful', 0)}/{(i.get('evidence') or {}).get('outcomes', 0)} useful",
|
|
152
|
+
"yes" if i.get("eligible") else "no: " + str((i.get("excluded_by") or ["?"])[0]).split(":", 1)[0],
|
|
153
|
+
]
|
|
154
|
+
for i in items
|
|
155
|
+
]
|
|
156
|
+
text = _table(rows, ["SERVICE", "WHAT", "PRICE", "DATA", "TESTED", "EVIDENCE", "NEW AGENT'S RULES ALLOW"])
|
|
157
|
+
return items, text + "\n\nLook closer: ekl show <@handle> <service>"
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _show(api: OwnerApi, handle: str, service: str | None) -> dict[str, Any]:
|
|
161
|
+
query = f"?{urllib.parse.urlencode({'service': service})}" if service else ""
|
|
162
|
+
shown: dict[str, Any] = api.request("GET", f"/network/agents/{urllib.parse.quote(handle)}{query}")
|
|
163
|
+
return shown
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def cmd_show(api: OwnerApi, args: argparse.Namespace) -> Any:
|
|
167
|
+
shown = _show(api, args.handle, args.service)
|
|
168
|
+
lines = [f"{shown['handle']} · {shown.get('display_name', '')} · {shown.get('organisation', '')}"]
|
|
169
|
+
if shown.get("purpose"):
|
|
170
|
+
lines.append(str(shown["purpose"]))
|
|
171
|
+
service = shown.get("service")
|
|
172
|
+
if not service:
|
|
173
|
+
lines += ["", "Services:"] + [f" {s['service']}: {s['summary']}" for s in shown.get("services") or []]
|
|
174
|
+
lines.append(f"\nLook at one: ekl show {args.handle} <service>")
|
|
175
|
+
return shown, "\n".join(lines)
|
|
176
|
+
plans = "; ".join(plan_text(p) for p in service.get("plans") or [])
|
|
177
|
+
lines += [
|
|
178
|
+
"",
|
|
179
|
+
f"{service['service']} v{service.get('version', '')}: {service.get('name', '')}",
|
|
180
|
+
str(service.get("summary", "")),
|
|
181
|
+
f"Limitations: {service.get('limitations') or '—'}",
|
|
182
|
+
f"Plans: {plans or 'free'}",
|
|
183
|
+
f"Data: {service.get('data_policy') or '—'}",
|
|
184
|
+
"New agent's rules: "
|
|
185
|
+
+ ("allow it" if service.get("eligible") else "exclude it: " + "; ".join(service.get("excluded_by") or [])),
|
|
186
|
+
f"Trials: {'accepted' if shown.get('accepts_trials') else 'not accepted'}",
|
|
187
|
+
"",
|
|
188
|
+
"Input schema:",
|
|
189
|
+
json.dumps(service.get("input_schema"), indent=2),
|
|
190
|
+
"Output schema:",
|
|
191
|
+
json.dumps(service.get("output_schema"), indent=2),
|
|
192
|
+
]
|
|
193
|
+
for example in service.get("examples") or []:
|
|
194
|
+
lines += [f"Example: {example.get('problem') or ''}", json.dumps(example.get("input"), indent=2)]
|
|
195
|
+
if args.schemas:
|
|
196
|
+
folder = Path(args.schemas)
|
|
197
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
198
|
+
stem = str(service["service"]).removeprefix("@").replace("/", ".")
|
|
199
|
+
for side in ("input", "output"):
|
|
200
|
+
target = folder / f"{stem}.{side}.schema.json"
|
|
201
|
+
target.write_text(json.dumps(service.get(f"{side}_schema"), indent=2, ensure_ascii=False) + "\n")
|
|
202
|
+
lines.append(f"\nwrote {stem}.input.schema.json and {stem}.output.schema.json to {folder}")
|
|
203
|
+
lines.append(f"\nTry it: ekl try {args.handle} {args.service} [--input '<json>'] [--expect '<json or words>']")
|
|
204
|
+
lines.append(f'Plan to use it: add {{"need": "…", "prefer": "{service["service"]}"}} to uses in eukollab.json')
|
|
205
|
+
return shown, "\n".join(lines)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _input(given: str | None) -> dict[str, Any] | None:
|
|
209
|
+
if given is None:
|
|
210
|
+
return None
|
|
211
|
+
text = Path(given).read_text() if not given.lstrip().startswith("{") and Path(given).is_file() else given
|
|
212
|
+
try:
|
|
213
|
+
value = json.loads(text)
|
|
214
|
+
except json.JSONDecodeError as exc:
|
|
215
|
+
raise CliError("EKL-603", str(exc)) from exc
|
|
216
|
+
if not isinstance(value, dict):
|
|
217
|
+
raise CliError("EKL-603")
|
|
218
|
+
return value
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _expect(given: str | None) -> dict[str, Any] | str | None:
|
|
222
|
+
"""An expectation as JSON, a file holding one, or words the network turns into checks. Anything that looks like
|
|
223
|
+
JSON or a file must be one: a typo never goes to the network as words, where it would cost a trial."""
|
|
224
|
+
if given is None:
|
|
225
|
+
return None
|
|
226
|
+
text = given.strip()
|
|
227
|
+
if not text:
|
|
228
|
+
raise CliError("EKL-604", "Give a JSON expectation, a file holding one, or a sentence.")
|
|
229
|
+
if not text.startswith(("{", "[")) and _looks_like_a_file(text):
|
|
230
|
+
if not Path(text).is_file():
|
|
231
|
+
raise CliError("EKL-604", f"It names a file that isn't there: {text}.")
|
|
232
|
+
text = Path(text).read_text().strip()
|
|
233
|
+
if not text.startswith("{"):
|
|
234
|
+
raise CliError("EKL-604", f"{given.strip()} must hold a JSON expectation.")
|
|
235
|
+
if not text.startswith(("{", "[")):
|
|
236
|
+
return text
|
|
237
|
+
try:
|
|
238
|
+
value = json.loads(text)
|
|
239
|
+
except json.JSONDecodeError as exc:
|
|
240
|
+
raise CliError("EKL-604", f"It isn't valid JSON: {exc}.") from exc
|
|
241
|
+
if not isinstance(value, dict):
|
|
242
|
+
raise CliError("EKL-604")
|
|
243
|
+
return value
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _looks_like_a_file(text: str) -> bool:
|
|
247
|
+
"""A single word ending .json, or holding a path separator, or an existing file: never a sentence."""
|
|
248
|
+
if Path(text).is_file():
|
|
249
|
+
return True
|
|
250
|
+
return " " not in text and (text.lower().endswith(".json") or "/" in text or "\\" in text)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _score(value: Any) -> str:
|
|
254
|
+
return "—" if not isinstance(value, (int, float)) else f"{value:.2f}"
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def cmd_try(api: OwnerApi, args: argparse.Namespace) -> Any:
|
|
258
|
+
"""One trial run of a service, never charged, scored against what a right answer looks like. A trial never returns
|
|
259
|
+
the service's answer, only how well it matched. It saves nothing: a service the developer chooses goes in
|
|
260
|
+
eukollab.json as `uses`."""
|
|
261
|
+
tried = api.request(
|
|
262
|
+
"POST",
|
|
263
|
+
"/network/trials",
|
|
264
|
+
{
|
|
265
|
+
"handle": args.handle,
|
|
266
|
+
"service": args.service,
|
|
267
|
+
"input": _input(args.input),
|
|
268
|
+
"expect": _expect(args.expect),
|
|
269
|
+
},
|
|
270
|
+
)
|
|
271
|
+
lines = [
|
|
272
|
+
f"{tried['service']} v{tried.get('version', '')}: {tried['status']} in {tried.get('seconds', 0)} s",
|
|
273
|
+
"Input:",
|
|
274
|
+
json.dumps(tried.get("input"), indent=2),
|
|
275
|
+
]
|
|
276
|
+
if tried.get("status") == "succeeded":
|
|
277
|
+
verdict = "passed" if tried.get("passed") else "did not pass"
|
|
278
|
+
lines.append(
|
|
279
|
+
f"Score: {_score(tried.get('score'))} of 1, {verdict} (threshold {_score(tried.get('threshold'))})"
|
|
280
|
+
)
|
|
281
|
+
rows = [
|
|
282
|
+
[str(c.get("id")), _score(c.get("score")), str(c.get("reason", "")).replace("_", " ")]
|
|
283
|
+
for c in tried.get("checks") or []
|
|
284
|
+
]
|
|
285
|
+
if rows:
|
|
286
|
+
lines.append(_table(rows, ["check", "score", "why"]))
|
|
287
|
+
else:
|
|
288
|
+
lines.append(f"Not scored: {tried.get('error_code') or tried.get('status')}")
|
|
289
|
+
if tried.get("compiled"):
|
|
290
|
+
lines += [
|
|
291
|
+
"Your words, as checks (keep and refine them with --expect):",
|
|
292
|
+
json.dumps(tried["compiled"], indent=2),
|
|
293
|
+
]
|
|
294
|
+
if args.expect is None:
|
|
295
|
+
lines.append("Checked against the service's output schema only: add --expect to score your own case.")
|
|
296
|
+
lines.append(
|
|
297
|
+
"A trial is never charged and never shows the service's answer; a real call would "
|
|
298
|
+
+ ("be charged under its plans." if tried.get("would_be_charged") else "be free.")
|
|
299
|
+
)
|
|
300
|
+
return tried, "\n".join(lines)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _table(rows: list[list[str]], headers: list[str]) -> str:
|
|
304
|
+
widths = [max(len(str(c)) for c in col) for col in zip(headers, *rows, strict=False)]
|
|
305
|
+
|
|
306
|
+
def line(cells: list[str]) -> str:
|
|
307
|
+
return " ".join(str(c).ljust(w) for c, w in zip(cells, widths, strict=False)).rstrip()
|
|
308
|
+
|
|
309
|
+
return "\n".join([line(headers), line(["-" * w for w in widths]), *(line(r) for r in rows)])
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def add_parsers(sub: Any) -> None:
|
|
313
|
+
find = sub.add_parser("find", help="search the services on the network, to plan an agent around them")
|
|
314
|
+
find.add_argument("query", nargs="?", help='what you need, e.g. "validate EU VAT numbers"')
|
|
315
|
+
find.add_argument("--max-price", help="at most this price per call, in USD")
|
|
316
|
+
find.add_argument("--no-retention", action="store_true", help="only services that keep no inputs")
|
|
317
|
+
find.add_argument("--no-training", action="store_true", help="only services that never train on inputs")
|
|
318
|
+
find.add_argument("--region", help="only services that process data in this country (e.g. DE)")
|
|
319
|
+
find.add_argument("--free", action="store_true", help="only free services")
|
|
320
|
+
find.add_argument("--limit", type=int, default=10, help="at most this many results (default 10)")
|
|
321
|
+
find.add_argument("--watch", action="store_true", help="email when a matching service is listed (30 days)")
|
|
322
|
+
find.add_argument("--watching", action="store_true", help="list your watched searches")
|
|
323
|
+
find.add_argument("--unwatch", metavar="WATCH_ID", help="stop watching a search")
|
|
324
|
+
find.set_defaults(fn=cmd_find)
|
|
325
|
+
show = sub.add_parser("show", help="an agent's profile, or a service's contract, examples, plans and data")
|
|
326
|
+
show.add_argument("handle", help="e.g. @vat-check")
|
|
327
|
+
show.add_argument("service", nargs="?", help="e.g. validate")
|
|
328
|
+
show.add_argument("--schemas", metavar="FOLDER", help="write the service's input and output schemas here")
|
|
329
|
+
show.set_defaults(fn=cmd_show)
|
|
330
|
+
trial = sub.add_parser("try", help="a design trial of a service: made-up input, never charged")
|
|
331
|
+
trial.add_argument("handle", help="the agent offering it, e.g. @vat-check")
|
|
332
|
+
trial.add_argument("service", help="the service, e.g. validate")
|
|
333
|
+
trial.add_argument("--input", help="a JSON object, or a file holding one; defaults to the service's example")
|
|
334
|
+
trial.add_argument(
|
|
335
|
+
"--expect",
|
|
336
|
+
help="what a right answer looks like: a JSON expectation ({checks, threshold}), a file holding one, or a "
|
|
337
|
+
"sentence; without it only the service's output schema is checked",
|
|
338
|
+
)
|
|
339
|
+
trial.set_defaults(fn=cmd_try)
|