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
@@ -0,0 +1,376 @@
1
+ # Copyright © 2026 EuKreate, Inc. All rights reserved.
2
+ """Signed releases: what `ekl upgrade` checks before it installs anything.
3
+
4
+ Three kinds of signed file, after The Update Framework's roles, served by the network from /downloads/signing/:
5
+
6
+ root.<n>.json {"_type": "root", "version": n, "expires": ISO 8601, "threshold": 1,
7
+ "root_keys": {key ID: SubjectPublicKeyInfo DER, base64}}
8
+ signed by the root keys of version n-1 and by its own: root.<n>.json.<key ID>.sig each
9
+ keys.json {"_type": "keys", "version": n, "expires": …, "release_keys": {key ID: SPKI}, "revoked": [key ID]}
10
+ signed by a root key of the current root: keys.json.sig
11
+ catalog.json {"_type": "catalog", "version": n, "expires": …,
12
+ "files": [{"name": …, "version": …, "sha256": …, "size": …}]}
13
+ signed by a release key keys.json lists and doesn't revoke: catalog.json.sig
14
+
15
+ The signed bytes are each file's bytes as served, UTF-8 JSON without a byte order mark; nothing is re-serialised. A
16
+ signature file holds the ASN.1 DER ECDSA P-256 signature over SHA-256 of those bytes, base64 without line breaks, then
17
+ one newline. A key ID is the SHA-256 hex of the key's SubjectPublicKeyInfo DER.
18
+
19
+ Order: from the trusted root (the one embedded in this ekl, or the last one reached), each next root in turn, until
20
+ one is missing; each must be exactly one version higher and signed by the keys before it and its own. Only the final
21
+ root's expiry counts. Then keys.json and catalog.json, each signed as above, never older than the highest version seen
22
+ (rollback) and never expired (freeze); a revoked key ID is never trusted again. Then each file's SHA-256 and size.
23
+
24
+ Signatures are checked only by the system's `openssl` (OpenSSL 1.1.1 or later, LibreSSL 2.8 or later). There is no
25
+ verifier of ekl's own and no fallback: without a supported openssl nothing is installed.
26
+ """
27
+
28
+ import base64
29
+ import datetime as dt
30
+ import hashlib
31
+ import json
32
+ import platform
33
+ import re
34
+ import shutil
35
+ import subprocess
36
+ import tempfile
37
+ import urllib.parse
38
+ from collections.abc import Callable
39
+ from dataclasses import dataclass, field
40
+ from importlib.resources import files
41
+ from pathlib import Path
42
+ from typing import Any
43
+
44
+ from ekl_cli.client import CliError, config_dir, write_private
45
+
46
+ STATE_FILE = "release-state.json"
47
+ SIGNING_PATH = "/downloads/signing/"
48
+ FILENAME = re.compile(r"^[A-Za-z0-9._+-]+\.(whl|tar\.gz)$")
49
+ SEMVER = re.compile(r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$")
50
+ MAX_ROOTS = 1000 # a chain longer than this is a server answering every name, not a history of rotations
51
+ NO_VERIFIER = (
52
+ "Can't verify EuKollab's release signature: install OpenSSL 1.1.1 or later (or LibreSSL 2.8 or later), "
53
+ "then run this again"
54
+ )
55
+
56
+ Fetch = Callable[[str], bytes | None]
57
+
58
+
59
+ class ReleaseRefusedError(CliError):
60
+ """A signed file, or a file it lists, that must not be trusted: nothing is installed."""
61
+
62
+ def __init__(self, reason: str) -> None:
63
+ # A sentence starts with a capital, but a file name, address or quoted name keeps its own case.
64
+ first = reason.split(" ", 1)[0]
65
+ super().__init__("EKL-130", reason[:1].upper() + reason[1:] if first.isalpha() else reason)
66
+
67
+
68
+ class NoVerifierError(CliError):
69
+ """No supported openssl on this machine: nothing is installed."""
70
+
71
+ def __init__(self, reason: str) -> None:
72
+ super().__init__("EKL-131", reason)
73
+
74
+
75
+ def install_hint(system: str | None = None, which: Callable[[str], str | None] = shutil.which) -> str:
76
+ """The command that installs a verifier here."""
77
+ system = system or platform.system()
78
+ if system == "Darwin":
79
+ return "brew install openssl"
80
+ for tool, command in (
81
+ ("apt-get", "sudo apt-get install openssl"),
82
+ ("dnf", "sudo dnf install openssl"),
83
+ ("yum", "sudo yum install openssl"),
84
+ ("apk", "sudo apk add openssl"),
85
+ ("pacman", "sudo pacman -S openssl"),
86
+ ("zypper", "sudo zypper install openssl"),
87
+ ):
88
+ if which(tool):
89
+ return command
90
+ return "install openssl with your system's package manager"
91
+
92
+
93
+ def supported(version_text: str) -> bool:
94
+ """OpenSSL 1.1.1 or later, or LibreSSL 2.8 or later, from `openssl version`."""
95
+ found = re.match(r"\s*(OpenSSL|LibreSSL)\s+(\d+)\.(\d+)\.(\d+)([a-z]*)", version_text)
96
+ if not found:
97
+ return False
98
+ kind, major, minor, patch = found.group(1), int(found.group(2)), int(found.group(3)), int(found.group(4))
99
+ if kind == "LibreSSL":
100
+ return (major, minor) >= (2, 8)
101
+ return (major, minor, patch) >= (1, 1, 1)
102
+
103
+
104
+ def verifier(openssl: str | None = None) -> str:
105
+ """The openssl to verify with, or NoVerifierError naming what to install."""
106
+ path = openssl or shutil.which("openssl")
107
+ if path:
108
+ try:
109
+ said = subprocess.run([path, "version"], capture_output=True, text=True, check=False, timeout=10).stdout
110
+ except OSError:
111
+ said = ""
112
+ if supported(said):
113
+ return path
114
+ raise NoVerifierError(f"{NO_VERIFIER}: {install_hint()}")
115
+
116
+
117
+ def key_id(spki_der: bytes) -> str:
118
+ return hashlib.sha256(spki_der).hexdigest()
119
+
120
+
121
+ def _pem(spki_der: bytes) -> str:
122
+ body = base64.b64encode(spki_der).decode()
123
+ lines = [body[i : i + 64] for i in range(0, len(body), 64)]
124
+ return "-----BEGIN PUBLIC KEY-----\n" + "\n".join(lines) + "\n-----END PUBLIC KEY-----\n"
125
+
126
+
127
+ def signature_valid(openssl: str, spki_der: bytes, data: bytes, signature_b64: bytes) -> bool:
128
+ """Whether `openssl dgst -sha256 -verify` accepts the base64 DER signature over these exact bytes."""
129
+ try:
130
+ der = base64.b64decode(signature_b64.strip(), validate=True)
131
+ except ValueError:
132
+ return False
133
+ with tempfile.TemporaryDirectory(prefix="ekl-verify-") as folder:
134
+ work = Path(folder)
135
+ (work / "key.pem").write_text(_pem(spki_der))
136
+ (work / "data").write_bytes(data)
137
+ (work / "sig").write_bytes(der)
138
+ done = subprocess.run(
139
+ [
140
+ openssl,
141
+ "dgst",
142
+ "-sha256",
143
+ "-verify",
144
+ str(work / "key.pem"),
145
+ "-signature",
146
+ str(work / "sig"),
147
+ str(work / "data"),
148
+ ],
149
+ capture_output=True,
150
+ check=False,
151
+ timeout=30,
152
+ )
153
+ return done.returncode == 0
154
+
155
+
156
+ def _expires(document: dict[str, Any]) -> dt.datetime:
157
+ text = str(document.get("expires") or "")
158
+ try:
159
+ when = dt.datetime.fromisoformat(text.replace("Z", "+00:00"))
160
+ except ValueError as exc:
161
+ raise ReleaseRefusedError(f"a signed file has no valid expiry ({text!r})") from exc
162
+ return when if when.tzinfo else when.replace(tzinfo=dt.UTC)
163
+
164
+
165
+ def _parse(data: bytes, kind: str) -> dict[str, Any]:
166
+ """A signed file's JSON, of the kind expected: root, keys or catalog."""
167
+ if data.startswith(b"\xef\xbb\xbf"):
168
+ raise ReleaseRefusedError(f"the {kind} file starts with a byte order mark")
169
+ try:
170
+ found = json.loads(data.decode("utf-8"))
171
+ except (UnicodeDecodeError, ValueError) as exc:
172
+ raise ReleaseRefusedError(f"the {kind} file isn't UTF-8 JSON") from exc
173
+ if not isinstance(found, dict) or found.get("_type") != kind or not isinstance(found.get("version"), int):
174
+ raise ReleaseRefusedError(f"that isn't a {kind} file")
175
+ return found
176
+
177
+
178
+ def _keys(document: dict[str, Any], field_name: str) -> dict[str, bytes]:
179
+ """The keys a document lists, each checked against its key ID."""
180
+ found: dict[str, bytes] = {}
181
+ for kid, encoded in dict(document.get(field_name) or {}).items():
182
+ try:
183
+ der = base64.b64decode(str(encoded), validate=True)
184
+ except ValueError as exc:
185
+ raise ReleaseRefusedError(f"a key in {field_name} isn't base64") from exc
186
+ if key_id(der) != kid:
187
+ raise ReleaseRefusedError(f"key {kid[:12]}… doesn't match its key ID")
188
+ found[kid] = der
189
+ return found
190
+
191
+
192
+ @dataclass
193
+ class State:
194
+ """The highest versions seen, the trusted root, and every revoked key ID: kept in ~/.config/ekl (0600)."""
195
+
196
+ root: dict[str, Any] | None = None
197
+ keys_version: int = 0
198
+ catalog_version: int = 0
199
+ revoked: set[str] = field(default_factory=set)
200
+
201
+ @classmethod
202
+ def load(cls, path: Path) -> "State":
203
+ if not path.is_file():
204
+ return cls()
205
+ try:
206
+ data = json.loads(path.read_text())
207
+ return cls(data.get("root"), int(data["keys_version"]), int(data["catalog_version"]), set(data["revoked"]))
208
+ except (ValueError, KeyError, TypeError) as exc:
209
+ raise ReleaseRefusedError(
210
+ f"{path} is damaged; remove it only if you trust the network you install from"
211
+ ) from exc
212
+
213
+ def save(self, path: Path) -> None:
214
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
215
+ data = {
216
+ "root": self.root,
217
+ "root_version": (self.root or {}).get("version", 0),
218
+ "keys_version": self.keys_version,
219
+ "catalog_version": self.catalog_version,
220
+ "revoked": sorted(self.revoked),
221
+ }
222
+ write_private(path, json.dumps(data, indent=2))
223
+
224
+
225
+ def embedded_root() -> dict[str, Any]:
226
+ """The root this ekl was built with. A build without EuKollab's real root refuses to verify anything."""
227
+ data = (files("ekl_cli") / "release_root.json").read_bytes()
228
+ found = json.loads(data)
229
+ if found.get("placeholder"):
230
+ raise ReleaseRefusedError(
231
+ "this ekl was built without EuKollab's release root, so it can't verify a release; install ekl from the "
232
+ "network's Downloads page"
233
+ )
234
+ return dict(found)
235
+
236
+
237
+ @dataclass
238
+ class Verified:
239
+ root: dict[str, Any]
240
+ keys: dict[str, Any]
241
+ catalog: dict[str, Any]
242
+
243
+ def file(self, name: str) -> dict[str, Any]:
244
+ for entry in self.catalog.get("files") or []:
245
+ if entry.get("name") == name:
246
+ return dict(entry)
247
+ raise ReleaseRefusedError(f"{name} isn't in the signed catalogue")
248
+
249
+
250
+ class Chain:
251
+ """One verification: the fetcher, the verifier and the clock."""
252
+
253
+ def __init__(self, fetch: Fetch, openssl: str, now: dt.datetime | None = None) -> None:
254
+ self.fetch = fetch
255
+ self.openssl = openssl
256
+ self.now = now or dt.datetime.now(dt.UTC)
257
+
258
+ def _signed_by(self, data: bytes, keys: dict[str, bytes], signature: bytes | None) -> str | None:
259
+ """The key ID among `keys` whose signature over `data` verifies, or None."""
260
+ if signature is None:
261
+ return None
262
+ for kid, der in keys.items():
263
+ if signature_valid(self.openssl, der, data, signature):
264
+ return kid
265
+ return None
266
+
267
+ def _root_step(self, current: dict[str, Any]) -> dict[str, Any] | None:
268
+ n = int(current["version"]) + 1
269
+ name = f"root.{n}.json"
270
+ data = self.fetch(name)
271
+ if data is None:
272
+ return None
273
+ found = _parse(data, "root")
274
+ if found["version"] != n:
275
+ raise ReleaseRefusedError(f"{name} says version {found['version']}: the chain must go up by one")
276
+ threshold = max(int(current.get("threshold") or 1), 1)
277
+ for signers, who in (
278
+ (_keys(current, "root_keys"), "the previous root's keys"),
279
+ (_keys(found, "root_keys"), "its own keys"),
280
+ ):
281
+ good = {kid for kid in signers if self._sig_ok(f"{name}.{kid}.sig", data, signers[kid])}
282
+ if len(good) < threshold:
283
+ raise ReleaseRefusedError(f"{name} isn't signed by {who}")
284
+ return found
285
+
286
+ def _sig_ok(self, sig_name: str, data: bytes, der: bytes) -> bool:
287
+ signature = self.fetch(sig_name)
288
+ return signature is not None and signature_valid(self.openssl, der, data, signature)
289
+
290
+ def roots(self, trusted: dict[str, Any]) -> dict[str, Any]:
291
+ current = trusted
292
+ for _ in range(MAX_ROOTS):
293
+ following = self._root_step(current)
294
+ if following is None:
295
+ break
296
+ # An intermediate root may have expired since; it only hands trust on to the next.
297
+ current = following
298
+ if _expires(current) <= self.now:
299
+ raise ReleaseRefusedError("the release root has expired; EuKollab will publish a new one")
300
+ return current
301
+
302
+ def verify(self, state: State, trusted: dict[str, Any]) -> Verified:
303
+ root = self.roots(state.root if state.root and state.root["version"] > trusted["version"] else trusted)
304
+ root_keys = {k: v for k, v in _keys(root, "root_keys").items() if k not in state.revoked}
305
+ data = self.fetch("keys.json")
306
+ if data is None:
307
+ raise ReleaseRefusedError("the network serves no keys.json")
308
+ keys = _parse(data, "keys")
309
+ if not self._signed_by(data, root_keys, self.fetch("keys.json.sig")):
310
+ raise ReleaseRefusedError("keys.json isn't signed by a current root key")
311
+ if keys["version"] < state.keys_version:
312
+ raise ReleaseRefusedError(
313
+ f"keys.json version {keys['version']} is older than {state.keys_version}: refused"
314
+ )
315
+ if _expires(keys) <= self.now:
316
+ raise ReleaseRefusedError("keys.json has expired; EuKollab will publish a new one")
317
+ revoked = state.revoked | {str(k) for k in keys.get("revoked") or []}
318
+ release_keys = {k: v for k, v in _keys(keys, "release_keys").items() if k not in revoked}
319
+ data = self.fetch("catalog.json")
320
+ if data is None:
321
+ raise ReleaseRefusedError("the network serves no catalog.json")
322
+ catalog = _parse(data, "catalog")
323
+ if not self._signed_by(data, release_keys, self.fetch("catalog.json.sig")):
324
+ raise ReleaseRefusedError("catalog.json isn't signed by a release key keys.json delegates")
325
+ if catalog["version"] < state.catalog_version:
326
+ raise ReleaseRefusedError(
327
+ f"catalog.json version {catalog['version']} is older than {state.catalog_version}: refused"
328
+ )
329
+ if _expires(catalog) <= self.now:
330
+ raise ReleaseRefusedError("catalog.json has expired; EuKollab will publish a new one")
331
+ state.root, state.keys_version, state.catalog_version = root, keys["version"], catalog["version"]
332
+ state.revoked = revoked
333
+ return Verified(root, keys, catalog)
334
+
335
+
336
+ def check_file(entry: dict[str, Any], data: bytes) -> None:
337
+ if len(data) != int(entry.get("size", -1)) or hashlib.sha256(data).hexdigest() != entry.get("sha256"):
338
+ raise ReleaseRefusedError(f"{entry.get('name')} doesn't match the signed catalogue's SHA-256 and size; refused")
339
+
340
+
341
+ def check_name(name: str, version: str) -> None:
342
+ """Before any path is built from them: a plain file name and a SemVer version."""
343
+ if not FILENAME.match(name) or ".." in name:
344
+ raise ReleaseRefusedError(f"{name!r} isn't a package file name")
345
+ if not SEMVER.match(version):
346
+ raise ReleaseRefusedError(f"{version!r} isn't a version")
347
+
348
+
349
+ def check_url(url: str, network: str) -> None:
350
+ """A download comes from the network's own host, over HTTPS (http only for a network on this machine)."""
351
+ parts, home = urllib.parse.urlsplit(url), urllib.parse.urlsplit(network)
352
+ loopback = parts.hostname in ("localhost", "127.0.0.1", "::1")
353
+ if parts.hostname != home.hostname or not (parts.scheme == "https" or (parts.scheme == "http" and loopback)):
354
+ raise ReleaseRefusedError(f"{url} isn't on {home.hostname} over HTTPS")
355
+
356
+
357
+ def state_path() -> Path:
358
+ return config_dir() / STATE_FILE
359
+
360
+
361
+ def verify_release(
362
+ fetch: Fetch,
363
+ *,
364
+ trusted: dict[str, Any] | None = None,
365
+ openssl: str | None = None,
366
+ now: dt.datetime | None = None,
367
+ state_file: Path | None = None,
368
+ ) -> Verified:
369
+ """Verify root chain, keys and catalogue, and record the versions reached. `trusted` is for tests; ekl uses the
370
+ root it was built with."""
371
+ tool = verifier(openssl) # first: without a verifier nothing else happens
372
+ path = state_file or state_path()
373
+ state = State.load(path)
374
+ verified = Chain(fetch, tool, now).verify(state, trusted or embedded_root())
375
+ state.save(path)
376
+ return verified
ekl_cli/repair.py ADDED
@@ -0,0 +1,266 @@
1
+ # Copyright © 2026 EuKreate, Inc. All rights reserved.
2
+ """What an earlier ekl left in an agent's folder, and its repair, offered by `ekl deploy`, `ekl check` and `ekl sync`.
3
+
4
+ Only what ekl itself wrote is touched, recognised by its marker ("written for ekl-provider-adapter …"), by matching a
5
+ file a released ekl wrote, or by a setting no current program reads. The publisher's own code and files are never
6
+ changed. At a terminal the repairs are listed and asked for; `ekl deploy --confirm` or `--force` makes them without
7
+ asking; with no one to ask, they are reported and the command carries on with the folder as it is.
8
+ """
9
+
10
+ import hashlib
11
+ import json
12
+ import re
13
+ import sys
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass
16
+ from functools import partial
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from ekl_cli import project, prompt
21
+
22
+ CALLBACKS_FILE = "eukollab_callbacks.py"
23
+ GUIDE_FILE = "EUKOLLAB.md"
24
+
25
+ # The callbacks file every released ekl wrote, by the fingerprint of its handlers: a file still matching one is ekl's,
26
+ # not the publisher's, whichever ekl wrote it. When the template's handlers change, its fingerprint is added here (a
27
+ # test checks the current one is).
28
+ WRITTEN_BY_EKL = frozenset(
29
+ {
30
+ "3d3541448699708e442d80dff9680de0ea99e401b86101c13cb41c55d9b84aae",
31
+ "5425ca8ed6404dfdf3965b0f706e846ec5c238cb31fc6a6c7ab8e7c405dfd8e9",
32
+ "74eb09ef117277efd682d7f2ef5f2af698cbb17934b5a73ac3f71a3b268b6592",
33
+ "91331588ac5c0157082d30347806bedd5f4dc37c202b4752928d4f3472c94a46",
34
+ "969d2f3fa2955c08d3631001737fad6d763dc76ad055c94b9e7c67ce259b7f22",
35
+ "97282e6c64ee69f743c87cc72d61a338f7e59ce3a2155874596acf5ff1246cef",
36
+ "a057db433ac25a0b227c146a6d62a240f397a1ad5563ed890fb0fb0a5dc8583e",
37
+ "ada35e21c747fe0bbc2bb1c3b41c34d68b5b45230ef1071fd85dc016b6cd3809",
38
+ "b2f3adc436292b74d503b72bef744351eebbbc7af44b0e1f1a5bb4a1df363355",
39
+ "06376b5a2e1b464e351d8fd1d06abfc6c56592b41345f7605b4058907087d02b",
40
+ "dcaac4be82295b33a99bdfed3676f2dc55efc441bbe3c285504cd9b52c10585b",
41
+ }
42
+ )
43
+
44
+ # Settings earlier ekl versions wrote to .env for the host deploys they had; no program reads them now.
45
+ RETIRED_SETTINGS = ("EKL_DEPLOY_MCP_URL", "EKL_DEPLOY_ADAPTER_STORAGE", "EKL_MANAGED_BY", "EKL_CONNECTOR_IMAGE")
46
+
47
+ # Commands an earlier ekl named in the comments of .env.example, and what does the same now.
48
+ RETIRED_COMMANDS = (
49
+ ("ekl agent rotate-key", "ekl sync --rotate-key"),
50
+ ("ekl agent take-part", "ekl status --settings --take-part"),
51
+ ("ekl agent settings", "ekl status --settings"),
52
+ ("ekl agent sync", "ekl sync"),
53
+ ("ekl agent check", "ekl check"),
54
+ ("ekl agent run", "ekl deploy"),
55
+ ("ekl agent deploy", "ekl deploy"),
56
+ ("ekl agent init", "ekl add"),
57
+ ("ekl new agent", "ekl add"),
58
+ )
59
+ _ADAPTER_MARK = re.compile(r"written for ekl-provider-adapter \d", re.IGNORECASE)
60
+ # Every instruction the Dockerfile.eukollab of an earlier ekl held: one with any other is the publisher's.
61
+ DOCKERFILE_LINES = frozenset(
62
+ {
63
+ 'CMD ["ekl-provider-connector"]',
64
+ "COPY agent.json .",
65
+ "COPY agent.json eukollab_callbacks.py* ./",
66
+ "COPY requirements.txt .",
67
+ "ENV EKL_AGENT_FILE=/app/agent.json PORT=8000 PYTHONUNBUFFERED=1",
68
+ "ENV PORT=8000 PYTHONUNBUFFERED=1",
69
+ "EXPOSE 8000",
70
+ "FROM python:3.13-slim",
71
+ "FROM python:3.13-slim@sha256:2d44738ebf4ce5f63b9d9ea871e9c7cfdc0426f7b0c97cac915fd88ded1d86bb",
72
+ "RUN pip install --no-cache-dir -r requirements.txt",
73
+ "RUN useradd --create-home connector",
74
+ "USER connector",
75
+ "WORKDIR /app",
76
+ "WORKDIR /home/connector",
77
+ }
78
+ )
79
+
80
+
81
+ def _handlers(text: str) -> dict[str, str]:
82
+ """Each top-level `on_…` function of a callbacks file, by name, its body without blank lines."""
83
+ found: dict[str, str] = {}
84
+ for part in text.split("\ndef ")[1:]:
85
+ name = part.split("(", 1)[0]
86
+ if name.startswith("on_"):
87
+ body = part.split("\n\n\n", 1)[0]
88
+ found[name] = "\n".join(line.rstrip() for line in body.splitlines() if line.strip())
89
+ return found
90
+
91
+
92
+ def fingerprint(text: str) -> str:
93
+ return hashlib.sha256(json.dumps(_handlers(text), sort_keys=True).encode()).hexdigest()
94
+
95
+
96
+ def callbacks_file(folder: Path) -> str:
97
+ """What eukollab_callbacks.py is: "none" (no file), "current" (the file this ekl writes, whose handlers decide
98
+ nothing and leave the console's rules in force), "earlier" (one an earlier ekl wrote, unchanged) or "own" (the
99
+ publisher's code)."""
100
+ path = folder / CALLBACKS_FILE
101
+ if not path.is_file():
102
+ return "none"
103
+ found = fingerprint(path.read_text(errors="replace"))
104
+ if found == fingerprint((project.templates_dir("python") / f"{CALLBACKS_FILE}.tmpl").read_text()):
105
+ return "current"
106
+ return "earlier" if found in WRITTEN_BY_EKL else "own"
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class Repair:
111
+ found: str
112
+ fix: str
113
+ apply: Callable[[], None]
114
+
115
+
116
+ def _values(folder: Path) -> dict[str, str]:
117
+ """What the files ekl writes are rendered with, from the folder's agent.json."""
118
+ try:
119
+ content: dict[str, Any] = json.loads((folder / "agent.json").read_text())
120
+ except (OSError, ValueError):
121
+ content = {}
122
+ agent = content.get("agent") or {}
123
+ return {
124
+ "name": str(agent.get("display_name") or folder.name),
125
+ "handle": str(agent.get("handle") or ""),
126
+ "adapter_version": project.adapter_version(),
127
+ }
128
+
129
+
130
+ def _rewrite_guide(folder: Path) -> None:
131
+ (folder / GUIDE_FILE).write_text(project.render("eukollab-agent.md", _values(folder)))
132
+
133
+
134
+ def _ekl_wrote(path: Path) -> bool:
135
+ """Whether a file of the removed host deploys is still the one ekl wrote."""
136
+ if not path.is_file():
137
+ return False
138
+ text = path.read_text(errors="replace")
139
+ if path.name == "Procfile":
140
+ return text.strip() == "web: ekl-provider-connector --port $PORT"
141
+ head = "\n".join(text.splitlines()[:3])
142
+ if not _ADAPTER_MARK.search(head):
143
+ return False
144
+ wanted = [line.strip() for line in text.splitlines() if line.strip() and not line.lstrip().startswith("#")]
145
+ if path.name == "requirements.txt":
146
+ # Only the connector's own requirement: anything else listed is the publisher's.
147
+ return all(line.startswith("ekl-provider-adapter") for line in wanted)
148
+ # A Dockerfile with any instruction ekl never wrote has the publisher's changes in it.
149
+ return all(line in DOCKERFILE_LINES for line in wanted)
150
+
151
+
152
+ def _drop_settings(path: Path, names: list[str]) -> None:
153
+ """Remove the settings, and in .env.example the comment lines just above each."""
154
+ lines = path.read_text().splitlines()
155
+ kept: list[str] = []
156
+ for line in lines:
157
+ name = line.split("=", 1)[0].strip()
158
+ if "=" in line and name in names:
159
+ while kept and kept[-1].startswith("#"):
160
+ kept.pop()
161
+ continue
162
+ kept.append(line)
163
+ text = "\n".join(kept).rstrip("\n") + "\n"
164
+ path.write_text(re.sub(r"\n{3,}", "\n\n", text))
165
+
166
+
167
+ def _command(words: str) -> re.Pattern[str]:
168
+ """A retired command as written in a comment, where wrapping may split it over lines ("ekl agent\n# take-part")."""
169
+ return re.compile(r"(?:\s|\n#\s?)+".join(re.escape(word) for word in words.split()))
170
+
171
+
172
+ def _renamed_commands(text: str) -> str:
173
+ for old, new in RETIRED_COMMANDS:
174
+ text = _command(old).sub(new, text)
175
+ return text
176
+
177
+
178
+ def _rename_commands(path: Path) -> None:
179
+ path.write_text(_renamed_commands(path.read_text()))
180
+
181
+
182
+ def found(folder: Path) -> list[Repair]:
183
+ """Every repair the folder needs, in the order they are made."""
184
+ repairs: list[Repair] = []
185
+ callbacks = folder / CALLBACKS_FILE
186
+ if callbacks_file(folder) == "earlier" and _renamed_commands(callbacks.read_text()) != callbacks.read_text():
187
+ # Its defaults keep running as they are (on EuKollab too): only the commands its comments name change.
188
+ repairs.append(
189
+ Repair(
190
+ f"{CALLBACKS_FILE}, which an earlier ekl wrote, names commands that were retired in its comments",
191
+ "name the current ones (its handlers stay as they are)",
192
+ partial(_rename_commands, callbacks),
193
+ )
194
+ )
195
+ guide = folder / GUIDE_FILE
196
+ if guide.is_file() and _renamed_commands(guide.read_text(errors="replace")) != guide.read_text(errors="replace"):
197
+ repairs.append(
198
+ Repair(
199
+ f"{GUIDE_FILE}, ekl's guide to the folder, names commands that were retired",
200
+ "write the current guide",
201
+ lambda: _rewrite_guide(folder),
202
+ )
203
+ )
204
+ for name in ("Dockerfile.eukollab", "Procfile", "requirements.txt"):
205
+ path = folder / name
206
+ if _ekl_wrote(path):
207
+ repairs.append(
208
+ Repair(f"{name} was written for the host deploys ekl no longer has", "delete it", path.unlink)
209
+ )
210
+ old_record = folder / ".ekl" / "deploy.json"
211
+ if old_record.is_file():
212
+ repairs.append(
213
+ Repair(".ekl/deploy.json records a host deploy ekl no longer has", "delete it", old_record.unlink)
214
+ )
215
+ for env_name in (".env", ".env.example"):
216
+ path = folder / env_name
217
+ if not path.is_file():
218
+ continue
219
+ text = path.read_text(errors="replace")
220
+ retired = [n for n in RETIRED_SETTINGS if re.search(rf"^{n}=", text, re.MULTILINE)]
221
+ if retired:
222
+ repairs.append(
223
+ Repair(
224
+ f"{env_name} holds settings nothing reads any more: {', '.join(retired)}",
225
+ "remove them",
226
+ partial(_drop_settings, path, retired),
227
+ )
228
+ )
229
+ if env_name == ".env.example" and _renamed_commands(text) != text:
230
+ repairs.append(
231
+ Repair(
232
+ ".env.example names commands that were retired",
233
+ "name the current ones",
234
+ partial(_rename_commands, path),
235
+ )
236
+ )
237
+ return repairs
238
+
239
+
240
+ def offer(folder: Path, *, confirm: bool = False, report_only: bool = False) -> list[Repair]:
241
+ """Find what an earlier ekl left in the folder and repair it: asked for at a terminal, made at once with
242
+ `confirm`, only reported with `report_only` or when no one is there to ask. Returns the repairs made. Everything it
243
+ says goes to stderr, so a command's own output (its --json) stays clean."""
244
+ repairs = found(folder)
245
+ if not repairs:
246
+ return []
247
+ details = [f"{r.found}: {r.fix}" for r in repairs]
248
+ if report_only or not (confirm or prompt.interactive()):
249
+ print(f"ekl found {len(repairs)} things an earlier ekl left in {folder}:", file=sys.stderr, flush=True)
250
+ for line in details:
251
+ print(f" {line}", file=sys.stderr, flush=True)
252
+ if not report_only:
253
+ print(
254
+ " repair them at a terminal, or with ekl deploy --force; carrying on as the folder is",
255
+ file=sys.stderr,
256
+ flush=True,
257
+ )
258
+ return []
259
+ if not confirm and not prompt.confirm(
260
+ f"Repair what an earlier ekl left in {folder}?", True, *details, "Nothing you wrote is changed."
261
+ ):
262
+ return []
263
+ for repair in repairs:
264
+ repair.apply()
265
+ print(f"repaired: {repair.found}: {repair.fix}", file=sys.stderr, flush=True)
266
+ return repairs