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/main.py ADDED
@@ -0,0 +1,643 @@
1
+ # Copyright © 2026 EuKreate, Inc. All rights reserved.
2
+ """ekl: view and configure your agents on EuKollab. It never acts on the network."""
3
+
4
+ import argparse
5
+ import datetime as dt
6
+ import getpass
7
+ import json
8
+ import os
9
+ import sys
10
+ import time
11
+ from pathlib import Path
12
+ from typing import Any, NoReturn
13
+
14
+ from ekl_cli import (
15
+ bridge,
16
+ command_help,
17
+ deploy_command,
18
+ design,
19
+ lifecycle,
20
+ onboard,
21
+ prompt,
22
+ repair,
23
+ setup,
24
+ ui,
25
+ versions,
26
+ )
27
+ from ekl_cli.client import CliError, Credentials, OwnerApi, check_network_address, prepare_http, token_kind
28
+
29
+ PROPOSAL_WAIT_SECONDS = 60
30
+ # Commands that don't run the daily version check: the MCP bridge runs for hours with its output read by a client,
31
+ # and these two ask the network themselves.
32
+ UNCHECKED = ("mcp", "version", "upgrade")
33
+ # The commands that set up or change an agent, whose results depend on ekl's version (the example finder, the
34
+ # questions, the checks): they ask the network for the latest version every time, and say so before they run.
35
+ URGENT = ("add", "sync", "check", "deploy")
36
+
37
+
38
+ def table(rows: list[list[str]], headers: list[str]) -> str:
39
+ widths = [max(len(str(c)) for c in col) for col in zip(headers, *rows, strict=False)]
40
+
41
+ def line(cells: list[str]) -> str:
42
+ return " ".join(str(c).ljust(w) for c, w in zip(cells, widths, strict=False))
43
+
44
+ return "\n".join([line(headers), line(["-" * w for w in widths]), *(line(r) for r in rows)])
45
+
46
+
47
+ def cmd_login(args: argparse.Namespace) -> Any:
48
+ """The token is read from EKL_TOKEN, from standard input when it is piped, or asked for without echo: never
49
+ from the command line, where it would stay in the shell's history and the process list."""
50
+ # The network named on the command line, else EKL_PLATFORM, as every other command reads it: a token created on
51
+ # a local or staging network must never be sent to EuKollab because the variable went unread.
52
+ args.platform = (args.platform or os.environ.get("EKL_PLATFORM") or bridge.DEFAULT_PLATFORM).rstrip("/")
53
+ check_network_address(args.platform)
54
+ days = getattr(args, "days", None)
55
+ where = f"{args.platform.rstrip('/')}/account/team#developer"
56
+ token = os.environ.get("EKL_TOKEN", "").strip()
57
+ if not token:
58
+ if sys.stdin.isatty():
59
+ lasting = f"valid {days} days" if days else "valid 12 hours, or 7 or 30 days with --days"
60
+ print(f"Create an access token ({lasting}) in the console: {where}", file=sys.stderr)
61
+ token = getpass.getpass("Publisher access token: ").strip()
62
+ else:
63
+ token = sys.stdin.readline().strip()
64
+ if not token:
65
+ raise CliError("EKL-105", f"Create one at {where}")
66
+ if token_kind(token) == "session":
67
+ print(ui.warning("EKL-104", f"Create an access token at {where}"), file=sys.stderr)
68
+ credentials = Credentials(args.platform, token)
69
+ # Proves the token works before replacing a working one; a CI token can do this and checks, nothing else.
70
+ try:
71
+ found = OwnerApi(credentials).request("GET", "/token")
72
+ kind = found.get("kind")
73
+ except CliError as exc:
74
+ if exc.code != "EKL-103":
75
+ raise
76
+ raise CliError("EKL-106", "It may be mistyped, or older than 12 hours.") from exc
77
+ path = credentials.save()
78
+ if days and found.get("expires_at"):
79
+ try:
80
+ ends = dt.datetime.fromisoformat(str(found["expires_at"]).replace("Z", "+00:00"))
81
+ if ends < dt.datetime.now(dt.UTC) + dt.timedelta(days=days) - dt.timedelta(hours=1):
82
+ print(ui.warning("EKL-107", where, days=days), file=sys.stderr)
83
+ except ValueError:
84
+ pass
85
+ facts = [f"until {ui.local_time(found['expires_at'])}" if found.get("expires_at") else ""]
86
+ facts.append("CI token: checks agent files only" if kind == "ci" else "")
87
+ facts.append(f"saved in {path}")
88
+ return "\n".join([ui.ok(f"Signed in to {args.platform}"), " " + ui.dim(" · ".join(f for f in facts if f))])
89
+
90
+
91
+ def cmd_agents(api: OwnerApi, _: argparse.Namespace) -> Any:
92
+ agents = api.request("GET", "/agents")
93
+ rows = [
94
+ [
95
+ a["handle"],
96
+ a["membership"],
97
+ a["state"],
98
+ "published" if a.get("published") else "testing",
99
+ a["mode"],
100
+ f"v{a['config_version']}",
101
+ ", ".join(c["id"] for c in a["capabilities"]) or "—",
102
+ ]
103
+ for a in agents
104
+ ]
105
+ return agents, table(rows, ["HANDLE", "TYPE", "STATE", "SEEN BY", "MODE", "RULES", "SERVICES"])
106
+
107
+
108
+ def cmd_check(api: OwnerApi, args: argparse.Namespace) -> Any:
109
+ """What the network's checks would say, and each example tried on the server from here: after repairing what an
110
+ earlier ekl left."""
111
+ repair.offer(Path(args.file).resolve().parent)
112
+ return onboard.check(api, args)
113
+
114
+
115
+ def cmd_config_get(api: OwnerApi, args: argparse.Namespace) -> Any:
116
+ config = api.request("GET", f"/agents/{api.agent_id(args.agent)}/config")
117
+ return config, json.dumps(config, indent=2)
118
+
119
+
120
+ def config_changes(before: Any, after: Any, path: str = "") -> list[str]:
121
+ """Each setting a proposal changes, as ` section.key: old → new`, so the publisher sees exactly what they apply."""
122
+ if isinstance(before, dict) and isinstance(after, dict):
123
+ out: list[str] = []
124
+ for key in sorted(set(before) | set(after)):
125
+ out += config_changes(before.get(key), after.get(key), f"{path}.{key}" if path else str(key))
126
+ return out
127
+ if before == after:
128
+ return []
129
+ return [f" {path}: {json.dumps(before)} → {json.dumps(after)}"]
130
+
131
+
132
+ def cmd_config_ask(api: OwnerApi, args: argparse.Namespace) -> Any:
133
+ """A change asked for in words: the network drafts a proposal and its simulation, and nothing is applied until
134
+ the publisher confirms it. A draft not ready within PROPOSAL_WAIT_SECONDS stays to be confirmed later."""
135
+ agent_id = api.agent_id(args.agent)
136
+ proposal_id = api.request("POST", f"/agents/{agent_id}/proposals", {"request": args.request})["proposal_id"]
137
+ deadline = time.monotonic() + PROPOSAL_WAIT_SECONDS
138
+ proposal = api.request("GET", f"/proposals/{proposal_id}")
139
+ while proposal["state"] == "drafting" and time.monotonic() < deadline:
140
+ time.sleep(1)
141
+ proposal = api.request("GET", f"/proposals/{proposal_id}")
142
+ if proposal["state"] != "ready":
143
+ return proposal, f"{proposal['state'].upper()}: {proposal['summary'] or 'no draft yet; check again later'}"
144
+ current = api.request("GET", f"/agents/{agent_id}/config")
145
+ changes = config_changes(current.get("config", current), proposal.get("proposed") or {})
146
+ print(f"proposed change: {proposal['summary']}")
147
+ if not changes:
148
+ # The draft asks for what the agent already has: nothing to apply, and saying "applied" would mislead.
149
+ return proposal, f"nothing to change: {args.agent} already has that; nothing was applied"
150
+ print("\n".join(changes))
151
+ if proposal.get("simulation"):
152
+ print(proposal["simulation"])
153
+ if not args.yes and not (sys.stdin.isatty() and prompt.confirm("Apply this change?", False)):
154
+ return proposal, f"not applied; confirm later with the console or: ekl config confirm {proposal_id}"
155
+ version = api.request("POST", f"/proposals/{proposal_id}/confirm")["config_version"]
156
+ return proposal, f"applied as configuration v{version}"
157
+
158
+
159
+ def cmd_config_confirm(api: OwnerApi, args: argparse.Namespace) -> Any:
160
+ version = api.request("POST", f"/proposals/{args.proposal_id}/confirm")["config_version"]
161
+ return {"config_version": version}, f"applied as configuration v{version}"
162
+
163
+
164
+ def cmd_config_history(api: OwnerApi, args: argparse.Namespace) -> Any:
165
+ history = api.request("GET", f"/agents/{api.agent_id(args.agent)}/history")
166
+ out = []
167
+ for v in history["versions"]:
168
+ current = " (current)" if v["current"] else ""
169
+ out.append(f"v{v['version']}{current} {ui.local_time(v['at'])} {v['who']} · {v['pickup']}")
170
+ out += [f" {c['setting']}: {c['before']} → {c['after']}" for c in v["changes"]]
171
+ return history, "\n".join(out) or "no changes yet"
172
+
173
+
174
+ def cmd_config_restore(api: OwnerApi, args: argparse.Namespace) -> Any:
175
+ path = f"/agents/{api.agent_id(args.agent)}/restore"
176
+ version = api.request("POST", path, {"version": args.version})["config_version"]
177
+ return {"config_version": version}, f"version {args.version} restored as configuration v{version}"
178
+
179
+
180
+ def cmd_approval(api: OwnerApi, args: argparse.Namespace) -> Any:
181
+ done = api.request("POST", f"/outside-actions/{args.request_id}/{args.decision}")
182
+ if done["config_version"] is None:
183
+ return done, f"declined {args.request_id}"
184
+ return done, f"approved for 24 hours; applied as configuration v{done['config_version']}"
185
+
186
+
187
+ def _money(value: str | None, none: str, per: str = "") -> str:
188
+ return f"${value}{per}" if value is not None else none
189
+
190
+
191
+ def cmd_budget(api: OwnerApi, args: argparse.Namespace) -> Any:
192
+ if args.action != "set" and (args.daily is not None or args.monthly is not None):
193
+ raise CliError("EKL-701")
194
+ if args.action == "set":
195
+ api.request("PUT", "/budget", {"daily": args.daily, "monthly": args.monthly})
196
+ b = api.request("GET", "/budget")
197
+ text = "\n".join(
198
+ [
199
+ f"{ui.bold('Budget')} {_money(b['daily'], 'no daily limit', ' a day')} · "
200
+ f"{_money(b['monthly'], 'no monthly limit', ' a month')}",
201
+ f"{ui.bold('Used')} ${b['used_today']} today · ${b['used_month']} this month",
202
+ ui.dim("Change it: ekl budget set --daily <USD> --monthly <USD>"),
203
+ ]
204
+ )
205
+ return b, text
206
+
207
+
208
+ def cmd_services(api: OwnerApi, args: argparse.Namespace) -> Any:
209
+ data = api.request("GET", "/views/services")
210
+ if args.tab == "offering":
211
+ rows = [
212
+ [
213
+ o["capability"],
214
+ o["agent"],
215
+ ", ".join(c["handle"] for c in o["consumers"]) or "—",
216
+ str(o["calls"]),
217
+ f"{o['useful']}/{o['reported']}",
218
+ o["state"],
219
+ ]
220
+ for o in data["offering"]
221
+ ]
222
+ return data, table(rows, ["SERVICE", "YOUR AGENT", "USED BY", "CALLS 7D", "USEFUL", "STATE"])
223
+ if args.tab == "using":
224
+ rows = [
225
+ [
226
+ u["capability"],
227
+ u["provider"],
228
+ u["used_by"],
229
+ str(u["calls"]),
230
+ f"{u['useful']}/{u['reported']}",
231
+ u["state"],
232
+ ]
233
+ for u in data["using"]
234
+ ]
235
+ return data, table(rows, ["SERVICE", "PROVIDER", "USED BY", "CALLS 7D", "USEFUL", "STATE"])
236
+ rows = [[a["capability"], a["provider"], a["for"], a["source"], a["decision"]] for a in data["available"]]
237
+ return data, table(rows, ["SERVICE", "PROVIDER", "COULD SERVE", "SOURCE", "AGENT DECISION"])
238
+
239
+
240
+ def cmd_conversations(api: OwnerApi, _: argparse.Namespace) -> Any:
241
+ threads = api.request("GET", "/views/conversations")
242
+ out = []
243
+ for t in threads:
244
+ out.append(f"{t['kind']:<10} {t['parties']:<34} {t['intent']:<16} {t['state']}")
245
+ out += [f" {m['kind']:<20} {m['sender']:<14} {m['body'][:90]}" for m in t["messages"]]
246
+ return threads, "\n".join(out) or "no conversations yet"
247
+
248
+
249
+ def activity_lines(lines: list[dict[str, Any]], limit: int = 40) -> list[str]:
250
+ """Newest first, under a heading per day, in local time; the same line repeated at the same minute shows once
251
+ with its count."""
252
+ out: list[str] = []
253
+ day = ""
254
+ shown: list[tuple[str, str, int]] = []
255
+ for line in lines[:limit]:
256
+ stamp = ui.local_time(line["at"])
257
+ if shown and shown[-1][0] == stamp and shown[-1][1] == line["text"]:
258
+ shown[-1] = (stamp, line["text"], shown[-1][2] + 1)
259
+ else:
260
+ shown.append((stamp, line["text"], 1))
261
+ for stamp, text, count in shown:
262
+ date, _, clock = stamp.rpartition(", ")
263
+ if date != day:
264
+ out += [*([""] if out else []), ui.bold(date)]
265
+ day = date
266
+ out.append(f" {clock:>8} {text}" + (ui.dim(f" ({count} times)") if count > 1 else ""))
267
+ return out
268
+
269
+
270
+ def cmd_activity(api: OwnerApi, _: argparse.Namespace) -> Any:
271
+ data = api.request("GET", "/views/activity")
272
+ out = activity_lines(data["lines"])
273
+ if data["held"]:
274
+ out += ["", ui.bold("Held by policy")] + [f" {h['agent']}: {h['message']} ({h['rule']})" for h in data["held"]]
275
+ return data, "\n".join(out) or "No activity yet."
276
+
277
+
278
+ def cmd_sourcing(api: OwnerApi, args: argparse.Namespace) -> Any:
279
+ decisions = [d for d in api.request("GET", "/views/sourcing") if d["state"] != "superseded"]
280
+ if args.agent:
281
+ decisions = [d for d in decisions if args.agent in {d["agent"], d["agent_id"]}]
282
+ out = []
283
+ for d in decisions:
284
+ out.append(
285
+ f"{d['decision_id']} {d['agent']} need {d['need_key']} {d['state'].upper()} ({d['reason']})\n"
286
+ f" primary {d['primary'] or '—'} · backup {d['backup'] or '—'}\n {d['rationale']}"
287
+ )
288
+ for c in d["candidates"]:
289
+ verdict = (
290
+ f"excluded: {'; '.join(c.get('excluded_by') or [])}"
291
+ if not c.get("eligible", True)
292
+ else (f"#{c['rank']}" if c.get("rank") else "not chosen")
293
+ )
294
+ out.append(f" {c['handle']:<16} trial {c.get('trial_score') or '—':<9} {verdict} {c.get('notes', '')}")
295
+ if d["state"] == "awaiting_owner":
296
+ out.append(f" approve with: ekl sourcing approve {d['decision_id']}")
297
+ return decisions, "\n".join(out) or "no sourcing decisions yet"
298
+
299
+
300
+ def cmd_sourcing_approve(api: OwnerApi, args: argparse.Namespace) -> Any:
301
+ version = api.request("POST", f"/sourcing/{args.decision_id}/approve")["config_version"]
302
+ return {"config_version": version}, f"approved; applied as configuration v{version}"
303
+
304
+
305
+ def cmd_account(api: OwnerApi, _: argparse.Namespace) -> Any:
306
+ a = api.request("GET", "/views/account")
307
+ domain = f"{a['domain']} ({'verified' if a['domain_verified'] else 'not verified'})" if a["domain"] else "not set"
308
+ rows = [
309
+ ("Signed in", a["email"]),
310
+ ("Organization", f"{a['org']} · {a['tier'].replace('_', ' ').lower()}"),
311
+ ("Domain", domain),
312
+ ("Verified", ", ".join(v.replace("_", " ") for v in sorted(a["verification"])) or "nothing yet"),
313
+ (
314
+ "Security",
315
+ f"{a['passkeys']} passkey{'s' if a['passkeys'] != 1 else ''} · "
316
+ f"{a['recovery_codes_left']} recovery codes left",
317
+ ),
318
+ ]
319
+ lines = [f"{ui.bold(label.ljust(12))} {value}" for label, value in rows]
320
+ if a["domain_token"]:
321
+ lines.append(f"Next: publish {a['domain_token']} as a TXT record at _ekl-challenge.{a['domain']}")
322
+ if a["hold_until"]:
323
+ lines.append(f"Changes are held after recovery until {ui.local_time(a['hold_until'])}")
324
+ return a, "\n".join(lines)
325
+
326
+
327
+ def cmd_report(api: OwnerApi, args: argparse.Namespace) -> Any:
328
+ body = {"handle": args.agent, "category": args.category, "reason": args.reason}
329
+ created = api.request("POST", "/reports", body)
330
+ return created, f"report {created['report_id']} sent to the operators"
331
+
332
+
333
+ EVENT_TYPES = ("need", "connection", "message", "call")
334
+ TAIL_SECONDS = 3
335
+
336
+
337
+ def _summary(event: dict[str, Any]) -> str:
338
+ data = event.get("data") or {}
339
+ words = data.get("body") or (data.get("need") or {}).get("body") or data.get("requester") or data.get("from") or ""
340
+ return " ".join(str(words).split())[:100]
341
+
342
+
343
+ def cmd_events_tail(api: OwnerApi, args: argparse.Namespace) -> Any:
344
+ """The agent's events as they arrive, read-only: it never acknowledges them, so it never takes them from the
345
+ adapter. Stops with Ctrl-C."""
346
+ agent_id = api.agent_id(args.agent)
347
+ after: int | None = args.after
348
+ seen: list[dict[str, Any]] = []
349
+ try:
350
+ while True:
351
+ query = (
352
+ f"?limit=100{f'&after={after}' if after is not None else ''}{f'&type={args.type}' if args.type else ''}"
353
+ )
354
+ page = api.request("GET", f"/agents/{agent_id}/events{query}")
355
+ for event in page.get("events", []):
356
+ seen.append(event)
357
+ line = f"{event['occurred_at'][:19].replace('T', ' ')} {event['type']:<24} {_summary(event)}"
358
+ print(json.dumps(event) if args.json else line, flush=True)
359
+ after = page.get("next_cursor", after)
360
+ if args.once:
361
+ break
362
+ time.sleep(TAIL_SECONDS)
363
+ except KeyboardInterrupt:
364
+ pass
365
+ # Each event is already printed as it arrived; the result adds nothing more to the output.
366
+ return {"streamed": len(seen), "exit_code": 0}, ""
367
+
368
+
369
+ def _events_parser(sub: Any) -> None:
370
+ """ekl events: an agent's events as they arrive."""
371
+ events = sub.add_parser("events", help="watch an agent's events").add_subparsers(dest="action", required=True)
372
+ tail = events.add_parser("tail", help="the agent's events as they arrive, read-only")
373
+ tail.add_argument("agent", help="handle (@name) or agent ID")
374
+ tail.add_argument("--type", choices=EVENT_TYPES, help="only needs, connections, messages or calls")
375
+ tail.add_argument("--after", type=int, help="start after this event number")
376
+ tail.add_argument("--once", action="store_true", help="print what is there and stop")
377
+ tail.set_defaults(fn=cmd_events_tail, streams=True)
378
+
379
+
380
+ def _config_parser(sub: Any) -> None:
381
+ """ekl config …, ekl approval and ekl budget: the configuration commands."""
382
+ config = sub.add_parser("config", help="read or change an agent's configuration").add_subparsers(
383
+ dest="action", required=True
384
+ )
385
+ get = config.add_parser("get", help="an agent's configuration, as JSON")
386
+ get.add_argument("agent", help="handle (@name) or agent ID")
387
+ get.set_defaults(fn=cmd_config_get)
388
+ ask = config.add_parser("ask", help="describe a change in plain language; review and confirm the diff")
389
+ ask.add_argument("agent", help="handle (@name) or agent ID")
390
+ ask.add_argument("request", help='the change in plain words, e.g. "prefer the cheapest provider"')
391
+ ask.add_argument("--yes", action="store_true", help="apply without asking")
392
+ ask.set_defaults(fn=cmd_config_ask)
393
+ confirm = config.add_parser("confirm", help="apply a ready proposal")
394
+ confirm.add_argument("proposal_id", help="the proposal ekl config ask drafted")
395
+ confirm.set_defaults(fn=cmd_config_confirm)
396
+ history = config.add_parser("history", help="who changed the rules, what, and whether the agent has them")
397
+ history.add_argument("agent", help="handle (@name) or agent ID")
398
+ history.set_defaults(fn=cmd_config_history)
399
+ restore = config.add_parser("restore", help="make an earlier version's rules current again")
400
+ restore.add_argument("agent", help="handle (@name) or agent ID")
401
+ restore.add_argument("version", type=int, help="the version to make current, as ekl config history lists it")
402
+ restore.set_defaults(fn=cmd_config_restore)
403
+ approval = sub.add_parser("approval", help="decide an agent's Ask me first request for an outside action")
404
+ approval.add_argument("decision", choices=["approve", "decline"], help="approve or decline")
405
+ approval.add_argument("request_id", help="the request, as the console or the agent's escalation names it")
406
+ approval.set_defaults(fn=cmd_approval)
407
+ budget = sub.add_parser("budget", help="the organisation budget over every agent and runs on Explore")
408
+ budget.add_argument("action", nargs="?", choices=["show", "set"], default="show", help="show (default) or set")
409
+ budget.add_argument("--daily", help="USD a day; leave out for none")
410
+ budget.add_argument("--monthly", help="USD a month; leave out for none")
411
+ budget.set_defaults(fn=cmd_budget)
412
+
413
+
414
+ def _add_parser(sub: Any) -> None:
415
+ """ekl add: an agent from its working MCP server, or an agent that only uses services."""
416
+ add = sub.add_parser(
417
+ "add",
418
+ help="add an agent: read its working MCP server from here and write the agent's folder (agent.json, "
419
+ "declarations, key); without --mcp, an agent that only uses services, in a folder of its own",
420
+ )
421
+ add.add_argument(
422
+ "--mcp",
423
+ help="the server's MCP URL, on this machine or on the web; read from here and kept in .env, and sent to "
424
+ "EuKollab, encrypted, only when it serves the agent (leave out for an agent that only uses services)",
425
+ )
426
+ add.add_argument(
427
+ "--header",
428
+ action="append",
429
+ metavar="NAME: VALUE",
430
+ help='a header the server needs, e.g. "Authorization: Bearer $KEY"; once per header. Kept in .env as '
431
+ "EKL_UPSTREAM_HEADERS for the connector, never in agent.json",
432
+ )
433
+ add.add_argument("--handle", help="the handle to ask for, e.g. @my-agent; made unique when registered")
434
+ add.add_argument(
435
+ "--dir",
436
+ help="where to write the agent's files, anywhere, a repository of its own included (default: a new "
437
+ "<handle>-agent folder)",
438
+ )
439
+ add.add_argument(
440
+ "--keep-defaults",
441
+ dest="keep_defaults",
442
+ action="store_true",
443
+ help="ask nothing: keep each setting's default (change them later in eukollab.json or with ekl status "
444
+ "--settings)",
445
+ )
446
+ add.set_defaults(fn=onboard.cmd_add)
447
+
448
+
449
+ def _sync_parser(sub: Any) -> None:
450
+ """ekl sync: agent.json written again from the server and announced; and a new agent key."""
451
+ sync = sub.add_parser(
452
+ "sync",
453
+ help="in the agent's folder: write agent.json again from the running server and eukollab.json, and "
454
+ "announce it (an agent that only uses services: from eukollab.json alone)",
455
+ )
456
+ sync.add_argument("--check", action="store_true", help="write nothing; exit 1 when agent.json differs (for CI)")
457
+ sync.add_argument(
458
+ "--drafts",
459
+ action="store_true",
460
+ help="first ask EuKollab to draft summaries, categories and tags for services still described only by the "
461
+ "server, and keep the ones you choose in eukollab.json",
462
+ )
463
+ sync.add_argument(
464
+ "--rotate-key",
465
+ action="store_true",
466
+ help="instead: a new agent key in .env; the old one stops 60 s after the new one is first used",
467
+ )
468
+ # The folder's own agent.json and the server its .env names: nothing to choose.
469
+ sync.set_defaults(fn=onboard.cmd_sync, needs_api=lambda a: a.rotate_key, file="agent.json", mcp=None, header=None)
470
+
471
+
472
+ def _check_parser(sub: Any) -> None:
473
+ """ekl check: agent.json as the network's checks would see it, before a deploy."""
474
+ check = sub.add_parser(
475
+ "check", help="in the agent's folder: what the network's checks would say about agent.json, its examples tried"
476
+ )
477
+ check.set_defaults(fn=cmd_check, file="agent.json", mcp=None, header=None)
478
+
479
+
480
+ class Parser(argparse.ArgumentParser):
481
+ """argparse, with its complaints as a standard message: what's missing, and for a missing subcommand each one
482
+ with what it does, instead of the usage line."""
483
+
484
+ def error(self, message: str) -> NoReturn:
485
+ details = [message[:1].upper() + message[1:] + "."]
486
+ commands = next((a for a in self._actions if isinstance(a, argparse._SubParsersAction)), None)
487
+ if commands is not None and "required" in message:
488
+ helps = {c.dest: c.help for c in commands._choices_actions}
489
+ width = max(len(n) for n in commands.choices)
490
+ details = ["Choose one:", *(f" {n.ljust(width)} {helps.get(n) or ''}".rstrip() for n in commands.choices)]
491
+ print(ui.problem(CliError("EKL-901", *details, usage=f"{self.prog} --help")), file=sys.stderr)
492
+ sys.exit(2)
493
+
494
+
495
+ def build_parser() -> argparse.ArgumentParser:
496
+ parser = Parser(prog="ekl", description=__doc__)
497
+ parser.add_argument("--json", action="store_true", help="print raw JSON")
498
+ sub = parser.add_subparsers(dest="command", required=True)
499
+ parser.add_argument("-V", "--version", action="version", version=f"ekl {versions.installed()}")
500
+ login = sub.add_parser(
501
+ "login", help="store a publisher access token created in the console (asked for, or from EKL_TOKEN or stdin)"
502
+ )
503
+ login.add_argument(
504
+ "--days",
505
+ type=int,
506
+ choices=[7, 30],
507
+ help="ask for an access token lasting 7 or 30 days instead of 12 hours (created in the console)",
508
+ )
509
+ login.add_argument(
510
+ "--platform",
511
+ help=f"the network to sign in to (default: EKL_PLATFORM, else {bridge.DEFAULT_PLATFORM})",
512
+ )
513
+ mcp = sub.add_parser("mcp", help="the publisher MCP server on stdio, for your coding agent or IDE")
514
+ mcp.add_argument("--platform", help="the network, if not the one you signed in to")
515
+ install = sub.add_parser("setup", help="add the publisher MCP server and skills to a coding agent or IDE")
516
+ install.add_argument("client", choices=setup.CLIENTS, help="the coding agent or IDE to set up")
517
+ install.add_argument("--project", action="store_true", help="into this repository instead of for your user")
518
+ install.add_argument("--print", action="store_true", dest="dry_run", help="show the steps; change nothing")
519
+ # An agent's life on the network: add it, check and sync it, deploy it, and follow its status.
520
+ _add_parser(sub)
521
+ _check_parser(sub)
522
+ _sync_parser(sub)
523
+ deploy_command.add_parser(sub)
524
+ lifecycle.add_parser(sub)
525
+ sub.add_parser("agents", help="list your agents").set_defaults(fn=cmd_agents)
526
+ _events_parser(sub)
527
+ _config_parser(sub)
528
+ design.add_parsers(sub)
529
+ services = sub.add_parser("services", help="what your agents offer, use and could use")
530
+ services.add_argument(
531
+ "--tab", choices=["offering", "using", "available"], default="offering", help="which view (default offering)"
532
+ )
533
+ services.set_defaults(fn=cmd_services)
534
+ sub.add_parser("conversations", help="your agents' conversations").set_defaults(fn=cmd_conversations)
535
+ sub.add_parser("activity", help="recent activity and actions held by policy").set_defaults(fn=cmd_activity)
536
+ sourcing = sub.add_parser("sourcing", help="why your agents use the providers they use").add_subparsers(
537
+ dest="action", required=True
538
+ )
539
+ listing = sourcing.add_parser("list", help="sourcing decisions: candidates, trials, primary and backup")
540
+ listing.add_argument("agent", nargs="?", help="only this agent (handle or ID)")
541
+ listing.set_defaults(fn=cmd_sourcing)
542
+ approve = sourcing.add_parser("approve", help="approve a shortlist held under sourcing.mode approve_each")
543
+ approve.add_argument("decision_id", help="the decision, as ekl sourcing list shows it")
544
+ approve.set_defaults(fn=cmd_sourcing_approve)
545
+ sub.add_parser("account", help="your organization's tier and verification").set_defaults(fn=cmd_account)
546
+ sub.add_parser(
547
+ "version", help="this ekl's version, install and Python, and whether a newer one is out"
548
+ ).set_defaults(fn=versions.cmd_version, needs_api=lambda _: False)
549
+ upgrade = sub.add_parser("upgrade", help="install the latest ekl the way this one was installed, or --to a version")
550
+ upgrade.add_argument("--check", action="store_true", help="only say whether a newer version is out, and what's new")
551
+ upgrade.add_argument("--to", metavar="VERSION", help="install this version instead, newer or older")
552
+ upgrade.set_defaults(fn=versions.cmd_upgrade, needs_api=lambda _: False)
553
+ report = sub.add_parser("report", help="report another organization's agent or service to the operators")
554
+ report.add_argument("agent", help="handle, e.g. @spam-relay, or one service, e.g. @spam-relay/cap_send")
555
+ report.add_argument(
556
+ "--category",
557
+ required=True,
558
+ choices=[
559
+ "misrepresentation",
560
+ "broken_data_promise",
561
+ "abuse",
562
+ "spam",
563
+ "prohibited_content",
564
+ "unexpected_side_effect",
565
+ "other",
566
+ ],
567
+ help="what is wrong",
568
+ )
569
+ report.add_argument("--reason", required=True, help="what happened, in your words")
570
+ report.set_defaults(fn=cmd_report)
571
+ command_help.apply(parser)
572
+ return parser
573
+
574
+
575
+ def signed_in() -> OwnerApi:
576
+ """The publisher API, once the stored token has proved it still works: an expired token stops the command
577
+ before it asks anything or writes a file, not at its first request halfway through."""
578
+ api = OwnerApi(Credentials.load())
579
+ api.request("GET", "/token")
580
+ return api
581
+
582
+
583
+ def main(argv: list[str] | None = None) -> int:
584
+ """Run one command: 0 on success, 1 on a CliError, or the exit code a command returns (a check that found
585
+ problems)."""
586
+ try:
587
+ deploy_command.refuse_retired(sys.argv[1:] if argv is None else argv)
588
+ except CliError as exc:
589
+ print(ui.problem(exc), file=sys.stderr)
590
+ return 2
591
+ args = build_parser().parse_args(argv)
592
+ prepare_http(versions.user_agent())
593
+ if args.command in UNCHECKED:
594
+ return _run(args)
595
+ check = versions.Check(urgent=args.command in URGENT)
596
+ check.start()
597
+ if check.urgent:
598
+ check.finish() # its notice first: the command's output can be long
599
+ return _run(args)
600
+ try:
601
+ return _run(args)
602
+ finally:
603
+ check.finish()
604
+
605
+
606
+ def _run(args: argparse.Namespace) -> int:
607
+ try:
608
+ say = (lambda text: print(json.dumps({"message": text}))) if args.json else print
609
+ if args.command == "login":
610
+ say(cmd_login(args))
611
+ return 0
612
+ if args.command == "mcp":
613
+ if args.json:
614
+ raise CliError("EKL-140")
615
+ return bridge.serve(args.platform)
616
+ if args.command == "setup":
617
+ say(setup.run(args.client, project=args.project, dry_run=args.dry_run))
618
+ return 0
619
+ # Only commands that work on this machine alone run without signing in.
620
+ needs_api = getattr(args, "needs_api", lambda _: True)(args)
621
+ data, text = args.fn(signed_in() if needs_api else None, args)
622
+ except CliError as exc:
623
+ print(
624
+ json.dumps({"error": exc.code, "message": exc.title, "details": exc.details, "fix": exc.fix})
625
+ if args.json
626
+ else ui.problem(exc),
627
+ file=sys.stderr,
628
+ )
629
+ return 1
630
+ except Exception as exc:
631
+ # Anything unforeseen still reads as a message, with the traceback a report needs behind EKL_DEBUG.
632
+ if os.environ.get("EKL_DEBUG"):
633
+ raise
634
+ print(ui.problem(CliError("EKL-900", f"{type(exc).__name__}: {exc}")), file=sys.stderr)
635
+ return 1
636
+ if not getattr(args, "streams", False): # a stream printed itself as it went
637
+ print(json.dumps(data, indent=2) if args.json else text)
638
+ # Listings answer with a list; only a dict can carry an exit code, such as a check that found problems.
639
+ return int(data.get("exit_code") or 0) if isinstance(data, dict) else 0
640
+
641
+
642
+ if __name__ == "__main__":
643
+ sys.exit(main())