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/icon.py ADDED
@@ -0,0 +1,102 @@
1
+ # Copyright © 2026 EuKreate, Inc. All rights reserved.
2
+ """The agent's icon from an image file in the agent's folder (spec 5.1, C.14.5).
3
+
4
+ eukollab.json may name a local file as `agent.logo` ("icon.png"). The network shows only images it checked and keeps
5
+ itself, so ekl uploads the file to it and agent.json carries the network's copy: <network>/media/<sha256>.<ext>. The
6
+ address follows from the file's bytes, so sync and check work it out without the network, and an unchanged file is
7
+ never uploaded twice.
8
+ """
9
+
10
+ import base64
11
+ import hashlib
12
+ import urllib.error
13
+ import urllib.parse
14
+ import urllib.request
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from ekl_cli.client import CliError, Credentials, OwnerApi
19
+
20
+ MAX_BYTES = 256 * 1024
21
+ # The image types the network accepts, by their first bytes: SVG and anything else is refused there too.
22
+ SUFFIXES = {".png": "png", ".jpg": "jpg", ".jpeg": "jpg", ".webp": "webp"}
23
+
24
+
25
+ def is_local(logo: str | None) -> bool:
26
+ """Whether agent.logo names a file rather than an address."""
27
+ return bool(logo) and "://" not in str(logo)
28
+
29
+
30
+ def _kind(data: bytes) -> str:
31
+ if data.startswith(b"\x89PNG\r\n\x1a\n"):
32
+ return "png"
33
+ if data.startswith(b"\xff\xd8"):
34
+ return "jpg"
35
+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
36
+ return "webp"
37
+ raise CliError("EKL-215", "It must be a PNG, JPEG or WebP image (SVG isn't accepted).")
38
+
39
+
40
+ def read(path: Path) -> tuple[bytes, str]:
41
+ """The image's bytes and extension, checked as far as can be here; the network checks its size in pixels."""
42
+ if not path.is_file():
43
+ raise CliError("EKL-215", f"{path} not found.")
44
+ data = path.read_bytes()
45
+ if len(data) > MAX_BYTES:
46
+ raise CliError("EKL-215", f"{path} is larger than 256 KB.")
47
+ return data, _kind(data)
48
+
49
+
50
+ def address(network: str, data: bytes, kind: str) -> str:
51
+ """Where the network serves its copy of these bytes."""
52
+ return f"{network.rstrip('/')}/media/{hashlib.sha256(data).hexdigest()}.{kind}"
53
+
54
+
55
+ def adopt(source: str) -> tuple[str, Path | None]:
56
+ """The name to declare as agent.logo for what the publisher gave: an address as given, or for a file, icon.<ext>
57
+ and the file to copy into the agent's folder, so the repository keeps it with eukollab.json."""
58
+ if not is_local(source):
59
+ if not source.startswith("https://"):
60
+ raise CliError("EKL-215", "Give an image file or an https:// address.")
61
+ return source, None
62
+ path = Path(source).expanduser()
63
+ _, kind = read(path)
64
+ return f"icon.{kind}", path
65
+
66
+
67
+ def localize(content: dict[str, Any], folder: Path, network: str) -> Path | None:
68
+ """agent.json with a local agent.logo replaced by the network's address for it; the file, to upload."""
69
+ logo = (content.get("agent") or {}).get("logo")
70
+ if not is_local(logo):
71
+ return None
72
+ path = folder / str(logo)
73
+ data, kind = read(path)
74
+ content["agent"]["logo"] = address(network, data, kind)
75
+ return path
76
+
77
+
78
+ def _present(url: str) -> bool:
79
+ if urllib.parse.urlsplit(url).scheme not in ("http", "https"):
80
+ return False # only a web address is asked, never a file: or another scheme
81
+ try:
82
+ request = urllib.request.Request(url, method="HEAD")
83
+ with urllib.request.urlopen(request, timeout=10) as response: # nosec B310 - http(s) only, checked above
84
+ return bool(response.status == 200)
85
+ except (urllib.error.URLError, OSError):
86
+ return False
87
+
88
+
89
+ def upload(path: Path | None, network: str, api: OwnerApi | None) -> str:
90
+ """Upload the icon unless the network already has it. A note for the output, or "" when there was nothing to do.
91
+ Without an api it uses the stored sign-in; signed out, it says how to upload later."""
92
+ if path is None:
93
+ return ""
94
+ data, kind = read(path)
95
+ if _present(address(network, data, kind)):
96
+ return ""
97
+ try:
98
+ api = api or OwnerApi(Credentials.load())
99
+ api.request("POST", "/agent-images", {"image": base64.b64encode(data).decode()})
100
+ except CliError as failed:
101
+ return f"icon {path.name} not uploaded ({failed}); run ekl sync once signed in"
102
+ return f"uploaded icon {path.name}; the network checks it with the agent and shows it once the checks pass"
ekl_cli/install.py ADDED
@@ -0,0 +1,185 @@
1
+ # Copyright © 2026 EuKreate, Inc. All rights reserved.
2
+ """Installs made by the installer script: each ekl version in its own folder, and a link to the one in use.
3
+
4
+ ~/.local/share/ekl/ EKL_HOME, or $XDG_DATA_HOME/ekl
5
+ versions/0.4.21/ a Python environment holding ekl 0.4.21
6
+ versions/0.4.22/
7
+ current -> versions/0.4.22
8
+ ~/.local/bin/ekl EKL_BIN_DIR; a link to current/bin/ekl
9
+
10
+ A new version is installed beside the others and only then made current, by replacing the link in one step, so a
11
+ failed upgrade leaves the working version in use. The previous version stays, so going back needs no download.
12
+ Standard library only, and nothing at import time beyond it: the installer script runs this module straight from the
13
+ downloaded wheel, before ekl is installed.
14
+ """
15
+
16
+ import os
17
+ import shutil
18
+ import subprocess
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ from ekl_cli import ui
23
+ from ekl_cli.bridge import DEFAULT_PLATFORM
24
+ from ekl_cli.messages import CliError
25
+
26
+ # The version in use and the one before it; older versions are removed after an upgrade.
27
+ KEEP = 2
28
+ # Written last into a version's folder: a folder without it is an install that didn't finish.
29
+ COMPLETE = ".ekl-complete"
30
+
31
+
32
+ class InstallError(CliError):
33
+ """A step of installing ekl that failed: nothing is switched to the new version."""
34
+
35
+
36
+ def home() -> Path:
37
+ if os.environ.get("EKL_HOME"):
38
+ return Path(os.environ["EKL_HOME"])
39
+ data = os.environ.get("XDG_DATA_HOME") or str(Path.home() / ".local" / "share")
40
+ return Path(data) / "ekl"
41
+
42
+
43
+ def bin_dir() -> Path:
44
+ return Path(os.environ.get("EKL_BIN_DIR") or Path.home() / ".local" / "bin")
45
+
46
+
47
+ def versions_dir() -> Path:
48
+ return home() / "versions"
49
+
50
+
51
+ def managed_version(prefix: Path) -> str | None:
52
+ """The version a Python environment holds, when it is one of these folders; None for any other install."""
53
+ try:
54
+ if prefix.resolve().parent == versions_dir().resolve() and (prefix / COMPLETE).is_file():
55
+ return prefix.name
56
+ except OSError:
57
+ return None
58
+ return None
59
+
60
+
61
+ def stable_path(path: Path, prefix: Path) -> Path:
62
+ """`path` inside this version's folder, named through `current` instead, so a coding agent that was given it
63
+ keeps finding it after an upgrade replaces the version."""
64
+ if managed_version(prefix) is None:
65
+ return path
66
+ try:
67
+ return home() / "current" / path.relative_to(prefix)
68
+ except ValueError:
69
+ return path
70
+
71
+
72
+ def current() -> str | None:
73
+ link = home() / "current"
74
+ return link.resolve().name if link.is_symlink() and link.resolve().is_dir() else None
75
+
76
+
77
+ def installed() -> list[str]:
78
+ """Every complete version here, in the order they were installed."""
79
+ if not versions_dir().is_dir():
80
+ return []
81
+ found = [d for d in versions_dir().iterdir() if (d / COMPLETE).is_file()]
82
+ return [d.name for d in sorted(found, key=lambda d: (d / COMPLETE).stat().st_mtime)]
83
+
84
+
85
+ def executable(version: str) -> Path:
86
+ return versions_dir() / version / "bin" / "ekl"
87
+
88
+
89
+ def install_wheel(wheel: Path, version: str, python: str) -> Path:
90
+ """A Python environment holding `wheel`, in the version's own folder. An environment can't be moved once made, so
91
+ it is built where it stays; a failure removes the folder and leaves every other version as it was."""
92
+ target = versions_dir() / version
93
+ if (target / COMPLETE).is_file():
94
+ return target
95
+ if target.exists():
96
+ shutil.rmtree(target) # an install of this version that didn't finish
97
+ versions_dir().mkdir(parents=True, exist_ok=True)
98
+ try:
99
+ _run([python, "-m", "venv", str(target)], f"creating {target}")
100
+ pip = [str(target / "bin" / "python"), "-m", "pip", "install", "--quiet", "--disable-pip-version-check"]
101
+ # ekl has no dependencies, so nothing but this file is installed and no index is asked.
102
+ _run([*pip, "--no-index", "--no-deps", str(wheel)], f"installing ekl {version}")
103
+ (target / COMPLETE).write_text(version + "\n")
104
+ except BaseException:
105
+ shutil.rmtree(target, ignore_errors=True)
106
+ raise
107
+ return target
108
+
109
+
110
+ def check_command() -> bool:
111
+ """Whether ekl's link is already in place; refuses when the command's place holds another install's ekl, such as
112
+ uv's or pipx's own link, which is never taken over."""
113
+ command = bin_dir() / "ekl"
114
+ if command.is_symlink() and command.readlink() == home() / "current" / "bin" / "ekl":
115
+ return True
116
+ if command.exists() or command.is_symlink():
117
+ found = f" (it leads to {command.resolve()})" if command.is_symlink() else ""
118
+ raise InstallError("EKL-125", found.strip(" ()").capitalize(), command=command)
119
+ return False
120
+
121
+
122
+ def activate(version: str) -> str | None:
123
+ """Make `version` the one in use; the version it replaces, if any. The link is replaced in one step, so `ekl`
124
+ always starts one complete version or the other."""
125
+ linked = check_command()
126
+ previous = current()
127
+ temporary = home() / f".current-{os.getpid()}"
128
+ temporary.unlink(missing_ok=True)
129
+ temporary.symlink_to(Path("versions") / version)
130
+ temporary.replace(home() / "current")
131
+ if not linked:
132
+ bin_dir().mkdir(parents=True, exist_ok=True)
133
+ (bin_dir() / "ekl").symlink_to(home() / "current" / "bin" / "ekl")
134
+ return previous
135
+
136
+
137
+ def prune(keep: list[str]) -> list[str]:
138
+ """Remove the complete versions not in `keep`; the ones removed."""
139
+ removed = []
140
+ for version in installed():
141
+ if version not in keep:
142
+ shutil.rmtree(versions_dir() / version, ignore_errors=True)
143
+ removed.append(version)
144
+ return removed
145
+
146
+
147
+ def keep_after(new: str, previous: str | None) -> list[str]:
148
+ """The versions to keep once `new` is in use: it, the one it replaced, and up to KEEP in all."""
149
+ keep = [new] + ([previous] if previous and previous != new else [])
150
+ return keep[:KEEP]
151
+
152
+
153
+ def _run(argv: list[str], doing: str) -> None:
154
+ done = subprocess.run(argv, capture_output=True, text=True, check=False)
155
+ if done.returncode:
156
+ said = (done.stdout + done.stderr).strip()
157
+ raise InstallError("EKL-124", f"{doing} failed: {said or done.returncode}")
158
+
159
+
160
+ def on_path() -> bool:
161
+ folders = [Path(p).resolve() for p in os.environ.get("PATH", "").split(os.pathsep) if p]
162
+ return bin_dir().resolve() in folders
163
+
164
+
165
+ def bootstrap(wheel: str, version: str, network: str) -> int:
166
+ """The installer script's last step: install the downloaded wheel, make it current and say what to do next."""
167
+ try:
168
+ check_command()
169
+ target = install_wheel(Path(wheel), version, sys.executable)
170
+ previous = activate(version)
171
+ except InstallError as exc:
172
+ print(ui.problem(exc), file=sys.stderr)
173
+ return 1
174
+ prune(keep_after(version, previous))
175
+ shown = str(target).replace(str(Path.home()), "~", 1)
176
+ lines = [f"installed ekl {version} in {shown}" + (f" (it replaces {previous})" if previous else "")]
177
+ first = shutil.which("ekl")
178
+ if not on_path():
179
+ rc = "~/.zshrc" if os.environ.get("SHELL", "").endswith("zsh") else "~/.bashrc or ~/.profile"
180
+ lines.append(f'add {bin_dir()} to your PATH, for example in {rc}: export PATH="{bin_dir()}:$PATH"')
181
+ elif first and Path(first).resolve() != executable(version).resolve():
182
+ lines.append(f"another ekl comes first on your PATH: {first}; remove it, or put {bin_dir()} before it")
183
+ lines.append("next: ekl login" + (f" --platform {network}" if network != DEFAULT_PLATFORM else ""))
184
+ print("\n".join(lines))
185
+ return 0
ekl_cli/lifecycle.py ADDED
@@ -0,0 +1,357 @@
1
+ # Copyright © 2026 EuKreate, Inc. All rights reserved.
2
+ """`ekl status`, and the review a deploy ends with: an agent's state on the network and what it waits for.
3
+
4
+ An agent's life on the network is five commands: `ekl add` writes its folder from a working MCP server, `ekl check`
5
+ and `ekl sync` keep agent.json true to the server, `ekl deploy` runs both and then makes it available (on EuKollab or
6
+ on this machine) and shows what it announced for the publisher to confirm, and `ekl status` reports where it stands.
7
+ Everything an agent's state needs beyond that, confirming a version, running its checks again, publishing it and its
8
+ settings on the network, is an option of `ekl status`, so there is one place to look and to act.
9
+ """
10
+
11
+ import argparse
12
+ import datetime as dt
13
+ import json
14
+ import time
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from ekl_cli import design, onboard, participation, prompt, supervise, ui
19
+ from ekl_cli.client import CliError, OwnerApi
20
+ from ekl_cli.finder import origin_of
21
+
22
+ LOCAL, MANAGED = "local", "managed"
23
+ # Where `ekl deploy` put the agent, kept in its folder so later deploys keep it there.
24
+ SAVED = ".ekl/deployment.json"
25
+ # How long a deploy waits for an agent run on this machine to announce itself before showing its review.
26
+ ANNOUNCE_WAIT_SECONDS = 20
27
+ WATCH_SECONDS = 2
28
+
29
+
30
+ def handle_in(folder: Path) -> str:
31
+ """The handle agent.json in an agent's folder names: what `ekl status` reads when no agent is given."""
32
+ file = folder / "agent.json"
33
+ try:
34
+ handle = str((json.loads(file.read_text()).get("agent") or {}).get("handle") or "")
35
+ except (OSError, ValueError) as exc:
36
+ raise CliError("EKL-204", f"{file} can't be read ({exc.__class__.__name__}).") from exc
37
+ if not handle:
38
+ raise CliError("EKL-203", path=file)
39
+ return handle
40
+
41
+
42
+ # --- the review ----------------------------------------------------------------------------------------------------
43
+
44
+
45
+ def _terms_shown(terms: dict[str, Any]) -> str:
46
+ """The terms as the review names them: a deployed connector announces them inline, as text."""
47
+ if terms.get("url") or terms.get("text_file"):
48
+ return str(terms.get("url") or terms.get("text_file"))
49
+ if terms.get("text"):
50
+ return "included" + (f", version {terms['version']}" if terms.get("version") else "")
51
+ return "none"
52
+
53
+
54
+ def _service_line(cap: dict[str, Any], defaults: list[dict[str, Any]]) -> str:
55
+ example = cap.get("example")
56
+ origin = origin_of(cap) if isinstance(example, dict) else None
57
+ tested = {
58
+ None: "not sample-tested",
59
+ "found": "example tested on your server",
60
+ "schema": "example from your schema",
61
+ }.get(origin, "your example")
62
+ # Its own plans, else the agent's: the price the person is confirming, as buyers will read it.
63
+ plans = "; ".join(design.plan_text(p) for p in cap.get("plans") or defaults) or "default plans"
64
+ return (
65
+ f" {cap.get('tool')}: {cap.get('name')} · {str(cap.get('class', '')).replace('_', ' ')} · {plans} · {tested}"
66
+ )
67
+
68
+
69
+ def review_lines(review: dict[str, Any]) -> list[str]:
70
+ """What the console's review page shows of an announced version, read-only."""
71
+ config = review.get("config") or {}
72
+ agent = config.get("agent") or {}
73
+ waiting = review.get("version")
74
+ uses_only = bool(config) and not config.get("capabilities")
75
+ lines = [
76
+ "endpoint none: it only uses other agents' services, and only connects out"
77
+ if uses_only
78
+ else f"endpoint {review.get('endpoint') or '—'}"
79
+ + (
80
+ f" → {review['announced_endpoint']} (announced: calls go there once you confirm)"
81
+ if review.get("announced_endpoint") and review.get("announced_endpoint") != review.get("endpoint")
82
+ else ""
83
+ ),
84
+ f"waiting for review: {f'version {waiting}' if waiting is not None else 'nothing'} · "
85
+ f"confirmed: {review.get('current_version') or 'none yet'}",
86
+ ]
87
+ if agent:
88
+ lines.append(f"{agent.get('display_name')}: {agent.get('purpose')}")
89
+ offered = [c for c in config.get("capabilities") or [] if c.get("offered", True) is not False]
90
+ if offered:
91
+ defaults = (config.get("defaults") or {}).get("plans") or []
92
+ lines += ["", "Services:", *(_service_line(c, defaults) for c in offered)]
93
+ if uses_only:
94
+ lines += ["", "Services: none; it offers nothing"]
95
+ elif config:
96
+ terms = config.get("terms") or {}
97
+ declared = "yes" if config.get("data_declared") else "no: services say the provider has not declared it"
98
+ lines += ["", f"data declared: {declared} · terms: {_terms_shown(terms)}"]
99
+ preflight = review.get("preflight") or {}
100
+ results = preflight.get("results") if isinstance(preflight, dict) else None
101
+ if isinstance(results, list) and results:
102
+ lines += ["", "Its adapter, checked as the review opened:"]
103
+ lines += [f" {'✓' if r.get('ok') else '✗'} {r.get('text', '')}" for r in results]
104
+ lines += ["", onboard.problems_text(review.get("problems") or [], onboard.tools_of(config))]
105
+ return lines
106
+
107
+
108
+ def confirm_version(api: OwnerApi, agent_id: str, handle: str, version: int | None) -> dict[str, Any]:
109
+ """Confirm an announced version: the publisher's declaration that its services and data statement are accurate.
110
+ Its checks start."""
111
+ if version is None:
112
+ version = api.request("GET", f"/agents/{agent_id}/review").get("version")
113
+ if version is None:
114
+ raise CliError("EKL-503", handle=handle)
115
+ confirmed: dict[str, Any] = api.request("POST", f"/agents/{agent_id}/confirm", {"version": version})
116
+ return confirmed
117
+
118
+
119
+ def offer_review(
120
+ api: OwnerApi | None, handle: str, *, confirm: bool, wait: float = 0, before: list[str] | None = None
121
+ ) -> list[str]:
122
+ """After a deploy, `before` (what the deploy did), then what the agent announced and the publisher's confirmation
123
+ of it. Asked at a terminal, done by --confirm, and otherwise left with the command that does it. An agent run here
124
+ announces itself as it starts, so its version may take a moment to appear. The lines to print come back, in order;
125
+ when it asks, it prints what comes before the question itself."""
126
+ before = before or []
127
+ if api is None:
128
+ return [*before, f"Next: ekl login, then read what it announced and confirm it: ekl status {handle} --confirm"]
129
+ agent_id = api.agent_id(handle)
130
+ deadline = time.monotonic() + wait
131
+ review = api.request("GET", f"/agents/{agent_id}/review")
132
+ while review.get("version") is None and time.monotonic() < deadline:
133
+ time.sleep(1)
134
+ review = api.request("GET", f"/agents/{agent_id}/review")
135
+ if review.get("version") is None:
136
+ return [
137
+ *before,
138
+ f"Nothing waits for your review ({str(review.get('state')).lower()}). Follow it: ekl status {handle}",
139
+ ]
140
+ shown = [*before, prompt.heading(f"{handle} announced version {review['version']}"), *review_lines(review)]
141
+ if not confirm and not prompt.interactive():
142
+ return [*shown, f"Next: read it, then confirm it: ekl status {handle} --confirm"]
143
+ if not confirm:
144
+ print("\n".join(shown), flush=True)
145
+ accurate = prompt.confirm(
146
+ "Is this accurate? Confirm it",
147
+ False,
148
+ "Confirming declares that its services, data handling and terms are as described; its checks start.",
149
+ f"No leaves it waiting: ekl status {handle} --confirm confirms it later.",
150
+ )
151
+ shown = []
152
+ if not accurate:
153
+ return [f"Left waiting for your review. Confirm it later: ekl status {handle} --confirm"]
154
+ confirmed = confirm_version(api, agent_id, handle, int(review["version"]))
155
+ return [
156
+ *shown,
157
+ ui.ok(f"Confirmed version {confirmed['version']}; its checks start."),
158
+ f"Next: ekl status {handle} --watch",
159
+ ]
160
+
161
+
162
+ # --- where it runs ---
163
+
164
+
165
+ def saved(folder: Path) -> dict[str, Any] | None:
166
+ try:
167
+ found: dict[str, Any] = json.loads((folder / SAVED).read_text())
168
+ except (OSError, ValueError):
169
+ return None
170
+ return found
171
+
172
+
173
+ def local_lines(folder: Path) -> list[str]:
174
+ """An agent run on this machine, for `ekl status`: whether its process runs, and its last lines."""
175
+ state = supervise.read_state(folder)
176
+ if state is None:
177
+ return [_row("Runs on", ui.bad("this machine, not running now")), " Next: ekl deploy starts it again"]
178
+ since = ui.local_time(dt.datetime.fromtimestamp(int(state.get("started_at") or 0), dt.UTC).isoformat())
179
+ return [_row("Runs on", f"this machine since {since}"), _row("", ui.dim(str(state.get("about") or "")))]
180
+
181
+
182
+ def _row(label: str, value: str) -> str:
183
+ return f" {ui.bold(label.ljust(9)) if label else ' ' * 9} {value}"
184
+
185
+
186
+ def status_text(found: dict[str, Any]) -> list[str]:
187
+ """A managed registration, for `ekl status`: where it serves from, its callbacks, and the last errors. Its
188
+ revision history is in --json."""
189
+ current: dict[str, Any] = next(
190
+ (r for r in found.get("revisions") or [] if r.get("revision") == found.get("active_revision")), {}
191
+ )
192
+ serving = found.get("availability") == "serving" or found.get("status") == "active"
193
+ # A removed registration has no active revision left to name.
194
+ where = "EuKollab" + (f" · revision {found['active_revision']}" if found.get("active_revision") is not None else "")
195
+ if current.get("digest"):
196
+ where += ui.dim(f" ({current['digest'][:12]})")
197
+ where += f" · {', '.join(dict.fromkeys([found['status'], found['availability']]))}"
198
+ if found.get("loaded_at"):
199
+ where += f" since {ui.local_time(found['loaded_at'])}"
200
+ lines = [_row("Runs on", where if serving else ui.bad(where))]
201
+ if current.get("callbacks") == "hosted":
202
+ lines.append(
203
+ _row("Callbacks", f"running on EuKollab since {ui.local_time(found.get('callbacks_started_at'))}")
204
+ if found.get("callbacks_running")
205
+ else _row("Callbacks", "on EuKollab, asleep until events wait for them")
206
+ )
207
+ if found.get("last_error"):
208
+ at = ui.local_time(found.get("last_error_at"))
209
+ lines.append(
210
+ _row("", f"{ui.paint(ui.WARN, ui.YELLOW)} Last error reaching its MCP server ({at}): {found['last_error']}")
211
+ )
212
+ if found.get("callbacks_error"):
213
+ lines.append(
214
+ _row("", f"{ui.paint(ui.WARN, ui.YELLOW)} Last error starting the callbacks: {found['callbacks_error']}")
215
+ )
216
+ return lines
217
+
218
+
219
+ # --- ekl status ----------------------------------------------------------------------------------------------------
220
+
221
+
222
+ def _deployment_lines(api: OwnerApi, agent_id: str, folder: Path) -> list[str]:
223
+ """Where the agent runs: on EuKollab (its revisions and health), on this machine (its process), or nowhere."""
224
+ found = api.request("GET", f"/agents/{agent_id}/deployment")
225
+ here = (saved(folder) or {}).get("location") == LOCAL or supervise.read_state(folder) is not None
226
+ # A registration EuKollab removed, when the agent moved here, is history: where it runs now is this machine.
227
+ if found.get("location") and not (here and found.get("status") == "removed"):
228
+ return status_text(found)
229
+ if here:
230
+ return local_lines(folder)
231
+ return [_row("Runs on", "nowhere yet"), " Next: ekl deploy, in its folder"]
232
+
233
+
234
+ STATE_COLOUR = {"ACTIVE": ui.GREEN, "VALIDATING": ui.YELLOW, "ADDED": ui.YELLOW}
235
+
236
+
237
+ def _validation_lines(agent: dict[str, Any]) -> list[str]:
238
+ """The agent in one line, then its checks: one line when they passed, each failure with its reason and fix."""
239
+ run = agent["validation"]
240
+ state = str(agent["state"])
241
+ # config_version counts the agent's rules (ekl config history), not agent.json's announced versions.
242
+ out = [
243
+ f"{ui.bold(agent['handle'])} {ui.paint('●', STATE_COLOUR.get(state, ui.RED))} {state.lower()} · "
244
+ f"{'published' if agent.get('published') else 'testing'} · rules v{agent['config_version']}"
245
+ ]
246
+ if run:
247
+ applied = [r for r in run["results"] if r["status"] != "SKIP"]
248
+ failed = [r for r in applied if r["status"] == "FAIL"]
249
+ passed = sum(r["status"] in ("PASS", "PARTIAL") for r in applied)
250
+ ref = ui.dim(f"({run['run_id']})")
251
+ if failed:
252
+ out.append(_row("Checks", f"{ui.bad(f'{len(failed)} of {len(applied)} failed')} {ref}"))
253
+ for r in failed:
254
+ out.append(
255
+ f" {ui.paint(ui.FAIL, ui.RED)} {r['n']:02d} {r['label'].split(' · ')[0]}: {r.get('reason', '')}"
256
+ )
257
+ if r.get("fix"):
258
+ out.append(f" Fix: {r['fix']}")
259
+ elif run["state"] == "running":
260
+ out.append(_row("Checks", f"running · {passed} of {len(applied)} passed so far {ref}"))
261
+ elif run["state"] == "failed":
262
+ # A run fails without a failed check too: a check never reached, or no card to activate.
263
+ out.append(_row("Checks", f"{ui.bad(f'failed · {passed} of {len(applied)} passed')} {ref}"))
264
+ else:
265
+ out.append(_row("Checks", f"{ui.ok(f'{passed} of {len(applied)} passed')} {ref}"))
266
+ if agent.get("validation_queued"):
267
+ out.append(_row("", "New checks are queued and start shortly."))
268
+ return out
269
+
270
+
271
+ def _checking(agent: dict[str, Any]) -> bool:
272
+ """An active agent keeps its state while a new version is checked: a queued or running run counts too. A
273
+ just-confirmed agent is ADDED with no run yet: its first checks are about to start."""
274
+ run = agent["validation"]
275
+ return (
276
+ agent["state"] == "VALIDATING"
277
+ or (run or {}).get("state") == "running"
278
+ or bool(agent.get("validation_queued"))
279
+ or (agent["state"] == "ADDED" and not run)
280
+ )
281
+
282
+
283
+ def _agent(api: OwnerApi, agent_id: str, ref: str) -> dict[str, Any]:
284
+ found = next((a for a in api.request("GET", "/agents") if a["id"] == agent_id), None)
285
+ if found is None:
286
+ raise CliError("EKL-501", ref=ref)
287
+ return dict(found)
288
+
289
+
290
+ ACTIONS = ("confirm", "recheck", "publish", "unpublish", "settings")
291
+
292
+
293
+ def cmd_status(api: OwnerApi, args: argparse.Namespace) -> tuple[Any, str]:
294
+ folder = Path(args.dir)
295
+ ref = args.agent or handle_in(folder)
296
+ chosen = [a for a in ACTIONS if getattr(args, a)]
297
+ if len(chosen) > 1:
298
+ raise CliError("EKL-502", chosen=", ".join("--" + a for a in chosen))
299
+ agent_id = api.agent_id(ref)
300
+ action = chosen[0] if chosen else None
301
+ if action == "confirm":
302
+ confirmed = confirm_version(api, agent_id, ref, None)
303
+ text = ui.ok(f"Confirmed version {confirmed['version']} of {ref}; its checks start.")
304
+ return confirmed, f"{text}\nNext: ekl status {ref} --watch"
305
+ if action == "recheck":
306
+ answered = api.request("POST", f"/agents/{agent_id}/checks")
307
+ return answered, f"{ui.ok(answered['message'])}\nNext: ekl status {ref} --watch"
308
+ if action in ("publish", "unpublish"):
309
+ answered = api.request("POST", f"/agents/{agent_id}/{action}")
310
+ return answered, ui.ok(str(answered["message"]))
311
+ if action == "settings":
312
+ settings_args = argparse.Namespace(**{**vars(args), "agent": ref, "env": str(folder / ".env")})
313
+ return participation.cmd_agent_settings(api, settings_args)
314
+ while True:
315
+ agent = _agent(api, agent_id, ref)
316
+ review = api.request("GET", f"/agents/{agent_id}/review")
317
+ lines = _validation_lines(agent)
318
+ lines += _deployment_lines(api, agent_id, folder)
319
+ if review.get("version") is not None:
320
+ lines += [
321
+ "",
322
+ prompt.heading(f"Version {review['version']} waits for your review"),
323
+ *review_lines(review),
324
+ f"Next: read it, then confirm it: ekl status {ref} --confirm",
325
+ ]
326
+ text = "\n".join(lines)
327
+ if not args.watch or not _checking(agent):
328
+ return {**agent, "review": review}, text
329
+ print(text + "\n", flush=True)
330
+ time.sleep(WATCH_SECONDS)
331
+
332
+
333
+ def add_parser(sub: Any) -> None:
334
+ status = sub.add_parser(
335
+ "status",
336
+ help="where the agent stands: its state, checks, where it runs and what waits for your review; and the "
337
+ "changes to that state",
338
+ )
339
+ status.add_argument(
340
+ "agent", nargs="?", help="handle (@name) or agent ID (default: the agent in this folder's agent.json)"
341
+ )
342
+ status.add_argument("--watch", action="store_true", help="follow until its checks finish")
343
+ status.add_argument("--confirm", action="store_true", help="confirm the version waiting for review; checks start")
344
+ status.add_argument(
345
+ "--recheck", action="store_true", help="run every check of an active agent again (at most every 10 minutes)"
346
+ )
347
+ status.add_argument("--publish", action="store_true", help="move it from testing to the published network")
348
+ status.add_argument("--unpublish", action="store_true", help="take it back to testing")
349
+ status.add_argument(
350
+ "--settings",
351
+ action="store_true",
352
+ help="its settings on the network (take part, Explore, paid agreements); asks with the current "
353
+ "ones as defaults",
354
+ )
355
+ participation.network_questions(status)
356
+ # The agent in this folder unless a handle is given; its .env is where --settings writes a credential.
357
+ status.set_defaults(fn=cmd_status, dir=".")