Files

118 lines
5.3 KiB
Python

#!/usr/bin/env python3
"""A throw-away /v1/responses server that makes the Codex CLI spawn sub-agents (TEST TOOLING, no model, no GPU, stdlib only).
mock_subagent_server.py PORT CAPTURE.jsonl [N_CHILDREN] [CHILD_DELAY_S]
Step P0. The root thread (the thread of the first request) is scripted: its first request is
answered with N_CHILDREN `multi_agent_v1.spawn_agent` calls in one response, the next request with a `wait_agent` call on the agent ids that
the spawn outputs returned, the last one with a final text. Every other thread (a sub-agent) answers with a one-line message after
CHILD_DELAY_S seconds. CAPTURE.jsonl gets one line per request: arrival and finish time, thread id, agent name, input and tool counts, the
tool names called in the answer. It shows whether the CLI fans out under `codex exec`, how many requests overlap and what the children send.
"""
import json
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
PORT, CAPTURE = int(sys.argv[1]), sys.argv[2]
N_CHILDREN = int(sys.argv[3]) if len(sys.argv) > 3 else 2
CHILD_DELAY_S = float(sys.argv[4]) if len(sys.argv) > 4 else 3.0
LOCK = threading.Lock()
T0 = time.time()
ROOT_REQUESTS = {"n": 0, "thread": None}
def is_root_thread(thread_id):
"""The thread of the first request is the root; the sub-agents send their own thread ids (their agent_name header says /root too)."""
with LOCK:
if ROOT_REQUESTS["thread"] is None:
ROOT_REQUESTS["thread"] = thread_id
return ROOT_REQUESTS["thread"] == thread_id
def spawned_ids(body):
"""Agent ids in the function_call_output items of the request (the spawn_agent results)."""
ids = []
for item in body.get("input") or []:
if item.get("type") == "function_call_output":
out = item.get("output")
text = out if isinstance(out, str) else json.dumps(out)
try:
ids.append(json.loads(text).get("agent_id"))
except (ValueError, AttributeError):
pass
return [i for i in ids if i]
def call_item(n, name, args):
return {"id": "fc_%d" % n, "type": "function_call", "call_id": "call_%d" % n, "name": name, "namespace": "multi_agent_v1",
"arguments": json.dumps(args), "status": "completed"}
def text_item(text):
return {"id": "msg_1", "type": "message", "role": "assistant", "status": "completed",
"content": [{"type": "output_text", "text": text, "annotations": []}]}
def root_answer(body):
"""The scripted root: spawn, then wait, then finish."""
with LOCK:
ROOT_REQUESTS["n"] += 1
k = ROOT_REQUESTS["n"]
if k == 1:
return [call_item(i, "spawn_agent", {"message": "mock task %d: reply with one word" % i}) for i in range(N_CHILDREN)]
ids = spawned_ids(body)
waited = any(i.get("type") == "function_call" and i.get("name") == "wait_agent" for i in body.get("input") or [])
if ids and not waited:
return [call_item(10, "wait_agent", {"targets": ids, "timeout_ms": 60000})]
return [text_item("mock root finished")]
def sse(output):
resp = {"id": "resp_mock", "object": "response", "status": "completed", "model": "mock", "output": output,
"usage": {"input_tokens": 10, "input_tokens_details": {"cached_tokens": 0}, "output_tokens": 2,
"output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 12}}
events = [("response.created", {"response": {**resp, "status": "in_progress", "output": []}})]
for i, item in enumerate(output):
events.append(("response.output_item.done", {"output_index": i, "item": item}))
events.append(("response.completed", {"response": resp}))
return b"".join(("event: %s\ndata: %s\n\n" % (n, json.dumps({"type": n, "sequence_number": i, **d}))).encode()
for i, (n, d) in enumerate(events))
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *args):
pass
def do_POST(self):
t_in = time.time() - T0
body = json.loads(self.rfile.read(int(self.headers.get("content-length", 0))))
agent = "root" if is_root_thread(self.headers.get("thread-id")) else "child"
if agent == "root":
output = root_answer(body)
else:
time.sleep(CHILD_DELAY_S)
output = [text_item("mock child done")]
data = sse(output)
self.send_response(200)
self.send_header("content-type", "text/event-stream")
self.send_header("content-length", str(len(data)))
self.end_headers()
self.wfile.write(data)
self.record(body, agent, t_in, output)
def record(self, body, agent, t_in, output):
rec = {"t_in_s": round(t_in, 3), "t_out_s": round(time.time() - T0, 3), "agent": agent, "thread": self.headers.get("thread-id"),
"n_input": len(body.get("input") or []), "n_tools": len(body.get("tools") or []),
"prefix_sha": hash(json.dumps(body.get("tools"), sort_keys=True)),
"called": [i.get("name") for i in output if i.get("type") == "function_call"],
"tool_outputs": [str(i.get("output"))[:300] for i in body.get("input") or [] if i.get("type") == "function_call_output"]}
with LOCK, open(CAPTURE, "a") as f:
f.write(json.dumps(rec) + "\n")
ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()