interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / seed / agent / bench / equal_mock.py

123 lines · 5243 bytes Raw Blame History
1#!/usr/bin/env python3
2"""TEST-ONLY scripted model server for the equal-work benchmark (omagent vs nanobot).
3
4Usage: equal_mock.py PORTFILE DELAY_MS
5Every POST /v1/chat/completions must ask for stream=true. The reply depends on how many tool
6results follow the last user message, so both harnesses walk the same four-step script:
7 0 -> call read_file {path: notes.txt} result must contain alpha-123
8 1 -> call write_file {path: out.txt, content: beta-456} result must mention 8
9 2 -> call the shell /bin/echo gamma-789 result must contain gamma-789
10 3 -> final answer "done delta-000"
11The shell call uses each harness's own schema: omagent run_command {argv:[...]}, nanobot exec
12{command: "..."}. Each reply is streamed as TOKENS chunks with DELAY_MS before every chunk, so
13DELAY_MS=0 measures the harness and DELAY_MS=50 imitates a 50 ms/token model.
14GET /state returns and resets {first_ns, last_ns, posts, bad, tools, req_bytes}; times are
15CLOCK_MONOTONIC nanoseconds of request arrival, comparable with the driver's monotonic_ns."""
16import http.server, json, socketserver, sys, threading, time
17
18TOKENS = 10
19DELAY = int(sys.argv[2]) / 1000.0
20LOCK = threading.Lock()
21STATE = {}
22
23
24def reset():
25 STATE.clear()
26 STATE.update(first_ns=0, last_ns=0, posts=0, bad=[], tools=[], req_bytes=0)
27
28
29reset()
30EXPECT = {1: "alpha-123", 2: "8", 3: "gamma-789"}
31
32
33def chunk(delta, finish=None):
34 return {"id": "x", "object": "chat.completion.chunk", "created": 0, "model": "mock-1",
35 "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
36
37
38def split(s, n):
39 k = max(1, -(-len(s) // n))
40 return [s[i:i + k] for i in range(0, len(s), k)] or [""]
41
42
43class H(http.server.BaseHTTPRequestHandler):
44 protocol_version = "HTTP/1.0"
45
46 def log_message(self, *a):
47 pass
48
49 def do_GET(self):
50 with LOCK:
51 b = json.dumps(STATE).encode()
52 reset()
53 self.send_response(200)
54 self.send_header("Content-Type", "application/json")
55 self.send_header("Content-Length", str(len(b)))
56 self.end_headers()
57 self.wfile.write(b)
58
59 def do_POST(self):
60 now = time.monotonic_ns()
61 raw = self.rfile.read(int(self.headers.get("Content-Length", "0")))
62 body = json.loads(raw or b"{}")
63 msgs = body.get("messages", [])
64 last_user = max([i for i, m in enumerate(msgs) if m.get("role") == "user"] or [0])
65 tool_msgs = [m for m in msgs[last_user:] if m.get("role") == "tool"]
66 step = len(tool_msgs)
67 names = [t.get("function", {}).get("name") for t in body.get("tools", [])]
68 with LOCK:
69 STATE["first_ns"] = STATE["first_ns"] or now
70 STATE["posts"] += 1
71 STATE["req_bytes"] += len(raw)
72 STATE["tools"] = sorted(n for n in names if n)
73 if not body.get("stream"):
74 STATE["bad"].append("step %d: stream not requested" % step)
75 if step in EXPECT:
76 c = tool_msgs[-1].get("content")
77 c = c if isinstance(c, str) else json.dumps(c)
78 if EXPECT[step] not in c:
79 STATE["bad"].append("step %d: tool result lacks %s: %r" % (step, EXPECT[step], c[:200]))
80 om = "run_command" in names
81 if step == 0:
82 call = ("read_file", {"path": "notes.txt"})
83 elif step == 1:
84 call = ("write_file", {"path": "out.txt", "content": "beta-456"})
85 elif step == 2:
86 # nanobot's restrictToWorkspace guard refuses absolute paths outside the workspace, so
87 # its command reaches the same echo through PATH; env makes it a real exec, not a builtin.
88 call = ("run_command", {"argv": ["/bin/echo", "gamma-789"]}) if om else ("exec", {"command": "env echo gamma-789"})
89 else:
90 call = None
91 self.send_response(200)
92 self.send_header("Content-Type", "text/event-stream")
93 self.end_headers()
94 evs = []
95 if call is None:
96 for i, piece in enumerate(split("done delta-000", TOKENS)):
97 evs.append(chunk({"role": "assistant", "content": piece} if i == 0 else {"content": piece}))
98 evs.append(chunk({}, "stop"))
99 else:
100 args = split(json.dumps(call[1]), TOKENS)
101 for i, piece in enumerate(args):
102 tc = {"index": 0, "function": {"arguments": piece}}
103 if i == 0:
104 tc.update(id="call_%d" % step, type="function")
105 tc["function"]["name"] = call[0]
106 evs.append(chunk({"role": "assistant", "tool_calls": [tc]} if i == 0 else {"tool_calls": [tc]}))
107 evs.append(chunk({}, "tool_calls"))
108 for i, ev in enumerate(evs):
109 if DELAY and i < TOKENS:
110 time.sleep(DELAY)
111 self.wfile.write(("data: %s\n\n" % json.dumps(ev)).encode())
112 self.wfile.flush()
113 self.wfile.write(b"data: [DONE]\n\n")
114
115
116class S(socketserver.ThreadingMixIn, http.server.HTTPServer):
117 daemon_threads = True
118
119
120s = S(("127.0.0.1", 0), H)
121assert s.server_address[1] != 18091
122open(sys.argv[1], "w").write(str(s.server_address[1]))
123s.serve_forever()