verifiers 0.2.2.dev87__py3-none-any.whl → 0.2.2.dev89__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,411 @@
1
+ # /// script
2
+ # requires-python = ">=3.10,<3.15"
3
+ # dependencies = ["agent-client-protocol==0.11.0"]
4
+ # ///
5
+ """Run harness segments through an ACP agent."""
6
+
7
+ import asyncio
8
+ import json
9
+ import os
10
+ import signal
11
+ import sys
12
+ import traceback
13
+ from contextlib import AsyncExitStack, suppress
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from acp import (
18
+ PROTOCOL_VERSION,
19
+ Client,
20
+ RequestError,
21
+ image_block,
22
+ spawn_agent_process,
23
+ text_block,
24
+ )
25
+ from acp.schema import (
26
+ AgentMessageChunk,
27
+ AllowedOutcome,
28
+ ClientCapabilities,
29
+ DeniedOutcome,
30
+ HttpMcpServer,
31
+ PermissionOption,
32
+ RequestPermissionResponse,
33
+ TextContentBlock,
34
+ ToolCall,
35
+ ToolCallUpdate,
36
+ )
37
+
38
+ MAX_PACKET_BYTES = 128 * 1024 * 1024
39
+
40
+
41
+ class VerifiersACPClient(Client):
42
+ def __init__(self) -> None:
43
+ self.visible_reply = ""
44
+ self.message_id: str | None = None
45
+ self.tool_calls: dict[str, str] = {}
46
+
47
+ def reset(self) -> None:
48
+ self.visible_reply = ""
49
+ self.message_id = None
50
+ self.tool_calls = {}
51
+
52
+ async def session_update(self, session_id: str, update: Any, **kwargs: Any) -> None:
53
+ if isinstance(update, ToolCall):
54
+ self.tool_calls[update.tool_call_id] = update.status or "pending"
55
+ return
56
+ if isinstance(update, ToolCallUpdate):
57
+ if update.status:
58
+ self.tool_calls[update.tool_call_id] = update.status
59
+ return
60
+ if not isinstance(update, AgentMessageChunk) or not isinstance(
61
+ update.content, TextContentBlock
62
+ ):
63
+ return
64
+ message_id = getattr(update, "message_id", None)
65
+ if message_id is not None and message_id != self.message_id:
66
+ self.visible_reply = ""
67
+ self.message_id = message_id
68
+ self.visible_reply += update.content.text
69
+
70
+ async def request_permission(
71
+ self,
72
+ session_id: str,
73
+ tool_call: Any,
74
+ options: list[PermissionOption],
75
+ **kwargs: Any,
76
+ ) -> RequestPermissionResponse:
77
+ option = next(
78
+ (item for item in options if item.kind in ("allow_once", "allow_always")),
79
+ None,
80
+ )
81
+ outcome = (
82
+ AllowedOutcome(outcome="selected", option_id=option.option_id)
83
+ if option
84
+ else DeniedOutcome(outcome="cancelled")
85
+ )
86
+ return RequestPermissionResponse(outcome=outcome)
87
+
88
+
89
+ def content_blocks(messages: list[dict], supports_images: bool) -> list:
90
+ blocks = []
91
+ transcript = len(messages) != 1 or messages[0].get("role") != "user"
92
+ for message in messages:
93
+ if transcript:
94
+ separator = "\n\n" if blocks else ""
95
+ blocks.append(
96
+ text_block(f"{separator}[{message.get('role', 'message')}]\n")
97
+ )
98
+ content = message.get("content") or ""
99
+ parts = (
100
+ [{"type": "text", "text": content}] if isinstance(content, str) else content
101
+ )
102
+ for part in parts:
103
+ if part["type"] == "text":
104
+ blocks.append(text_block(part["text"]))
105
+ continue
106
+ if not supports_images:
107
+ raise ValueError("ACP agent does not support image prompts")
108
+ url = part["image_url"]["url"]
109
+ metadata, separator, data = url.partition(",")
110
+ media_type, *parameters = metadata.removeprefix("data:").split(";")
111
+ if (
112
+ not separator
113
+ or not metadata.startswith("data:image/")
114
+ or not any(value.lower() == "base64" for value in parameters)
115
+ ):
116
+ raise ValueError("ACP image prompts require base64 data:image URLs")
117
+ blocks.append(image_block(data, media_type))
118
+ metadata = {
119
+ key: value
120
+ for key, value in message.items()
121
+ if key not in ("role", "content") and value
122
+ }
123
+ if metadata:
124
+ blocks.append(text_block("\n" + json.dumps(metadata, ensure_ascii=False)))
125
+ return blocks
126
+
127
+
128
+ def mcp_servers(config: dict) -> list[HttpMcpServer]:
129
+ return [
130
+ HttpMcpServer(type="http", name=name, url=url, headers=[])
131
+ for name, url in config["mcp_urls"].items()
132
+ ]
133
+
134
+
135
+ def segment_messages(config: dict, is_new: bool) -> list[dict]:
136
+ messages = config["messages"]
137
+ if not is_new:
138
+ last_assistant = max(
139
+ (
140
+ index
141
+ for index, message in enumerate(messages)
142
+ if message.get("role") == "assistant"
143
+ ),
144
+ default=-1,
145
+ )
146
+ messages = messages[last_assistant + 1 :]
147
+ if is_new and config["system_prompt"]:
148
+ messages = [
149
+ {"role": "system", "content": config["system_prompt"]},
150
+ *messages,
151
+ ]
152
+ return messages
153
+
154
+
155
+ async def prompt(
156
+ client: VerifiersACPClient,
157
+ connection: Any,
158
+ capabilities: Any,
159
+ session_id: str,
160
+ config: dict,
161
+ *,
162
+ is_new: bool,
163
+ ) -> str:
164
+ prompt_capabilities = capabilities and capabilities.prompt_capabilities
165
+ supports_images = bool(prompt_capabilities and prompt_capabilities.image)
166
+ blocks = content_blocks(segment_messages(config, is_new), supports_images)
167
+ if not blocks:
168
+ raise ValueError("ACP prompt has no content")
169
+ client.reset()
170
+ try:
171
+ response = await connection.prompt(session_id=session_id, prompt=blocks)
172
+ except RequestError as error:
173
+ detail = error.data.get("details") if isinstance(error.data, dict) else None
174
+ raise RuntimeError(detail or str(error)) from error
175
+ tool_statuses = list(client.tool_calls.values())
176
+ completed_tool_turn = (
177
+ config.get("allow_empty_tool_reply", False)
178
+ and response.stop_reason == "end_turn"
179
+ and bool(tool_statuses)
180
+ and all(status in ("completed", "failed") for status in tool_statuses)
181
+ )
182
+ if not client.visible_reply.strip() and not completed_tool_turn:
183
+ raise RuntimeError(
184
+ "ACP agent produced no visible reply "
185
+ f"(stop_reason={response.stop_reason}, tool_statuses={tool_statuses})"
186
+ )
187
+ return client.visible_reply
188
+
189
+
190
+ async def run_once(config: dict) -> str:
191
+ client = VerifiersACPClient()
192
+ command = config["command"]
193
+ async with spawn_agent_process(
194
+ client,
195
+ command[0],
196
+ *command[1:],
197
+ env=os.environ.copy(),
198
+ transport_kwargs={"stderr": None},
199
+ ) as (connection, _process):
200
+ initialized = await connection.initialize(
201
+ protocol_version=PROTOCOL_VERSION,
202
+ client_capabilities=ClientCapabilities(),
203
+ )
204
+ capabilities = initialized.agent_capabilities
205
+ session_path = Path(config["session_path"]) if config["session_path"] else None
206
+ is_new = session_path is None or not session_path.exists()
207
+ servers = mcp_servers(config)
208
+ if is_new:
209
+ session = await connection.new_session(cwd=os.getcwd(), mcp_servers=servers)
210
+ session_id = session.session_id
211
+ else:
212
+ session_id = session_path.read_text().strip()
213
+ session_capabilities = capabilities and capabilities.session_capabilities
214
+ if session_capabilities and session_capabilities.resume is not None:
215
+ await connection.resume_session(
216
+ cwd=os.getcwd(), session_id=session_id, mcp_servers=servers
217
+ )
218
+ elif capabilities and capabilities.load_session:
219
+ await connection.load_session(
220
+ cwd=os.getcwd(), session_id=session_id, mcp_servers=servers
221
+ )
222
+ else:
223
+ raise RuntimeError("ACP agent does not support resuming sessions")
224
+
225
+ reply = await prompt(
226
+ client,
227
+ connection,
228
+ capabilities,
229
+ session_id,
230
+ config,
231
+ is_new=is_new,
232
+ )
233
+ if session_path and is_new:
234
+ session_path.parent.mkdir(parents=True, exist_ok=True)
235
+ session_path.write_text(session_id)
236
+ return reply
237
+
238
+
239
+ class LiveACPSession:
240
+ """One live ACP process, connection, and session shared by several turns."""
241
+
242
+ def __init__(self) -> None:
243
+ self.client = VerifiersACPClient()
244
+ self._reset()
245
+
246
+ def _reset(self) -> None:
247
+ self.stack = AsyncExitStack()
248
+ self.connection: Any = None
249
+ self.capabilities: Any = None
250
+ self.session_id: str | None = None
251
+ self.command: list[str] | None = None
252
+ self.server_urls: dict[str, str] | None = None
253
+ self.system_prompt: str | None = None
254
+ self.is_new = True
255
+
256
+ async def start(self, config: dict) -> None:
257
+ command = config["command"]
258
+ try:
259
+ self.connection, _process = await self.stack.enter_async_context(
260
+ spawn_agent_process(
261
+ self.client,
262
+ command[0],
263
+ *command[1:],
264
+ env=os.environ.copy(),
265
+ transport_kwargs={"stderr": None},
266
+ )
267
+ )
268
+ initialized = await self.connection.initialize(
269
+ protocol_version=PROTOCOL_VERSION,
270
+ client_capabilities=ClientCapabilities(),
271
+ )
272
+ self.capabilities = initialized.agent_capabilities
273
+ session = await self.connection.new_session(
274
+ cwd=os.getcwd(), mcp_servers=mcp_servers(config)
275
+ )
276
+ except BaseException:
277
+ with suppress(BaseException):
278
+ await self.stack.aclose()
279
+ self._reset()
280
+ raise
281
+ self.session_id = session.session_id
282
+ self.command = command
283
+ self.server_urls = config["mcp_urls"]
284
+ self.system_prompt = config["system_prompt"]
285
+ self.is_new = True
286
+
287
+ async def run(self, config: dict) -> str:
288
+ if self.connection is None:
289
+ await self.start(config)
290
+ elif (
291
+ config["command"] != self.command
292
+ or config["mcp_urls"] != self.server_urls
293
+ or config["system_prompt"] != self.system_prompt
294
+ ):
295
+ raise RuntimeError("ACP session configuration changed")
296
+ assert self.session_id is not None
297
+ reply = await prompt(
298
+ self.client,
299
+ self.connection,
300
+ self.capabilities,
301
+ self.session_id,
302
+ config,
303
+ is_new=self.is_new,
304
+ )
305
+ self.is_new = False
306
+ return reply
307
+
308
+ async def close(self) -> None:
309
+ try:
310
+ if self.connection is not None and self.session_id is not None:
311
+ session_capabilities = (
312
+ self.capabilities and self.capabilities.session_capabilities
313
+ )
314
+ if session_capabilities and session_capabilities.close is not None:
315
+ with suppress(Exception):
316
+ await self.connection.close_session(session_id=self.session_id)
317
+ await self.stack.aclose()
318
+ finally:
319
+ self._reset()
320
+
321
+
322
+ async def read_packet(stream: asyncio.StreamReader) -> dict | None:
323
+ try:
324
+ header = await stream.readexactly(8)
325
+ except asyncio.IncompleteReadError as error:
326
+ if not error.partial:
327
+ return None
328
+ raise EOFError("ACP session packet ended early") from error
329
+ size = int.from_bytes(header, "big")
330
+ if size > MAX_PACKET_BYTES:
331
+ raise ValueError(f"ACP session packet is too large: {size} bytes")
332
+ try:
333
+ return json.loads((await stream.readexactly(size)).decode())
334
+ except asyncio.IncompleteReadError as error:
335
+ raise EOFError("ACP session packet ended early") from error
336
+
337
+
338
+ def write_packet(stream: Any, value: dict) -> None:
339
+ data = json.dumps(value, ensure_ascii=False).encode()
340
+ if len(data) > MAX_PACKET_BYTES:
341
+ raise ValueError(f"ACP session packet is too large: {len(data)} bytes")
342
+ stream.write(len(data).to_bytes(8, "big"))
343
+ stream.write(data)
344
+ stream.flush()
345
+
346
+
347
+ async def serve_stream() -> None:
348
+ session = LiveACPSession()
349
+ closed = False
350
+ reader = asyncio.StreamReader()
351
+ protocol = asyncio.StreamReaderProtocol(reader)
352
+ await asyncio.get_running_loop().connect_read_pipe(
353
+ lambda: protocol, sys.stdin.buffer
354
+ )
355
+ try:
356
+ while request := await read_packet(reader):
357
+ stop = False
358
+ try:
359
+ operation = request.get("operation")
360
+ if operation == "prompt":
361
+ response = {
362
+ "ok": True,
363
+ "reply": await session.run(request["config"]),
364
+ }
365
+ elif operation == "shutdown":
366
+ await session.close()
367
+ closed = True
368
+ stop = True
369
+ response = {"ok": True}
370
+ else:
371
+ raise ValueError(f"unknown ACP session operation: {operation!r}")
372
+ except Exception as error: # noqa: BLE001 - serialize protocol failures
373
+ traceback.print_exc()
374
+ response = {
375
+ "ok": False,
376
+ "error": f"{type(error).__name__}: {error}",
377
+ }
378
+ write_packet(sys.stdout.buffer, response)
379
+ if stop:
380
+ break
381
+ finally:
382
+ if not closed:
383
+ await session.close()
384
+
385
+
386
+ def read_config(path_value: str) -> dict:
387
+ path = Path(path_value)
388
+ config = json.loads(path.read_text())
389
+ path.unlink()
390
+ return config
391
+
392
+
393
+ async def main() -> None:
394
+ operation = sys.argv[1]
395
+ if operation == "once":
396
+ sys.stdout.write(await run_once(read_config(sys.argv[2])))
397
+ elif operation == "stream":
398
+ task = asyncio.current_task()
399
+ loop = asyncio.get_running_loop()
400
+ if task is not None:
401
+ for sig in (signal.SIGTERM, signal.SIGINT):
402
+ with suppress(NotImplementedError):
403
+ loop.add_signal_handler(sig, task.cancel)
404
+ with suppress(asyncio.CancelledError):
405
+ await serve_stream()
406
+ else:
407
+ raise ValueError(f"unknown ACP runner operation: {operation!r}")
408
+
409
+
410
+ if __name__ == "__main__":
411
+ asyncio.run(main())
verifiers/v1/harness.py CHANGED
@@ -127,10 +127,9 @@ class Harness(ABC, Generic[ConfigT]):
127
127
  data: TaskData,
128
128
  messages: Messages | None = None,
129
129
  ) -> None:
130
- """Run ONE segment of the exchange: the program from launch (or, with
131
- `messages`, the user's next turn(s) via `resume`) until it yields — a segment
132
- ends when the program exits. The rollout loop owns the exchange across
133
- segments (and stamps its end); a harness only ever sees one segment."""
130
+ """Run ONE segment of the exchange without retaining a process: the program
131
+ from launch (or, with `messages`, the user's next turn(s) via `resume`) until
132
+ it yields. The rollout loop owns the exchange across segments."""
134
133
  async with boundary(HarnessError, f"harness {self.config.id!r}"):
135
134
  if messages is None:
136
135
  result = await self.launch(
@@ -140,19 +139,45 @@ class Harness(ABC, Generic[ConfigT]):
140
139
  result = await self.resume(
141
140
  ctx, trace, runtime, endpoint, secret, mcp_urls, data, messages
142
141
  )
142
+ await self._check_result(trace, runtime, result)
143
+
144
+ async def _check_result(
145
+ self, trace: Trace, runtime: Runtime, result: ProgramResult
146
+ ) -> None:
143
147
  if trace.stop_condition is not None:
144
- return # a @stop refused a turn mid-rollout; the harness's exit is expected
145
- if result.exit_code != 0:
146
- # The real cause is at the END of a traceback, so keep the tail.
147
- detail = (result.stderr or result.stdout).strip()[-2000:] or "<no output>"
148
- if not await runtime.alive():
149
- raise SandboxError(
150
- f"runtime died under harness {self.config.id!r} "
151
- f"(exit {result.exit_code}): {detail}"
152
- )
153
- raise HarnessError(
154
- f"harness {self.config.id!r} exited {result.exit_code}: {detail}"
148
+ return # a @stop refused a turn mid-rollout; the exit is expected
149
+ if result.exit_code == 0:
150
+ return
151
+ # The real cause is at the END of a traceback, so keep the tail.
152
+ detail = (result.stderr or result.stdout).strip()[-2000:] or "<no output>"
153
+ if not await runtime.alive():
154
+ raise SandboxError(
155
+ f"runtime died under harness {self.config.id!r} "
156
+ f"(exit {result.exit_code}): {detail}"
155
157
  )
158
+ raise HarnessError(
159
+ f"harness {self.config.id!r} exited {result.exit_code}: {detail}"
160
+ )
161
+
162
+ async def session(
163
+ self,
164
+ ctx: ModelContext,
165
+ trace: Trace,
166
+ runtime: Runtime,
167
+ endpoint: str,
168
+ secret: str,
169
+ mcp_urls: dict[str, str],
170
+ data: TaskData,
171
+ ) -> HarnessSession:
172
+ """Create the rollout-scoped handle that drives this harness.
173
+
174
+ The default adapts the existing launch/resume contract. Stateful harness
175
+ transports override this factory so one handle can own their live process,
176
+ connection, or native session for the rollout's full interaction.
177
+ """
178
+ return HarnessSession(
179
+ self, ctx, trace, runtime, endpoint, secret, mcp_urls, data
180
+ )
156
181
 
157
182
  async def score(self, trace: Trace, runtime: Runtime) -> None:
158
183
  """Run this harness's `@metric` methods over the finished trace, recording
@@ -240,3 +265,69 @@ class Harness(ABC, Generic[ConfigT]):
240
265
  loop in-process instead of launching a program, as long as every model call
241
266
  goes through `endpoint` + `secret` — it then returns a synthetic success
242
267
  `ProgramResult`, and the trace is the record of what ran."""
268
+
269
+
270
+ class HarnessSession:
271
+ """One rollout's stateful handle onto one harness execution.
272
+
273
+ The base adapter preserves the segment-oriented harness interface by invoking
274
+ `launch()` once and `resume()` for later caller turns. Specialized handles can
275
+ override `_run()` and `close()` to retain transport state across those turns.
276
+ """
277
+
278
+ def __init__(
279
+ self,
280
+ harness: Harness,
281
+ ctx: ModelContext,
282
+ trace: Trace,
283
+ runtime: Runtime,
284
+ endpoint: str,
285
+ secret: str,
286
+ mcp_urls: dict[str, str],
287
+ data: TaskData,
288
+ ) -> None:
289
+ self.harness = harness
290
+ self.ctx = ctx
291
+ self.trace = trace
292
+ self.runtime = runtime
293
+ self.endpoint = endpoint
294
+ self.secret = secret
295
+ self.mcp_urls = mcp_urls
296
+ self.data = data
297
+ self._closed = False
298
+
299
+ async def turn(self, messages: Messages | None = None) -> None:
300
+ """Run one harness segment while retaining session state for the next."""
301
+ if self._closed:
302
+ raise HarnessError(
303
+ f"harness {self.harness.config.id!r} session is already closed"
304
+ )
305
+ async with boundary(HarnessError, f"harness {self.harness.config.id!r}"):
306
+ result = await self._run(messages)
307
+ await self.harness._check_result(self.trace, self.runtime, result)
308
+
309
+ async def _run(self, messages: Messages | None) -> ProgramResult:
310
+ if messages is None:
311
+ return await self.harness.launch(
312
+ self.ctx,
313
+ self.trace,
314
+ self.runtime,
315
+ self.endpoint,
316
+ self.secret,
317
+ self.mcp_urls,
318
+ self.data,
319
+ )
320
+ return await self.harness.resume(
321
+ self.ctx,
322
+ self.trace,
323
+ self.runtime,
324
+ self.endpoint,
325
+ self.secret,
326
+ self.mcp_urls,
327
+ self.data,
328
+ messages,
329
+ )
330
+
331
+ async def close(self) -> None:
332
+ """Close session-owned resources. Idempotent."""
333
+ self._closed = True