cairn-client 0.1.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.
@@ -0,0 +1,703 @@
1
+ """cairn-client — the typed Python client for the cairn control plane (#1194).
2
+
3
+ Design (ADR-0085 D7):
4
+
5
+ - **Spec-anchored, not memory-anchored**: every typed method carries its
6
+ ``(VERB, /path/template)`` in ``_SURFACE``; a repo test diffs that table
7
+ against the committed ``console/openapi.json`` so client/contract drift
8
+ fails CI, exactly like the console's freshness gate.
9
+ - **No cairn.core imports** — this package is the dependency boundary the
10
+ CLI port (#1195) and ask port (#1196) build on. CI enforces the rule.
11
+ - **Thin by intent**: httpx + dicts. Full codegen (models for 164 operations)
12
+ can replace the internals later without changing this surface.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from typing import Any, Optional
17
+
18
+ import httpx
19
+
20
+ __all__ = ["CairnClient", "AsyncCairnClient", "CairnAPIError", "AskUnavailableError"]
21
+
22
+ #: (method, path-template) for every typed method — the contract table the
23
+ #: spec-anchoring test verifies. Keep in lockstep with the methods below.
24
+ _SURFACE: dict[str, tuple[str, str]] = {
25
+ "healthz": ("get", "/healthz"),
26
+ "login": ("post", "/token"),
27
+ "runs": ("get", "/runs"),
28
+ "run": ("get", "/runs/{run_id}"),
29
+ "resume_run": ("post", "/runs/{run_id}/resume"),
30
+ "cancel_run": ("post", "/runs/{run_id}/cancel"),
31
+ "run_artifacts": ("get", "/runs/{run_id}/artifacts"),
32
+ "run_events": ("get", "/runs/{run_id}/events"),
33
+ # #1790 findings doors — added in PR #1795, which missed this table; the
34
+ # contract test went red on main until the next PR's review caught it.
35
+ "run_findings": ("get", "/runs/{run_id}/findings"),
36
+ "pipeline_findings": ("get", "/pipelines/{pipeline_id}/findings"),
37
+ "pending_approval": ("get", "/runs/{run_id}/pending-approval"),
38
+ "trigger_manual": ("post", "/triggers/manual"),
39
+ "packs": ("get", "/packs"),
40
+ "run_template": ("post", "/packs/{pack}/{template}/run"),
41
+ "preflight": ("post", "/packs/{pack}/{template}/preflight"),
42
+ "pipelines": ("get", "/pipelines"),
43
+ "installed_pipelines": ("get", "/pipelines/installed"),
44
+ "pipeline": ("get", "/pipelines/{pipeline_id}"),
45
+ # #1792 — the dry-run "how will each step be triggered" projection
46
+ "explain_pipeline": ("get", "/pipelines/{pack}/{name}/explain"),
47
+ "launch_pipeline": ("post", "/pipelines/launch"),
48
+ # #1789 — named launch presets for a pipeline (ADR-0071 §6)
49
+ "pipeline_presets": ("get", "/pipelines/presets"),
50
+ "save_pipeline_preset": ("post", "/pipelines/presets"),
51
+ "delete_pipeline_preset": ("delete", "/pipelines/presets"),
52
+ "cancel_pipeline": ("post", "/pipelines/{pipeline_id}/cancel"),
53
+ "advance_step": ("post", "/pipelines/{pipeline_id}/steps/{step_id}/advance"),
54
+ "approve_step": ("post", "/pipelines/{pipeline_id}/steps/{step_id}/approve"),
55
+ "ask": ("post", "/ask"), # platform-only: the public server has no /ask (ADR-0123 D1)
56
+ "installed_workflows": ("get", "/registry/installed-workflows"),
57
+ # #1629 (ADR-0095) — production signal capture. `capture_trace` and
58
+ # `capture_feedback` are the two calls an application makes; the rest is the
59
+ # operator's side (read, stats, consent, export).
60
+ "capture_trace": ("post", "/capture/events"),
61
+ "capture_feedback": ("post", "/capture/events"),
62
+ "capture_batch": ("post", "/capture/events"),
63
+ "capture_events": ("get", "/capture/events"),
64
+ "capture_stats": ("get", "/capture/stats"),
65
+ "capture_consent": ("get", "/capture/consent"),
66
+ "set_capture_consent": ("put", "/capture/consent"),
67
+ "export_capture": ("post", "/capture/export"),
68
+ }
69
+
70
+
71
+ def _split_pipeline_ref(ref: str) -> tuple[str, str]:
72
+ """``[pipeline:]<pack>/<name>`` → ``(pack, name)`` for the path-templated
73
+ pipeline doors. A module function, not a method, so the sync and async
74
+ twins split identically (the parity test compares signatures, which would
75
+ not catch one of them mishandling the prefix)."""
76
+ raw = (ref or "").strip()
77
+ if raw.startswith("pipeline:"):
78
+ raw = raw[len("pipeline:"):]
79
+ pack, _, name = raw.partition("/")
80
+ return pack, name
81
+
82
+
83
+ def _ws_header(workspace: Optional[str]) -> Optional[dict]:
84
+ return {"X-Cairn-Workspace": workspace} if workspace else None
85
+
86
+
87
+ # The capture bodies are built by module functions, not methods, so the sync and
88
+ # async twins send byte-identical requests: the parity test compares signatures,
89
+ # which would not catch one of them quietly dropping `adapter_uri`.
90
+ def _capture_trace_body(trace_id, prompt, completion, model, adapter_uri, run_id,
91
+ workflow_ref, source, payload) -> dict:
92
+ return {"kind": "trace", "trace_id": trace_id, "prompt": prompt,
93
+ "completion": completion, "model": model, "adapter_uri": adapter_uri,
94
+ "run_id": run_id, "workflow_ref": workflow_ref, "source": source,
95
+ "payload": payload or {}}
96
+
97
+
98
+ def _capture_feedback_body(kind, trace_id, run_id, edited_text, score, score_scale,
99
+ note, model, adapter_uri, prompt, completion, source,
100
+ payload) -> dict:
101
+ body: dict[str, Any] = {
102
+ "kind": kind, "trace_id": trace_id, "run_id": run_id,
103
+ "edited_text": edited_text, "score_scale": score_scale, "note": note,
104
+ "model": model, "adapter_uri": adapter_uri, "prompt": prompt,
105
+ "completion": completion, "source": source, "payload": payload or {},
106
+ }
107
+ if score is not None:
108
+ body["score"] = score
109
+ return body
110
+
111
+
112
+ def _capture_export_body(kinds, since, holdout_fraction) -> dict:
113
+ body: dict[str, Any] = {}
114
+ if kinds is not None:
115
+ body["kinds"] = kinds
116
+ if since is not None:
117
+ body["since"] = since
118
+ if holdout_fraction is not None:
119
+ body["holdout_fraction"] = holdout_fraction
120
+ return body
121
+
122
+
123
+ class CairnAPIError(RuntimeError):
124
+ """A non-2xx response, carrying the status and the server's detail."""
125
+
126
+ def __init__(self, status_code: int, detail: str, method: str, path: str) -> None:
127
+ super().__init__(f"{method.upper()} {path} → {status_code}: {detail}")
128
+ self.status_code = status_code
129
+ self.detail = detail
130
+
131
+
132
+ class AskUnavailableError(CairnAPIError):
133
+ """``POST /ask`` answered 404: Cairn Ask is part of cairn-platform, and this deployment
134
+ does not serve it (ADR-0127 D7, #2573). A :class:`CairnAPIError`, so existing handlers
135
+ still catch it."""
136
+
137
+ def __init__(self, err: CairnAPIError) -> None:
138
+ super().__init__(err.status_code, err.detail, "post", "/ask")
139
+ self.args = ("Cairn Ask is part of cairn-platform; this deployment does not serve "
140
+ "POST /ask (the public engine never does)",)
141
+
142
+
143
+ def _ask_or_explain(err: CairnAPIError) -> CairnAPIError:
144
+ return AskUnavailableError(err) if err.status_code == 404 else err
145
+
146
+
147
+ class CairnClient:
148
+ """A synchronous client for one cairn deployment.
149
+
150
+ ``token`` may be passed directly, obtained via :meth:`login`, or omitted
151
+ entirely against an auth-disabled dev engine."""
152
+
153
+ def __init__(
154
+ self,
155
+ base_url: str,
156
+ *,
157
+ token: Optional[str] = None,
158
+ timeout: Optional[float] = 30.0,
159
+ transport: Optional[httpx.BaseTransport] = None,
160
+ ) -> None:
161
+ """``transport`` injects a custom httpx transport — the seam that lets
162
+ an engine-side factory hand in an in-process transport (#1196) without
163
+ this package ever importing cairn. Mock transports for tests ride the
164
+ same door."""
165
+ self.base_url = base_url.rstrip("/")
166
+ self.token = token
167
+ self._http = httpx.Client(
168
+ base_url=self.base_url, timeout=timeout, transport=transport
169
+ )
170
+
171
+ # ── plumbing ─────────────────────────────────────────────────────────
172
+ def request(self, method: str, path: str, **kwargs: Any) -> Any:
173
+ """The generic door — any route, same auth/error handling as the
174
+ typed methods. Returns the parsed JSON body (``None`` for empty)."""
175
+ headers = dict(kwargs.pop("headers", {}) or {})
176
+ if self.token:
177
+ headers.setdefault("Authorization", f"Bearer {self.token}")
178
+ r = self._http.request(method, path, headers=headers, **kwargs)
179
+ if r.status_code >= 400:
180
+ try:
181
+ detail = str(r.json().get("detail", r.text))
182
+ except Exception: # noqa: BLE001 — a non-JSON error body is still an error
183
+ detail = r.text
184
+ raise CairnAPIError(r.status_code, detail, method, path)
185
+ if not r.content:
186
+ return None
187
+ return r.json()
188
+
189
+ def close(self) -> None:
190
+ self._http.close()
191
+
192
+ def __enter__(self) -> "CairnClient":
193
+ return self
194
+
195
+ def __exit__(self, *exc: object) -> None:
196
+ self.close()
197
+
198
+ # ── auth ─────────────────────────────────────────────────────────────
199
+ def login(self, username: str, password: str) -> str:
200
+ """POST /token (form-encoded, the FastAPI OAuth2 shape) and hold the JWT."""
201
+ out = self.request("post", "/token", data={"username": username, "password": password})
202
+ self.token = out["access_token"]
203
+ return self.token
204
+
205
+ # ── health ───────────────────────────────────────────────────────────
206
+ def healthz(self) -> dict:
207
+ return self.request("get", "/healthz")
208
+
209
+ # ── runs ─────────────────────────────────────────────────────────────
210
+ def runs(self, *, status: Optional[str] = None, limit: Optional[int] = None) -> list[dict]:
211
+ params = {k: v for k, v in {"status": status, "limit": limit}.items() if v is not None}
212
+ out = self.request("get", "/runs", params=params)
213
+ # the list rides under the legacy `investigations` key
214
+ return out.get("investigations", out.get("runs", []))
215
+
216
+ def run(self, run_id: str) -> dict:
217
+ return self.request("get", f"/runs/{run_id}")
218
+
219
+ def resume_run(
220
+ self,
221
+ run_id: str,
222
+ *,
223
+ decision: str,
224
+ approver: str = "api-user",
225
+ note: Optional[str] = None,
226
+ ) -> dict:
227
+ """Deliver a HITL decision (``'approve'`` / ``'reject'``). ``decision``
228
+ is REQUIRED by the server (#628: no fail-open default — an omitted
229
+ decision is a 422, never a silent approve)."""
230
+ body: dict[str, Any] = {"decision": decision, "approver": approver}
231
+ if note is not None:
232
+ body["note"] = note
233
+ return self.request("post", f"/runs/{run_id}/resume", json=body)
234
+
235
+ def run_events(self, run_id: str, *, after_seq: int = 0) -> Any:
236
+ return self.request("get", f"/runs/{run_id}/events", params={"after_seq": after_seq})
237
+
238
+ def pending_approval(self, run_id: str) -> Any:
239
+ return self.request("get", f"/runs/{run_id}/pending-approval")
240
+
241
+ def cancel_run(self, run_id: str) -> dict:
242
+ return self.request("post", f"/runs/{run_id}/cancel")
243
+
244
+ def run_artifacts(self, run_id: str) -> Any:
245
+ return self.request("get", f"/runs/{run_id}/artifacts")
246
+
247
+ def run_findings(self, run_id: str) -> dict:
248
+ """GET /runs/{id}/findings — the normalized output the gates read (#1790)."""
249
+ return self.request("get", f"/runs/{run_id}/findings")
250
+
251
+ # ── triggers ─────────────────────────────────────────────────────────
252
+ def trigger_manual(self, body: dict) -> dict:
253
+ """Submit a manual trigger event (the `cairn remote submit` door)."""
254
+ return self.request("post", "/triggers/manual", json=body)
255
+
256
+ # ── packs / templates ────────────────────────────────────────────────
257
+ def packs(self) -> dict:
258
+ return self.request("get", "/packs")
259
+
260
+ def installed_workflows(self, *, workspace: Optional[str] = None) -> dict:
261
+ """GET /registry/installed-workflows — the workspace's runnable set
262
+ (ADR-0049: the DB is the runnable set)."""
263
+ headers = {"X-Cairn-Workspace": workspace} if workspace else None
264
+ return self.request("get", "/registry/installed-workflows", headers=headers)
265
+
266
+ def run_template(self, pack: str, template: str, inputs: dict, **params: Any) -> dict:
267
+ return self.request("post", f"/packs/{pack}/{template}/run", json=inputs, params=params or None)
268
+
269
+ def preflight(self, pack: str, template: str, inputs: dict) -> dict:
270
+ return self.request("post", f"/packs/{pack}/{template}/preflight", json=inputs)
271
+
272
+ # ── pipelines ────────────────────────────────────────────────────────
273
+ def pipelines(self, *, status: Optional[str] = None) -> dict:
274
+ return self.request("get", "/pipelines", params={"status": status} if status else None)
275
+
276
+ def installed_pipelines(self) -> Any:
277
+ return self.request("get", "/pipelines/installed")
278
+
279
+ def pipeline(self, pipeline_id: str) -> dict:
280
+ return self.request("get", f"/pipelines/{pipeline_id}")
281
+
282
+ def pipeline_findings(self, pipeline_id: str) -> dict:
283
+ """GET /pipelines/{id}/findings — every non-pending step's findings,
284
+ readable mid-run (#1790)."""
285
+ return self.request("get", f"/pipelines/{pipeline_id}/findings")
286
+
287
+ def explain_pipeline(
288
+ self, ref: str, *, environment: Optional[str] = None,
289
+ preset: Optional[str] = None,
290
+ ) -> dict:
291
+ """GET /pipelines/{pack}/{name}/explain — the dry-run projection of how
292
+ every step will be triggered (#1792). ``ref`` is ``<pack>/<name>`` with
293
+ or without the ``pipeline:`` prefix."""
294
+ pack, name = _split_pipeline_ref(ref)
295
+ params = {k: v for k, v in
296
+ {"environment": environment, "preset": preset}.items() if v}
297
+ return self.request("get", f"/pipelines/{pack}/{name}/explain",
298
+ params=params or None)
299
+
300
+ def launch_pipeline(
301
+ self, ref: str, inputs: dict, *, environment: Optional[str] = None,
302
+ expected_hash: Optional[str] = None, preset: Optional[str] = None,
303
+ ) -> dict:
304
+ body: dict[str, Any] = {"ref": ref, "inputs": inputs}
305
+ if environment:
306
+ body["environment"] = environment
307
+ if expected_hash:
308
+ # #1255 — pin the exact installed record; the server 409s on drift
309
+ body["expected_hash"] = expected_hash
310
+ if preset:
311
+ # #1789 — the NAME travels; the server expands it. `inputs` is then
312
+ # only what overrides the preset, per key.
313
+ body["preset"] = preset
314
+ return self.request("post", "/pipelines/launch", json=body)
315
+
316
+ # ── pipeline launch presets (#1789) ──────────────────────────────────
317
+ def pipeline_presets(self, ref: str) -> dict:
318
+ return self.request("get", "/pipelines/presets", params={"ref": ref})
319
+
320
+ def save_pipeline_preset(
321
+ self, ref: str, name: str, inputs: dict, *, description: str = "",
322
+ ) -> dict:
323
+ body: dict[str, Any] = {"ref": ref, "name": name, "inputs": inputs}
324
+ if description:
325
+ body["description"] = description
326
+ return self.request("post", "/pipelines/presets", json=body)
327
+
328
+ def delete_pipeline_preset(self, ref: str, name: str) -> dict:
329
+ return self.request("delete", "/pipelines/presets", params={"ref": ref, "name": name})
330
+
331
+ def cancel_pipeline(self, pipeline_id: str) -> dict:
332
+ return self.request("post", f"/pipelines/{pipeline_id}/cancel")
333
+
334
+ def advance_step(
335
+ self, pipeline_id: str, step_id: str, *, approver: Optional[str] = None
336
+ ) -> dict:
337
+ body = {"approver": approver} if approver else {}
338
+ return self.request("post", f"/pipelines/{pipeline_id}/steps/{step_id}/advance", json=body)
339
+
340
+ def approve_step(
341
+ self, pipeline_id: str, step_id: str, *, approver: Optional[str] = None
342
+ ) -> dict:
343
+ body = {"approver": approver} if approver else {}
344
+ return self.request("post", f"/pipelines/{pipeline_id}/steps/{step_id}/approve", json=body)
345
+
346
+
347
+ # ── ask ──────────────────────────────────────────────────────────────
348
+ def ask(
349
+ self,
350
+ query: str,
351
+ *,
352
+ thread_id: Optional[str] = None,
353
+ workspace: Optional[str] = None,
354
+ ) -> dict:
355
+ """POST /ask — the ONE governed read door for the ask agent (#621).
356
+ ``workspace`` scopes the read via the X-Cairn-Workspace header.
357
+
358
+ Platform-only: the public server answers 404 unless the platform's ask router is
359
+ installed (ADR-0123 D1, #2427); that 404 is raised as :class:`AskUnavailableError`."""
360
+ body: dict[str, Any] = {"query": query}
361
+ if thread_id is not None:
362
+ body["thread_id"] = thread_id
363
+ headers = {"X-Cairn-Workspace": workspace} if workspace else None
364
+ try:
365
+ return self.request("post", "/ask", json=body, headers=headers)
366
+ except CairnAPIError as e:
367
+ raise _ask_or_explain(e) from e
368
+
369
+ # ── capture (#1629) ──────────────────────────────────────────────────
370
+ # The thin SDK helper the loop's fuel arrives through. `model` /
371
+ # `adapter_uri` are named parameters rather than payload keys on purpose:
372
+ # they say WHICH version a signal is evidence about, and without them cycle
373
+ # N trains on complaints about cycle N−3 (ADR-0095, capture decision 1).
374
+ def capture_trace(
375
+ self, trace_id: str, *, prompt: str = "", completion: str = "",
376
+ model: str = "", adapter_uri: str = "", run_id: str = "",
377
+ workflow_ref: str = "", source: str = "sdk",
378
+ payload: Optional[dict] = None, workspace: Optional[str] = None,
379
+ ) -> dict:
380
+ """Record what the agent did. Idempotent per ``trace_id``: the same
381
+ trace seen again — including via a gateway/Langfuse tap — dedups."""
382
+ return self.request("post", "/capture/events", json=_capture_trace_body(
383
+ trace_id, prompt, completion, model, adapter_uri, run_id,
384
+ workflow_ref, source, payload), headers=_ws_header(workspace))
385
+
386
+ def capture_feedback(
387
+ self, kind: str, *, trace_id: str = "", run_id: str = "",
388
+ edited_text: str = "", score: Optional[float] = None, score_scale: str = "",
389
+ note: str = "", model: str = "", adapter_uri: str = "", prompt: str = "",
390
+ completion: str = "", source: str = "sdk", payload: Optional[dict] = None,
391
+ workspace: Optional[str] = None,
392
+ ) -> dict:
393
+ """Record what the user did with it: ``accept | reject | edit | retry |
394
+ score``. At least one of ``trace_id`` / ``run_id`` is required — the
395
+ server 422s otherwise, because feedback about nothing trains nothing."""
396
+ return self.request("post", "/capture/events", json=_capture_feedback_body(
397
+ kind, trace_id, run_id, edited_text, score, score_scale, note, model,
398
+ adapter_uri, prompt, completion, source, payload),
399
+ headers=_ws_header(workspace))
400
+
401
+ def capture_batch(self, events: list[dict], *, workspace: Optional[str] = None) -> dict:
402
+ """Send many events in one POST (the server caps the batch at 500)."""
403
+ return self.request("post", "/capture/events", json={"events": events},
404
+ headers=_ws_header(workspace))
405
+
406
+ def capture_events(
407
+ self, *, kind: Optional[str] = None, since: Optional[str] = None,
408
+ limit: Optional[int] = None, workspace: Optional[str] = None,
409
+ ) -> dict:
410
+ params = {k: v for k, v in {"kind": kind, "since": since, "limit": limit}.items()
411
+ if v is not None}
412
+ return self.request("get", "/capture/events", params=params or None,
413
+ headers=_ws_header(workspace))
414
+
415
+ def capture_stats(self, *, workspace: Optional[str] = None) -> dict:
416
+ """Counts by kind — the cheap "is there enough new signal?" read."""
417
+ return self.request("get", "/capture/stats", headers=_ws_header(workspace))
418
+
419
+ def capture_consent(self, *, workspace: Optional[str] = None) -> dict:
420
+ return self.request("get", "/capture/consent", headers=_ws_header(workspace))
421
+
422
+ def set_capture_consent(self, allow: bool, *, workspace: Optional[str] = None) -> dict:
423
+ """Flip training consent for a workspace. Fail-closed by default: the
424
+ export refuses with a 409 until this is true."""
425
+ return self.request("put", "/capture/consent", json={"allow": bool(allow)},
426
+ headers=_ws_header(workspace))
427
+
428
+ def export_capture(
429
+ self, *, kinds: Optional[list[str]] = None, since: Optional[str] = None,
430
+ holdout_fraction: Optional[float] = None, workspace: Optional[str] = None,
431
+ ) -> dict:
432
+ """Materialize the window as a governed dataset version — returns
433
+ ``{ref: 'dataset:capture-signal@N', rows, holdout_rows, holdout_ref?}``."""
434
+ return self.request("post", "/capture/export",
435
+ json=_capture_export_body(kinds, since, holdout_fraction),
436
+ headers=_ws_header(workspace))
437
+
438
+
439
+ class AsyncCairnClient:
440
+ """The async twin of :class:`CairnClient` — same ``_SURFACE``, same error
441
+ shape, for async consumers (the ask agent and REPL, #1196). A repo test
442
+ enforces method parity with the sync client, so the two cannot drift.
443
+
444
+ ``transport`` accepts an ``httpx.AsyncBaseTransport`` — the engine-side
445
+ factory injects an in-process ASGI transport here for the single-binary,
446
+ no-server path."""
447
+
448
+ def __init__(
449
+ self,
450
+ base_url: str,
451
+ *,
452
+ token: Optional[str] = None,
453
+ timeout: Optional[float] = 30.0,
454
+ transport: Optional[httpx.AsyncBaseTransport] = None,
455
+ ) -> None:
456
+ self.base_url = base_url.rstrip("/")
457
+ self.token = token
458
+ self._http = httpx.AsyncClient(
459
+ base_url=self.base_url, timeout=timeout, transport=transport
460
+ )
461
+
462
+ # ── plumbing ─────────────────────────────────────────────────────────
463
+ async def request(self, method: str, path: str, **kwargs: Any) -> Any:
464
+ headers = dict(kwargs.pop("headers", {}) or {})
465
+ if self.token:
466
+ headers.setdefault("Authorization", f"Bearer {self.token}")
467
+ r = await self._http.request(method, path, headers=headers, **kwargs)
468
+ if r.status_code >= 400:
469
+ try:
470
+ detail = str(r.json().get("detail", r.text))
471
+ except Exception: # noqa: BLE001 — a non-JSON error body is still an error
472
+ detail = r.text
473
+ raise CairnAPIError(r.status_code, detail, method, path)
474
+ if not r.content:
475
+ return None
476
+ return r.json()
477
+
478
+ async def close(self) -> None:
479
+ await self._http.aclose()
480
+
481
+ async def __aenter__(self) -> "AsyncCairnClient":
482
+ return self
483
+
484
+ async def __aexit__(self, *exc: object) -> None:
485
+ await self.close()
486
+
487
+ # ── auth ─────────────────────────────────────────────────────────────
488
+ async def login(self, username: str, password: str) -> str:
489
+ out = await self.request("post", "/token", data={"username": username, "password": password})
490
+ self.token = out["access_token"]
491
+ return self.token
492
+
493
+ # ── health ───────────────────────────────────────────────────────────
494
+ async def healthz(self) -> dict:
495
+ return await self.request("get", "/healthz")
496
+
497
+ # ── runs ─────────────────────────────────────────────────────────────
498
+ async def runs(self, *, status: Optional[str] = None, limit: Optional[int] = None) -> list[dict]:
499
+ params = {k: v for k, v in {"status": status, "limit": limit}.items() if v is not None}
500
+ out = await self.request("get", "/runs", params=params)
501
+ return out.get("investigations", out.get("runs", []))
502
+
503
+ async def run(self, run_id: str) -> dict:
504
+ return await self.request("get", f"/runs/{run_id}")
505
+
506
+ async def resume_run(
507
+ self,
508
+ run_id: str,
509
+ *,
510
+ decision: str,
511
+ approver: str = "api-user",
512
+ note: Optional[str] = None,
513
+ ) -> dict:
514
+ body: dict[str, Any] = {"decision": decision, "approver": approver}
515
+ if note is not None:
516
+ body["note"] = note
517
+ return await self.request("post", f"/runs/{run_id}/resume", json=body)
518
+
519
+ async def run_events(self, run_id: str, *, after_seq: int = 0) -> Any:
520
+ return await self.request("get", f"/runs/{run_id}/events", params={"after_seq": after_seq})
521
+
522
+ async def pending_approval(self, run_id: str) -> Any:
523
+ return await self.request("get", f"/runs/{run_id}/pending-approval")
524
+
525
+ async def cancel_run(self, run_id: str) -> dict:
526
+ return await self.request("post", f"/runs/{run_id}/cancel")
527
+
528
+ async def run_artifacts(self, run_id: str) -> Any:
529
+ return await self.request("get", f"/runs/{run_id}/artifacts")
530
+
531
+ async def run_findings(self, run_id: str) -> dict:
532
+ """GET /runs/{id}/findings — the normalized output the gates read (#1790)."""
533
+ return await self.request("get", f"/runs/{run_id}/findings")
534
+
535
+ # ── triggers ─────────────────────────────────────────────────────────
536
+ async def trigger_manual(self, body: dict) -> dict:
537
+ return await self.request("post", "/triggers/manual", json=body)
538
+
539
+ # ── packs / templates ────────────────────────────────────────────────
540
+ async def packs(self) -> dict:
541
+ return await self.request("get", "/packs")
542
+
543
+ async def installed_workflows(self, *, workspace: Optional[str] = None) -> dict:
544
+ headers = {"X-Cairn-Workspace": workspace} if workspace else None
545
+ return await self.request("get", "/registry/installed-workflows", headers=headers)
546
+
547
+ async def run_template(self, pack: str, template: str, inputs: dict, **params: Any) -> dict:
548
+ return await self.request(
549
+ "post", f"/packs/{pack}/{template}/run", json=inputs, params=params or None
550
+ )
551
+
552
+ async def preflight(self, pack: str, template: str, inputs: dict) -> dict:
553
+ return await self.request("post", f"/packs/{pack}/{template}/preflight", json=inputs)
554
+
555
+ # ── pipelines ────────────────────────────────────────────────────────
556
+ async def pipelines(self, *, status: Optional[str] = None) -> dict:
557
+ return await self.request("get", "/pipelines", params={"status": status} if status else None)
558
+
559
+ async def installed_pipelines(self) -> Any:
560
+ return await self.request("get", "/pipelines/installed")
561
+
562
+ async def pipeline(self, pipeline_id: str) -> dict:
563
+ return await self.request("get", f"/pipelines/{pipeline_id}")
564
+
565
+ async def pipeline_findings(self, pipeline_id: str) -> dict:
566
+ """GET /pipelines/{id}/findings — every non-pending step's findings,
567
+ readable mid-run (#1790)."""
568
+ return await self.request("get", f"/pipelines/{pipeline_id}/findings")
569
+
570
+ async def explain_pipeline(
571
+ self, ref: str, *, environment: Optional[str] = None,
572
+ preset: Optional[str] = None,
573
+ ) -> dict:
574
+ """GET /pipelines/{pack}/{name}/explain — see the sync twin (#1792)."""
575
+ pack, name = _split_pipeline_ref(ref)
576
+ params = {k: v for k, v in
577
+ {"environment": environment, "preset": preset}.items() if v}
578
+ return await self.request("get", f"/pipelines/{pack}/{name}/explain",
579
+ params=params or None)
580
+
581
+ async def launch_pipeline(
582
+ self, ref: str, inputs: dict, *, environment: Optional[str] = None,
583
+ expected_hash: Optional[str] = None, preset: Optional[str] = None,
584
+ ) -> dict:
585
+ body: dict[str, Any] = {"ref": ref, "inputs": inputs}
586
+ if environment:
587
+ body["environment"] = environment
588
+ if expected_hash:
589
+ # #1255 — pin the exact installed record; the server 409s on drift
590
+ body["expected_hash"] = expected_hash
591
+ if preset:
592
+ # #1789 — the NAME travels; the server expands it (see the sync twin)
593
+ body["preset"] = preset
594
+ return await self.request("post", "/pipelines/launch", json=body)
595
+
596
+ # ── pipeline launch presets (#1789) ──────────────────────────────────
597
+ async def pipeline_presets(self, ref: str) -> dict:
598
+ return await self.request("get", "/pipelines/presets", params={"ref": ref})
599
+
600
+ async def save_pipeline_preset(
601
+ self, ref: str, name: str, inputs: dict, *, description: str = "",
602
+ ) -> dict:
603
+ body: dict[str, Any] = {"ref": ref, "name": name, "inputs": inputs}
604
+ if description:
605
+ body["description"] = description
606
+ return await self.request("post", "/pipelines/presets", json=body)
607
+
608
+ async def delete_pipeline_preset(self, ref: str, name: str) -> dict:
609
+ return await self.request(
610
+ "delete", "/pipelines/presets", params={"ref": ref, "name": name})
611
+
612
+ async def cancel_pipeline(self, pipeline_id: str) -> dict:
613
+ return await self.request("post", f"/pipelines/{pipeline_id}/cancel")
614
+
615
+ async def advance_step(
616
+ self, pipeline_id: str, step_id: str, *, approver: Optional[str] = None
617
+ ) -> dict:
618
+ body = {"approver": approver} if approver else {}
619
+ return await self.request(
620
+ "post", f"/pipelines/{pipeline_id}/steps/{step_id}/advance", json=body
621
+ )
622
+
623
+ async def approve_step(
624
+ self, pipeline_id: str, step_id: str, *, approver: Optional[str] = None
625
+ ) -> dict:
626
+ body = {"approver": approver} if approver else {}
627
+ return await self.request(
628
+ "post", f"/pipelines/{pipeline_id}/steps/{step_id}/approve", json=body
629
+ )
630
+
631
+
632
+ # ── ask ──────────────────────────────────────────────────────────────
633
+ async def ask(
634
+ self,
635
+ query: str,
636
+ *,
637
+ thread_id: Optional[str] = None,
638
+ workspace: Optional[str] = None,
639
+ ) -> dict:
640
+ """POST /ask (see :meth:`CairnClient.ask`). Platform-only: the public server answers
641
+ 404 unless the platform's ask router is installed (ADR-0123 D1, #2427)."""
642
+ body: dict[str, Any] = {"query": query}
643
+ if thread_id is not None:
644
+ body["thread_id"] = thread_id
645
+ headers = {"X-Cairn-Workspace": workspace} if workspace else None
646
+ try:
647
+ return await self.request("post", "/ask", json=body, headers=headers)
648
+ except CairnAPIError as e:
649
+ raise _ask_or_explain(e) from e
650
+
651
+ # ── capture (#1629) ──────────────────────────────────────────────────
652
+ async def capture_trace(
653
+ self, trace_id: str, *, prompt: str = "", completion: str = "",
654
+ model: str = "", adapter_uri: str = "", run_id: str = "",
655
+ workflow_ref: str = "", source: str = "sdk",
656
+ payload: Optional[dict] = None, workspace: Optional[str] = None,
657
+ ) -> dict:
658
+ return await self.request("post", "/capture/events", json=_capture_trace_body(
659
+ trace_id, prompt, completion, model, adapter_uri, run_id,
660
+ workflow_ref, source, payload), headers=_ws_header(workspace))
661
+
662
+ async def capture_feedback(
663
+ self, kind: str, *, trace_id: str = "", run_id: str = "",
664
+ edited_text: str = "", score: Optional[float] = None, score_scale: str = "",
665
+ note: str = "", model: str = "", adapter_uri: str = "", prompt: str = "",
666
+ completion: str = "", source: str = "sdk", payload: Optional[dict] = None,
667
+ workspace: Optional[str] = None,
668
+ ) -> dict:
669
+ return await self.request("post", "/capture/events", json=_capture_feedback_body(
670
+ kind, trace_id, run_id, edited_text, score, score_scale, note, model,
671
+ adapter_uri, prompt, completion, source, payload),
672
+ headers=_ws_header(workspace))
673
+
674
+ async def capture_batch(self, events: list[dict], *, workspace: Optional[str] = None) -> dict:
675
+ return await self.request("post", "/capture/events", json={"events": events},
676
+ headers=_ws_header(workspace))
677
+
678
+ async def capture_events(
679
+ self, *, kind: Optional[str] = None, since: Optional[str] = None,
680
+ limit: Optional[int] = None, workspace: Optional[str] = None,
681
+ ) -> dict:
682
+ params = {k: v for k, v in {"kind": kind, "since": since, "limit": limit}.items()
683
+ if v is not None}
684
+ return await self.request("get", "/capture/events", params=params or None,
685
+ headers=_ws_header(workspace))
686
+
687
+ async def capture_stats(self, *, workspace: Optional[str] = None) -> dict:
688
+ return await self.request("get", "/capture/stats", headers=_ws_header(workspace))
689
+
690
+ async def capture_consent(self, *, workspace: Optional[str] = None) -> dict:
691
+ return await self.request("get", "/capture/consent", headers=_ws_header(workspace))
692
+
693
+ async def set_capture_consent(self, allow: bool, *, workspace: Optional[str] = None) -> dict:
694
+ return await self.request("put", "/capture/consent", json={"allow": bool(allow)},
695
+ headers=_ws_header(workspace))
696
+
697
+ async def export_capture(
698
+ self, *, kinds: Optional[list[str]] = None, since: Optional[str] = None,
699
+ holdout_fraction: Optional[float] = None, workspace: Optional[str] = None,
700
+ ) -> dict:
701
+ return await self.request("post", "/capture/export",
702
+ json=_capture_export_body(kinds, since, holdout_fraction),
703
+ headers=_ws_header(workspace))
cairn_client/py.typed ADDED
File without changes
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.5
2
+ Name: cairn-client
3
+ Version: 0.1.0
4
+ Summary: Typed Python client for the cairn control-plane API
5
+ Project-URL: Homepage, https://cairndev.sh
6
+ Project-URL: Documentation, https://docs.cairndev.sh
7
+ Project-URL: Source, https://github.com/cairndev-sh/cairn
8
+ Project-URL: Issues, https://github.com/cairndev-sh/cairn/issues
9
+ Author: cairn maintainers
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Requires-Python: >=3.12
14
+ Requires-Dist: httpx>=0.27
15
+ Description-Content-Type: text/markdown
16
+
17
+ # cairn-client
18
+
19
+ The typed Python client for the cairn control-plane API (#1194, ADR-0085 D7).
20
+
21
+ Every method maps 1:1 onto a route in the committed contract
22
+ (`console/openapi.json`) — a test fails if the client and the spec drift.
23
+ It imports **nothing** from `cairn.core` (CI-enforced): this package is the
24
+ boundary that lets the CLI's user commands (#1195) and the ask agent (#1196)
25
+ work against a cairn deployment without engine internals.
26
+
27
+ ```python
28
+ from cairn_client import CairnClient
29
+
30
+ c = CairnClient("http://localhost:8000")
31
+ c.login("dev", "dev") # cairn dev's seeded login
32
+ c.healthz()
33
+ c.launch_pipeline("training/e2e-finetune", {"dataset": "…"})
34
+ c.advance_step(pid, "promote-model", approver="me")
35
+ ```
36
+
37
+ Auth: pass `token=` directly, call `login()`, or neither (an auth-disabled
38
+ dev engine accepts bare requests). The generic `request()` door covers any
39
+ route a typed method doesn't wrap yet.
@@ -0,0 +1,7 @@
1
+ cairn_client/__init__.py,sha256=Wr381NPncgZD7NcrEaxmOg25t321DlSTjbPU9b7V590,35352
2
+ cairn_client/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ cairn_client-0.1.0.dist-info/METADATA,sha256=5m0XnBYl1yhSfWW3RCqr2loaKBr4NTzKXJijpWVPg4Q,1453
4
+ cairn_client-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
5
+ cairn_client-0.1.0.dist-info/licenses/LICENSE,sha256=GtDubm0xm2Z7fR01xhEjSTZV-wWFmIMGIU9_8P0ZgZk,11315
6
+ cairn_client-0.1.0.dist-info/licenses/NOTICE,sha256=OB3tw_YnxqppCAHm0fTLadobe5xCwHbzMvC2lru44f4,446
7
+ cairn_client-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 The cairn Authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -0,0 +1,12 @@
1
+ cairn-client
2
+ Copyright 2026 The cairn Authors
3
+
4
+ This package is part of the cairn project (https://cairndev.sh,
5
+ source: https://github.com/cairndev-sh/cairn) and is licensed under the Apache
6
+ License, Version 2.0. A copy of the License is in the LICENSE file
7
+ distributed with this package, or at:
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Third-party dependencies are licensed under their own terms; see each
12
+ package's metadata for details.