"""The KAB API, as the automation identity: the same endpoints `cp1-agents/scripts/kab_run_workflow.py` uses. Every call takes a fresh token from the token source, so a run that lasts hours never needs a person. A 401 renews the token once; 429 and 5xx are retried with back-off. Errors raise KabError; nothing calls sys.exit. """ from __future__ import annotations import json import time import urllib.error import urllib.request from typing import Any, Callable, Protocol DEFAULT_API = "https://api.kab-dev.kyndemo.live" CP1_TENANT = "6ae37d13999438461a529409" RETRIES = 4 class TokenSource(Protocol): def token(self, force: bool = False) -> str: ... class KabError(RuntimeError): def __init__(self, message: str, status: int | None = None) -> None: super().__init__(message) self.status = status Transport = Callable[[str, str, dict, bytes | None], tuple[int, bytes]] def _urllib_transport(method: str, url: str, headers: dict, data: bytes | None) -> tuple[int, bytes]: request = urllib.request.Request(url, data=data, headers=headers, method=method) try: with urllib.request.urlopen(request, timeout=120) as response: return response.status, response.read() except urllib.error.HTTPError as error: return error.code, error.read() or b"" except urllib.error.URLError as error: return 599, str(error.reason).encode() class Kab: def __init__(self, tokens: TokenSource, api: str = DEFAULT_API, tenant: str = CP1_TENANT, project: str | None = None, transport: Transport = _urllib_transport, sleep: Callable[[float], None] = time.sleep) -> None: self.tokens = tokens self.api = api.rstrip("/") self.tenant = tenant self.project = project self._transport = transport self._sleep = sleep def call(self, method: str, path: str, body: dict | None = None) -> Any: data = json.dumps(body).encode() if body is not None else None force = False for attempt in range(RETRIES + 1): headers = {"Authorization": f"Bearer {self.tokens.token(force=force)}", "X-Tenant-ID": self.tenant, "Content-Type": "application/json"} if self.project: headers["X-Project-ID"] = self.project status, raw = self._transport(method, f"{self.api}{path}", headers, data) if 200 <= status < 300: return json.loads(raw) if raw else {} if status == 401 and not force: force = True continue if (status == 429 or status >= 500) and attempt < RETRIES: self._sleep(min(60, 5 * 2 ** attempt)) continue raise KabError(f"{method} {path}: HTTP {status}: {raw[:400].decode(errors='replace')}", status) raise KabError(f"{method} {path}: gave up after {RETRIES} retries") # The calls the runner makes. def workflow(self, workflow_id: str) -> dict: found = self.call("GET", f"/api/v1/workflow-catalog/workflows/{workflow_id}") return found.get("workflow", found) def api_sample(self, workflow_id: str) -> dict: return self.call("GET", f"/api/workflows/{workflow_id}/api-sample") def project_name(self, project_id: str) -> str | None: try: found = self.call("GET", f"/api/v1/projects/{project_id}") except KabError: return None return (found.get("project") or found).get("name") def execute(self, template: dict, inputs: dict) -> dict: return self.call("POST", "/api/workflows/execute", {"template": template, "inputs": inputs}) def status(self, execution_id: str) -> dict: return self.call("GET", f"/api/workflows/status/{execution_id}") def steps(self, execution_id: str) -> Any: return self.call("GET", f"/api/workflows/executions/{execution_id}/steps") def reviews(self, execution_id: str) -> dict: return self.call("GET", f"/api/workflows/executions/{execution_id}/reviews") def decide(self, execution_id: str, checkpoint_id: str, decision: str, note: str) -> dict: return self.call("POST", f"/api/workflows/executions/{execution_id}/reviews/{checkpoint_id}", {"decision": decision, "note": note})