"""Offline Messages replies and recorded gateway model catalogs.""" import json from harness import Provider from provider_events import messages_events class Gateway(Provider): """Serve Messages through Provider and record model catalog requests.""" def __init__(self, script, *, catalog): super().__init__(script, catalog=catalog, chunk_size=7) self.model_requests = [] self.catalog_status = 200 self.catalog_payload = None self.catalog_redirect = None def _get(owner, self): with owner._lock: owner.model_requests.append( { "path": self.path, "authorization": self.headers.get("Authorization"), } ) if owner.catalog_redirect is not None: self.send_response(302) self.send_header("Location", owner.catalog_redirect) self.send_header("Content-Length", "0") self.end_headers() return payload = ( owner.catalog_payload if owner.catalog_payload is not None else json.dumps(owner.catalog).encode() ) self.send_response(owner.catalog_status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(payload))) self.end_headers() self.wfile.write(payload) def redacted_tool(reply): """Insert an opaque redacted block before signed thinking and a tool call.""" arguments = json.dumps({"code": reply.value, "timeout_ms": 60000}) events = list(messages_events(reply, arguments, "fixture-call-1", 7)) for event in events: if "index" in event: event["index"] += 1 if event.get("content_block", {}).get("type") == "thinking": event["content_block"]["signature"] = "stale-start-signature" signature = next( index for index, event in enumerate(events) if event.get("delta", {}).get("type") == "signature_delta" ) index = events[signature]["index"] events[signature : signature + 1] = [ { "type": "content_block_delta", "index": index, "delta": {"type": "signature_delta", "signature": "fixture-"}, }, { "type": "content_block_delta", "index": index, "delta": {"type": "signature_delta", "signature": "signature"}, }, ] events[1:1] = [ { "type": "content_block_start", "index": 0, "content_block": { "type": "redacted_thinking", "data": "cmVkYWN0ZWQtZml4dHVyZQ==", }, }, {"type": "content_block_stop", "index": 0}, ] reply.events = events return reply def cached_messages(reply, *, read=400, creation=200): """Add cache usage to the normal fake provider Messages stream.""" events = list(messages_events(reply, "", "unused", 7)) events[0]["message"]["usage"].update( cache_read_input_tokens=read, cache_creation_input_tokens=creation ) reply.events = events return reply