eden-client 0.6.1__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.
@@ -0,0 +1,592 @@
1
+ """Eden's Python client: the same calls and the same fail-open contract as ``@eden/client`` (TypeScript).
2
+
3
+ from eden_client import EdenClient, with_context
4
+
5
+ eden = EdenClient(api_key=key, user_id=user, session_id=session, on_error=log.warning)
6
+ result = eden.observe({"kind": "user_message", "text": text}) # each event; waits up to 3 s on a user message
7
+ messages = with_context(messages, eden.collect(result["injection"])) # before each model call
8
+ answer = eden.ask("What did Dana say about the renewal?") # or expose as the agent's ask_context tool
9
+ tools = guard_tools(eden, {"send_email": send_email}) # acting tools: check first (D376, D420)
10
+
11
+ Fails open, always (D14): a network error, a timeout, a non-2xx or an answer of the wrong shape is "no context"
12
+ (``None``, ``[]``, or ``proceed`` for ``check``), never an exception in the agent's loop. Errors go to ``on_error``.
13
+ Standard library only (``urllib``), synchronous; asyncio agents use ``eden_client.aio.AsyncEden``.
14
+ Never logs the API key; ``on_error`` gets the error, never the request.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import asyncio
20
+ import functools
21
+ import hashlib
22
+ import inspect
23
+ import json
24
+ import math
25
+ import os
26
+ import re
27
+ import sys
28
+ import time
29
+ import urllib.error
30
+ import urllib.request
31
+ from typing import Any, Callable, Dict, List, Optional
32
+
33
+ from .model_probe import probe_local_model
34
+
35
+ __all__ = [
36
+ "ASK_CONTEXT_DESCRIPTION",
37
+ "DEFAULT_WAIT_MS",
38
+ "MAX_PUSHED_ITEMS",
39
+ "EdenClient",
40
+ "default_on_error",
41
+ "eden_env",
42
+ "eden_id",
43
+ "fix_for",
44
+ "guard_tool",
45
+ "guard_tools",
46
+ "held_result",
47
+ "with_context",
48
+ "probe_local_model",
49
+ ]
50
+
51
+ #: The observe wait on a sent user message (D112): the wait the shipped default was measured with.
52
+ DEFAULT_WAIT_MS = 3_000
53
+ #: The server's cap on an observe's wait; the client clamps to the same range.
54
+ MAX_WAIT_MS = 5_000
55
+ #: Items or refs per ``/v1/sources/items``, ``/removed`` or ``/refs`` call (``MAX_PUSHED_ITEMS`` in @eden/protocol).
56
+ MAX_PUSHED_ITEMS = 100
57
+ #: The description Eden recommends for its ask tool (``ASK_CONTEXT_DESCRIPTION`` in @eden/protocol; keep it, D70).
58
+ ASK_CONTEXT_DESCRIPTION = (
59
+ "Ask the user's context partner a question. It searches the user's connected sources (mail, calendar, "
60
+ "documents, CRM and more) and answers with citations. Use it when you need a fact about the user, their "
61
+ "people, projects or history that is not in the conversation."
62
+ )
63
+
64
+ _ID = re.compile(r"^[A-Za-z0-9._:@-]{1,128}$")
65
+ _KEPT = re.compile(r"[A-Za-z0-9.:@-]")
66
+ _ID_RULE = "1-128 characters of [A-Za-z0-9._:@-]"
67
+ _ERROR_BODY_BYTES = 2_048
68
+ _ERROR_TEXT_CHARS = 300
69
+ _REASONS = {"push-off", "not-synced", "not-notifying"}
70
+ _SEQUENCES = (list, tuple, set, frozenset)
71
+
72
+
73
+ # -- the default on_error (D850; ``on-error.ts`` in @eden/client) ---------------------------------------------------
74
+
75
+ _UNSET: Any = object()
76
+ _PRINTED: set = set()
77
+ _MAX_PRINTED = 256
78
+
79
+
80
+ def eden_env(env: Optional[Dict[str, str]] = None) -> str:
81
+ """``"production"`` when ``EDEN_ENV`` (else ``NODE_ENV``) says so, else ``"development"``."""
82
+ e = os.environ if env is None else env
83
+ v = (e.get("EDEN_ENV") if e.get("EDEN_ENV") is not None else e.get("NODE_ENV", "")) or ""
84
+ return "production" if v.strip().lower() in ("production", "prod") else "development"
85
+
86
+
87
+ def fix_for(message: str) -> Optional[str]:
88
+ """The fix for a client error, as ``fixFor`` in @eden/client words it; None when there is no specific advice."""
89
+ rules = (
90
+ (r"must be 1-128 characters",
91
+ "map user and session ids with edenId(raw) (Python: eden_id) before passing them; the same mapping everywhere"),
92
+ (r"cannot reach",
93
+ "start the server (bun run dev, or the Docker image) and check baseUrl (default http://127.0.0.1:8790)"),
94
+ (r": 401\b",
95
+ "the server refused the key: pass apiKey (one of EDEN_API_KEYS on the server), or omit it against EDEN_DEV=1"),
96
+ (r": 403\b", "the key belongs to another tenant: drop tenantId or use that tenant's key"),
97
+ (r": 404\b", "baseUrl should be the server's root (no /v1 suffix); upgrade an older server"),
98
+ (r": 413\b", "the event is too large: send the text the agent saw, not whole attachments"),
99
+ (r": 429\b", "the tenant's rate cap was hit; Eden stays silent until it frees"),
100
+ (r": 400\b", "the server refused the request's shape; the reason above names the field"),
101
+ (r": 5\d\d\b", "the server failed internally; its log has the cause (the agent was not affected)"),
102
+ (r"not an? \w+ answer|unreadable answer",
103
+ "something other than Eden answered at baseUrl (a proxy or another service on that port)"),
104
+ )
105
+ for pattern, fix in rules:
106
+ if re.search(pattern, message):
107
+ return fix
108
+ return None
109
+
110
+
111
+ def _kind_of(message: str) -> str:
112
+ m = re.match(r"^eden (\S+?):? (\d{3}|cannot reach|not an? \w+|an unreadable)", message)
113
+ return f"{m.group(1)} {m.group(2)}" if m else message[:80]
114
+
115
+
116
+ def default_on_error(env: Optional[str] = None,
117
+ warn: Optional[Callable[[str], Any]] = None) -> Callable[[Exception], None]:
118
+ """The ``on_error`` a client uses when none is passed (D850), as ``defaultOnError`` in @eden/client.
119
+
120
+ Development (the default): each distinct problem printed once to stderr with its fix. Production (``EDEN_ENV``
121
+ or ``NODE_ENV`` is ``production``): the first problem of each route and status, once per process. Never raises.
122
+ ``on_error=None`` silences it.
123
+ """
124
+ mode = env or eden_env()
125
+
126
+ def out(line: str) -> None:
127
+ if warn is not None:
128
+ warn(line)
129
+ else:
130
+ print(line, file=sys.stderr)
131
+
132
+ def on_error(e: Exception) -> None:
133
+ message = str(e)
134
+ key = ("p:" + _kind_of(message)) if mode == "production" else ("d:" + message)
135
+ if key in _PRINTED or len(_PRINTED) >= _MAX_PRINTED:
136
+ return
137
+ _PRINTED.add(key)
138
+ fix = fix_for(message)
139
+ tail = (" (Eden failed open; further errors of this kind are not printed. Set on_error to log them.)"
140
+ if mode == "production" else
141
+ " (Eden failed open: the agent got no context. Set on_error to handle errors yourself, or None to "
142
+ "silence.)")
143
+ out(message + tail + (f"\n fix: {fix}" if fix else ""))
144
+
145
+ return on_error
146
+
147
+
148
+ def _reset_default_on_error() -> None:
149
+ """Clears what the default has printed (tests)."""
150
+ _PRINTED.clear()
151
+
152
+
153
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
154
+ """Follows no redirect: a 3xx is a failure like any non-2xx (its status reaches ``on_error``).
155
+
156
+ urllib's own handler re-sends a 301/302/303 as a GET with every header, the API key included, to whatever host
157
+ the ``location`` names; the TypeScript client's ``fetch`` drops the key across origins. Eden never redirects.
158
+ """
159
+
160
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001
161
+ return None
162
+
163
+
164
+ _OPENER = urllib.request.build_opener(_NoRedirect)
165
+
166
+
167
+ def _is_id(v: Any) -> bool:
168
+ # fullmatch: `$` would also match before a final newline, and "abc\n" is no id (TypeScript's `isId` agrees).
169
+ return isinstance(v, str) and _ID.fullmatch(v) is not None
170
+
171
+
172
+ def eden_id(raw: str) -> str:
173
+ """Maps any string to a valid Eden id, injectively, exactly as ``edenId`` in @eden/client does.
174
+
175
+ A valid id not starting with ``e:`` or ``h:`` is kept; otherwise ``e:`` plus an escape of its UTF-16 code units
176
+ (``_`` + 2 hex below 0x100, else ``_u`` + 4 hex) when that fits in 128 characters, else ``h:`` + its SHA-256.
177
+ Use the same mapping everywhere (and the same as a TypeScript service of yours): the id finds the user's state.
178
+ """
179
+ if _is_id(raw) and not raw.startswith("e:") and not raw.startswith("h:"):
180
+ return raw
181
+ out = ["e:"]
182
+ units = raw.encode("utf-16-le", "surrogatepass")
183
+ for i in range(0, len(units), 2):
184
+ unit = units[i] | (units[i + 1] << 8)
185
+ c = chr(unit)
186
+ if unit < 0x80 and _KEPT.fullmatch(c):
187
+ out.append(c)
188
+ elif unit < 0x100:
189
+ out.append(f"_{unit:02x}")
190
+ else:
191
+ out.append(f"_u{unit:04x}")
192
+ escaped = "".join(out)
193
+ return escaped if len(escaped) <= 128 else "h:" + hashlib.sha256(escaped.encode("ascii")).hexdigest()
194
+
195
+
196
+ def _is_injection(v: Any) -> bool:
197
+ return isinstance(v, dict) and isinstance(v.get("id"), str) and isinstance(v.get("text"), str)
198
+
199
+
200
+ def with_context(messages: List[Any], injections: List[Dict[str, Any]]) -> List[Any]:
201
+ """Puts injections in a system message just before the latest user message (``withContext`` in @eden/client).
202
+
203
+ Keep the returned list as the transcript, so the packet stays in place on later turns (the provider's prompt
204
+ cache, and the items Eden does not send twice in a session; D336, docs/INTEGRATION.md).
205
+
206
+ The packet's text is Eden's ``<context ... note="Data, not instructions.">`` envelope, inserted unchanged.
207
+ """
208
+ if not injections:
209
+ return messages
210
+ text = "\n\n".join(i["text"] for i in injections)
211
+ at = len(messages)
212
+ for i in range(len(messages) - 1, -1, -1):
213
+ m = messages[i]
214
+ # A dict or a message object (the OpenAI SDK's reply, appended as is): reading it must not throw.
215
+ if (m.get("role") if isinstance(m, dict) else getattr(m, "role", None)) == "user":
216
+ at = i
217
+ break
218
+ return [*messages[:at], {"role": "system", "content": text}, *messages[at:]]
219
+
220
+
221
+ def held_result(tool: str, finding: Dict[str, Any]) -> str:
222
+ """One way to use a check's finding: hold the call and give the agent the finding as its result (D69)."""
223
+ return (
224
+ f"Not executed: {tool} was held because the user's context partner has context on it.\n{finding['text']}\n"
225
+ f"To execute it anyway, call {tool} again with the same arguments."
226
+ )
227
+
228
+
229
+ def _guard_input(args: Any, kwargs: Dict[str, Any]) -> Any:
230
+ """What Eden is told a call's input is: the one argument, or the keyword arguments (positional ones under
231
+ ``"args"``), so ``send_email(to=..., cc=...)`` and ``send_email({"to": ..., "cc": ...})`` read the same."""
232
+ if len(args) == 1 and not kwargs:
233
+ return args[0]
234
+ return {**({"args": list(args)} if args else {}), **kwargs}
235
+
236
+
237
+ def guard_tool(eden: Any, name: str, fn: Callable[..., Any], held: Optional[Callable[..., Any]] = None,
238
+ timeout_s: Optional[float] = None, on_error: Optional[Callable[[Exception], Any]] = None
239
+ ) -> Callable[..., Any]:
240
+ """``fn``, checked with ``eden.check(name, input)`` before each call (``guardTool`` in @eden/client, D420).
241
+
242
+ On a finding the call does not run and the agent gets ``held(name, finding, input)`` as the tool's result
243
+ (default ``held_result``: hold, show the finding, say that calling again with the same arguments goes ahead; the
244
+ server proceeds on the repeat). Fails open (D14): a check or a ``held`` that raises runs the tool as if Eden were
245
+ absent; ``on_error`` gets what was swallowed. The tool's own exceptions are its own and propagate. An ``async``
246
+ tool gets an ``async`` wrapper, whose check runs in a thread (the client is synchronous). An ``AsyncEden``
247
+ unwraps to its ``EdenClient`` — its coroutine ``check`` would answer nothing here.
248
+ """
249
+
250
+ # `aio.AsyncEden`'s calls are coroutines; the check itself is synchronous work for the thread to run.
251
+ eden = getattr(eden, "sync", eden)
252
+
253
+ def report(e: Exception) -> None:
254
+ try:
255
+ if on_error:
256
+ on_error(e)
257
+ except Exception: # noqa: BLE001
258
+ pass
259
+
260
+ def ask(args: Any, kwargs: Dict[str, Any]) -> Any:
261
+ """The held result, or ``_RUN`` to run the tool."""
262
+ data = _guard_input(args, kwargs)
263
+ try:
264
+ res = eden.check(name, data) if timeout_s is None else eden.check(name, data, timeout_s=timeout_s)
265
+ finding = res.get("finding") if isinstance(res, dict) and res.get("verdict") == "finding" else None
266
+ # The same test as guardTool's: a finding with text is held (its id is not needed to show it).
267
+ if not isinstance(finding, dict) or not isinstance(finding.get("text"), str):
268
+ return _RUN
269
+ return held(name, finding, data) if held else held_result(name, finding)
270
+ except Exception as e: # noqa: BLE001 - fail open on anything (D14)
271
+ report(e)
272
+ return _RUN
273
+
274
+ if _is_async(fn):
275
+ @functools.wraps(fn)
276
+ async def guarded_async(*args: Any, **kwargs: Any) -> Any:
277
+ try:
278
+ out = await asyncio.to_thread(ask, args, kwargs)
279
+ if inspect.isawaitable(out):
280
+ out = await out
281
+ except Exception as e: # noqa: BLE001
282
+ report(e)
283
+ out = _RUN
284
+ return await fn(*args, **kwargs) if out is _RUN else out
285
+
286
+ return guarded_async
287
+
288
+ @functools.wraps(fn)
289
+ def guarded(*args: Any, **kwargs: Any) -> Any:
290
+ out = ask(args, kwargs)
291
+ if inspect.isawaitable(out):
292
+ # An async ``held`` on a sync tool cannot be awaited here: never hand the agent a coroutine object.
293
+ close = getattr(out, "close", None)
294
+ if callable(close):
295
+ close()
296
+ report(TypeError(f"guard_tool({name!r}): held returned an awaitable for a sync tool; the tool ran"))
297
+ out = _RUN
298
+ return fn(*args, **kwargs) if out is _RUN else out
299
+
300
+ return guarded
301
+
302
+
303
+ def guard_tools(eden: Any, tools: Dict[str, Callable[..., Any]], **options: Any) -> Dict[str, Callable[..., Any]]:
304
+ """Every tool in ``tools``, each checked under its key as its name (``guardTools``). Wrap the tools that act
305
+ (send, book, pay, share, order); ``options`` are ``guard_tool``'s ``held``, ``timeout_s`` and ``on_error``."""
306
+ return {name: guard_tool(eden, name, fn, **options) for name, fn in tools.items()}
307
+
308
+
309
+ _RUN = object()
310
+
311
+
312
+ def _is_async(fn: Any) -> bool:
313
+ """An ``async def``, a ``functools.partial`` of one, or an object whose ``__call__`` is one."""
314
+ while isinstance(fn, functools.partial):
315
+ fn = fn.func
316
+ return inspect.iscoroutinefunction(fn) or inspect.iscoroutinefunction(getattr(fn, "__call__", None))
317
+
318
+
319
+ class EdenError(Exception):
320
+ """What ``on_error`` receives: the route, the status and the server's reason (never the request or the key)."""
321
+
322
+
323
+
324
+ _URL = re.compile(r"\b([a-z][a-z0-9+.-]*://)(?:[^\s/]*@)?([^\s?#)]*)(?:[?#][^\s)]*)?", re.I)
325
+
326
+
327
+ def redact_urls(text: str) -> str:
328
+ """Text with every URL's credentials and query removed (`user:password@`, `?token=`), as the TS `redactUrls`."""
329
+ return _URL.sub(r"\1\2", text)
330
+
331
+
332
+ class EdenClient:
333
+ def __init__(
334
+ self,
335
+ user_id: str,
336
+ session_id: str,
337
+ api_key: Optional[str] = None,
338
+ tenant_id: Optional[str] = None,
339
+ base_url: Optional[str] = None,
340
+ timeout_s: Optional[float] = None,
341
+ default_wait_ms: Optional[int] = None,
342
+ on_error: Optional[Callable[[Exception], Any]] = _UNSET,
343
+ shadow: bool = False,
344
+ *,
345
+ bypass_proxies: bool = False,
346
+ ) -> None:
347
+ # None is the default, as `??` reads it in TypeScript: `base_url=os.environ.get(...)` when it is unset.
348
+ # Unset: the environment's EDEN_URL and EDEN_API_KEY, as the TS client, the proxy and `eden doctor` (D856).
349
+ env_url = os.environ.get("EDEN_URL") or None
350
+ self._base = (base_url if base_url is not None else env_url or "http://127.0.0.1:8790").rstrip("/")
351
+ self._key = api_key if api_key is not None else (os.environ.get("EDEN_API_KEY") or None)
352
+ self._tenant = tenant_id
353
+ self._user = user_id
354
+ self._session = session_id
355
+ self._timeout = 0.8 if timeout_s is None else timeout_s
356
+ self._default_wait = DEFAULT_WAIT_MS if default_wait_ms is None else default_wait_ms
357
+ # Unset: the default (D850) prints misuse with its fix, so a refused key is not mistaken for silence.
358
+ self._on_error = default_on_error() if on_error is _UNSET else on_error
359
+ # Shadow mode (the TS client's `shadow`, D282): what Eden returns is not given to the agent, so the server is
360
+ # told (`?shadow=1` on events and pending) and learns nothing from it as if the agent had been shown it.
361
+ self._shadow = shadow is True
362
+ # Sources a bare-signal advice was already reported for (D2008): once per source and process.
363
+ self._signal_advice_seen: set = set()
364
+ self._opener = (urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect)
365
+ if bypass_proxies else _OPENER)
366
+ bad = [f for f, v in (("tenantId", tenant_id), ("userId", user_id), ("sessionId", session_id))
367
+ if (f != "tenantId" or v) and not _is_id(v)]
368
+ # Every call would be refused (400): said once, up front, without the ids (they may be personal data).
369
+ if bad:
370
+ self._report(EdenError(f"eden: {', '.join(bad)} must be {_ID_RULE} (map ids with eden_id)"))
371
+
372
+ # -- plumbing -------------------------------------------------------------------------------------------------
373
+
374
+ def _who(self, session: bool = True) -> Dict[str, Any]:
375
+ who: Dict[str, Any] = {"tenantId": self._tenant} if self._tenant else {}
376
+ who["userId"] = self._user
377
+ if session:
378
+ who["sessionId"] = self._session
379
+ return who
380
+
381
+ def _report(self, e: Exception) -> None:
382
+ try:
383
+ if self._on_error:
384
+ self._on_error(e)
385
+ except Exception:
386
+ pass # The integrator's logger failing is no reason to throw into the agent's loop.
387
+
388
+ def _post(self, path: str, body: Dict[str, Any], timeout_s: Optional[float] = None,
389
+ valid: Optional[Callable[[Any], bool]] = None,
390
+ failed: Optional[Callable[[Exception], Any]] = None) -> Any:
391
+ """POSTs JSON; the parsed answer, or None on any failure (reported to ``failed`` and ``on_error``).
392
+
393
+ ``timeout_s`` bounds the connect, each socket read, and the body as a whole (the TypeScript client's
394
+ ``AbortSignal.timeout`` bounds the whole request). Not bounded: name resolution (``getaddrinfo`` takes no
395
+ timeout) and a status line and headers trickled a byte at a time, each read within the timeout.
396
+ """
397
+ route = path.split("?")[0]
398
+ headers = {"content-type": "application/json"}
399
+ if self._key:
400
+ headers["authorization"] = f"Bearer {self._key}"
401
+ try:
402
+ # Inside the try: a body that cannot be serialised (a datetime in a tool's input) is no context.
403
+ data = json.dumps(body).encode()
404
+ req = urllib.request.Request(self._base + path, data=data, method="POST", headers=headers)
405
+ timeout = self._timeout if timeout_s is None else timeout_s
406
+ deadline = time.monotonic() + timeout
407
+ with self._opener.open(req, timeout=timeout) as res:
408
+ answer = json.loads(_read_by(res, deadline).decode())
409
+ if valid is not None and not valid(answer):
410
+ name = route[len("/v1/"):]
411
+ raise EdenError(f"eden {route}: not {'an' if name[:1] in 'aeiou' else 'a'} {name} answer")
412
+ return answer
413
+ except urllib.error.HTTPError as e:
414
+ err: Exception = EdenError(f"eden {route}: {e.code}{_server_error(e)}")
415
+ # An answer that arrived but could not be read is not "cannot reach" (D365).
416
+ except (json.JSONDecodeError, UnicodeDecodeError) as e:
417
+ err = EdenError(f"eden {route}: an unreadable answer ({type(e).__name__})")
418
+ except Exception as e: # noqa: BLE001 - fail open on anything (D14)
419
+ # Where it was sending, so a server that is down or on another port is obvious (D365); never the key.
420
+ err = e if isinstance(e, EdenError) else EdenError(
421
+ f"eden {route}: cannot reach {redact_urls(self._base)} ({type(e).__name__}: {redact_urls(str(e))})")
422
+ if failed is not None:
423
+ failed(err)
424
+ self._report(err)
425
+ return None
426
+
427
+ # -- the calls ------------------------------------------------------------------------------------------------
428
+
429
+ def observe(self, event: Dict[str, Any], wait_ms: Optional[float] = None) -> Dict[str, Any]:
430
+ """Reports an event; ``{"injection": ... or None, "pending": bool}``. A sent user message waits by default."""
431
+ # Not a dict (a caller's slip): sent as an empty event, which the server refuses and this reports, never raises.
432
+ if not isinstance(event, dict):
433
+ event = {}
434
+ sent = event.get("kind") == "user_message" and not event.get("draft")
435
+ asked = wait_ms if wait_ms is not None else (self._default_wait if sent else 0)
436
+ try:
437
+ wait = int(min(MAX_WAIT_MS, asked)) if asked > 0 else 0 # NaN > 0 is False: waits 0.
438
+ except TypeError:
439
+ wait = 0
440
+ body = {**self._who(), "at": int(time.time() * 1000), **event}
441
+ query = "&".join(([f"waitMs={wait}"] if wait else []) + (["shadow=1"] if self._shadow else []))
442
+ res = self._post(
443
+ f"/v1/events?{query}" if query else "/v1/events",
444
+ body,
445
+ self._timeout + wait / 1000,
446
+ lambda v: isinstance(v, dict) and (v.get("injection") is None or _is_injection(v.get("injection"))),
447
+ )
448
+ return {"injection": (res or {}).get("injection"), "pending": (res or {}).get("pending") is True}
449
+
450
+ def pending(self) -> List[Dict[str, Any]]:
451
+ """Injections queued by slower lookups since the last call (drains the queue)."""
452
+ res = self._post("/v1/pending?shadow=1" if self._shadow else "/v1/pending", self._who(),
453
+ valid=lambda v: isinstance(v, dict) and isinstance(v.get("injections"), list))
454
+ return [i for i in (res or {}).get("injections", []) if _is_injection(i)]
455
+
456
+ def collect(self, injection: Optional[Dict[str, Any]]) -> List[Dict[str, Any]]:
457
+ """``observe``'s injection plus anything pending, in one list."""
458
+ return ([injection] if injection else []) + self.pending()
459
+
460
+ def ask(self, question: str, max_items: Optional[int] = None,
461
+ timeout_s: Optional[float] = None,
462
+ item: Optional[str] = None) -> Optional[Dict[str, Any]]:
463
+ """Asks Eden (the ``ask_context`` tool); the answer with citations, or None.
464
+
465
+ ``item`` (D2022): a citation's item id from an earlier answer's Sources list; the answer is
466
+ that item's parts in full. It trails ``timeout_s`` so a positional ``timeout_s`` still binds."""
467
+ body = {**self._who(), "question": question}
468
+ if max_items is not None:
469
+ body["maxItems"] = max_items
470
+ if item is not None:
471
+ body["itemId"] = item
472
+ return self._post("/v1/ask", body, 8.0 if timeout_s is None else timeout_s,
473
+ lambda v: isinstance(v, dict) and isinstance(v.get("answer"), str)
474
+ and isinstance(v.get("citations"), list))
475
+
476
+ def check(self, tool: str, input: Any, timeout_s: Optional[float] = None) -> Dict[str, Any]:
477
+ """The party check (on in the server's default, D376); ``proceed`` on any failure."""
478
+ unavailable = {"verdict": "proceed", "finding": None, "reason": "unavailable", "latencyMs": 0}
479
+ body = {**self._who(), "at": int(time.time() * 1000), "kind": "tool_call", "tool": tool, "input": input}
480
+ res = self._post("/v1/check", body, timeout_s)
481
+ if res is None:
482
+ return unavailable
483
+ finding = isinstance(res, dict) and res.get("verdict") == "finding" and _is_injection(res.get("finding"))
484
+ if not finding and not (isinstance(res, dict) and res.get("verdict") == "proceed"):
485
+ self._report(EdenError("eden /v1/check: not a check"))
486
+ return unavailable
487
+ return res
488
+
489
+ def feedback(self, injection_id: str, used: bool) -> None:
490
+ """Tells Eden whether the agent used an injection."""
491
+ self._post("/v1/feedback", {**self._who(), "injectionId": injection_id, "used": bool(used)})
492
+
493
+ def health(self, timeout_s: Optional[float] = None) -> Dict[str, Any]:
494
+ """Whether the server answers and accepts the key, tenant and ids (``/v1/whoami``, changes nothing)."""
495
+ errors: List[Exception] = []
496
+ res = self._post("/v1/whoami", self._who(), timeout_s, failed=errors.append)
497
+ return {"ok": True} if res is not None else {"ok": False, "error": str(errors[0]) if errors else "unavailable"}
498
+
499
+ def explain(self, timeout_s: Optional[float] = None) -> List[Dict[str, Any]]:
500
+ """Why Eden spoke or stayed silent in this session (D277): its last decisions, each with ``why``; no content."""
501
+ res = self._post("/v1/explain", self._who(), timeout_s,
502
+ lambda v: isinstance(v, dict) and isinstance(v.get("decisions"), list))
503
+ return [d for d in (res or {}).get("decisions", [])
504
+ if isinstance(d, dict) and isinstance(d.get("decision"), str) and isinstance(d.get("why"), str)
505
+ and isinstance(d.get("itemIds"), list)]
506
+
507
+ def source_changed(self, source_id: str, items: Optional[List[Dict[str, Any]]] = None,
508
+ removed: Optional[List[str]] = None, refs: Optional[List[str]] = None) -> bool:
509
+ """Forwards a source's change notification with what it names (D421): ``refs`` where the connector reports
510
+ changed ids (the default; D347: Eden reads them itself and puts nothing else of the source in doubt), ``items``
511
+ where the notice carries the content (D210), ``removed`` for deletions. True when every part reached the
512
+ server and was taken. A part that did not is followed by the bare signal, so Eden polls the source rather than
513
+ miss the change. With no items and no refs, it is the bare signal (the slow path).
514
+ """
515
+ # A tuple or a set of refs is as idiomatic in Python as a list; anything else (a str, a dict) is read as none.
516
+ items = list(items) if isinstance(items, _SEQUENCES) else []
517
+ removed = list(removed) if isinstance(removed, _SEQUENCES) else []
518
+ refs = list(refs) if isinstance(refs, _SEQUENCES) else []
519
+ if not items and not removed and not refs:
520
+ notice = self.source_notice(source_id)
521
+ return bool(notice and notice["synced"])
522
+ delivered = True
523
+ for i in range(0, len(refs), MAX_PUSHED_ITEMS):
524
+ res = self._post("/v1/sources/refs",
525
+ {**self._who(session=False), "sourceId": source_id, "refs": refs[i:i + MAX_PUSHED_ITEMS]},
526
+ valid=lambda v: isinstance(v, dict) and isinstance(v.get("synced"), bool))
527
+ if res is None or res["synced"] is not True:
528
+ delivered = False
529
+ for i in range(0, len(items), MAX_PUSHED_ITEMS):
530
+ if self._pushed("/v1/sources/items", "items", "stored", source_id, items[i:i + MAX_PUSHED_ITEMS]) is None:
531
+ delivered = False
532
+ for i in range(0, len(removed), MAX_PUSHED_ITEMS):
533
+ if self._pushed("/v1/sources/removed", "refs", "removed", source_id,
534
+ removed[i:i + MAX_PUSHED_ITEMS]) is None:
535
+ delivered = False
536
+ if not delivered:
537
+ self.source_notice(source_id)
538
+ return delivered
539
+
540
+ def source_notice(self, source_id: str) -> Optional[Dict[str, Any]]:
541
+ """The bare change signal; ``{"synced": bool, "reason"?: str}``, or None when unreachable."""
542
+ res = self._post("/v1/sources/changed", {**self._who(session=False), "sourceId": source_id})
543
+ if not isinstance(res, dict):
544
+ return None
545
+ # The server can re-read this source's items by ref, so a bare signal is the expensive shape (D2008):
546
+ # once per source and process, as ``n``'s distinct-problem-once rule has it.
547
+ if res.get("advice") == "refs" and source_id not in self._signal_advice_seen:
548
+ self._signal_advice_seen.add(source_id)
549
+ self._report(EdenError(
550
+ "eden /v1/sources/changed: this source re-reads items by ref; send the changed refs "
551
+ "(/v1/sources/refs) or the items themselves, not a bare signal (a signal re-reads every held copy)"))
552
+ out: Dict[str, Any] = {"synced": res.get("synced") is True}
553
+ if res.get("reason") in _REASONS:
554
+ out["reason"] = res["reason"]
555
+ if res.get("advice") == "refs":
556
+ out["advice"] = "refs"
557
+ return out
558
+
559
+ def _pushed(self, path: str, field: str, count: str, source_id: str, part: List[Any]) -> Optional[int]:
560
+ res = self._post(path, {**self._who(session=False), "sourceId": source_id, field: part},
561
+ valid=lambda v: isinstance(v, dict) and _count(v.get(count)))
562
+ return None if res is None else int(res[count])
563
+
564
+
565
+ def _read_by(res: Any, deadline: float) -> bytes:
566
+ """The body, read a chunk at a time until ``deadline``: urllib's timeout bounds one read, so a server sending a
567
+ byte at a time would otherwise hold the call for as long as it likes."""
568
+ chunks: List[bytes] = []
569
+ while True:
570
+ if time.monotonic() > deadline:
571
+ raise TimeoutError("timed out")
572
+ chunk = res.read1(65_536)
573
+ if not chunk:
574
+ return b"".join(chunks)
575
+ chunks.append(chunk)
576
+
577
+
578
+ def _count(v: Any) -> bool:
579
+ """A count a server may send: a finite number, not a bool (``json.loads`` accepts ``Infinity`` and ``NaN``)."""
580
+ return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
581
+
582
+
583
+ def _server_error(e: urllib.error.HTTPError) -> str:
584
+ """The server's ``{error}`` text, bounded, with a leading space; "" when there is none."""
585
+ try:
586
+ text = e.read(_ERROR_BODY_BYTES + 1)
587
+ if len(text) > _ERROR_BODY_BYTES:
588
+ return ""
589
+ error = json.loads(text.decode()).get("error")
590
+ return f" {error[:_ERROR_TEXT_CHARS]}" if isinstance(error, str) else ""
591
+ except Exception: # noqa: BLE001
592
+ return ""