"""A mock of Anthropic's Messages API for claude to call at `ANTHROPIC_BASE_URL`: it keeps each request and answers as a worker that is done, or as a judge that rules the chunk finished. It answers no other path of the API: claude runs a chunk without them. """ import http.server import json import threading import typing # What the worker says, whole. The judge quotes it as its evidence, which build-release checks against the transcript. WORKER_REPLY = "The note is written, so the chunk is finished." class Requests: """Every body posted to the Messages API so far, oldest first.""" def __init__(self) -> None: self.lock = threading.Lock() self.bodies: list[dict[str, typing.Any]] = [] def add(self, body: dict[str, typing.Any]) -> None: with self.lock: self.bodies.append(body) def texts(self) -> list[str]: """Each request as JSON text, to search for what claude sent.""" with self.lock: return [json.dumps(body, ensure_ascii=False) for body in self.bodies] def verdict_tool(body: dict[str, typing.Any]) -> str | None: """The name of the tool claude offers for a reply that fits build-release's judge schema, which is how `--json-schema` asks for one; None in any other request.""" for tool in body.get("tools", []): if {"finished", "interrupt", "evidence"} <= set(tool.get("input_schema", {}).get("properties", {})): return tool["name"] return None def answered(body: dict[str, typing.Any]) -> bool: """Whether the request's last message returns a tool's result, so the verdict was already given.""" content = body["messages"][-1]["content"] return isinstance(content, list) and any(block.get("type") == "tool_result" for block in content) def verdict(schema: dict[str, typing.Any]) -> dict[str, typing.Any]: """A reply that fits schema and rules the chunk finished on the worker's reply: every other field is empty or false.""" empty = {name: "" if field["type"] == "string" else False if field["type"] == "boolean" else 0 for name, field in schema["properties"].items()} return {**empty, "finished": True, "evidence": WORKER_REPLY} def reply_block(body: dict[str, typing.Any]) -> dict[str, typing.Any]: """The one content block that answers body.""" tool = verdict_tool(body) if tool is None or answered(body): return {"type": "text", "text": WORKER_REPLY} schema = next(each["input_schema"] for each in body["tools"] if each["name"] == tool) return {"type": "tool_use", "id": "toolu_verdict", "name": tool, "input": verdict(schema)} def message(body: dict[str, typing.Any], block: dict[str, typing.Any]) -> dict[str, typing.Any]: return { "id": "msg_mock", "type": "message", "role": "assistant", "model": body.get("model", "mock"), "content": [block], "stop_reason": "tool_use" if block["type"] == "tool_use" else "end_turn", "stop_sequence": None, "usage": {"input_tokens": 1, "output_tokens": 1}, } def stream(whole: dict[str, typing.Any]) -> bytes: """whole as the server-sent events of a streamed reply.""" block = whole["content"][0] if block["type"] == "text": start, delta = {"type": "text", "text": ""}, {"type": "text_delta", "text": block["text"]} else: start, delta = {**block, "input": {}}, {"type": "input_json_delta", "partial_json": json.dumps(block["input"])} events = [ {"type": "message_start", "message": {**whole, "content": [], "stop_reason": None}}, {"type": "content_block_start", "index": 0, "content_block": start}, {"type": "content_block_delta", "index": 0, "delta": delta}, {"type": "content_block_stop", "index": 0}, {"type": "message_delta", "delta": {"stop_reason": whole["stop_reason"], "stop_sequence": None}, "usage": {"output_tokens": 1}}, {"type": "message_stop"}, ] return "".join(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n" for event in events).encode() def serve(requests: Requests) -> http.server.ThreadingHTTPServer: """Starts the mock on a free port of this machine, and returns its server, whose `server_port` names the port.""" class Handler(http.server.BaseHTTPRequestHandler): def do_POST(self) -> None: body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) if self.path.split("?")[0] != "/v1/messages": self.answer(404, "application/json", b'{"type": "error", "error": {"type": "not_found_error", "message": "the mock answers only /v1/messages"}}') return requests.add(body) whole = message(body, reply_block(body)) if body.get("stream"): self.answer(200, "text/event-stream", stream(whole)) else: self.answer(200, "application/json", json.dumps(whole).encode()) def answer(self, status: int, kind: str, content: bytes) -> None: self.send_response(status) self.send_header("Content-Type", kind) self.send_header("Content-Length", str(len(content))) self.end_headers() self.wfile.write(content) def log_message(self, format: str, *args: typing.Any) -> None: """Silent: the run's own output says what failed.""" server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) threading.Thread(target=server.serve_forever, daemon=True).start() return server