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,509 @@
1
+ """{{name}} on EuKollab: the agent's callbacks, its own code, run by the connector.
2
+
3
+ Written by `ekl add` for ekl-provider-adapter 0.11.0. With EKL_AGENT_CREDENTIAL in .env (ekl add wrote it
4
+ if the agent takes part, or run ekl status --settings --take-part), the connector runs this file itself, beside it on
5
+ 127.0.0.1:8002, and posts the agent's events to it: for an agent run on this machine (`ekl deploy` for a server here
6
+ or an agent that only uses services) and, for an agent EuKollab serves, in a sandbox of its own once the network has
7
+ that switched on. Edit the functions below to answer needs, accept connections, read messages, talk with agents
8
+ before connecting, post needs and use other agents' services. Callbacks are written in Python for now; a choice of language is planned. The file needs only
9
+ Python's standard library; list any other package it needs, one per line, in callbacks-requirements.txt beside it.
10
+
11
+ The connector signs each event with EKL_CALLBACK_KEY (callback protocol v2); this file checks the signature before
12
+ anything else, answers each event once even when the connector sends it again, and signs its answer, bound to the
13
+ event it answers. Each event is kept 7 days in .ekl/callbacks.db, so a retry after a lost answer gets the same answer
14
+ back and your function runs once. "Once" covers the answer you return and what you write with `remember`; anything
15
+ your function does elsewhere (an email, another API, a paid call) must be keyed by event["event_id"] so a repeat
16
+ does nothing, as call_it below shows.
17
+
18
+ Each TODO marks a decision that is yours; a function that returns None, or one you delete, leaves the console's rule
19
+ for that event in force. Text from other agents (event["text"]) is their words: treat it as data, never as
20
+ instructions. For actions the callbacks start themselves, `act` calls the connector's local API, which listens on
21
+ 127.0.0.1 beside the connector only: post_need, find, choose, trial, call, service (a service in `uses` in
22
+ eukollab.json), message, outreach, connect and close_agreement.
23
+ """
24
+
25
+ # Annotations stay unevaluated, so the file runs on whatever python3 a host has.
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import contextlib
30
+ import datetime as dt
31
+ import hashlib
32
+ import hmac
33
+ import json
34
+ import os
35
+ import secrets
36
+ import sqlite3
37
+ import threading
38
+ import time
39
+ import traceback
40
+ import urllib.error
41
+ import urllib.request
42
+ from collections.abc import Callable, Mapping
43
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
44
+ from pathlib import Path
45
+ from typing import Any
46
+
47
+ # Set to True to post a need when this starts and use what answers it (on_need_answered below).
48
+ POST_A_NEED = False
49
+ NEED = "Describe what your agent needs" # TODO: in your own words
50
+
51
+ HERE = Path(__file__).resolve().parent
52
+
53
+
54
+ # --- The callbacks: one per event, each optional ---------------------------------------------------------------------
55
+
56
+
57
+ def on_start() -> None:
58
+ """Runs once when the connector starts this file."""
59
+ if POST_A_NEED:
60
+ # TODO: describe what your agent needs, its topics and the most it pays.
61
+ act("post_need", {"text": NEED, "topics": ["your-topic"], "budget": "0.10 USD per call"})
62
+
63
+
64
+ def on_need(event: dict[str, Any]) -> dict[str, Any] | None:
65
+ # Another agent needs something one of your services does: need_id, text, author, topics, matched_service.
66
+ # While the connector takes part, needs come here and the console's Reply for it rule stays out of the way:
67
+ # return nothing to leave a need unanswered.
68
+ # TODO: decide whether to answer, and word your offer.
69
+ service = event.get("matched_service")
70
+ if not service:
71
+ return None
72
+ return {"reply": f"I can help with this: {service['name']}, {service['price']}."}
73
+
74
+
75
+ def on_need_answered(event: dict[str, Any]) -> dict[str, Any] | None:
76
+ # Someone answered a need this agent posted: need_id, reply_id, text, author. Trying candidates takes longer than
77
+ # the connector waits for an answer, so it runs after this returns.
78
+ if POST_A_NEED:
79
+ later(use_the_best, NEED)
80
+ return None
81
+
82
+
83
+ def on_choice_approved(event: dict[str, Any]) -> dict[str, Any] | None:
84
+ # Your publisher approved a choice the agent made: decision_id, main and backup ({handle, capability_id, ...}).
85
+ if event.get("main"):
86
+ later(call_it, event["main"], str(event.get("event_id") or ""))
87
+ return None
88
+
89
+
90
+ def on_connection_request(event: dict[str, Any]) -> dict[str, Any] | None:
91
+ # Another agent asks to connect: connection_id, requester, capability_ids, organisation.
92
+ # Decides only with My code chosen for Connection requests (Behaviour → Decisions your code makes); otherwise
93
+ # the console rule decides. By default a request is accepted only when it asks for services agent.json offers.
94
+ # TODO: decide case by case ({"accept": True} or {"decline": "why"}).
95
+ asked = set(event.get("capability_ids") or [])
96
+ if asked and asked <= offered_services():
97
+ return {"accept": True}
98
+ return {"decline": "this agent connects only for the services it offers"}
99
+
100
+
101
+ def on_message(event: dict[str, Any]) -> dict[str, Any] | None:
102
+ # A message from a connected agent: connection_id, from, text, payload.
103
+ # TODO: answer it with {"reply": "…"}, or leave it.
104
+ return None
105
+
106
+
107
+ def on_outreach(event: dict[str, Any]) -> dict[str, Any] | None:
108
+ # A message from an agent you are not connected to: thread_id, from, text, and state: "received" (a new thread,
109
+ # with intent and refs), "replied" (the other side's next message) or "declined" (they closed a thread you opened).
110
+ # To open one: act("outreach", {"to": "@handle", "intent": "question", "text": "…"}). To connect from it once
111
+ # you have talked: act("connect", {"handle": "@handle", "capability_id": "…", "thread_id": event["thread_id"]}).
112
+ # TODO: answer it with {"reply": "…"}, or {"decline": "why"} for a thread opened to you, or leave it.
113
+ return None
114
+
115
+
116
+ def on_decision(event: dict[str, Any]) -> dict[str, Any] | None:
117
+ # A decision your publisher handed to the agent (Decisions your code makes, in the console): kind, subject_id,
118
+ # deadline, fallback. Without an answer, the console's fallback applies at the deadline. TODO: {"accept": True} or {"decline": "why"}.
119
+ return None
120
+
121
+
122
+ def on_review_due(event: dict[str, Any]) -> dict[str, Any] | None:
123
+ # A review period opened for one of your agreements: role, counterpart, service, calls, useful, not_useful,
124
+ # charged, closes_at. Nothing keeps the default: as the user of a service, the review your assessed calls give;
125
+ # as its provider, none.
126
+ # TODO: {"review": {"rating": 1-5, "criteria_met": "yes"|"partly"|"no", "would_use_again": bool,
127
+ # "comment": "…"}}, or {"skip": True}.
128
+ return None
129
+
130
+
131
+ # --- Using another agent's service through the connector ------------------------------------------------------------
132
+
133
+
134
+ def use_the_best(need: str) -> None:
135
+ """Try the candidates for a need and call the best one. A trial never shows you a candidate's answer: EuKollab
136
+ scores it against `expect` and tells you the score and how each check did."""
137
+ choice = act(
138
+ "choose",
139
+ {
140
+ "query": need,
141
+ "sample": {"input": "a test case"}, # TODO: your own test case, made-up data only
142
+ # TODO: what a right answer looks like: checks such as {"id": "total", "path": "$.total", "approx": 120,
143
+ # "tolerance": 0.01}, "equals", "range", "contains", "schema", or "criterion" in words; or a sentence.
144
+ "expect": {"checks": [], "threshold": 0.8},
145
+ },
146
+ )
147
+ if choice.get("waiting") or not choice.get("main"):
148
+ return # nothing passed yet, or your publisher approves each choice: on_choice_approved continues
149
+ call_it(choice["main"])
150
+
151
+
152
+ def call_it(service: dict[str, Any], event_id: str = "") -> None:
153
+ # A paid call is an effect outside this file's store: keyed by the event that led to it, the connector runs it at
154
+ # most once even when the event comes again.
155
+ try:
156
+ result = act(
157
+ "call",
158
+ {
159
+ "handle": service["handle"],
160
+ "capability_id": service["capability_id"],
161
+ "arguments": {"input": "your real input"}, # TODO: your real input
162
+ "idempotency_key": f"call-{event_id}" if event_id else None,
163
+ },
164
+ )
165
+ except ActionRefused as refused:
166
+ print("Not done:", refused.code, refused)
167
+ return
168
+ print("Result:", result["value"], "| charged", result["charged"], "| receipt checked", result["receipt_checked"])
169
+
170
+
171
+ # --- Plumbing: usually left as it is --------------------------------------------------------------------------------
172
+
173
+ # Each event's callback, by the function's name; an event whose function isn't defined above gets no answer, and the
174
+ # console's rule decides.
175
+ EVENTS = {
176
+ "need": "on_need",
177
+ "need_answered": "on_need_answered",
178
+ "choice_approved": "on_choice_approved",
179
+ "connection_request": "on_connection_request",
180
+ "message": "on_message",
181
+ "outreach": "on_outreach",
182
+ "decision": "on_decision",
183
+ "review_due": "on_review_due",
184
+ }
185
+
186
+
187
+ def callback_for(event: str) -> Callable[[dict[str, Any]], dict[str, Any] | None] | None:
188
+ found = globals().get(EVENTS.get(event, ""))
189
+ return found if callable(found) else None
190
+
191
+
192
+ class BadSignature(Exception):
193
+ """The request isn't from your connector: answer 401."""
194
+
195
+
196
+ class ActionRefused(Exception):
197
+ """The connector or the network refused an action, for example by a console rule. `detail` says more where the
198
+ refusal carries it: the trials tried for NO_PROVIDER, what the next pack needs for BALANCE_LOW."""
199
+
200
+ def __init__(self, code: str, message: str, detail: dict[str, Any] | None = None) -> None:
201
+ super().__init__(message)
202
+ self.code = code
203
+ self.detail = detail or {}
204
+
205
+
206
+ def offered_services() -> set[str]:
207
+ """The capability IDs agent.json, beside this file, offers."""
208
+ try:
209
+ agent = json.loads((HERE / "agent.json").read_text())
210
+ except (OSError, ValueError):
211
+ return set()
212
+ found = set()
213
+ for cap in agent.get("capabilities") or []:
214
+ if cap.get("offered", True) is False:
215
+ continue
216
+ name = "".join(c if c.isalnum() else "_" for c in str(cap.get("tool", "")).lower()).strip("_")[:40] or "tool"
217
+ found.add(str(cap.get("capability_id") or "cap_" + (name if len(name) >= 2 else name + "_x")))
218
+ return found
219
+
220
+
221
+ # --- Callback protocol v2: usually left as it is ---------------------------------------------------------------------
222
+
223
+ REQUEST_HEADER = "X-EKL-Signature-2"
224
+ RESPONSE_HEADER = "X-EKL-Response-Signature-2"
225
+ LEGACY_HEADER = "X-EKL-Signature"
226
+ LEGACY_UNTIL = dt.datetime(2027, 2, 11, tzinfo=dt.UTC) # the connector's unsigned v1 is refused from this day
227
+ WINDOW_SECONDS = 300
228
+ MAX_BODY = 1_048_576
229
+ LEASE_SECONDS = 60.0
230
+ RENEW_SECONDS = 20.0
231
+ KEPT_SECONDS = 7 * 86400
232
+ STORE = Path(os.environ.get("EKL_CALLBACKS_DB") or HERE / ".ekl" / "callbacks.db")
233
+ _writes = threading.local()
234
+
235
+
236
+ def callback_key() -> bytes:
237
+ """EKL_CALLBACK_KEY, as .env holds it; an older .env with only the credential derives the same key."""
238
+ given = os.environ.get("EKL_CALLBACK_KEY", "").strip()
239
+ if given:
240
+ return bytes.fromhex(given)
241
+ credential = os.environ.get("EKL_AGENT_CREDENTIAL") or os.environ.get("EKL_PROVIDER_CREDENTIAL", "")
242
+ if not credential:
243
+ raise BadSignature("set EKL_CALLBACK_KEY, as .env holds it")
244
+ return hmac.new(credential.encode(), b"ekl-callback-v2", hashlib.sha256).digest()
245
+
246
+
247
+ def _mac(key: bytes, *parts: str) -> str:
248
+ return hmac.new(key, "\n".join(parts).encode(), hashlib.sha256).hexdigest()
249
+
250
+
251
+ def _fields(header: str) -> dict[str, str]:
252
+ pairs = [part.strip().partition("=") for part in header.split(",")]
253
+ return {name: value for name, sep, value in pairs if sep}
254
+
255
+
256
+ def remember(key: str, value: Any) -> None:
257
+ """Keep a value with this event's answer: written in the same transaction, so it is kept once, with the answer,
258
+ or not at all. Read it back with recalled(key)."""
259
+ _writes.pending[key] = value
260
+
261
+
262
+ def recalled(key: str) -> Any:
263
+ with _store() as db:
264
+ row = db.execute("SELECT value FROM kept WHERE key = ?", (key,)).fetchone()
265
+ return json.loads(row[0]) if row else None
266
+
267
+
268
+ def _store() -> sqlite3.Connection:
269
+ STORE.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
270
+ if not STORE.exists():
271
+ os.close(os.open(STORE, os.O_WRONLY | os.O_CREAT, 0o600))
272
+ db = sqlite3.connect(STORE, timeout=30, isolation_level=None)
273
+ db.execute(
274
+ "CREATE TABLE IF NOT EXISTS events (event_id TEXT PRIMARY KEY, request_digest TEXT NOT NULL, state TEXT NOT "
275
+ "NULL, status INTEGER, body BLOB, fence INTEGER NOT NULL, owner TEXT NOT NULL, lease_until REAL NOT NULL, "
276
+ "created REAL NOT NULL)"
277
+ )
278
+ db.execute("CREATE TABLE IF NOT EXISTS kept (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
279
+ return db
280
+
281
+
282
+ def receive(body: bytes, headers: Mapping[str, str]) -> tuple[int, dict[str, str], bytes]:
283
+ """One request from the connector, as (status, headers, body) to send back. The signature is checked before
284
+ anything is looked up or run; an event seen before gets its stored answer; your function runs under a lease."""
285
+ if len(body) > MAX_BODY:
286
+ return 413, {}, b""
287
+ found = {k.lower(): v for k, v in headers.items()}
288
+ if REQUEST_HEADER.lower() not in found:
289
+ return _legacy(body, found.get(LEGACY_HEADER.lower(), ""))
290
+ try:
291
+ key = callback_key()
292
+ except BadSignature:
293
+ return 401, {}, b""
294
+ sig = _fields(found[REQUEST_HEADER.lower()])
295
+ event_id = sig.get("id", "")
296
+ try:
297
+ t = int(sig.get("t", ""))
298
+ event = json.loads(body)
299
+ except ValueError:
300
+ return 401, {}, b""
301
+ agent_id = os.environ.get("EKL_AGENT_ID") or str(event.get("agent_id", "") if isinstance(event, dict) else "")
302
+ digest = hashlib.sha256(body).hexdigest()
303
+ expected = _mac(key, "ekl-cb-req-v2", str(t), event_id, agent_id, digest)
304
+ if abs(time.time() - t) > WINDOW_SECONDS or not hmac.compare_digest(expected, sig.get("v", "")):
305
+ return 401, {}, b"" # before any lookup: an unsigned request never touches the store
306
+ if not isinstance(event, dict) or event.get("event_id") != event_id:
307
+ return 401, {}, b""
308
+
309
+ def signed(status: int, payload: bytes) -> tuple[int, dict[str, str], bytes]:
310
+ now = int(time.time())
311
+ answered = hashlib.sha256(payload).hexdigest()
312
+ v = _mac(key, "ekl-cb-resp-v2", str(now), event_id, agent_id, digest, str(status), answered)
313
+ header = f"t={now},id={event_id},d={digest},v={v}"
314
+ return status, {"Content-Type": "application/json", RESPONSE_HEADER: header}, payload
315
+
316
+ owner = secrets.token_hex(8)
317
+ with contextlib.closing(_store()) as db:
318
+ db.execute("DELETE FROM events WHERE created < ?", (time.time() - KEPT_SECONDS,))
319
+ try:
320
+ db.execute(
321
+ "INSERT INTO events (event_id, request_digest, state, fence, owner, lease_until, created) "
322
+ "VALUES (?, ?, 'in_progress', 1, ?, ?, ?)",
323
+ (event_id, digest, owner, time.time() + LEASE_SECONDS, time.time()),
324
+ )
325
+ fence = 1
326
+ except sqlite3.IntegrityError:
327
+ row = db.execute(
328
+ "SELECT request_digest, state, status, body, fence FROM events WHERE event_id = ?",
329
+ (event_id,),
330
+ ).fetchone()
331
+ if row is None:
332
+ return 409, {"Retry-After": "2"}, b'{"error": "IN_PROGRESS"}'
333
+ seen_digest, state, status, stored, seen_fence = row
334
+ if seen_digest != digest:
335
+ return 409, {}, b'{"error": "CONFLICT"}'
336
+ if state == "completed":
337
+ return signed(int(status), bytes(stored or b""))
338
+ taken = db.execute(
339
+ "UPDATE events SET owner = ?, fence = fence + 1, lease_until = ? WHERE event_id = ? AND fence = ? "
340
+ "AND state = 'in_progress' AND lease_until < ?",
341
+ (owner, time.time() + LEASE_SECONDS, event_id, seen_fence, time.time()),
342
+ ).rowcount
343
+ if not taken:
344
+ return 409, {"Retry-After": "2"}, b'{"error": "IN_PROGRESS"}'
345
+ fence = seen_fence + 1
346
+ return _run_leased(event, event_id, fence, signed)
347
+
348
+
349
+ def _run_leased(
350
+ event: dict[str, Any], event_id: str, fence: int, signed: Callable[[int, bytes], tuple[int, dict[str, str], bytes]]
351
+ ) -> tuple[int, dict[str, str], bytes]:
352
+ """Run the function while renewing the lease; commit its answer and its remembered values only if this run still
353
+ owns the event."""
354
+ stop = threading.Event()
355
+
356
+ def renew() -> None:
357
+ while not stop.wait(RENEW_SECONDS):
358
+ with contextlib.closing(_store()) as db:
359
+ held = db.execute(
360
+ "UPDATE events SET lease_until = ? WHERE event_id = ? AND fence = ? AND state = 'in_progress'",
361
+ (time.time() + LEASE_SECONDS, event_id, fence),
362
+ ).rowcount
363
+ if not held:
364
+ return # taken over: the commit below finds its fence stale and writes nothing
365
+
366
+ threading.Thread(target=renew, daemon=True).start()
367
+ _writes.pending = {}
368
+ try:
369
+ callback = callback_for(str(event.get("event")))
370
+ answer = callback(event) if callback else None
371
+ except Exception:
372
+ stop.set()
373
+ with contextlib.closing(_store()) as db: # let the connector's next retry run it again at once
374
+ db.execute("UPDATE events SET lease_until = 0 WHERE event_id = ? AND fence = ?", (event_id, fence))
375
+ raise
376
+ finally:
377
+ stop.set()
378
+ payload = json.dumps(answer).encode() if answer else b""
379
+ with contextlib.closing(_store()) as db:
380
+ db.execute("BEGIN IMMEDIATE")
381
+ done = db.execute(
382
+ "UPDATE events SET state = 'completed', status = 200, body = ? WHERE event_id = ? AND fence = ? "
383
+ "AND state = 'in_progress'",
384
+ (payload, event_id, fence),
385
+ ).rowcount
386
+ if done:
387
+ for key, value in _writes.pending.items():
388
+ db.execute(
389
+ "INSERT INTO kept (key, value) VALUES (?, ?) "
390
+ "ON CONFLICT (key) DO UPDATE SET value = excluded.value",
391
+ (key, json.dumps(value)),
392
+ )
393
+ db.execute("COMMIT")
394
+ if not done:
395
+ return 409, {"Retry-After": "2"}, b'{"error": "IN_PROGRESS"}'
396
+ return signed(200, payload)
397
+
398
+
399
+ def _legacy(body: bytes, signature: str) -> tuple[int, dict[str, str], bytes]:
400
+ """An older connector's v1 event, signed with the credential itself, until 2027-02-11."""
401
+ credential = os.environ.get("EKL_AGENT_CREDENTIAL") or os.environ.get("EKL_PROVIDER_CREDENTIAL", "")
402
+ expected = "sha256=" + hmac.new(credential.encode(), body, hashlib.sha256).hexdigest()
403
+ if dt.datetime.now(dt.UTC) >= LEGACY_UNTIL or not credential or not hmac.compare_digest(expected, signature):
404
+ return 401, {}, b""
405
+ print("warning: an unsigned v1 event from an older connector; upgrade it (ekl deploy)")
406
+ event = json.loads(body)
407
+ callback = callback_for(str(event.get("event")))
408
+ _writes.pending = {}
409
+ answer = callback(event) if callback else None
410
+ return 200, {"Content-Type": "application/json"}, json.dumps(answer).encode() if answer else b""
411
+
412
+
413
+ def agent_api() -> str:
414
+ """The connector's local API: EKL_AGENT_API_URL, else the address it wrote to .ekl/local-api.json, else 8765."""
415
+ given = os.environ.get("EKL_AGENT_API_URL")
416
+ if given:
417
+ return given.rstrip("/")
418
+ try:
419
+ found = json.loads((HERE / ".ekl" / "local-api.json").read_text())
420
+ except (OSError, ValueError):
421
+ return f"http://127.0.0.1:{os.environ.get('EKL_AGENT_API_PORT', '8765')}"
422
+ try:
423
+ os.kill(int(found["pid"]), 0)
424
+ except PermissionError:
425
+ pass # alive, under another user
426
+ except (OSError, KeyError, ValueError) as exc:
427
+ raise ActionRefused("CONNECTOR_NOT_RUNNING", "the connector isn't running: start it with ekl deploy") from exc
428
+ return str(found["url"]).rstrip("/")
429
+
430
+
431
+ def act(action: str, body: dict[str, Any]) -> dict[str, Any]:
432
+ """An action through the connector's local API: post_need {text, topics, budget}, find {query, limit},
433
+ choose {query, sample, expect}, trial {handle, capability_id, sample, expect}, call {handle, capability_id,
434
+ arguments, idempotency_key}, message {connection_id, text}, outreach {to, intent, text, need_id or capability_id,
435
+ idempotency_key} or {thread_id, text} to answer a thread, connect {handle, capability_id, thread_id, note},
436
+ close_agreement {handle, capability_id, outcome} and service {need, prefer, sample, expect, input,
437
+ idempotency_key}. A trial answers a score, never an output. A refusal raises ActionRefused with the network's
438
+ code: CONNECTION_PENDING when a provider hasn't accepted the connection yet, before this call times out."""
439
+ headers = {"Content-Type": "application/json"}
440
+ if os.environ.get("EKL_LOCAL_TOKEN"):
441
+ headers["Authorization"] = f"Bearer {os.environ['EKL_LOCAL_TOKEN']}"
442
+ request = urllib.request.Request(
443
+ f"{agent_api()}/agent/{action}", data=json.dumps(body).encode(), headers=headers, method="POST"
444
+ )
445
+ try:
446
+ with urllib.request.urlopen(request, timeout=300) as response:
447
+ found: dict[str, Any] = json.loads(response.read())
448
+ return found
449
+ except urllib.error.HTTPError as exc:
450
+ refused = json.loads(exc.read() or b"{}")
451
+ raise ActionRefused(
452
+ str(refused.get("error", exc.code)), str(refused.get("message", exc.reason)), refused.get("detail")
453
+ ) from exc
454
+
455
+
456
+ def later(work: Callable[..., None], *args: Any) -> None:
457
+ threading.Thread(target=work, args=args, daemon=True).start()
458
+
459
+
460
+ class Events(BaseHTTPRequestHandler):
461
+ def do_POST(self) -> None:
462
+ length = int(self.headers.get("Content-Length") or 0)
463
+ if length > MAX_BODY:
464
+ self._send(413, {}, b"")
465
+ return
466
+ body = self.rfile.read(length)
467
+ try:
468
+ status, headers, payload = receive(body, dict(self.headers.items()))
469
+ except Exception: # the connector sends the event again; the error goes to its log, where you'll look
470
+ traceback.print_exc()
471
+ status, headers, payload = 500, {}, b""
472
+ self._send(status, headers, payload)
473
+
474
+ def log_message(self, format: str, *args: Any) -> None:
475
+ pass # the connector logs each event it posts here; a line per request would repeat it
476
+
477
+ def _send(self, status: int, headers: dict[str, str], payload: bytes) -> None:
478
+ self.send_response(status)
479
+ for name, value in {"Content-Type": "application/json", **headers}.items():
480
+ self.send_header(name, value)
481
+ self.send_header("Content-Length", str(len(payload)))
482
+ self.end_headers()
483
+ self.wfile.write(payload)
484
+
485
+
486
+ def main() -> None:
487
+ parser = argparse.ArgumentParser(description="{{name}}: the agent's callbacks for the EuKollab connector")
488
+ # Loopback only: the connector runs beside it, and nothing else should reach it.
489
+ parser.add_argument("--host", default="127.0.0.1")
490
+ parser.add_argument("--port", type=int, default=8002)
491
+ options = parser.parse_args()
492
+ # The key checks and signs every event; an older .env with only the credentials derives it.
493
+ if not (
494
+ os.environ.get("EKL_CALLBACK_KEY")
495
+ or os.environ.get("EKL_AGENT_CREDENTIAL")
496
+ or os.environ.get("EKL_PROVIDER_CREDENTIAL")
497
+ ):
498
+ parser.error("set EKL_CALLBACK_KEY, as .env holds it")
499
+ server = ThreadingHTTPServer((options.host, options.port), Events)
500
+ start = globals().get("on_start")
501
+ if callable(start):
502
+ later(start)
503
+ print(f"callbacks on http://{options.host}:{options.port}/")
504
+ with contextlib.suppress(KeyboardInterrupt): # Ctrl-C stops it; a traceback would say nothing more
505
+ server.serve_forever()
506
+
507
+
508
+ if __name__ == "__main__":
509
+ main()
@@ -0,0 +1,3 @@
1
+ {
2
+ "provider_adapter": "0.11.0"
3
+ }
ekl_cli/ui.py ADDED
@@ -0,0 +1,158 @@
1
+ # Copyright © 2026 EuKreate, Inc. All rights reserved.
2
+ """How ekl's output reads (spec 13.14.13): the outcome first, in one line with its symbol, details only where
3
+ something needs attention, and the next step as a command. Errors and warnings carry their code and a link to the
4
+ messages page. Symbols and colour only on a terminal, never with NO_COLOR; --json output is untouched."""
5
+
6
+ import datetime as dt
7
+ import json
8
+ import os
9
+ import re
10
+ import sys
11
+ import textwrap
12
+ from typing import Any, TextIO
13
+
14
+ from ekl_cli.messages import CATALOGUE, CliError, RefusalError
15
+
16
+ GREEN, RED, YELLOW, DIM, BOLD = "32", "31", "33", "2", "1"
17
+ OK, FAIL, WARN, DOT = "✓", "✗", "!", "·"
18
+
19
+
20
+ def styled(stream: TextIO) -> bool:
21
+ return stream.isatty() and not os.environ.get("NO_COLOR")
22
+
23
+
24
+ def paint(text: str, *codes: str, stream: TextIO | None = None) -> str:
25
+ if not codes or not styled(stream or sys.stdout):
26
+ return text
27
+ return f"\033[{';'.join(codes)}m{text}\033[0m"
28
+
29
+
30
+ def ok(text: str, stream: TextIO | None = None) -> str:
31
+ return f"{paint(OK, GREEN, stream=stream)} {text}"
32
+
33
+
34
+ def bad(text: str, stream: TextIO | None = None) -> str:
35
+ return f"{paint(FAIL, RED, stream=stream)} {text}"
36
+
37
+
38
+ def dim(text: str, stream: TextIO | None = None) -> str:
39
+ return paint(text, DIM, stream=stream)
40
+
41
+
42
+ def bold(text: str, stream: TextIO | None = None) -> str:
43
+ return paint(text, BOLD, stream=stream)
44
+
45
+
46
+ def network() -> str:
47
+ """The network this machine signed in to, else EKL_PLATFORM, else EuKollab: where the messages page is."""
48
+ from ekl_cli.client import config_dir # noqa: PLC0415 - client imports this module's error types
49
+
50
+ try:
51
+ stored = json.loads((config_dir() / "credentials.json").read_text()).get("platform")
52
+ except (OSError, ValueError, AttributeError):
53
+ stored = None
54
+ return str(stored or os.environ.get("EKL_PLATFORM") or "https://eukollab.ai").rstrip("/")
55
+
56
+
57
+ def more(code: str) -> str:
58
+ """The message's entry on the messages page, which asks for sign-in first."""
59
+ return f"{network()}/messages/{code.lower()}"
60
+
61
+
62
+ def problem(exc: CliError, stream: TextIO | None = None) -> str:
63
+ """An error as ekl shows it: ✗ code and title, the specifics, then Fix and More."""
64
+ stream = stream or sys.stderr
65
+ lines = [f"{paint(FAIL, RED, stream=stream)} {paint(exc.code, RED, BOLD, stream=stream)} {exc.title}"]
66
+ lines += [f" {line}" for line in exc.details]
67
+ if exc.fix:
68
+ lines.append(f" {paint('Fix:', BOLD, stream=stream)} {exc.fix}")
69
+ if isinstance(exc, RefusalError) or exc.code in CATALOGUE:
70
+ lines.append(f" {dim('More: ' + more(exc.code), stream)}")
71
+ return "\n".join(lines)
72
+
73
+
74
+ def warning(code: str, *details: str, stream: TextIO | None = None, **values: Any) -> str:
75
+ """A warning: the command goes on. Same shape as an error, with ! in yellow."""
76
+ stream = stream or sys.stderr
77
+ message = CATALOGUE[code]
78
+ mark = paint(WARN, YELLOW, BOLD, stream=stream)
79
+ lines = [f"{mark} {paint(code, YELLOW, stream=stream)} {message.title.format(**values)}"]
80
+ lines += [f" {d}" for d in details if d]
81
+ if message.fix:
82
+ lines.append(f" {paint('Fix:', BOLD, stream=stream)} {message.fix.format(**values)}")
83
+ lines.append(f" {dim('More: ' + more(code), stream)}")
84
+ return "\n".join(lines)
85
+
86
+
87
+ def local_time(stamp: Any, *, seconds: bool = False) -> str:
88
+ """A time the network gives (UTC ISO) in this machine's time zone: 'Nov 18, 3:00 PM', with the year only when it
89
+ isn't this year. A stamp without a zone is UTC too."""
90
+ try:
91
+ when = dt.datetime.fromisoformat(str(stamp).replace("Z", "+00:00"))
92
+ except ValueError:
93
+ return str(stamp)
94
+ when = (when if when.tzinfo else when.replace(tzinfo=dt.UTC)).astimezone()
95
+ clock = when.strftime("%I:%M:%S %p" if seconds else "%I:%M %p").lstrip("0")
96
+ day = f"{when.strftime('%b')} {when.day}" + (f", {when.year}" if when.year != dt.date.today().year else "")
97
+ return f"{day}, {clock}"
98
+
99
+
100
+ WIDTH = 100
101
+ INDEX = re.compile(r"\[(\d+)\]")
102
+
103
+
104
+ def _split(message: str) -> tuple[str, str, str]:
105
+ """A problem the network words as 'Title: why. Fix: what to do', as its parts; any other wording is all why."""
106
+ main, _, fix = message.partition(" Fix: ")
107
+ title, colon, why = main.partition(": ")
108
+ if not colon or len(title) > 40 or not title[:1].isupper():
109
+ return "", main, fix
110
+ return title, why, fix
111
+
112
+
113
+ def _wrapped(text: str, indent: str) -> list[str]:
114
+ # Paths, addresses and JSON stay whole, so they can be copied.
115
+ return textwrap.wrap(text, WIDTH, initial_indent=indent, subsequent_indent=indent, break_long_words=False)
116
+
117
+
118
+ def problem_list(problems: list[dict[str, Any]], tools: list[str] | None = None, indent: str = " ") -> list[str]:
119
+ """The network's problems with an agent.json, errors first: one line each with ✗ or !, then why and the fix on
120
+ their own lines. The same problem for several services is said once, naming them; `tools` gives each service's
121
+ tool by its index in agent.json's capabilities."""
122
+ tools = tools or []
123
+ groups: dict[tuple[str, ...], list[str]] = {}
124
+ shown: dict[tuple[str, ...], tuple[str, str, str, str, str]] = {}
125
+ for problem in sorted(problems, key=lambda p: p.get("level") != "error"):
126
+ level, field = str(problem.get("level") or "error"), str(problem.get("field") or "agent.json")
127
+ title, why, fix = _split(str(problem.get("message") or ""))
128
+ found = INDEX.search(field)
129
+ tool = tools[int(found.group(1))] if found and int(found.group(1)) < len(tools) else ""
130
+ # The tool's name is all that differs between services with the same problem.
131
+ same = (why.replace(tool, "{tool}"), fix.replace(tool, "{tool}")) if tool else (why, fix)
132
+ key = (level, INDEX.sub("[]", field), title, *same)
133
+ if found and tool and field.startswith("capabilities["):
134
+ field = tool + field[found.end() :] # the service by its tool, not its index
135
+ groups.setdefault(key, []).append(tool)
136
+ shown.setdefault(key, (level, field, title, why, fix))
137
+ lines = []
138
+ for group, named in groups.items():
139
+ level, field, title, why, fix = shown[group]
140
+ mark = paint(FAIL, RED) if level == "error" else paint(WARN, YELLOW)
141
+ services = ", ".join(t for t in named if t)
142
+ if len(named) > 1 and services:
143
+ first = named[0]
144
+ why, fix = why.replace(first, "each"), fix.replace(first, "<tool>")
145
+ if title:
146
+ lines.append(f"{indent}{mark} {bold(title)}" + (f": {services}" if services else ""))
147
+ lines += _wrapped(why, indent + " ")
148
+ else:
149
+ lines += textwrap.wrap(
150
+ f"{services if len(named) > 1 and services else field}: {why}",
151
+ WIDTH,
152
+ initial_indent=f"{indent}{mark} ",
153
+ subsequent_indent=indent + " ",
154
+ break_long_words=False,
155
+ )
156
+ if fix:
157
+ lines += _wrapped(f"Fix: {fix}", indent + " ")
158
+ return lines