"""Synthetic read-only support workflow; no model SDK, transport or credentials.""" import asyncio import copy import math import re async def run(model, lookup, account, requested_order, *, max_calls=2, deadline=1.0, dependency_timeout=0.1): # account and requested_order come from the application's authenticated task. if not isinstance(account, str) or not account: raise ValueError("authenticated account required") if not isinstance(requested_order, str) or not re.fullmatch(r"order-[0-9]{1,12}", requested_order): raise ValueError("invalid requested order") if type(max_calls) is not int or not 0 <= max_calls <= 10: raise ValueError("invalid call budget") for seconds in (deadline, dependency_timeout): if type(seconds) not in (int, float) or not math.isfinite(seconds) or not 0 < seconds <= 60: raise ValueError("invalid timeout") trace, calls = [], 0 def stop(reason): return {"outcome": reason, "trace": trace} try: async with asyncio.timeout(deadline): while True: try: proposal = await asyncio.wait_for(model(copy.deepcopy(trace)), dependency_timeout) except TimeoutError: return stop("model_timeout") except OSError: return stop("model_unavailable") if type(proposal) is not dict: return stop("invalid_proposal") if set(proposal) == {"finish"}: # Return a status draft, never free-form model prose. if proposal["finish"] is not True or not trace or not trace[-1]["ok"]: return stop("unresolved") return {"outcome": "draft", "order_id": requested_order, "status": trace[-1]["status"], "trace": trace} if calls >= max_calls: return stop("call_limit") calls += 1 # Count denied attempts too; retries consume the same budget. if set(proposal) != {"tool", "arguments"} or proposal["tool"] != "lookup_order": return stop("tool_denied") args = proposal["arguments"] if type(args) is not dict or set(args) != {"order_id"}: return stop("invalid_arguments") if type(args["order_id"]) is not str or args["order_id"] != requested_order: return stop("task_mismatch") try: raw = await asyncio.wait_for(lookup(account, requested_order), dependency_timeout) except TimeoutError: trace.append({"ok": False, "error": "lookup_timeout"}) continue except OSError: trace.append({"ok": False, "error": "lookup_unavailable"}) continue if raw is None: trace.append({"ok": False, "error": "not_found"}) elif type(raw) is dict and raw.get("status") in ("processing", "shipped"): # Do not pass arbitrary database notes or instructions to the model. trace.append({"ok": True, "status": raw["status"]}) else: return stop("invalid_tool_result") except TimeoutError: return stop("deadline") def gate(results, required_categories): """Fail closed on missing categories, failures or an empty evaluation.""" return bool(required_categories) and set(results) == set(required_categories) and all( type(values) is list and bool(values) and all(value is True for value in values) for values in results.values() )