#!/usr/bin/env python3 """Check a saved request, read TESI credits or receipts, or submit Work.""" import argparse from io import BytesIO from zipfile import BadZipFile, ZIP_STORED, ZipFile from datetime import datetime, timedelta, timezone import sys import hashlib import http.client import json import os import re import secrets import ssl import stat import struct import tempfile import time from urllib.parse import urlencode, urlsplit HOST = "toolsenabled.ai" ID = re.compile(r"mw_[a-f0-9]{32}") STARTER_ID = re.compile(r"[a-z0-9][a-z0-9-]{0,63}") KEY = re.compile(r"tesi_ak_[A-Za-z0-9_-]{20,80}") USAGE_CURSOR = re.compile(r"[A-Za-z0-9_-]{1,64}") PICO = re.compile(r"[0-9]+") CHECKOUT_SESSION = re.compile(r"cs_(?:live|test)_[A-Za-z0-9]{8,240}") MAX_REQUEST_BYTES = 1024 * 1024 MAX_OFFER_BYTES = 128 * 1024 MAX_RECEIPT_BYTES = 32 * 1024 * 1024 MAX_PROMPT_BYTES = 500_000 MAX_CREDIT_BATCH_ITEMS = 20 EFFORTS = ("auto", "auto-fast", "auto-ultrafast", "low", "medium", "high", "xhigh", "max", "ultra") ECMASCRIPT_SPACE = "\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff" POLL_SECONDS = 5 READ_TIMEOUT = 10 PICO_PER_CENT = 10_000_000_000 TEMPORARY_RECEIPT_ERRORS = (408, 500, 502, 503, 504) PUBLIC_ORIGINS = {f"https://{HOST}", f"https://app.{HOST}"} PUBLIC_OFFER_PATH = "/api/v1/agents" PUBLIC_OPENAPI_PATH = "/agents/openapi.yaml" PUBLIC_MCP_PATH = "/agents/tesi-agent-mcp.py.txt" PUBLIC_SKILL_PATH = "/agents/SKILL.md" PUBLIC_SAMPLE_PATH = "/agents/examples/newsletter.zip" CHECKED_REQUEST_HEADER = {"name": "TESI-Checked-Request", "format": "requestId.requestBodySha256"} SERVER_CHECK_FIELDS = {"status", "routeMode", "mode", "effort", "requestId", "promptBytes", "requestBodySha256", "minimumAvailablePico", "creditUnit"} def request_file(path): try: flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) fd = os.open(path, flags) with os.fdopen(fd, "rb") as handle: if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode): raise ValueError raw = handle.read(MAX_REQUEST_BYTES + 1) if len(raw) > MAX_REQUEST_BYTES: raise ValueError data = json.loads(raw.decode("utf-8")) if not isinstance(data, dict): raise ValueError except (OSError, ValueError, RecursionError): raise ValueError("Open a saved request JSON file of 1 MiB or less.") from None return raw, data def request_id(value): if not isinstance(value, str) or not ID.fullmatch(value): raise ValueError("Use the original request ID, mw_ followed by 32 lowercase hex digits.") return value def load_key(path): if path is None: key = os.environ.get("TESI_API_KEY", "") else: try: fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) with os.fdopen(fd, "rb") as handle: info = os.fstat(handle.fileno()) if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o600): raise ValueError raw = handle.read(4097) if len(raw) > 4096: raise ValueError entry = json.loads(raw.decode("utf-8")) key = entry.get("apiKey") if isinstance(entry, dict) else None except (OSError, ValueError, RecursionError): raise ValueError("Use the original private key.json file with mode 0600.") from None if not isinstance(key, str) or not KEY.fullmatch(key): raise ValueError("Use the original bearer key from TESI_API_KEY or --key-file.") return key def body_fingerprint(mode, effort, message): normalized = json.dumps([mode, effort, message], ensure_ascii=False, separators=(",", ":")).encode("utf-8") return hashlib.sha256(normalized).hexdigest() def request_fingerprint(brief): return brief["requestId"] + "." + brief["requestBodySha256"] def saved_request(path, *, receipt_lookup=False): raw, data = request_file(path) return raw, request_fields(data, len(raw), receipt_lookup=receipt_lookup) def request_fields(data, body_bytes, *, receipt_lookup=False): identifier, mode, effort, message = (data.get(name) for name in ("requestId", "mode", "effort", "message")) if receipt_lookup and data.keys() == {"requestId"}: return {"requestId": request_id(identifier)} implicit_mode = receipt_lookup and "mode" not in data if (set(data) - {"requestId", "mode", "effort", "message"} or not isinstance(identifier, str) or not ID.fullmatch(identifier) or (not implicit_mode and mode not in ("ask", "work")) or ("effort" in data and effort not in EFFORTS) or not isinstance(message, str)): raise ValueError("Submit a saved JSON request with requestId, mode, message and optional effort.") message = message.strip(ECMASCRIPT_SPACE) try: prompt_bytes = len(message.encode("utf-8")) if not prompt_bytes or prompt_bytes > MAX_PROMPT_BYTES: raise ValueError except ValueError: raise ValueError("Use a nonempty UTF-8 message of at most 500,000 bytes.") from None fingerprint = ({kind: body_fingerprint(kind, effort, message) for kind in ("ask", "work")} if implicit_mode else body_fingerprint(mode, effort, message)) return { "requestId": identifier, "mode": mode, "bodyBytes": body_bytes, "promptBytes": prompt_bytes, "requestBodySha256": fingerprint, } def read_public_asset(path, media_type, maximum): connection = http.client.HTTPSConnection(HOST, timeout=READ_TIMEOUT) try: connection.request("GET", path, headers={"Accept": media_type}) response = connection.getresponse() if response.status != 200: return response.status, None, retry_delay(response.getheader("Retry-After")) actual_type = response.getheader("Content-Type", "").split(";", 1)[0].strip().lower() raw = response.read(maximum + 1) if actual_type == media_type else None return response.status, raw if raw is not None and len(raw) <= maximum else None, None finally: connection.close() def read_public_offer(path=PUBLIC_OFFER_PATH): code, raw, delay = read_public_asset(path, "application/json", MAX_OFFER_BYTES) return code, json.loads(raw) if raw is not None else None, delay def shortlist_budget_pico(value): if not re.fullmatch(r"[0-9]{1,13}(?:\.[0-9]{1,12})?", value): raise argparse.ArgumentTypeError("use nonnegative TESI credits with up to 12 decimal places") whole, _, fraction = value.partition(".") return str(int(whole + fraction.ljust(12, "0"))) def shortlist_work(key, budget_pico=None): try: code, offer, delay = read_public_offer(PUBLIC_OFFER_PATH + "/quickstart") if code == 429: return {"status": "rate_limited", "retryAfterSeconds": delay} if code != 200: return {"status": "starter_catalog_unavailable", "httpStatus": code} if offer["available"] is False: return {"status": "agent_api_unavailable"} if offer["available"] is not True or not isinstance(offer["workStarters"], list): raise ValueError starters = offer["workStarters"] if not isinstance(offer["sampleProject"], dict): raise ValueError seen = set() for row in starters: if (not STARTER_ID.fullmatch(row["id"]) or row["id"] in seen or not re.fullmatch(r"[1-9][0-9]{0,24}", row["minimumAvailablePico"]) or not isinstance(row["expectedOutput"], str) or not isinstance(row["browserPreviewUrl"], str) or ("acceptanceChecks" in row and ( not isinstance(row["acceptanceChecks"], list) or not row["acceptanceChecks"] or any(not isinstance(check, str) or not check.strip() for check in row["acceptanceChecks"]))) or ("suggestedEffort" in row and row["suggestedEffort"] not in EFFORTS)): raise ValueError seen.add(row["id"]) except (OSError, http.client.HTTPException): return {"status": "starter_catalog_unavailable"} except (KeyError, TypeError, ValueError, RecursionError): return {"status": "invalid_starter_catalog"} available = budget_pico if available is None: ledger = read_credits(key) if ledger["status"] != "credits_ready": return {"status": "balance_unavailable", "balanceStatus": ledger["status"], **{field: ledger[field] for field in ("httpStatus", "retryAfterSeconds") if field in ledger}} available = ledger["balance"]["availablePico"] available_pico = int(available) matches = [] nearest = None for row in starters: gap = int(row["minimumAvailablePico"]) - available_pico starter_id = row["id"] preview = {"id": starter_id, "deliverable": row["expectedOutput"], "prepareArgs": ["--file", f"{starter_id}.json", "--prepare-work", starter_id], "minimumAvailablePico": row["minimumAvailablePico"], "browserPreviewUrl": row["browserPreviewUrl"]} for field in ("acceptanceChecks", "suggestedEffort", "referenceFiles", "referenceCheck", "acceptanceFixture", "sampleDeliverable"): if field in row: preview[field] = row[field] if gap <= 0: matches.append(preview) elif nearest is None or gap < int(nearest["shortfallPico"]): nearest = {**preview, "shortfallPico": str(gap), "shortfallCredits": format_credits(str(gap))} result = {"status": "work_shortlist_ready", "availablePico": available, "availableCredits": format_credits(available), "matches": matches, "balanceSource": "planned_budget" if budget_pico is not None else "key_balance"} if nearest is not None: result["nearestUnaffordableStarter"] = nearest if not matches: result["sampleProject"] = offer["sampleProject"] return result def checked_pack_amounts(amounts): if (not isinstance(amounts, list) or not 1 <= len(amounts) <= 10 or any(type(amount) is not int or not 100 <= amount <= 1_000_000 for amount in amounts) or len(amounts) != len(set(amounts))): raise ValueError return amounts def offered_pack_amounts(offer): if (offer["service"] != "TESI Agent API" or offer["available"] is not True or offer["currency"] != "usd" or offer["payFirst"] is not True): raise ValueError return checked_pack_amounts(offer["amountsCents"]) def verify_public(): checks = [] identifier = "discovery" def failure(reason, **details): return {"status": "public_checks_failed", "failedCheck": identifier, "reason": reason, "checks": checks, **details} try: code, offer, delay = read_public_offer() if code != 200: return failure("rate_limited" if code == 429 else "http_error", httpStatus=code, retryAfterSeconds=delay) amounts = offered_pack_amounts(offer) initial = offer["defaultAmountCents"] endpoints = offer["endpoints"] evidence = offer["buyerGuide"]["publicEvidence"] mcp_meta = offer["buyerGuide"]["mcpServer"] published_hash = evidence["sampleSha256"] mcp_hash = mcp_meta["sha256"] skill_hash = evidence["skillSha256"] urls = [(endpoints["chat"], PUBLIC_OFFER_PATH + "/chat"), (endpoints["work"], PUBLIC_OFFER_PATH + "/work"), (endpoints["turnReceipt"], PUBLIC_OFFER_PATH + "/turns/{requestId}"), (evidence["openApiUrl"], PUBLIC_OPENAPI_PATH), (mcp_meta["serverUrl"], PUBLIC_MCP_PATH), (evidence["skillUrl"], PUBLIC_SKILL_PATH), (evidence["sampleUrl"], PUBLIC_SAMPLE_PATH)] if (type(initial) is not int or initial not in amounts or not all(re.fullmatch(r"[a-f0-9]{64}", h) for h in (published_hash, mcp_hash, skill_hash)) or not any(all(url == origin + path for url, path in urls) for origin in PUBLIC_ORIGINS)): return failure("invalid_offer") checks.append({"id": identifier, "amountsCents": amounts, "defaultAmountCents": initial, "currency": "usd"}) identifier = "openapi" code, raw, delay = read_public_asset(PUBLIC_OPENAPI_PATH, "application/yaml", 256 * 1024) if code != 200: return failure("rate_limited" if code == 429 else "http_error", httpStatus=code, retryAfterSeconds=delay) if raw is None: return failure("invalid_openapi") document = raw.decode("utf-8") version = re.search(r"^openapi: (3\.1\.[0-9]+)[ \t]*$", document, re.MULTILINE) required = {"discoverAgentOffer", "askTESI", "commissionTESIWork", "readAgentTurnReceipt"} operations = set(re.findall(r"^[ \t]+operationId: ([A-Za-z]+)[ \t]*$", document, re.MULTILINE)) if not version or not required <= operations: return failure("invalid_openapi") checks.append({"id": identifier, "version": version[1], "operations": sorted(required), "bytes": len(raw)}) identifier = "mcp_server" code, raw, delay = read_public_asset(PUBLIC_MCP_PATH, "text/plain", 256 * 1024) if code != 200: return failure("rate_limited" if code == 429 else "http_error", httpStatus=code, retryAfterSeconds=delay) if raw is None: return failure("invalid_mcp_server") mcp_digest = hashlib.sha256(raw).hexdigest() if mcp_digest != mcp_hash: return failure("checksum_mismatch") checks.append({"id": identifier, "sha256": mcp_digest, "bytes": len(raw)}) identifier = "skill" code, raw, delay = read_public_asset(PUBLIC_SKILL_PATH, "text/markdown", 128 * 1024) if code != 200: return failure("rate_limited" if code == 429 else "http_error", httpStatus=code, retryAfterSeconds=delay) if raw is None: return failure("invalid_skill") skill_digest = hashlib.sha256(raw).hexdigest() if skill_digest != skill_hash: return failure("checksum_mismatch") checks.append({"id": identifier, "sha256": skill_digest, "bytes": len(raw)}) identifier = "sample" code, raw, delay = read_public_asset(PUBLIC_SAMPLE_PATH, "application/zip", 512 * 1024) if code != 200: return failure("rate_limited" if code == 429 else "http_error", httpStatus=code, retryAfterSeconds=delay) if raw is None: return failure("invalid_sample") digest = hashlib.sha256(raw).hexdigest() if digest != published_hash: return failure("checksum_mismatch") checks.append({"id": identifier, "sha256": digest, "bytes": len(raw)}) except (KeyError, TypeError, ValueError, RecursionError): return failure({"discovery": "invalid_offer", "openapi": "invalid_openapi", "mcp_server": "invalid_mcp_server", "skill": "invalid_skill", "sample": "invalid_sample"}[identifier]) except (OSError, http.client.HTTPException): return failure("read_unavailable") return {"status": "public_checks_passed", "checks": checks} def supports_submission(manual_topup=False, checked_binding=None): try: code, data, _ = read_public_offer() if code != 200: return False guide = data["buyerGuide"]["request"] return (data["available"] is True and guide["receiptRequestHash"] == "sha256_normalized_request" and (not manual_topup or guide.get("manualTopupHeader") == {"name": "TESI-Topup-Mode", "value": "manual"}) and (checked_binding is None or guide.get("checkedRequestHeader") == CHECKED_REQUEST_HEADER)) except (AttributeError, KeyError, TypeError, ValueError, OSError, http.client.HTTPException, RecursionError): return False def valid_checkout_link(link): if not isinstance(link, str) or not link.startswith("https://checkout.stripe.com/"): return False destination = urlsplit(link) return (destination.scheme == "https" and destination.netloc == "checkout.stripe.com" and not any(ord(char) < 33 or ord(char) == 127 or char.isspace() for char in link)) def payment_details(body, manual_topup=False): try: data = json.loads(body.decode("utf-8")) if (data["error"] != "insufficient_credits" or data["unpaidStatus"] != 402 or data["currency"] != "usd" or not PICO.fullmatch(data["balance"]["availablePico"])): return None if manual_topup: if (data["status"] != "manual_topup_required" or any(field in data for field in ("checkoutUrl", "sessionId", "reconcileBody", "amountCents"))): return None value = {"status": data["status"], "currency": "usd", "availablePico": data["balance"]["availablePico"]} if "minimumAvailablePico" in data: if not PICO.fullmatch(data["minimumAvailablePico"]): return None value["minimumAvailablePico"] = data["minimumAvailablePico"] return value if (type(data["amountCents"]) is not int or data["amountCents"] <= 0 or data["status"] not in ("open", "pending", "paid") or not CHECKOUT_SESSION.fullmatch(data["sessionId"]) or data["reconcileBody"]["sessionId"] != data["sessionId"]): return None value = {name: data[name] for name in ("status", "amountCents", "currency")} value["availablePico"] = data["balance"]["availablePico"] link = data.get("checkoutUrl") if data["status"] == "open": if not valid_checkout_link(link): return None value["checkoutUrl"] = link elif link is not None: return None return value except (KeyError, TypeError, ValueError, AttributeError, RecursionError): return None def submit_request(mode, raw, key, manual_topup=False, checked_binding=None): connection = http.client.HTTPSConnection(HOST, timeout=30) try: path = "/api/v1/agents/" + ("work" if mode == "work" else "chat") headers = {"Authorization": "Bearer " + key, "Content-Type": "application/json", "Accept": "application/json"} if manual_topup: headers["TESI-Topup-Mode"] = "manual" if checked_binding is not None: headers[CHECKED_REQUEST_HEADER["name"]] = checked_binding connection.request("POST", path, raw, headers) response = connection.getresponse() payment = None if response.status == 402: raw = response.read(16385) if len(raw) <= 16384: payment = payment_details(raw, manual_topup) delay = retry_delay(response.getheader("Retry-After")) if response.status == 429 else None return response.status, payment, delay except (OSError, http.client.HTTPException): return None, None, None finally: connection.close() def fetch_receipt(identifier, key, timeout): connection = http.client.HTTPSConnection(HOST, timeout=timeout) try: connection.request( "GET", "/api/v1/agents/turns/" + identifier, headers={"Authorization": "Bearer " + key, "Accept": "application/json"}, ) response = connection.getresponse() limit = {200: MAX_RECEIPT_BYTES, 404: 4096}.get(response.status) body = response.read(limit + 1) if limit else b"" return response.status, response.getheader("Retry-After"), body finally: connection.close() def retry_delay(header): value = (header or "").strip() return (int(value) or None) if re.fullmatch(r"[0-9]{1,9}", value) else None def read_once(identifier, key, timeout, fetch, expected_hash=None): try: code, retry_after, body = fetch(identifier, key, timeout) except ssl.SSLError: return {"requestId": identifier, "status": "read_unavailable"} except (OSError, http.client.HTTPException): return {"requestId": identifier, "status": "read_unavailable", "retryAfterSeconds": POLL_SECONDS} base = {"requestId": identifier, "httpStatus": code} if code == 429: return {**base, "status": "rate_limited", "retryAfterSeconds": retry_delay(retry_after)} if code in TEMPORARY_RECEIPT_ERRORS: return {**base, "status": "read_unavailable", "retryAfterSeconds": retry_delay(retry_after) or POLL_SECONDS} if code in (401, 403): return {**base, "status": "key_rejected"} if code == 404: if expected_hash is not None: try: detail = json.loads(body) if len(body) <= 4096 else None except (ValueError, RecursionError): detail = None if not isinstance(detail, dict) or detail.get("error") != "agent_turn_receipt_unknown": return {**base, "status": "read_unavailable"} return {**base, "status": "receipt_missing"} if code != 200: return {**base, "status": "read_unavailable"} try: if len(body) > MAX_RECEIPT_BYTES: return {**base, "status": "receipt_too_large"} data = json.loads(body.decode("utf-8")) except (ValueError, RecursionError): return {**base, "status": "invalid_receipt"} if (not isinstance(data, dict) or data.get("requestId") != identifier or data.get("mode") not in ("ask", "work") or type(data.get("receivedAt")) is not int or data["receivedAt"] < 0 or data.get("status") not in ("processing", "outcome_unknown", "result_ready") or data.get("requestCost") != "unavailable"): return {**base, "status": "invalid_receipt"} result = {**base, **{field: data[field] for field in ("mode", "receivedAt", "status", "requestCost")}} if expected_hash is not None: digest = expected_hash[data["mode"]] if isinstance(expected_hash, dict) else expected_hash if data.get("requestBodySha256") != digest: return {**base, "status": "receipt_request_mismatch"} result["requestBodySha256"] = digest if result["status"] == "result_ready": if (not isinstance(data.get("reply"), str) or not data["reply"].strip() or type(data.get("resultSavedAt")) is not int or data["resultSavedAt"] < 0): return {**base, "status": "invalid_receipt"} if "replySha256" in data: try: digest = hashlib.sha256(data["reply"].encode("utf-8")).hexdigest() except UnicodeEncodeError: return {**base, "status": "invalid_receipt"} if data["replySha256"] != digest: return {**base, "status": "reply_digest_mismatch"} result["replySha256"] = digest result.update(resultSavedAt=data["resultSavedAt"], reply=data["reply"]) return result def receipt_metadata(result): metadata = {field: value for field, value in result.items() if field != "reply"} epoch = datetime(1970, 1, 1, tzinfo=timezone.utc) for field in ("receivedAt", "resultSavedAt"): if field not in metadata: continue try: timestamp = epoch + timedelta(milliseconds=metadata[field]) except OverflowError: continue metadata[field + "Utc"] = timestamp.isoformat(timespec="milliseconds").replace("+00:00", "Z") return metadata def write_new_file(destination, payload): target = os.path.abspath(destination) fd, temporary = tempfile.mkstemp(prefix=".tesi-write-", dir=os.path.dirname(target)) try: with os.fdopen(fd, "wb") as handle: handle.write(payload) handle.flush() os.fsync(handle.fileno()) os.link(temporary, target) finally: try: os.unlink(temporary) except FileNotFoundError: pass def write_prepared_request(destination, template): identifier = "mw_" + secrets.token_hex(16) while identifier == template.get("requestId"): identifier = "mw_" + secrets.token_hex(16) brief = {**template, "requestId": identifier} payload = (json.dumps(brief, indent=2, ensure_ascii=False) + "\n").encode("utf-8") if len(payload) > MAX_REQUEST_BYTES: payload = json.dumps(brief, separators=(",", ":"), ensure_ascii=False).encode("utf-8") if len(payload) > MAX_REQUEST_BYTES: return {"status": "request_file_too_large"} try: write_new_file(destination, payload) except FileExistsError: return {"status": "request_file_exists"} except (ValueError, OSError, NotImplementedError): return {"status": "request_file_unavailable"} return {"status": "request_prepared", "requestId": identifier, "requestFile": destination} def prepare_ask(destination, *, message_stdin=False): message = "Return the sum of 17 and 25 as a single number." if message_stdin: raw = sys.stdin.buffer.read(MAX_PROMPT_BYTES + 1) if len(raw) > MAX_PROMPT_BYTES: raise ValueError("Use a nonempty UTF-8 message of at most 500,000 bytes.") try: message = raw.decode("utf-8") except UnicodeDecodeError: raise ValueError("Use a nonempty UTF-8 message of at most 500,000 bytes.") from None if not message.strip(ECMASCRIPT_SPACE): raise ValueError("Use a nonempty UTF-8 message of at most 500,000 bytes.") template = {"mode": "ask", "message": message} return write_prepared_request(destination, template) def copy_brief(source, destination): raw, template = request_file(source) original = request_fields(template, len(raw)) result = write_prepared_request(destination, template) if result["status"] == "request_prepared": result["sourceRequestId"] = original["requestId"] return result def prepare_work(destination, starter_id): try: code, offer, delay = read_public_offer() except (OSError, http.client.HTTPException): return {"status": "starter_catalog_unavailable"} except (ValueError, RecursionError): return {"status": "invalid_work_starter"} if code == 429: return {"status": "rate_limited", "retryAfterSeconds": delay} if code != 200: return {"status": "starter_catalog_unavailable", "httpStatus": code} try: if offer["service"] != "TESI Agent API": raise ValueError starters = offer["buyerGuide"]["starters"] if not isinstance(starters, list): raise ValueError matches = [item for item in starters if isinstance(item, dict) and item.get("id") == starter_id] if not matches or (len(matches) == 1 and matches[0].get("mode") != "work"): return {"status": "work_starter_unavailable", "starterId": starter_id} if len(matches) != 1: raise ValueError template = matches[0]["workRequestTemplate"] if (not isinstance(template, dict) or set(template) != {"mode", "effort", "message"} or template["mode"] != "work" or template["effort"] not in EFFORTS or not isinstance(template["message"], str) or not template["message"].strip(ECMASCRIPT_SPACE) or len(template["message"].encode("utf-8")) > MAX_PROMPT_BYTES): raise ValueError except (KeyError, TypeError, ValueError): return {"status": "invalid_work_starter"} result = write_prepared_request(destination, template) return {**result, "starterId": starter_id} PACK_SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv", "dist", "build", ".pytest_cache", "tesi-purchase"} PACK_SECRET_NAMES = {".env", "key.json", "purchase.json", "session.json", "confirmation.json", "credentials.json"} PACK_SECRET_PATTERNS = re.compile( r"(?:tesi_ak_[A-Za-z0-9_-]{20,80}|sk_(?:live|test)_[A-Za-z0-9]{16,}|rk_(?:live|test)_[A-Za-z0-9]{16,}|whsec_[A-Za-z0-9_+/=-]{16,}|-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----)" ) FENCED_FILE_RE = re.compile( r"^```[A-Za-z0-9_+.-]*[ \t]+(?:path|file)=([^\s`]+)[ \t]*\r?\n(.*?)^```[ \t]*$", re.MULTILINE | re.DOTALL, ) def _is_secret_filename(name): lower = name.lower() return ( lower in PACK_SECRET_NAMES or lower.startswith(".env.") or lower.endswith((".pem", ".key", ".p12", ".pfx")) or lower.startswith(("id_rsa", "id_ed25519")) ) def _validate_rel_posix(raw_path): if ( not isinstance(raw_path, str) or not (1 <= len(raw_path) <= 200) or raw_path.startswith("/") or "\\" in raw_path or ":" in raw_path or any(ord(ch) < 32 for ch in raw_path) ): return None parts = raw_path.split("/") if any(part in ("", ".", "..") or part in PACK_SKIP_DIRS for part in parts): return None if _is_secret_filename(parts[-1]): return None return "/".join(parts) def pack_project(source_dir, destination, prompt_text, effort="medium"): if not isinstance(prompt_text, str) or not prompt_text.strip(ECMASCRIPT_SPACE): return {"status": "invalid_project_prompt"} root = os.path.abspath(source_dir) if os.path.islink(source_dir) or not os.path.isdir(root): return {"status": "project_dir_unavailable"} manifest = [] sections = [] total_source_bytes = 0 for current, dirs, filenames in os.walk(root, topdown=True, followlinks=False): if os.path.islink(current): return {"status": "unsafe_symlink_refused", "path": os.path.relpath(current, root)} dirs[:] = sorted(d for d in dirs if d not in PACK_SKIP_DIRS and not d.startswith(".tesi")) for fname in sorted(filenames): if fname.endswith((".pyc", ".pyo")) or fname == ".DS_Store" or fname.startswith(".tesi"): continue full = os.path.join(current, fname) rel = os.path.relpath(full, root).replace(os.sep, "/") if os.path.islink(full): return {"status": "unsafe_symlink_refused", "path": rel} if _is_secret_filename(fname): return {"status": "secret_file_refused", "path": rel} try: with open(full, "rb") as handle: data = handle.read(MAX_PROMPT_BYTES + 1) except OSError: return {"status": "project_file_unreadable", "path": rel} if len(data) > MAX_PROMPT_BYTES or b"\x00" in data: return {"status": "binary_or_oversize_file_refused", "path": rel} try: text = data.decode("utf-8") except UnicodeDecodeError: return {"status": "binary_or_oversize_file_refused", "path": rel} if PACK_SECRET_PATTERNS.search(text): return {"status": "secret_content_refused", "path": rel} if "```" in text: return {"status": "triple_backtick_in_source_unsupported", "path": rel} total_source_bytes += len(data) sha = hashlib.sha256(data).hexdigest() manifest.append({"path": rel, "bytes": len(data), "sha256": sha}) ext = os.path.splitext(fname)[1].lstrip(".") or "text" content_body = text if text.endswith("\n") else text + "\n" sections.append(f"```{ext} path={rel}\n{content_body}```") if not manifest: return {"status": "empty_project_dir"} header_lines = [ prompt_text.strip(ECMASCRIPT_SPACE), "", "Return every created or modified file in full as a fenced code block whose opening fence includes path= (for example: ```python path=app.py), followed by the exact test command and observed results.", "", f"Supplied project files ({len(manifest)} files, {total_source_bytes} UTF-8 bytes):", ] for item in manifest: header_lines.append(f"- {item['path']} ({item['bytes']} bytes, sha256={item['sha256']})") message = "\n".join(header_lines) + "\n\n" + "\n\n".join(sections) if len(message.encode("utf-8")) > MAX_PROMPT_BYTES: return {"status": "project_too_large_for_prompt", "promptBytes": len(message.encode("utf-8"))} result = write_prepared_request(destination, {"mode": "work", "effort": effort, "message": message}) if result["status"] != "request_prepared": return result return { **result, "packedFileCount": len(manifest), "packedSourceBytes": total_source_bytes, "promptBytes": len(message.encode("utf-8")), "files": manifest, } def extract_reply_files(reply_path, dest_dir): try: with open(reply_path, "rb") as handle: raw = handle.read(MAX_RECEIPT_BYTES + 1) if not raw or len(raw) > MAX_RECEIPT_BYTES: return {"status": "reply_file_unavailable"} reply_text = raw.decode("utf-8") except (OSError, UnicodeDecodeError): return {"status": "reply_file_unavailable"} reply_sha = hashlib.sha256(raw).hexdigest() matches = list(FENCED_FILE_RE.finditer(reply_text)) if not matches: return {"status": "no_fenced_files_found", "replySha256": reply_sha} planned = [] seen = set() for match in matches: clean_rel = _validate_rel_posix(match.group(1)) if clean_rel is None or clean_rel == "TESI-DELIVERY-MANIFEST.json": return {"status": "unsafe_extract_path_refused", "path": match.group(1)} if clean_rel in seen: return {"status": "duplicate_extract_path_refused", "path": clean_rel} seen.add(clean_rel) body_bytes = match.group(2).encode("utf-8") planned.append((clean_rel, body_bytes, hashlib.sha256(body_bytes).hexdigest())) target_root = os.path.abspath(dest_dir) if os.path.exists(target_root): if os.path.islink(target_root) or not os.path.isdir(target_root) or os.listdir(target_root): return {"status": "extract_destination_not_empty", "destinationDir": dest_dir} else: os.makedirs(target_root, mode=0o700, exist_ok=False) manifest_rows = [] for rel_path, body_bytes, file_sha in planned: full_out = os.path.join(target_root, *rel_path.split("/")) os.makedirs(os.path.dirname(full_out), mode=0o700, exist_ok=True) write_new_file(full_out, body_bytes) manifest_rows.append({"path": rel_path, "bytes": len(body_bytes), "sha256": file_sha}) manifest_doc = { "schema": "tesi-extracted-delivery/v1", "replySha256": reply_sha, "fileCount": len(manifest_rows), "files": manifest_rows, } write_new_file( os.path.join(target_root, "TESI-DELIVERY-MANIFEST.json"), (json.dumps(manifest_doc, indent=2, sort_keys=True) + "\n").encode("utf-8"), ) return { "status": "files_extracted", "destinationDir": dest_dir, "replySha256": reply_sha, "fileCount": len(manifest_rows), "files": manifest_rows, } def export_reply(result, destination, *, request=None): if result["status"] != "result_ready": return result reply = result.pop("reply") if "replySha256" not in result: return {**result, "status": "reply_digest_unavailable"} bundle = request is not None try: payload = reply.encode("utf-8") if bundle: receipt = {**result, "status": "reply_saved", "replyFile": "reply.md"} archive = BytesIO() with ZipFile(archive, "w") as output: output.writestr("request.json", request) output.writestr("reply.md", payload) output.writestr("reply-receipt.json", json.dumps(receipt, ensure_ascii=True) + "\n") payload = archive.getbuffer() write_new_file(destination, payload) except FileExistsError: return {**result, "status": "reply_bundle_exists" if bundle else "reply_file_exists"} except (ValueError, OSError, NotImplementedError): return {**result, "status": "reply_bundle_unavailable" if bundle else "reply_file_unavailable"} if bundle: return {**result, "status": "reply_bundle_saved", "replyBundle": destination} return {**result, "status": "reply_saved", "replyFile": destination} def reply_receipt_error(brief, receipt): expected = receipt.get("replySha256") if (receipt.get("status") != "reply_saved" or receipt.get("httpStatus") != 200 or not isinstance(expected, str) or not re.fullmatch(r"[a-f0-9]{64}", expected) or type(receipt.get("resultSavedAt")) is not int or receipt["resultSavedAt"] < 0): return "invalid_export_receipt" if (receipt.get("requestId") != brief["requestId"] or receipt.get("mode") != brief["mode"] or receipt.get("requestBodySha256") != brief["requestBodySha256"]): return "receipt_request_mismatch" return None def hash_reply(handle): digest = hashlib.sha256() size = 0 while chunk := handle.read(64 * 1024): size += len(chunk) if size > MAX_RECEIPT_BYTES: raise ValueError digest.update(chunk) if not size: raise ValueError return digest.hexdigest(), size def checked_reply(brief, receipt, digest, size, status): identifier = brief["requestId"] if digest != receipt["replySha256"]: return {"status": "reply_digest_mismatch", "requestId": identifier} return {"status": status, "requestId": identifier, "mode": brief["mode"], "requestBodySha256": brief["requestBodySha256"], "replySha256": digest, "resultSavedAt": receipt["resultSavedAt"], "replyBytes": size} def verify_saved_reply(brief, receipt_path, reply_path): identifier = brief["requestId"] try: _, receipt = request_file(receipt_path) except ValueError: return {"status": "invalid_export_receipt", "requestId": identifier} error = reply_receipt_error(brief, receipt) if error: return {"status": error, "requestId": identifier} try: flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) with os.fdopen(os.open(reply_path, flags), "rb") as handle: info = os.fstat(handle.fileno()) if not stat.S_ISREG(info.st_mode) or not 0 < info.st_size <= MAX_RECEIPT_BYTES: raise ValueError digest, size = hash_reply(handle) except (OSError, ValueError): return {"status": "reply_file_unavailable", "requestId": identifier} return checked_reply(brief, receipt, digest, size, "saved_reply_verified") def verify_reply_bundle(path, expected_fingerprint=None): limits = {"request.json": MAX_REQUEST_BYTES, "reply.md": MAX_RECEIPT_BYTES, "reply-receipt.json": MAX_REQUEST_BYTES} try: flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) with os.fdopen(os.open(path, flags), "rb") as handle: info = os.fstat(handle.fileno()) if not stat.S_ISREG(info.st_mode) or not 0 < info.st_size <= sum(limits.values()) + 65536: raise ValueError with ZipFile(handle) as archive: entries = archive.infolist() if (len(entries) != len(limits) or {entry.filename for entry in entries} != limits.keys() or any(entry.orig_filename != entry.filename or entry.compress_type != ZIP_STORED or entry.flag_bits & 1 or entry.compress_size != entry.file_size or not 0 < entry.file_size <= limits[entry.filename] for entry in entries)): raise ValueError raw = archive.read("request.json") request = json.loads(raw.decode("utf-8")) receipt = json.loads(archive.read("reply-receipt.json").decode("utf-8")) if not isinstance(request, dict) or not isinstance(receipt, dict): raise ValueError brief = request_fields(request, len(raw)) if expected_fingerprint is not None and request_fingerprint(brief) != expected_fingerprint: return {"status": "bundle_request_mismatch"} error = reply_receipt_error(brief, receipt) if error: return {"status": error, "requestId": brief["requestId"]} with archive.open("reply.md") as reply: digest, size = hash_reply(reply) except (OSError, ValueError, EOFError, BadZipFile, RuntimeError, struct.error): return {"status": "invalid_reply_bundle"} result = checked_reply(brief, receipt, digest, size, "reply_bundle_verified") if expected_fingerprint is not None and result["status"] == "reply_bundle_verified": result["expectedRequestMatched"] = True return result def recover(identifier, key, wait, fetch=fetch_receipt, clock=time.monotonic, sleep=time.sleep, expected_hash=None, first=None, wait_for_admission=False): deadline = clock() + wait timeout = min(READ_TIMEOUT, wait) if wait else READ_TIMEOUT while True: result = first if first is not None else read_once(identifier, key, timeout, fetch, expected_hash) first = None status = result["status"] if status in ("rate_limited", "read_unavailable"): delay = result.get("retryAfterSeconds") elif status in ("processing", "outcome_unknown") or (wait_for_admission and status == "receipt_missing"): delay = POLL_SECONDS else: return result remaining = deadline - clock() if delay is None or remaining <= delay: return result sleep(delay) remaining = deadline - clock() if remaining <= 0: return result timeout = min(READ_TIMEOUT, remaining) def run_saved_request(identifier, mode, raw, body_hash, key, wait, manual_topup=False, checked_binding=None): if not supports_submission(manual_topup, checked_binding): return {"requestId": identifier, "status": "submission_unavailable"} first = read_once(identifier, key, READ_TIMEOUT, fetch_receipt, body_hash) if first["status"] != "receipt_missing": return recover(identifier, key, wait, expected_hash=body_hash, first=first) status, payment, delay = submit_request(mode, raw, key, manual_topup, checked_binding) if checked_binding is not None and status == 412: return {"requestId": identifier, "status": "checked_request_mismatch", "postHttpStatus": status} # A 409 means the ID was already recorded, possibly after the first receipt read. uncertain = status is None or status == 409 or 200 <= status < 300 or status >= 500 result = recover(identifier, key, 0 if payment is not None else wait, expected_hash=body_hash, wait_for_admission=uncertain) result["postHttpStatus"] = status if result["status"] == "result_ready": return result if payment is not None: result["payment"] = payment if result["status"] == "receipt_missing": result.update(status="payment_required", receiptStatus="receipt_missing") elif result["status"] == "receipt_missing" and status == 429: result.update(status="rate_limited", retryAfterSeconds=delay) elif result["status"] in ("receipt_missing", "read_unavailable") and (uncertain or status == 402): result.update(status="submission_unknown", receiptStatus=result["status"]) return result def list_receipts(key, cursor=None, mode=None, delivery=None, page_size=25): connection = http.client.HTTPSConnection(HOST, timeout=READ_TIMEOUT) try: query = {} if cursor is not None: query["cursor"] = cursor if mode is not None: query["mode"] = mode if delivery is not None: query["delivery"] = delivery if page_size != 25: query["limit"] = page_size path = "/api/v1/agents/turns" + ("?" + urlencode(query) if query else "") connection.request("GET", path, headers={"Authorization": "Bearer " + key, "Accept": "application/json"}) response = connection.getresponse() base = {"httpStatus": response.status} if response.status == 429: return {**base, "status": "rate_limited", "retryAfterSeconds": retry_delay(response.getheader("Retry-After"))} if response.status in (401, 403): return {**base, "status": "key_rejected"} if response.status == 400: reason = "invalid_receipt_cursor" if cursor is not None else "invalid_receipt_query" return {**base, "status": reason} if response.status != 200: return {**base, "status": "receipt_history_unavailable"} limit = 32768 raw = response.read(limit + 1) except (OSError, http.client.HTTPException): return {"status": "receipt_history_unavailable"} finally: connection.close() try: data = json.loads(raw.decode("utf-8")) if len(raw) <= limit else {} if set(data) != {"receipts", "nextCursor"} or not isinstance(data["receipts"], list): raise ValueError rows = data["receipts"] if len(rows) > page_size: raise ValueError previous = None ids = set() for row in rows: expected = {"requestId", "mode", "receivedAt", "requestBodySha256", "status"} ready = row["status"] == "result_ready" if ready: expected.add("resultSavedAt") if (set(row) != expected or not ID.fullmatch(row["requestId"]) or row["requestId"] == cursor or row["requestId"] in ids or row["mode"] not in ("ask", "work") or (mode is not None and row["mode"] != mode) or (delivery is not None and ready != (delivery == "ready")) or row["status"] not in ("processing", "outcome_unknown", "result_ready") or not re.fullmatch(r"[a-f0-9]{64}", row["requestBodySha256"]) or type(row["receivedAt"]) is not int or row["receivedAt"] < 0 or (ready and (type(row["resultSavedAt"]) is not int or row["resultSavedAt"] < 0))): raise ValueError order = (row["receivedAt"], row["requestId"]) if previous is not None and order >= previous: raise ValueError previous = order ids.add(row["requestId"]) next_cursor = data["nextCursor"] if next_cursor is not None and (len(rows) != page_size or next_cursor != rows[-1]["requestId"]): raise ValueError except (KeyError, TypeError, ValueError, RecursionError, AttributeError): return {**base, "status": "invalid_receipt_history"} return {**base, "status": "receipts_ready", "receipts": rows, "nextCursor": next_cursor} def read_credits(key, cursor=None, refresh=False, window_hours=None): connection = http.client.HTTPSConnection(HOST, timeout=READ_TIMEOUT) try: path = "/api/v1/agents/balance" if refresh else "/api/v1/agents/usage" if cursor: path += "?cursor=" + cursor if window_hours is not None: path += "?windowHours=" + str(window_hours) connection.request("GET", path, headers={"Authorization": "Bearer " + key, "Accept": "application/json"}) response = connection.getresponse() base = {"httpStatus": response.status} if response.status == 429: return {**base, "status": "rate_limited", "retryAfterSeconds": retry_delay(response.getheader("Retry-After"))} if response.status in (401, 403): return {**base, "status": "key_rejected"} if response.status == 422 and window_hours is not None: return {**base, "status": "usage_window_too_large"} if response.status != 200: return {**base, "status": "credits_unavailable"} raw = response.read(MAX_REQUEST_BYTES + 1) except (OSError, http.client.HTTPException): return {"status": "credits_unavailable"} finally: connection.close() try: data = json.loads(raw.decode("utf-8")) if len(raw) <= MAX_REQUEST_BYTES else {} if data["creditUnit"] != "TESI credits": raise ValueError if window_hours is not None: fields = {"scope", "creditUnit", "windowHours", "sinceAt", "observedAt", "chargeCount", "debitPico"} if (data.keys() != fields or data["scope"] != "key_settled_debits_in_window" or type(data["windowHours"]) is not int or data["windowHours"] != window_hours or type(data["sinceAt"]) is not int or data["sinceAt"] < 0 or type(data["observedAt"]) is not int or data["observedAt"] - data["sinceAt"] != window_hours * 3_600_000 or type(data["chargeCount"]) is not int or not 0 <= data["chargeCount"] <= 10_000 or not PICO.fullmatch(data["debitPico"]) or (data["chargeCount"] == 0 and data["debitPico"] != "0")): raise ValueError return {**base, "status": "credits_window_ready", **data} ledger = data if refresh else data["balance"] balance = {field: ledger[field] for field in ("creditPico", "availablePico", "heldPico", "usedPico", "refundedPico")} if not all(isinstance(value, str) and PICO.fullmatch(value) for value in balance.values()): raise ValueError if refresh: return {**base, "status": "credits_ready", "creditUnit": "TESI credits", "balance": balance} if type(data["observedAt"]) is not int or data["observedAt"] < 0: raise ValueError rows = data["charges"] if not isinstance(rows, list) or len(rows) > 100: raise ValueError charges = [{field: row[field] for field in ("chargeId", "settledAt", "debitPico")} for row in rows] if any(not re.fullmatch(r"agc_[a-f0-9]{64}", row["chargeId"]) or type(row["settledAt"]) is not int or row["settledAt"] < 0 or not PICO.fullmatch(row["debitPico"]) for row in charges): raise ValueError next_cursor = data["nextCursor"] if next_cursor is not None and not USAGE_CURSOR.fullmatch(next_cursor): raise ValueError except (KeyError, TypeError, ValueError, RecursionError): return {**base, "status": "invalid_credits"} return {**base, "status": "credits_ready", "creditUnit": "TESI credits", "observedAt": data["observedAt"], "balance": balance, "charges": charges, "nextCursor": next_cursor} def matches_server_check(checked, raw, brief): return (checked["routeMode"] == brief["mode"] and checked["mode"] == brief["mode"] and checked["effort"] == json.loads(raw).get("effort") and checked["requestId"] == brief["requestId"] and type(checked["promptBytes"]) is int and checked["promptBytes"] == brief["promptBytes"] and checked["requestBodySha256"] == brief["requestBodySha256"] and re.fullmatch(r"[1-9][0-9]{0,24}", checked["minimumAvailablePico"]) and checked["creditUnit"] == "TESI credits") def read_checked_binding(path, raw, brief): try: _, checked = request_file(path) if (checked.keys() != SERVER_CHECK_FIELDS | {"httpStatus"} or checked["status"] != "server_request_valid" or type(checked["httpStatus"]) is not int or checked["httpStatus"] != 200): return "invalid_request_check", None if not matches_server_check(checked, raw, brief): return "checked_request_mismatch", None except (KeyError, TypeError, ValueError, RecursionError): return "invalid_request_check", None return None, brief["requestId"] + "." + brief["requestBodySha256"] def check_server_request(raw, brief): connection = http.client.HTTPSConnection(HOST, timeout=READ_TIMEOUT) try: path = "/api/v1/agents/request-check?as=" + brief["mode"] connection.request("POST", path, body=raw, headers={"Content-Type": "application/json", "Accept": "application/json"}) response = connection.getresponse() base = {"httpStatus": response.status} if response.status == 429: return {**base, "status": "rate_limited", "retryAfterSeconds": retry_delay(response.getheader("Retry-After"))} if response.status != 200: status = "server_request_rejected" if response.status in (400, 413, 415) else "server_check_unavailable" return {**base, "status": status} data = response.read(4097) except (OSError, http.client.HTTPException): return {"status": "server_check_unavailable"} finally: connection.close() try: checked = json.loads(data) if len(data) <= 4096 else {} if (checked.keys() != SERVER_CHECK_FIELDS or checked["status"] != "request_valid" or not matches_server_check(checked, raw, brief)): raise ValueError except (AttributeError, KeyError, TypeError, ValueError, RecursionError): return {**base, "status": "invalid_server_check"} return {**base, **checked, "status": "server_request_valid"} def check_batch_starting_credit(briefs, key): path = "/api/v1/agents/starting-credit/batch?" + urlencode( [("promptBytes", brief["promptBytes"]) for brief in briefs]) headers = {"Accept": "application/json"} if key is not None: headers["Authorization"] = "Bearer " + key connection = http.client.HTTPSConnection(HOST, timeout=READ_TIMEOUT) try: connection.request("GET", path, headers=headers) response = connection.getresponse() if response.status != 200: status = {401: "key_rejected", 403: "key_rejected", 429: "rate_limited"}.get( response.status, "batch_starting_credit_unavailable") result = {"status": status, "httpStatus": response.status} delay = retry_delay(response.getheader("Retry-After")) if response.status == 429 and delay is not None: result["retryAfterSeconds"] = delay return result data = response.read(4097) except (OSError, http.client.HTTPException): return {"status": "batch_starting_credit_unavailable"} finally: connection.close() try: body = json.loads(data.decode("utf-8")) if len(data) <= 4096 else {} expected_fields = {"basis", "creditUnit", "quotes"} if key is not None: expected_fields.add("availablePico") if (not isinstance(body, dict) or body.keys() != expected_fields or body["basis"] != "initial_available_credit" or body["creditUnit"] != "TESI credits"): raise ValueError available = body.get("availablePico") if key is not None and not re.fullmatch(r"0|[1-9][0-9]{0,24}", available): raise ValueError quotes = body["quotes"] if not isinstance(quotes, list) or len(quotes) != len(briefs): raise ValueError balance = int(available) if available is not None else None requests = [] for brief, quote in zip(briefs, quotes): if (not isinstance(quote, dict) or quote.keys() != {"promptBytes", "minimumAvailablePico"} or type(quote["promptBytes"]) is not int or quote["promptBytes"] != brief["promptBytes"] or not re.fullmatch(r"[1-9][0-9]{0,24}", quote["minimumAvailablePico"])): raise ValueError minimum = quote["minimumAvailablePico"] row = {**brief, "minimumAvailablePico": minimum} if balance is not None: row["meetsStartingCredit"] = balance >= int(minimum) requests.append(row) result = {"status": "batch_starting_credit_ready", "basis": body["basis"], "creditUnit": body["creditUnit"], "requests": requests} if available is not None: result["availablePico"] = available return result except (KeyError, TypeError, ValueError, RecursionError): return {"status": "invalid_batch_starting_credit"} def format_credits(pico): digits = (pico.lstrip("0") or "0").zfill(13) fraction = digits[-12:].rstrip("0").ljust(2, "0") return digits[:-12] + "." + fraction def check_starting_credit(brief, key, *, include_packs=False, refresh=False): if refresh: reconciled = read_credits(key, refresh=True) if reconciled["status"] != "credits_ready": result = {**brief, "status": "balance_unavailable", "balanceStatus": reconciled["status"]} if "httpStatus" in reconciled: result["balanceHttpStatus"] = reconciled["httpStatus"] if "retryAfterSeconds" in reconciled: result["retryAfterSeconds"] = reconciled["retryAfterSeconds"] return result comparison = check_batch_starting_credit([brief], key) if key is not None else None if comparison and comparison["status"] == "batch_starting_credit_ready": row = comparison["requests"][0] available = comparison["availablePico"] return { **row, "status": "starting_credit_ready", "creditUnit": comparison["creditUnit"], "minimumAvailableCredits": format_credits(row["minimumAvailablePico"]), "availablePico": available, "availableCredits": format_credits(available), } result = dict(brief) connection = http.client.HTTPSConnection(HOST, timeout=READ_TIMEOUT) try: path = "/api/v1/agents/starting-credit?promptBytes=" + str(brief["promptBytes"]) if include_packs: path += "&includePacks=1" connection.request("GET", path, headers={"Accept": "application/json"}) response = connection.getresponse() if response.status != 200: return {**result, "status": "starting_credit_unavailable", "httpStatus": response.status} data = response.read(4097) except (OSError, http.client.HTTPException): return {**result, "status": "starting_credit_unavailable"} finally: connection.close() try: quote = json.loads(data.decode("utf-8")) if len(data) <= 4096 else {} minimum = quote["minimumAvailablePico"] if (quote["basis"] != "initial_available_credit" or quote["creditUnit"] != "TESI credits" or type(quote["promptBytes"]) is not int or quote["promptBytes"] != brief["promptBytes"] or not re.fullmatch(r"[1-9][0-9]{0,24}", minimum)): raise ValueError if include_packs: packs = quote["packOptions"] amounts = checked_pack_amounts(packs["amountsCents"]) smallest = min((amount for amount in amounts if amount * PICO_PER_CENT >= int(minimum)), default=None) claimed = packs["smallestEligibleAmountCents"] if (claimed is not None and type(claimed) is not int) or claimed != smallest: raise ValueError result["packOptions"] = {"amountsCents": amounts, "smallestEligibleAmountCents": smallest} except (KeyError, TypeError, ValueError, RecursionError): return {**result, "status": "invalid_starting_credit"} result.update(status="starting_credit_ready", minimumAvailablePico=minimum, minimumAvailableCredits=format_credits(minimum), creditUnit="TESI credits") if comparison is not None: balance_status = { "batch_starting_credit_unavailable": "credits_unavailable", "invalid_batch_starting_credit": "invalid_credits", }.get(comparison["status"], comparison["status"]) result.update(status="balance_unavailable", balanceStatus=balance_status) if "httpStatus" in comparison: result["balanceHttpStatus"] = comparison["httpStatus"] if "retryAfterSeconds" in comparison: result["retryAfterSeconds"] = comparison["retryAfterSeconds"] return result def pack_review_result(quote, amount): whole, cents = divmod(amount, 100) price = f"${whole:,}.{cents:02d}" credits = format_credits(quote["minimumAvailablePico"]) task = "an Ask" if quote["mode"] == "ask" else "a Work" url = f"https://{HOST}/agents/?agentPack={amount}#agent-funding" summary = "\n".join([ f"Please review a one-time {price} USD TESI credit pack for {task} request.", f"Request ID: {quote['requestId']}", f"The request needs {credits} TESI credits to start. Usage is metered as it runs.", f"Review the pack at {url}", ]) return {**quote, "status": "request_pack_review_ready", "amountCents": amount, "currency": "usd", "packCreditPico": str(amount * PICO_PER_CENT), "reviewUrl": url, "approvalSummary": summary} def plan_topup(brief, key): receipt = read_once(brief["requestId"], key, READ_TIMEOUT, fetch_receipt, brief["requestBodySha256"]) if receipt["status"] != "receipt_missing": receipt.pop("reply", None) if receipt["status"] in ("result_ready", "processing", "outcome_unknown"): receipt["nextAction"] = "recover_original_receipt" return receipt result = {**brief, "receiptStatus": "receipt_missing"} connection = http.client.HTTPSConnection(HOST, timeout=READ_TIMEOUT) try: path = "/api/v1/agents/topup?promptBytes=" + str(brief["promptBytes"]) connection.request("GET", path, headers={"Authorization": "Bearer " + key, "Accept": "application/json"}) response = connection.getresponse() result["httpStatus"] = response.status if response.status == 429: return {**result, "status": "rate_limited", "retryAfterSeconds": retry_delay(response.getheader("Retry-After"))} if response.status in (401, 403): return {**result, "status": "key_rejected"} if response.status != 200: return {**result, "status": "topup_plan_unavailable"} raw = response.read(4097) except (OSError, http.client.HTTPException): return {**result, "status": "topup_plan_unavailable"} finally: connection.close() try: plan = json.loads(raw) if len(raw) <= 4096 else {} fields = {"basis", "promptBytes", "creditUnit", "minimumAvailablePico", "availablePico", "heldPico", "shortfallPico", "hasUnsettledTopup", "unsettledTopups", "amountsCents", "recommendedAmountCents"} if (plan.keys() != fields or plan["basis"] != "initial_available_credit" or plan["creditUnit"] != "TESI credits" or type(plan["promptBytes"]) is not int or plan["promptBytes"] != brief["promptBytes"] or type(plan["hasUnsettledTopup"]) is not bool): raise ValueError amounts = checked_pack_amounts(plan["amountsCents"]) minimum, available, held, shortfall = [plan[field] for field in ("minimumAvailablePico", "availablePico", "heldPico", "shortfallPico")] unsettled = plan["unsettledTopups"] order_states = ("creating", "open", "pending") if unsettled.keys() != {*order_states, "creditIfSettledPico"}: raise ValueError counts = [unsettled[state] for state in order_states] if any(type(count) is not int or not 0 <= count <= 2**53 - 1 for count in counts): raise ValueError potential = unsettled["creditIfSettledPico"] if (not re.fullmatch(r"[1-9][0-9]{0,24}", minimum) or any(not re.fullmatch(r"(?:0|[1-9][0-9]{0,24})", value) for value in (available, held, shortfall, potential))): raise ValueError if bool(sum(counts)) != plan["hasUnsettledTopup"] or bool(int(potential)) != plan["hasUnsettledTopup"]: raise ValueError gap = max(0, int(minimum) - int(available)) eligible = [amount for amount in amounts if amount * PICO_PER_CENT >= gap] recommended = min(eligible) if gap and not plan["hasUnsettledTopup"] and eligible else None claimed = plan["recommendedAmountCents"] if int(shortfall) != gap or (claimed is not None and type(claimed) is not int) or claimed != recommended: raise ValueError except (AttributeError, KeyError, TypeError, ValueError, RecursionError): return {**result, "status": "invalid_topup_plan"} if not gap: status = "starting_credit_ready" elif plan["hasUnsettledTopup"]: status = "topup_reconcile_first" elif recommended is None: status = "no_pack_covers_shortfall" else: status = "topup_plan_ready" result.update(plan, status=status) if status == "topup_plan_ready": dollars, cents = divmod(recommended, 100) result["approvalSummary"] = "\n".join([ f"Please approve a one-time ${dollars:,}.{cents:02d} USD top-up to the original TESI key.", f"Request ID: {brief['requestId']}", f"Spendable now: {format_credits(available)} TESI credits.", f"Required to start: {format_credits(minimum)} TESI credits.", f"Credit shortfall: {format_credits(shortfall)} TESI credits.", f"Pack credit: {format_credits(str(recommended * PICO_PER_CENT))} TESI credits.", "Usage is metered as the request runs. After approval, the agent can prepare the same-key Checkout.", ]) return result def read_topup_checkout(key, amount): path = "/api/v1/agents/topup/checkout?amountCents=" + str(amount) connection = http.client.HTTPSConnection(HOST, timeout=READ_TIMEOUT) try: connection.request("GET", path, headers={"Authorization": "Bearer " + key, "Accept": "application/json"}) response = connection.getresponse() base = {"httpStatus": response.status} if response.status == 429: return {**base, "status": "rate_limited", "retryAfterSeconds": retry_delay(response.getheader("Retry-After"))} if response.status != 200: states = {401: "key_rejected", 403: "key_rejected", 404: "no_unfinished_topup", 409: "checkout_unconfirmed", 503: "checkout_unconfirmed"} return {**base, "status": states.get(response.status, "checkout_unavailable")} raw = response.read(4097) except (OSError, http.client.HTTPException): return {"status": "checkout_unavailable"} finally: connection.close() try: data = json.loads(raw) if len(raw) <= 4096 else {} status = data["status"] fields = {"status", "amountCents", "currency", "expiresAt"} if status == "open": fields.add("checkoutUrl") if (data.keys() != fields or status not in ("open", "pending", "paid", "expired") or type(data["amountCents"]) is not int or data["amountCents"] != amount or data["currency"] != "usd" or type(data["expiresAt"]) is not int or not 0 < data["expiresAt"] <= 2**53 - 1): raise ValueError if status == "open" and (data["expiresAt"] <= int(time.time()) or not valid_checkout_link(data["checkoutUrl"])): raise ValueError except (AttributeError, KeyError, TypeError, ValueError, RecursionError): return {**base, "status": "invalid_checkout_lookup"} return {**base, **data, "status": "checkout_" + status} def review_request_pack(brief, amount): if amount == "smallest": quote = check_starting_credit(brief, None, include_packs=True) if quote["status"] != "starting_credit_ready": return quote smallest = quote["packOptions"]["smallestEligibleAmountCents"] if smallest is None: return {**quote, "status": "no_pack_covers_starting_credit"} return pack_review_result(quote, smallest) try: code, offer, delay = read_public_offer() if code != 200: return {**brief, "status": "rate_limited" if code == 429 else "offer_unavailable", "httpStatus": code, "retryAfterSeconds": delay} amounts = offered_pack_amounts(offer) except (KeyError, TypeError, ValueError, RecursionError): return {**brief, "status": "invalid_offer"} except (OSError, http.client.HTTPException): return {**brief, "status": "offer_unavailable"} if amount not in amounts: return {**brief, "status": "pack_unavailable", "advertisedAmountsCents": amounts} quote = check_starting_credit(brief, None) if quote["status"] != "starting_credit_ready": return quote minimum = int(quote["minimumAvailablePico"]) pack_pico = amount * PICO_PER_CENT review = {**quote, "amountCents": amount, "currency": "usd", "packCreditPico": str(pack_pico)} if pack_pico < minimum: return {**review, "status": "pack_below_starting_credit", "eligibleAmountsCents": [value for value in amounts if value * PICO_PER_CENT >= minimum]} return pack_review_result(quote, amount) def pack_selector(value): if value == "smallest": return value try: return int(value) except ValueError: raise argparse.ArgumentTypeError("use an amount in cents or smallest") from None def print_key_result(result, key_file): if result["status"] == "key_rejected" or ( result["status"] == "balance_unavailable" and result.get("balanceStatus") == "key_rejected" ): result["nextAction"] = "restore_original_key" result["keySource"] = "key_file" if key_file is not None else "TESI_API_KEY" print(json.dumps(result, ensure_ascii=True, allow_nan=False)) def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) source = parser.add_mutually_exclusive_group(required=True) source.add_argument("--file", help="saved request JSON, verified against its receipt when recovering") source.add_argument("--id", help="look up an original request ID without a saved brief") source.add_argument("--credits", action="store_true", help="read spendable credit and one page of settled debits") source.add_argument("--shortlist-work", action="store_true", help="list Work starters within a spendable balance or budget") parser.add_argument("--budget-credits", type=shortlist_budget_pico, metavar="TESI_CREDITS", help="with --shortlist-work, compare this planned balance without a key") source.add_argument("--receipts", action="store_true", help="list this key's recent Ask and Work receipt IDs") source.add_argument("--recover-topup", type=int, metavar="AMOUNT_CENTS", help="read the sole unfinished Checkout at the original amount without opening one") source.add_argument("--verify-reply-bundle", metavar="ZIP", help="verify the three records in a reply ZIP offline without extracting them") source.add_argument("--verify-public", action="store_true", help="verify the offer, OpenAPI and sample with public GETs") source.add_argument("--batch-credit", nargs="+", metavar="REQUEST_JSON", help="check starting credit for up to 20 saved requests in one read") source.add_argument("--extract-files", metavar="DEST_DIR", help="extract path-labeled fenced files from --reply-file into a new local directory") parser.add_argument("--cursor", help="nextCursor from the previous --credits or --receipts result") parser.add_argument("--mode", choices=("ask", "work"), help="with --receipts, list this request mode") parser.add_argument("--delivery", choices=("ready", "unresolved"), help="with --receipts, filter by reply availability") parser.add_argument("--limit", type=int, help="with --receipts, return 1–100 rows (default 25)") parser.add_argument("--refresh", action="store_true", help="with --credits or an explicit key comparison, reconcile existing top-ups") parser.add_argument("--window-hours", type=int, help="with --credits, total settled debits over the last 1–744 hours") parser.add_argument("--key-file", help="private key.json written by the buyer client") action = parser.add_mutually_exclusive_group() action.add_argument("--submit", action="store_true", help="authorize one saved request using prepaid credits") action.add_argument("--metadata-only", action="store_true", help="with --file or --id, print receipt status and UTC timestamps without the reply") parser.add_argument("--no-checkout", action="store_true", help="with --submit, return insufficient credit without preparing a top-up Checkout") parser.add_argument("--require-check", metavar="CHECK_JSON", help="with --submit, verify the request against saved --server-check output before sending") parser.add_argument("--expect-request-fingerprint", metavar="ID.SHA256", help="with --verify-reply-bundle, compare with a trusted original request fingerprint") parser.add_argument("--reply-file", metavar="PATH", help="export the original reply to a new file, or read the file with --verify-reply") action.add_argument("--reply-bundle", metavar="PATH", help="with --file, save the original brief, verified reply and receipt in a new ZIP") action.add_argument("--verify-reply", metavar="RECEIPT_JSON", help="verify a saved brief and reply offline against the JSON from reply export") action.add_argument("--validate", action="store_true", help="check a saved request locally before using credits") action.add_argument("--server-check", action="store_true", help="send a non-sensitive saved request to the server parser without submitting paid work") action.add_argument("--prepare-ask", action="store_true", help="with --file, save a new example Ask request with its own ID, offline") parser.add_argument("--message-stdin", action="store_true", help="with --prepare-ask, read the UTF-8 question from standard input") action.add_argument("--prepare-work", metavar="STARTER", help="with --file, save a published Work starter with its own ID") action.add_argument("--pack-project", metavar="SOURCE_DIR", help="with --file and --prompt, bundle safe local UTF-8 files into a new Work request") parser.add_argument("--prompt", help="with --pack-project, task instructions for the packed project") parser.add_argument("--effort", choices=EFFORTS, help="with --pack-project, Work effort (default medium)") action.add_argument("--copy-brief", metavar="SOURCE_JSON", help="with --file, copy a saved Ask or Work brief to a fresh request ID, offline") action.add_argument("--check-credit", action="store_true", help="look up starting credit and optionally compare the saved key's balance") parser.add_argument("--compare-key-balance", action="store_true", help="with --check-credit, compare against the key in TESI_API_KEY or --key-file") action.add_argument("--plan-topup", action="store_true", help="check the original receipt and current key before reviewing a top-up") action.add_argument("--review-pack", type=pack_selector, metavar="AMOUNT_CENTS_OR_SMALLEST", help="compare a pack or find the smallest offered pack that covers starting credit") parser.add_argument("--wait", type=int, default=0, metavar="SECONDS", help="poll the same receipt through temporary read failures; 0–300 seconds, default one read") args = parser.parse_args(argv) if not 0 <= args.wait <= 300: parser.error("--wait must be between 0 and 300 seconds.") try: if args.compare_key_balance and not args.check_credit: parser.error("--compare-key-balance requires --check-credit.") if args.budget_credits is not None and (not args.shortlist_work or args.key_file is not None): parser.error("--budget-credits requires --shortlist-work without --key-file.") if args.metadata_only and (not (args.file or args.id) or args.reply_file is not None): parser.error("--metadata-only requires --file or --id and takes no --reply-file.") expected_fingerprint = args.expect_request_fingerprint if expected_fingerprint is not None: if args.verify_reply_bundle is None: parser.error("--expect-request-fingerprint requires --verify-reply-bundle.") if not re.fullmatch(r"mw_[a-f0-9]{32}\.[a-f0-9]{64}", expected_fingerprint): parser.error("Use the original request ID followed by a dot and its lowercase SHA-256.") if args.verify_reply_bundle is not None: if any(value != parser.get_default(name) for name, value in vars(args).items() if name not in ("verify_reply_bundle", "expect_request_fingerprint")): parser.error("--verify-reply-bundle takes the ZIP path and optional request fingerprint.") result = verify_reply_bundle(args.verify_reply_bundle, expected_fingerprint) print(json.dumps(result, ensure_ascii=True, allow_nan=False)) return 0 if result["status"] == "reply_bundle_verified" else 2 if args.extract_files is not None: if not args.reply_file or any( value != parser.get_default(name) for name, value in vars(args).items() if name not in ("extract_files", "reply_file") ): parser.error("--extract-files requires --reply-file and takes no key, wait or request options.") result = extract_reply_files(args.reply_file, args.extract_files) print(json.dumps(result, ensure_ascii=True, allow_nan=False)) return 0 if result["status"] == "files_extracted" else 2 if (args.prompt is not None or args.effort is not None) and args.pack_project is None: parser.error("--prompt and --effort require --pack-project.") if args.reply_bundle is not None and (not args.file or args.reply_file is not None): parser.error("--reply-bundle requires --file and takes no --reply-file.") if args.submit and not args.file: parser.error("--submit requires --file.") if args.plan_topup and (not args.file or args.wait): parser.error("--plan-topup requires --file and takes no wait option.") if args.no_checkout and not args.submit: parser.error("--no-checkout requires --submit.") if args.require_check is not None and not args.submit: parser.error("--require-check requires --submit.") if not args.receipts and any(value is not None for value in (args.mode, args.delivery, args.limit)): parser.error("--mode, --delivery and --limit require --receipts.") if args.limit is not None and not 1 <= args.limit <= 100: parser.error("--limit must be between 1 and 100.") if args.message_stdin and not args.prepare_ask: parser.error("--message-stdin requires --prepare-ask.") preparing = ( args.prepare_ask or args.prepare_work is not None or args.copy_brief is not None or args.pack_project is not None ) if args.reply_file is not None and (not args.file or args.submit or args.validate or args.server_check or args.check_credit or args.plan_topup or args.review_pack is not None or preparing): parser.error("--reply-file requires --file and a read-only receipt lookup.") if args.verify_reply is not None: if not args.file or not args.reply_file or args.key_file is not None or args.wait: parser.error("--verify-reply requires --file and --reply-file and takes no key or wait options.") _, brief = saved_request(args.file) result = verify_saved_reply(brief, args.verify_reply, args.reply_file) print(json.dumps(result, ensure_ascii=True, allow_nan=False)) return 0 if result["status"] == "saved_reply_verified" else 2 if args.cursor is not None: valid_cursor = (args.credits and USAGE_CURSOR.fullmatch(args.cursor) or args.receipts and ID.fullmatch(args.cursor)) if not valid_cursor: parser.error("--cursor requires --credits or --receipts and the previous nextCursor.") if args.refresh and (args.cursor is not None or not ( args.credits or (args.check_credit and (args.compare_key_balance or args.key_file is not None)) )): parser.error("--refresh requires --credits without --cursor, or --check-credit with a key comparison.") if args.window_hours is not None and (not args.credits or args.cursor is not None or args.refresh or not 1 <= args.window_hours <= 744): parser.error("--window-hours requires --credits and 1–744 hours, with no cursor or refresh.") if (args.credits or args.receipts) and args.wait: parser.error("--wait is for a Work or Ask receipt.") if args.shortlist_work: if (args.wait or args.validate or args.server_check or args.check_credit or args.plan_topup or args.review_pack is not None or preparing): parser.error("--shortlist-work takes a key or planned credits.") key = load_key(args.key_file) if args.budget_credits is None else None result = shortlist_work(key, args.budget_credits) print(json.dumps(result, ensure_ascii=True, allow_nan=False)) return {"work_shortlist_ready": 0, "rate_limited": 1}.get(result["status"], 2) if args.batch_credit is not None: if (args.wait or args.validate or args.server_check or args.check_credit or args.review_pack is not None or preparing): parser.error("--batch-credit takes only saved request paths and an optional key file.") if len(args.batch_credit) > MAX_CREDIT_BATCH_ITEMS: parser.error("--batch-credit accepts at most 20 saved requests.") briefs = [saved_request(path)[1] for path in args.batch_credit] if len({brief["requestId"] for brief in briefs}) != len(briefs): raise ValueError("Each saved request in --batch-credit needs a distinct request ID.") key = load_key(args.key_file) if args.key_file is not None else None result = check_batch_starting_credit(briefs, key) print_key_result(result, args.key_file) return {"batch_starting_credit_ready": 0, "rate_limited": 1}.get(result["status"], 2) if args.recover_topup is not None: if not 100 <= args.recover_topup <= 1_000_000: parser.error("--recover-topup requires an amount in cents between 100 and 1000000.") if (args.wait or args.validate or args.server_check or args.check_credit or args.review_pack is not None or args.verify_reply is not None or preparing): parser.error("--recover-topup takes a key and the original amount only.") result = read_topup_checkout(load_key(args.key_file), args.recover_topup) print_key_result(result, args.key_file) status = result["status"] if status in ("checkout_open", "checkout_paid", "checkout_expired"): return 0 return 1 if status in ("checkout_pending", "checkout_unconfirmed", "rate_limited") else 2 if args.verify_public: if (args.key_file is not None or args.wait or args.validate or args.server_check or args.check_credit or args.review_pack is not None or preparing): parser.error("--verify-public takes no key, wait or request options.") result = verify_public() print(json.dumps(result, ensure_ascii=True, allow_nan=False)) return 0 if result["status"] == "public_checks_passed" else 2 if preparing: flag = "--prepare-ask" if args.prepare_ask else "--prepare-work" if args.copy_brief is not None: flag = "--copy-brief" elif args.pack_project is not None: flag = "--pack-project" if not args.file or args.key_file is not None or args.wait: parser.error(flag + " requires --file and takes no key or wait options.") if args.pack_project is not None and not args.prompt: parser.error("--pack-project requires --prompt.") if args.prepare_work is not None and not STARTER_ID.fullmatch(args.prepare_work): parser.error("--prepare-work requires a published starter ID.") if args.copy_brief is not None: result = copy_brief(args.copy_brief, args.file) elif args.pack_project is not None: result = pack_project(args.pack_project, args.file, args.prompt, args.effort or "medium") elif args.prepare_ask: result = prepare_ask(args.file, message_stdin=args.message_stdin) else: result = prepare_work(args.file, args.prepare_work) print(json.dumps(result, ensure_ascii=True, allow_nan=False)) return {"request_prepared": 0, "rate_limited": 1}.get(result["status"], 2) if args.validate or args.server_check or args.check_credit or args.review_pack is not None: if args.validate and (not args.file or args.key_file is not None or args.wait): parser.error("--validate requires --file and takes no key or wait options.") if args.server_check and (not args.file or args.key_file is not None or args.wait): parser.error("--server-check requires --file and takes no key or wait options.") if args.check_credit and (not args.file or args.wait): parser.error("--check-credit requires --file and takes no wait option.") if args.review_pack is not None and (not args.file or args.wait or args.key_file is not None): parser.error("--review-pack requires --file and takes no key or wait options.") if args.review_pack not in (None, "smallest") and not 100 <= args.review_pack <= 1_000_000: parser.error("--review-pack requires an amount in cents between 100 and 1000000.") try: raw, brief = saved_request(args.file) except ValueError as error: result = {"status": "invalid_request", "message": str(error)} else: if args.review_pack is not None: result = review_request_pack(brief, args.review_pack) elif args.server_check: result = check_server_request(raw, brief) elif args.check_credit: compare = args.key_file is not None or args.compare_key_balance key = load_key(args.key_file) if compare else None result = check_starting_credit(brief, key, refresh=args.refresh) else: result = {"status": "request_valid", **brief, "requestFingerprint": request_fingerprint(brief)} print_key_result(result, args.key_file) if result["status"] == "rate_limited": return 1 return 0 if result["status"] in ("request_valid", "server_request_valid", "starting_credit_ready", "request_pack_review_ready") else 2 checked_draft = None checked_binding = None if args.require_check is not None: checked_draft = saved_request(args.file) raw, brief = checked_draft error, checked_binding = read_checked_binding(args.require_check, raw, brief) if error: print(json.dumps({"status": error, "requestId": brief["requestId"]}, ensure_ascii=True)) return 2 key = load_key(args.key_file) if args.credits: result = read_credits(key, args.cursor, args.refresh, args.window_hours) elif args.receipts: result = list_receipts(key, args.cursor, args.mode, args.delivery, args.limit or 25) elif args.plan_topup: _, brief = saved_request(args.file) result = plan_topup(brief, key) elif args.submit: raw, brief = checked_draft if checked_draft is not None else saved_request(args.file) result = run_saved_request(brief["requestId"], brief["mode"], raw, brief["requestBodySha256"], key, args.wait, args.no_checkout, checked_binding) if (result["status"] == "payment_required" and result.get("payment", {}).get("status") == "manual_topup_required"): result["nextAction"] = "plan_same_key_topup" elif (result["status"] in ("processing", "outcome_unknown", "submission_unknown", "read_unavailable") or (result["status"] == "rate_limited" and result.get("postHttpStatus") == 409)): result["nextAction"] = "recover_original_receipt" elif args.file: raw, brief = saved_request(args.file, receipt_lookup=args.reply_file is None and args.reply_bundle is None) expected_hash = brief.get("requestBodySha256") result = recover(brief["requestId"], key, args.wait, expected_hash=expected_hash, wait_for_admission=expected_hash is not None) if result["status"] in ("receipt_missing", "processing", "outcome_unknown", "read_unavailable", "rate_limited"): result["nextAction"] = "recover_original_receipt" if args.reply_bundle is not None: result = export_reply(result, args.reply_bundle, request=raw) elif args.reply_file is not None: result = export_reply(result, args.reply_file) else: result = recover(request_id(args.id), key, args.wait) except ValueError as error: parser.error(str(error)) if result["status"] == "receipt_request_mismatch": result["nextAction"] = "recover_with_original_brief" if args.metadata_only: result = receipt_metadata(result) print_key_result(result, args.key_file) if result["status"] in ("result_ready", "credits_ready", "credits_window_ready", "reply_saved", "reply_bundle_saved", "receipts_ready", "starting_credit_ready", "topup_plan_ready"): return 0 return 1 if result["status"] in ("processing", "outcome_unknown", "receipt_missing", "rate_limited", "submission_unknown", "payment_required", "topup_reconcile_first") else 2 if __name__ == "__main__": raise SystemExit(main())