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/schema.py ADDED
@@ -0,0 +1,117 @@
1
+ # Copyright © 2026 EuKreate, Inc. All rights reserved.
2
+ """The part of JSON Schema that tool output schemas use, standard library only: enough to say whether a result fits
3
+ the schema a tool declares. Keywords outside it are ignored, so a result is never refused
4
+ for something this module doesn't read; a malformed schema refuses nothing either, as the platform's check does.
5
+ """
6
+
7
+ import operator
8
+ import re
9
+ from typing import Any
10
+
11
+ TYPES: dict[str, Any] = {
12
+ "object": dict,
13
+ "array": list,
14
+ "string": str,
15
+ "boolean": bool,
16
+ "null": type(None),
17
+ }
18
+
19
+ BOUNDS = (
20
+ ("minimum", operator.lt),
21
+ ("maximum", operator.gt),
22
+ ("exclusiveMinimum", operator.le),
23
+ ("exclusiveMaximum", operator.ge),
24
+ )
25
+
26
+
27
+ def _is(value: Any, kind: str) -> bool:
28
+ # bool is an int in Python and is no number in JSON.
29
+ if kind == "integer":
30
+ return (isinstance(value, int) and not isinstance(value, bool)) or (
31
+ isinstance(value, float) and value.is_integer()
32
+ )
33
+ if kind == "number":
34
+ return isinstance(value, int | float) and not isinstance(value, bool)
35
+ expected = TYPES.get(kind)
36
+ return expected is None or isinstance(value, expected)
37
+
38
+
39
+ def _resolve(root: dict[str, Any], ref: str) -> dict[str, Any] | None:
40
+ if not ref.startswith("#"):
41
+ return None # a remote reference: not fetched, so not checked
42
+ node: Any = root
43
+ for part in [p.replace("~1", "/").replace("~0", "~") for p in ref[1:].split("/") if p]:
44
+ if not isinstance(node, dict) or part not in node:
45
+ return None
46
+ node = node[part]
47
+ return node if isinstance(node, dict) else None
48
+
49
+
50
+ def _object_errors(value: dict[str, Any], schema: dict[str, Any], root: dict[str, Any], at: str) -> list[str]:
51
+ found = [f"{at}: '{name}' is required" for name in schema.get("required") or [] if name not in value]
52
+ props = schema.get("properties") or {}
53
+ extra = schema.get("additionalProperties", True)
54
+ for key, item in value.items():
55
+ if isinstance(props.get(key), dict):
56
+ found += errors(item, props[key], root, f"{at}.{key}")
57
+ elif extra is False:
58
+ found.append(f"{at}: '{key}' is not allowed")
59
+ elif isinstance(extra, dict):
60
+ found += errors(item, extra, root, f"{at}.{key}")
61
+ return found
62
+
63
+
64
+ def _bounds(value: Any, schema: dict[str, Any], at: str) -> list[str]:
65
+ found = []
66
+ if isinstance(value, str):
67
+ if len(value) < schema.get("minLength", 0) or len(value) > schema.get("maxLength", len(value)):
68
+ found.append(f"{at}: length {len(value)} is outside the allowed length")
69
+ pattern = schema.get("pattern")
70
+ if isinstance(pattern, str):
71
+ try:
72
+ if not re.search(pattern, value):
73
+ found.append(f"{at}: does not match {pattern}")
74
+ except re.error:
75
+ pass # a pattern Python can't read: not checked
76
+ if isinstance(value, int | float) and not isinstance(value, bool):
77
+ for key, breaks in BOUNDS:
78
+ limit = schema.get(key)
79
+ if isinstance(limit, int | float) and not isinstance(limit, bool) and breaks(value, limit):
80
+ found.append(f"{at}: {value} breaks {key} {limit}")
81
+ if isinstance(value, list) and (
82
+ len(value) < schema.get("minItems", 0) or len(value) > schema.get("maxItems", len(value))
83
+ ):
84
+ found.append(f"{at}: {len(value)} items is outside the allowed number")
85
+ return found
86
+
87
+
88
+ def errors(value: Any, schema: Any, root: dict[str, Any] | None = None, at: str = "result") -> list[str]:
89
+ """Why `value` does not fit `schema`, empty when it does."""
90
+ if not isinstance(schema, dict):
91
+ return []
92
+ root = schema if root is None else root
93
+ if isinstance(schema.get("$ref"), str):
94
+ target = _resolve(root, schema["$ref"])
95
+ return errors(value, target, root, at) if target is not None else []
96
+ kinds = schema.get("type")
97
+ kinds = [kinds] if isinstance(kinds, str) else kinds if isinstance(kinds, list) else []
98
+ if kinds and not any(_is(value, str(k)) for k in kinds):
99
+ return [f"{at}: expected {' or '.join(str(k) for k in kinds)}"]
100
+ if "const" in schema and value != schema["const"]:
101
+ return [f"{at}: must be {schema['const']!r}"]
102
+ if isinstance(schema.get("enum"), list) and value not in schema["enum"]:
103
+ return [f"{at}: must be one of {schema['enum']}"]
104
+ found: list[str] = []
105
+ for part in schema.get("allOf") or []:
106
+ found += errors(value, part, root, at)
107
+ for key in ("anyOf", "oneOf"):
108
+ choices = [c for c in schema.get(key) or [] if isinstance(c, dict)]
109
+ fitting = sum(1 for c in choices if not errors(value, c, root, at))
110
+ if choices and (fitting == 0 or (key == "oneOf" and fitting > 1)):
111
+ found.append(f"{at}: fits {fitting} of the {len(choices)} choices of {key}")
112
+ if isinstance(value, dict):
113
+ found += _object_errors(value, schema, root, at)
114
+ if isinstance(value, list) and isinstance(schema.get("items"), dict):
115
+ for i, item in enumerate(value):
116
+ found += errors(item, schema["items"], root, f"{at}[{i}]")
117
+ return found + _bounds(value, schema, at)
ekl_cli/setup.py ADDED
@@ -0,0 +1,326 @@
1
+ # Copyright © 2026 EuKreate, Inc. All rights reserved.
2
+ """`ekl setup <client>`: add the publisher MCP server and the skills to a coding agent or IDE.
3
+
4
+ The packages ship inside this wheel (`ekl_cli/clients/`), so setup works offline
5
+ and always matches the installed `ekl`. Each client is set up its own way: through its command line where that is how
6
+ it installs plugins, otherwise by merging one entry into its configuration file or copying the package where the client
7
+ looks for it. A merge changes only the `eukollab-publisher` entry, keeps a `.bak` copy of the previous file, and
8
+ running setup again changes nothing unless ekl has changed: then it brings the client's copy up to this version, which
9
+ is how `ekl upgrade` refreshes every client set up for the user (their names are kept in ~/.config/ekl/setup.json).
10
+ No step ever writes a token: every client starts `ekl mcp`, which signs in with what `ekl login` stored.
11
+ """
12
+
13
+ import filecmp
14
+ import json
15
+ import os
16
+ import re
17
+ import shutil
18
+ import subprocess
19
+ import sys
20
+ import tomllib
21
+ from collections.abc import Callable
22
+ from dataclasses import dataclass
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ from ekl_cli import install
27
+ from ekl_cli.client import CliError, Credentials, config_dir
28
+
29
+ CLIENTS = ("claude-code", "codex", "cursor", "vscode", "gemini", "generic")
30
+ SERVER_NAME = "eukollab-publisher"
31
+ PLUGIN = "eukollab"
32
+ MARKETPLACE = "eukollab"
33
+ SERVER = {"command": "ekl", "args": ["mcp"]}
34
+ TITLES = {
35
+ "claude-code": "Claude Code",
36
+ "codex": "Codex",
37
+ "cursor": "Cursor",
38
+ "vscode": "VS Code",
39
+ "gemini": "Gemini CLI",
40
+ "generic": "your MCP client",
41
+ }
42
+
43
+
44
+ def clients_dir() -> Path:
45
+ # Named through the installer's `current` link when ekl came from it, so a client keeps finding the packages after
46
+ # an upgrade removes the version that set it up.
47
+ return install.stable_path(Path(__file__).parent / "clients", Path(sys.prefix))
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class Places:
52
+ """Where setup reads and writes: the user's home, the current repository and the clients' command lines."""
53
+
54
+ home: Path
55
+ cwd: Path
56
+ which: Callable[[str], str | None]
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class Run:
61
+ """Run the client's own command line (how Claude Code and Codex install plugins)."""
62
+
63
+ argv: list[str]
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class MergeJson:
68
+ """Set the `eukollab-publisher` entry under `table` in a JSON configuration file, leaving every other entry."""
69
+
70
+ path: Path
71
+ table: str
72
+ entry: dict[str, Any]
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class MergeToml:
77
+ """Replace or add the TOML table `table` with `body`, leaving the rest of the file as it was."""
78
+
79
+ path: Path
80
+ table: str
81
+ body: str
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class Copy:
86
+ """Copy a package folder from the wheel to where the client looks for it."""
87
+
88
+ source: Path
89
+ target: Path
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class Show:
94
+ """Instructions to show, for a client setup can't configure itself."""
95
+
96
+ text: str
97
+
98
+
99
+ Step = Run | MergeJson | MergeToml | Copy | Show
100
+
101
+
102
+ def plan(client: str, project: bool, places: Places) -> list[Step]:
103
+ """The steps that set up one client, without doing any of them."""
104
+ planner = PLANNERS.get(client)
105
+ if planner is None:
106
+ raise CliError(
107
+ "EKL-901", f"No such coding agent: {client}. Choose one of {', '.join(CLIENTS)}.", usage="ekl setup --help"
108
+ )
109
+ return planner(project, places, clients_dir())
110
+
111
+
112
+ def _claude_code(project: bool, places: Places, packages: Path) -> list[Step]:
113
+ if project:
114
+ return [
115
+ MergeJson(places.cwd / ".mcp.json", "mcpServers", SERVER),
116
+ Copy(packages / "claude-code" / "skills", places.cwd / ".claude" / "skills"),
117
+ ]
118
+ if places.which("claude") is None:
119
+ raise CliError("EKL-801")
120
+ # Adding and installing what is already there changes nothing, so the updates bring an installed plugin up to
121
+ # this ekl's version.
122
+ return [
123
+ Run(["claude", "plugin", "marketplace", "add", str(packages)]),
124
+ Run(["claude", "plugin", "marketplace", "update", MARKETPLACE]),
125
+ Run(["claude", "plugin", "install", f"{PLUGIN}@{MARKETPLACE}"]),
126
+ Run(["claude", "plugin", "update", f"{PLUGIN}@{MARKETPLACE}"]),
127
+ ]
128
+
129
+
130
+ def _codex(project: bool, places: Places, packages: Path) -> list[Step]:
131
+ codex_home = places.cwd / ".codex" if project else Path(os.environ.get("CODEX_HOME", places.home / ".codex"))
132
+ config = codex_home / "config.toml"
133
+ if not project and places.which("codex"):
134
+ return [
135
+ Run(["codex", "plugin", "marketplace", "add", str(packages)]),
136
+ MergeToml(config, f'plugins."{PLUGIN}@{MARKETPLACE}"', "enabled = true"),
137
+ ]
138
+ # Without Codex's command line, or for one repository: the server alone, in Codex's own configuration.
139
+ return [MergeToml(config, f"mcp_servers.{SERVER_NAME}", 'command = "ekl"\nargs = ["mcp"]')]
140
+
141
+
142
+ def _cursor(project: bool, places: Places, packages: Path) -> list[Step]:
143
+ if project:
144
+ return [
145
+ MergeJson(places.cwd / ".cursor" / "mcp.json", "mcpServers", SERVER),
146
+ Copy(packages / "cursor" / "rules", places.cwd / ".cursor" / "rules"),
147
+ ]
148
+ return [Copy(packages / "cursor", places.home / ".cursor" / "plugins" / "local" / PLUGIN)]
149
+
150
+
151
+ def _vscode(project: bool, places: Places, packages: Path) -> list[Step]:
152
+ entry = {"type": "stdio", **SERVER}
153
+ if project:
154
+ return [
155
+ MergeJson(places.cwd / ".vscode" / "mcp.json", "servers", entry),
156
+ Copy(packages / "vscode" / "instructions", places.cwd / ".github" / "instructions"),
157
+ ]
158
+ return [MergeJson(_vscode_user_dir(places.home) / "mcp.json", "servers", entry)]
159
+
160
+
161
+ def _gemini(project: bool, places: Places, packages: Path) -> list[Step]:
162
+ if project:
163
+ return [MergeJson(places.cwd / ".gemini" / "settings.json", "mcpServers", SERVER)]
164
+ return [Copy(packages / "gemini", places.home / ".gemini" / "extensions" / PLUGIN)]
165
+
166
+
167
+ def _generic(_: bool, __: Places, packages: Path) -> list[Step]:
168
+ snippet = (packages / "generic" / "mcp.json").read_text().rstrip()
169
+ return [
170
+ Show(f"Add this server to your client's MCP configuration:\n{snippet}"),
171
+ Show(f"If your client reads AGENTS.md, add {packages / 'generic' / 'AGENTS.md'} to your repository's."),
172
+ ]
173
+
174
+
175
+ PLANNERS: dict[str, Callable[[bool, Places, Path], list[Step]]] = {
176
+ "claude-code": _claude_code,
177
+ "codex": _codex,
178
+ "cursor": _cursor,
179
+ "vscode": _vscode,
180
+ "gemini": _gemini,
181
+ "generic": _generic,
182
+ }
183
+
184
+
185
+ def _vscode_user_dir(home: Path) -> Path:
186
+ if sys.platform == "darwin":
187
+ return home / "Library" / "Application Support" / "Code" / "User"
188
+ if sys.platform == "win32":
189
+ return Path(os.environ.get("APPDATA", home / "AppData" / "Roaming")) / "Code" / "User"
190
+ return home / ".config" / "Code" / "User"
191
+
192
+
193
+ def describe(step: Step, places: Places) -> str:
194
+ """One step in words, with paths a reader can compare across machines."""
195
+
196
+ def shown(path: Path | str) -> str:
197
+ text = str(path).replace(str(clients_dir()), "<ekl>/clients")
198
+ return text.replace(str(places.home), "~", 1) if text.startswith(str(places.home)) else text
199
+
200
+ if isinstance(step, Run):
201
+ return "run " + " ".join(shown(a) for a in step.argv)
202
+ if isinstance(step, MergeJson):
203
+ return f"merge {shown(step.path)}: {step.table}.{SERVER_NAME}"
204
+ if isinstance(step, MergeToml):
205
+ return f"merge {shown(step.path)}: [{step.table}]"
206
+ if isinstance(step, Copy):
207
+ return f"copy {shown(step.source)} → {shown(step.target)}"
208
+ return shown(step.text)
209
+
210
+
211
+ def apply(step: Step) -> str:
212
+ """Do one step; say whether it changed anything."""
213
+ if isinstance(step, Run):
214
+ done = subprocess.run(step.argv, capture_output=True, text=True, check=False)
215
+ said = (done.stdout + done.stderr).strip()
216
+ if done.returncode and not any(w in said.lower() for w in ("already", "up to date", "latest version")):
217
+ raise CliError("EKL-803", str(said or done.returncode), command=" ".join(step.argv[:3]))
218
+ return "done" if not done.returncode else "already there"
219
+ if isinstance(step, MergeJson):
220
+ return _merge_json(step)
221
+ if isinstance(step, MergeToml):
222
+ return _merge_toml(step)
223
+ if isinstance(step, Copy):
224
+ return _copy(step)
225
+ return ""
226
+
227
+
228
+ def _write(path: Path, text: str) -> str:
229
+ """Write a configuration file, keeping the previous one as .bak; nothing happens when it is already so."""
230
+ if path.exists():
231
+ before = path.read_text()
232
+ if before == text:
233
+ return "unchanged"
234
+ path.with_name(path.name + ".bak").write_text(before)
235
+ path.parent.mkdir(parents=True, exist_ok=True)
236
+ path.write_text(text)
237
+ return "updated"
238
+
239
+
240
+ def _merge_json(step: MergeJson) -> str:
241
+ data: dict[str, Any] = {}
242
+ if step.path.exists() and step.path.read_text().strip():
243
+ try:
244
+ data = json.loads(step.path.read_text())
245
+ except ValueError as exc:
246
+ raise CliError("EKL-802", f"It isn't valid JSON: {exc}.", path=step.path) from exc
247
+ if not isinstance(data, dict) or not isinstance(data.setdefault(step.table, {}), dict):
248
+ raise CliError("EKL-802", "It has an unexpected shape.", path=step.path)
249
+ data[step.table][SERVER_NAME] = step.entry
250
+ return _write(step.path, json.dumps(data, indent=2) + "\n")
251
+
252
+
253
+ def _merge_toml(step: MergeToml) -> str:
254
+ text = step.path.read_text() if step.path.exists() else ""
255
+ block = f"[{step.table}]\n{step.body}\n"
256
+ header = re.compile(rf"^\[{re.escape(step.table)}\]\s*$", re.M)
257
+ found = header.search(text)
258
+ if found:
259
+ following = re.compile(r"^\[", re.M).search(text, found.end())
260
+ end = following.start() if following else len(text)
261
+ merged = text[: found.start()] + block + ("\n" if following else "") + text[end:].lstrip("\n")
262
+ else:
263
+ merged = text + ("\n" if text and not text.endswith("\n\n") else "") + block
264
+ # Parsed before writing: a merge that would leave the file unreadable is refused, not written.
265
+ try:
266
+ tomllib.loads(merged)
267
+ except tomllib.TOMLDecodeError as exc:
268
+ raise CliError("EKL-802", f"It isn't valid TOML: {exc}.", path=step.path) from exc
269
+ return _write(step.path, merged)
270
+
271
+
272
+ def _copy(step: Copy) -> str:
273
+ if step.target.exists() and not _differs(filecmp.dircmp(step.source, step.target)):
274
+ return "unchanged"
275
+ shutil.copytree(step.source, step.target, dirs_exist_ok=True)
276
+ return "updated"
277
+
278
+
279
+ def _differs(compared: filecmp.dircmp[str]) -> bool:
280
+ # Files only in the target are the user's own and don't count; copytree never removes them.
281
+ if compared.left_only or compared.diff_files or compared.funny_files:
282
+ return True
283
+ return any(_differs(sub) for sub in compared.subdirs.values())
284
+
285
+
286
+ def run(client: str, *, project: bool = False, dry_run: bool = False, places: Places | None = None) -> str:
287
+ """Set up one client (or, with dry_run, only say what would change) and say what to do next."""
288
+ places = places or Places(Path.home(), Path.cwd(), shutil.which)
289
+ steps = plan(client, project, places)
290
+ lines = []
291
+ for step in steps:
292
+ line = describe(step, places)
293
+ outcome = "" if dry_run else apply(step)
294
+ lines.append(f"{line} ({outcome})" if outcome else line)
295
+ if not dry_run and not project and client != "generic":
296
+ _record(client)
297
+ try:
298
+ Credentials.load()
299
+ signed_in = True
300
+ except CliError:
301
+ signed_in = False
302
+ if not signed_in:
303
+ lines.append("Then sign in: ekl login")
304
+ lines.append(f"Restart {TITLES[client]}, then ask it to list your agents.")
305
+ return "\n".join(lines)
306
+
307
+
308
+ def recorded() -> list[str]:
309
+ """The clients set up for this user, which `ekl upgrade` sets up again. A repository's own setup (--project) is
310
+ the repository's to change, so it isn't kept."""
311
+ try:
312
+ found = json.loads((config_dir() / "setup.json").read_text()).get("clients")
313
+ except (OSError, ValueError, AttributeError):
314
+ return []
315
+ return [c for c in found if c in CLIENTS] if isinstance(found, list) else []
316
+
317
+
318
+ def _record(client: str) -> None:
319
+ clients = recorded()
320
+ if client in clients:
321
+ return
322
+ try:
323
+ config_dir().mkdir(mode=0o700, parents=True, exist_ok=True)
324
+ (config_dir() / "setup.json").write_text(json.dumps({"clients": [*clients, client]}, indent=2) + "\n")
325
+ except OSError:
326
+ pass # only means ekl upgrade won't set this client up again
ekl_cli/supervise.py ADDED
@@ -0,0 +1,162 @@
1
+ # Copyright © 2026 EuKreate, Inc. All rights reserved.
2
+ """The agent kept running on this machine after `ekl deploy` for a server on this machine returns (spec 13.14.8).
3
+
4
+ `start` launches this module as its own process, in its own session, so closing the terminal doesn't stop it. It runs
5
+ the agent's command and starts it again whenever it stops, waiting longer after each quick failure; the connector's
6
+ output goes to `.ekl/local.log` in the agent folder, and `.ekl/local.json` says which process supervises it. `stop`
7
+ ends the supervisor, which ends the agent's process on its way out. Availability is this machine's: asleep or offline,
8
+ the agent is away, and its calls are answered as such until it is back.
9
+
10
+ python -m ekl_cli.supervise <folder> -- <command…>
11
+ """
12
+
13
+ import contextlib
14
+ import json
15
+ import os
16
+ import signal
17
+ import subprocess
18
+ import sys
19
+ import time
20
+ from pathlib import Path
21
+ from types import FrameType
22
+ from typing import Any
23
+
24
+ STATE, LOG = ".ekl/local.json", ".ekl/local.log"
25
+ # Waits before each restart after a run that ended within a minute; a run that lasted longer starts again at once.
26
+ BACKOFF_SECONDS = (1, 2, 5, 10, 30, 60)
27
+ STEADY_SECONDS = 60
28
+ LOG_BYTES = 5_000_000
29
+ STOP_SECONDS = 10
30
+
31
+
32
+ def state_file(folder: Path) -> Path:
33
+ return folder / STATE
34
+
35
+
36
+ def log_file(folder: Path) -> Path:
37
+ return folder / LOG
38
+
39
+
40
+ def read_state(folder: Path) -> dict[str, Any] | None:
41
+ """What supervises the agent here, or None when nothing does (never started, stopped, or its process is gone)."""
42
+ try:
43
+ found: dict[str, Any] = json.loads(state_file(folder).read_text())
44
+ except (OSError, ValueError):
45
+ return None
46
+ pid = int(found.get("pid") or 0)
47
+ if pid <= 0 or not _alive(pid):
48
+ return None
49
+ return found
50
+
51
+
52
+ def _alive(pid: int) -> bool:
53
+ try:
54
+ os.kill(pid, 0)
55
+ except ProcessLookupError:
56
+ return False
57
+ except PermissionError:
58
+ return True
59
+ return True
60
+
61
+
62
+ def start(folder: Path, argv: list[str], env: dict[str, str], cwd: Path | None, about: str) -> dict[str, Any]:
63
+ """Start the supervisor and return what it records. `env` is the agent's whole environment: it reaches the
64
+ process directly, never a command line or a file."""
65
+ (folder / ".ekl").mkdir(parents=True, exist_ok=True)
66
+ log = log_file(folder)
67
+ if log.exists() and log.stat().st_size > LOG_BYTES:
68
+ log.replace(log.with_suffix(".log.1"))
69
+ command = [sys.executable, "-m", "ekl_cli.supervise", str(folder.resolve()), "--", *argv]
70
+ with log.open("ab") as out:
71
+ # Its own session: the terminal closing, or Ctrl-C in it, reaches neither the supervisor nor the agent.
72
+ process = subprocess.Popen(
73
+ command,
74
+ env={**os.environ, **env},
75
+ cwd=cwd,
76
+ stdin=subprocess.DEVNULL,
77
+ stdout=out,
78
+ stderr=subprocess.STDOUT,
79
+ start_new_session=True,
80
+ )
81
+ state = {"pid": process.pid, "started_at": int(time.time()), "about": about, "log": str(log)}
82
+ state_file(folder).write_text(json.dumps(state))
83
+ return state
84
+
85
+
86
+ def stop(folder: Path) -> bool:
87
+ """End the supervisor and the agent with it. False when nothing ran."""
88
+ found = read_state(folder)
89
+ with contextlib.suppress(OSError):
90
+ state_file(folder).unlink()
91
+ if found is None:
92
+ return False
93
+ pid = int(found["pid"])
94
+ with contextlib.suppress(ProcessLookupError):
95
+ os.kill(pid, signal.SIGTERM)
96
+ deadline = time.monotonic() + STOP_SECONDS + 2
97
+ while _alive(pid) and time.monotonic() < deadline:
98
+ time.sleep(0.1)
99
+ if _alive(pid):
100
+ with contextlib.suppress(ProcessLookupError):
101
+ os.kill(pid, signal.SIGKILL)
102
+ return True
103
+
104
+
105
+ def tail(folder: Path, lines: int = 15) -> list[str]:
106
+ try:
107
+ return log_file(folder).read_text(errors="replace").splitlines()[-lines:]
108
+ except OSError:
109
+ return []
110
+
111
+
112
+ def _say(line: str) -> None:
113
+ print(f"{time.strftime('%Y-%m-%d %H:%M:%S')} ekl: {line}", flush=True)
114
+
115
+
116
+ def supervise(argv: list[str]) -> int:
117
+ """Run `argv` until told to stop, starting it again whenever it stops."""
118
+ child: subprocess.Popen[bytes] | None = None
119
+ stopping = False
120
+
121
+ def on_stop(_signum: int, _frame: FrameType | None) -> None:
122
+ nonlocal stopping
123
+ stopping = True
124
+ if child is not None and child.poll() is None:
125
+ child.terminate()
126
+
127
+ signal.signal(signal.SIGTERM, on_stop)
128
+ signal.signal(signal.SIGINT, on_stop)
129
+ failures = 0
130
+ while not stopping:
131
+ started = time.monotonic()
132
+ _say("starting the agent")
133
+ child = subprocess.Popen(argv)
134
+ try:
135
+ code = child.wait()
136
+ except KeyboardInterrupt:
137
+ code = 0
138
+ if stopping:
139
+ with contextlib.suppress(subprocess.TimeoutExpired):
140
+ child.wait(STOP_SECONDS)
141
+ if child.poll() is None:
142
+ child.kill()
143
+ break
144
+ failures = 0 if time.monotonic() - started >= STEADY_SECONDS else min(failures + 1, len(BACKOFF_SECONDS))
145
+ wait = BACKOFF_SECONDS[failures - 1] if failures else 0
146
+ _say(f"the agent stopped (exit code {code}); starting it again in {wait} s")
147
+ deadline = time.monotonic() + wait
148
+ while not stopping and time.monotonic() < deadline:
149
+ time.sleep(0.2)
150
+ _say("stopped")
151
+ return 0
152
+
153
+
154
+ def main() -> None:
155
+ args = sys.argv[1:]
156
+ if "--" not in args or args.index("--") != 1 or len(args) < 3:
157
+ sys.exit("usage: python -m ekl_cli.supervise <folder> -- <command…>")
158
+ sys.exit(supervise(args[2:]))
159
+
160
+
161
+ if __name__ == "__main__":
162
+ main()