def _run(packet, context, *, output_path, api_key=None, config_path=None, transport=None, calibration=False): started = datetime.now(UTC).isoformat() digest = packet_hash(packet) base = {"schema_version": 1, "role": "external_advisory", "packet_sha256": digest, "started_at": started, "configured_model": MODEL, "configured_provider": PROVIDER, "scope": "supplied_excerpts_only", "required_reviews_replaced": False} owned = transport is None client = transport or _HTTP() policy = None existing_paid = None try: existing_paid = _existing_paid_report(output_path) configuration = json.loads(Path(config_path or CONFIG).read_text(encoding="utf-8")) policy = _policy(configuration) if existing_paid is not None and not policy["paid"]: raise PaidReceiptConflict("existing_paid_receipt_route_changed") base.update(configured_model=policy["model"], configured_provider=policy["provider"]) if not calibration: _require_qualification(configuration, policy) key = api_key if api_key is not None else os.environ.get("OPENROUTER_API_KEY") if not key: raise ReviewUnavailable("key_unavailable") public_context = public_review_context(context) data = _json({"publication_copy": _public_packet(packet), "source_excerpts": public_context}) if len(data.encode()) > INPUT_CAP: raise ReviewUnavailable("input_size_exceeded") if SECRET_PATTERN.search(data) or key in data: raise ReviewUnavailable("credential_pattern_in_input") request = _request(data, policy) binding = { "packet_sha256": digest, "public_input_sha256": hashlib.sha256(data.encode()).hexdigest(), "request_sha256": hashlib.sha256(_json(request).encode()).hexdigest(), "configuration_sha256": hashlib.sha256(_json(configuration).encode()).hexdigest(), "calibration_run": calibration, } if policy["paid"]: retained = _retained_paid_report(existing_paid, binding) if retained is not None: return _write(output_path, retained) deadline = time.monotonic() + TOTAL_SECONDS route = _check_endpoint(client, deadline, policy) if policy["paid"]: reservation, input_bound = _paid_reservation(request, policy, route) key_budget = _check_key_budget(client, deadline, key, policy, reservation) base.update( **binding, **key_budget, paid_request=True, reserved_cost_usd=float(reservation), cost_usd=None, cost_status="unknown", charged_or_reserved_usd=float(reservation), input_token_upper_bound=input_bound, max_output_tokens=policy["max_tokens"], configured_provider_tag=policy["tag"], ) # This receipt survives an abrupt termination before a response. # The provider's verified monthly key limit is the durable cap; # this local file is an audit reservation, not that enforcement. _write(output_path, {**base, "status": "reserved"}) # One inference attempt per invocation. Quota/outage retries belong to # a deliberately new attempt, never an automatic replay of this receipt. response = client("POST", f"{BASE}/chat/completions", headers={ "Authorization": "Bearer " + key, "Content-Type": "application/json", "HTTP-Referer": "https://ledecaf.com", "X-OpenRouter-Title": "LeDecaf experimental editorial review", }, body=request, deadline=deadline, cap=RESPONSE_CAP) usage = response.get("usage") or {} cost = usage.get("cost") if isinstance(usage, dict) else None if policy["paid"]: # Capture accounting before rejecting identity, truncation or copy. generation = response.get("id") if isinstance(generation, str) and re.fullmatch(r"[a-zA-Z0-9_-]{1,180}", generation): base["generation_id"] = generation amount = _amount(cost, "paid_cost_not_confirmed") # A hostile oversized numeric value must remain serializable too. recorded_cost = float(amount) if amount <= Decimal("1e100") else str(amount) base.update(cost_usd=recorded_cost, cost_status="confirmed", charged_or_reserved_usd=recorded_cost, cost_basis="openrouter_credits") details = usage.get("cost_details") or {} if not isinstance(details, dict): raise ReviewUnavailable("paid_cost_details_invalid") upstream = details.get("upstream_inference_cost") if upstream is not None: upstream = _amount(upstream, "paid_cost_details_invalid") base["upstream_inference_cost_usd"] = ( float(upstream) if upstream <= Decimal("1e100") else str(upstream)) byok = usage.get("is_byok") if type(byok) is bool: base["is_byok"] = byok if byok is not False: # Credit-funded requests also report a positive upstream cost. # Only explicit BYOK means that amount is a separate bill. accounted = max(reservation, amount + (upstream or 0)) base.update( cost_status="separate_byok_charge" if byok is True and upstream is not None else "unknown", charged_or_reserved_usd=float(accounted) if accounted <= Decimal("1e100") else str(accounted), ) raise ReviewUnavailable("unexpected_byok_request" if byok is True else "byok_status_unconfirmed") base["usage_tokens"] = {name: usage[name] for name in ("prompt_tokens", "completion_tokens", "total_tokens") if type(usage.get(name)) is int and 0 <= usage[name] <= 2_000_000} if amount > reservation: raise ReviewUnavailable("paid_cost_exceeded_reservation") elif type(cost) not in (int, float) or cost != 0: raise ReviewUnavailable("zero_cost_not_confirmed") if response.get("model") != policy["model"] or response.get("provider") != policy["provider"]: raise ReviewUnavailable("returned_identity_mismatch") choices = response.get("choices", []) if isinstance(choices, list) and len(choices) == 1 and isinstance(choices[0], dict): finish = choices[0].get("finish_reason") if finish in {"stop", "length", "error"}: base["response_finish_reason"] = finish if (len(choices) != 1 or choices[0].get("finish_reason") != "stop" or choices[0].get("message", {}).get("tool_calls")): raise ReviewUnavailable("incomplete_response") review = json.loads(choices[0]["message"]["content"]) if list(Draft202012Validator(REVIEW_SCHEMA).iter_errors(review)): raise ReviewUnavailable("invalid_review_schema") known_ids = {identifier for snapshot in public_context["snapshots"] for identifier in snapshot.get("evidence_ids", [])} known_ids.update(item.get("id") for story in packet.get("stories", []) for item in story.get("evidence", [])) if any(not set(finding["evidence_ids"]) <= known_ids for finding in review["findings"]): raise ReviewUnavailable("unknown_evidence_reference") material = [finding["id"] for finding in review["findings"] if finding["severity"] in ("medium", "high", "critical")] if material and review["decision"] == "approve": raise ReviewUnavailable("inconsistent_review_decision") report = {**base, **review, "status": "complete", "model": response["model"], "provider": response["provider"], "cost_usd": float(amount) if policy["paid"] else 0, "material_findings": material, "completed_at": datetime.now(UTC).isoformat(), "public_input_sha256": hashlib.sha256(data.encode()).hexdigest(), "input_bytes": len(data.encode()), "calibration_run": calibration, "limitations": ["Only supplied excerpts were inspected; no URLs were independently opened.", "Private memory, predecessor drafts and internal associations were excluded.", "This advisory assessment does not replace required factual and editorial reviews."]} return _write(output_path, report) except ReviewUnavailable as error: if existing_paid is not None: raise PaidReceiptConflict("existing_paid_receipt_not_overwritten") from None return _write(output_path, {**base, "status": "unavailable", "reason": str(error), **({"retry_after_seconds": error.retry_after_seconds} if error.retry_after_seconds is not None else {}), "completed_at": datetime.now(UTC).isoformat()}) except (ValueError, TypeError, KeyError, AttributeError, IndexError, OSError): if existing_paid is not None: raise PaidReceiptConflict("existing_paid_receipt_not_overwritten") from None return _write(output_path, {**base, "status": "unavailable", "reason": "invalid_input_or_configuration", "completed_at": datetime.now(UTC).isoformat()}) finally: if owned: client.close()