#!/usr/bin/env python3 """Zero-dependency Python 3.10+ SDK for the TESI Agent API (https://toolsenabled.ai/agents/). Drop into LangGraph, CrewAI, AutoGen, OpenAI Agents SDK, PydanticAI, or any Python service. Uses only the Python standard library; enforces TESI-Topup-Mode: manual by default, verifies replySha256, and automatically recovers interrupted turns via GET /api/v1/agents/turns/{requestId}. """ from __future__ import annotations import hashlib import json import os import re import secrets import sys import time from typing import Any import urllib.error import urllib.parse import urllib.request DEFAULT_ORIGIN = "https://toolsenabled.ai" KEY_RE = re.compile(r"^tesi_ak_[A-Za-z0-9_-]{20,80}$") TURN_ID_RE = re.compile(r"^mw_[a-f0-9]{32}$") JS_WS = " \t\n\r\v\f\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff" class TesiApiError(RuntimeError): def __init__(self, status: int, payload: dict[str, Any]) -> None: self.status = status self.payload = payload super().__init__(f"HTTP {status}: {payload.get('error', 'tesi_error')} - {payload.get('message', '')}") def _turn_identity_sha256(mode: str, effort: str | None, message: str) -> str: trimmed = message.strip(JS_WS) raw = json.dumps([mode, effort, trimmed], ensure_ascii=False, separators=(",", ":")).encode("utf-8") return hashlib.sha256(raw).hexdigest() class TesiAgentClient: def __init__( self, api_key: str | None = None, *, origin: str | None = None, host_header: str | None = None, timeout: float = 120.0, ) -> None: self.origin = (origin or os.environ.get("TESI_ORIGIN") or DEFAULT_ORIGIN).rstrip("/") self.host_header = (host_header or os.environ.get("TESI_HOST_HEADER") or "").strip() or None self.api_key = (api_key or os.environ.get("TESI_API_KEY") or "").strip() or None if self.api_key is not None and not KEY_RE.fullmatch(self.api_key): raise ValueError("Invalid tesi_ak_... bearer key format.") self.timeout = timeout def _request( self, method: str, path: str, payload: dict[str, Any] | None = None, *, auth: bool = False, extra_headers: dict[str, str] | None = None, allow_402: bool = False, ) -> tuple[int, dict[str, Any]]: headers = {"Accept": "application/json", "User-Agent": "tesi-sdk-py/1.0"} if self.host_header: headers["Host"] = self.host_header if auth: if not self.api_key: raise ValueError("api_key (or TESI_API_KEY) is required for authenticated TESI calls.") headers["Authorization"] = f"Bearer {self.api_key}" if extra_headers: headers.update(extra_headers) data = None if payload is not None: data = json.dumps(payload, ensure_ascii=False).encode("utf-8") headers["Content-Type"] = "application/json" req = urllib.request.Request(f"{self.origin}{path}", data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=self.timeout) as resp: return resp.status, json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as err: raw = err.read().decode("utf-8", errors="replace") parsed = json.loads(raw) if raw.startswith("{") else {"error": "http_error", "message": raw[:200]} if allow_402 and err.code == 402: return 402, parsed raise TesiApiError(err.code, parsed) from None def discover(self, *, full: bool = False) -> dict[str, Any]: _, data = self._request("GET", "/api/v1/agents" if full else "/api/v1/agents/quickstart") return data def quote(self, message: str, *, include_packs: bool = True) -> dict[str, Any]: prompt_bytes = len(message.strip(JS_WS).encode("utf-8")) q = urllib.parse.urlencode({"promptBytes": prompt_bytes, **({"includePacks": "1"} if include_packs else {})}) _, data = self._request("GET", f"/api/v1/agents/starting-credit?{q}") return data def prepare_key_purchase(self, amount_cents: int = 1000, *, label: str | None = None) -> dict[str, Any]: body: dict[str, Any] = {"amountCents": amount_cents} if label: body["label"] = label status, data = self._request("POST", "/api/v1/agents/keys", body, allow_402=True) return {"httpStatus": status, **data} def claim_key(self, session_id: str) -> dict[str, Any]: _, data = self._request("POST", "/api/v1/agents/keys", {"sessionId": session_id}) if "apiKey" in data: self.api_key = data["apiKey"] return data def balance(self) -> dict[str, Any]: _, data = self._request("GET", "/api/v1/agents/balance", auth=True) return data def usage(self, *, limit: int = 25, window_hours: int | None = None) -> dict[str, Any]: q = urllib.parse.urlencode({"windowHours": window_hours} if window_hours else {"limit": limit}) _, data = self._request("GET", f"/api/v1/agents/usage?{q}", auth=True) return data def topup(self, *, amount_cents: int | None = None, session_id: str | None = None) -> dict[str, Any]: body = {"sessionId": session_id} if session_id else {"amountCents": amount_cents or 1000} status, data = self._request("POST", "/api/v1/agents/topup", body, auth=True, allow_402=True) return {"httpStatus": status, **data} def _run_turn( self, mode: str, message: str, *, effort: str | None = None, request_id: str | None = None, wait_seconds: int = 90, ) -> dict[str, Any]: rid = request_id or ("mw_" + secrets.token_hex(16)) if not TURN_ID_RE.fullmatch(rid): raise ValueError("request_id must match mw_ followed by 32 lowercase hex digits.") trimmed = message.strip(JS_WS) body_sha = _turn_identity_sha256(mode, effort, trimmed) payload: dict[str, Any] = {"requestId": rid, "mode": mode, "message": trimmed} if effort is not None: payload["effort"] = effort route = "/api/v1/agents/work" if mode == "work" else "/api/v1/agents/chat" headers = {"TESI-Topup-Mode": "manual", "TESI-Checked-Request": f"{rid}.{body_sha}"} try: _, res = self._request("POST", route, payload, auth=True, extra_headers=headers) if hashlib.sha256(res["reply"].encode("utf-8")).hexdigest() != res["replySha256"]: raise RuntimeError("replySha256 verification failed.") return res except (TesiApiError, OSError, TimeoutError) as exc: if isinstance(exc, TesiApiError) and exc.status not in (409, 502, 503, 504): raise deadline = time.monotonic() + max(1, wait_seconds) while time.monotonic() < deadline: _, rec = self._request("GET", f"/api/v1/agents/turns/{rid}", auth=True) if rec.get("status") == "result_ready": if rec.get("requestBodySha256") != body_sha: raise RuntimeError("Turn receipt requestBodySha256 mismatch.") if hashlib.sha256(rec["reply"].encode("utf-8")).hexdigest() != rec["replySha256"]: raise RuntimeError("Turn receipt replySha256 mismatch.") return {"recoveredFromReceipt": True, **rec} time.sleep(2.0) raise def ask(self, message: str, *, effort: str = "low", request_id: str | None = None) -> dict[str, Any]: return self._run_turn("ask", message, effort=effort, request_id=request_id, wait_seconds=60) def work( self, message: str, *, acceptance_checks: list[str] | None = None, effort: str = "medium", request_id: str | None = None, ) -> dict[str, Any]: full_msg = message.rstrip() if acceptance_checks and "Acceptance checks:" not in full_msg: bullets = "\n".join(f"- {c.strip()}" for c in acceptance_checks if c.strip()) full_msg = f"{full_msg}\n\nAcceptance checks:\n{bullets}" return self._run_turn("work", full_msg, effort=effort, request_id=request_id, wait_seconds=120) def execute_tool_call(self, name: str, arguments: dict[str, Any] | str) -> dict[str, Any]: args = json.loads(arguments) if isinstance(arguments, str) else dict(arguments or {}) if name == "tesi_work": return self.work( str(args["message"]), acceptance_checks=args.get("acceptanceChecks"), effort=str(args.get("effort") or "medium"), request_id=args.get("requestId"), ) if name == "tesi_ask": return self.ask( str(args["message"]), effort=str(args.get("effort") or "low"), request_id=args.get("requestId"), ) if name == "tesi_quote": return self.quote(str(args["message"])) if name == "tesi_balance": return self.balance() raise ValueError(f"Unsupported TESI tool call: {name}") TESI_TOOL_DEFINITIONS: list[dict[str, Any]] = [ { "type": "function", "function": { "name": "tesi_work", "description": "Delegate a scoped coding, UI prototype, download-check, or CSV reconciliation task with runnable acceptance checks to an isolated TESI Linux computer.", "parameters": { "type": "object", "additionalProperties": False, "required": ["message", "acceptanceChecks"], "properties": { "message": {"type": "string", "description": "Concrete deliverable specification."}, "acceptanceChecks": {"type": "array", "items": {"type": "string"}, "minItems": 1}, "effort": {"type": "string", "enum": ["low", "medium", "high"]}, }, }, }, }, { "type": "function", "function": { "name": "tesi_ask", "description": "Run a fast read-only analysis, code review, or verification question on your isolated TESI computer.", "parameters": { "type": "object", "additionalProperties": False, "required": ["message"], "properties": {"message": {"type": "string"}}, }, }, }, { "type": "function", "function": { "name": "tesi_quote", "description": "Check free minimum starting credit and eligible USD packs before spending.", "parameters": { "type": "object", "additionalProperties": False, "required": ["message"], "properties": {"message": {"type": "string"}}, }, }, }, { "type": "function", "function": { "name": "tesi_balance", "description": "Read remaining prepaid TESI credits and USD balance on the configured bearer key.", "parameters": {"type": "object", "additionalProperties": False, "properties": {}}, }, }, ] if __name__ == "__main__": if "--self-check" in sys.argv: sample_sha = _turn_identity_sha256("work", "medium", "Build service") assert len(sample_sha) == 64 and len(TESI_TOOL_DEFINITIONS) == 4 c = TesiAgentClient() print(json.dumps({"status": "tesi_python_sdk_ready", "origin": c.origin, "toolCount": len(TESI_TOOL_DEFINITIONS), "sampleIdentitySha256": sample_sha})) raise SystemExit(0) print("Import TesiAgentClient / TESI_TOOL_DEFINITIONS or run with --self-check.")