verifiers 0.2.2.dev54__py3-none-any.whl → 0.2.2.dev56__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.
@@ -31,7 +31,7 @@ from verifiers.v1.cli.resolve import narrow_taskset_config
31
31
  from verifiers.v1.configs.agent import WireAgentConfig
32
32
  from verifiers.v1.configs.cli.replay import ReplayConfig
33
33
  from verifiers.v1.state import state_cls
34
- from verifiers.v1.task import Task, WireTaskData, task_data_cls
34
+ from verifiers.v1.task import Task, WireTaskData
35
35
  from verifiers.v1.trace import Trace
36
36
  from verifiers.v1.utils.interrupt import install_interrupt
37
37
  from verifiers.v1.utils.logging import setup_logging
@@ -76,7 +76,7 @@ async def run_replay(config: ReplayConfig, source: Path, out: Path) -> list[Trac
76
76
  "score() — multi-agent runs don't support replay"
77
77
  )
78
78
  task_cls = vf.task_type(config.taskset.id)
79
- data_cls = task_data_cls(task_cls)
79
+ data_cls = task_cls.data_type()
80
80
  # `WireTaskData` reads any taskset's saved task without importing its Task type.
81
81
  # An episode may hold no traces (its env hooks failed before any agent ran);
82
82
  # there's nothing to re-score, so it drops out in the flatten. Each kept trace
@@ -1,4 +1,8 @@
1
1
  from verifiers.v1.harnesses.bash import BashHarness, BashHarnessConfig
2
+ from verifiers.v1.harnesses.browser_use import (
3
+ BrowserUseHarness,
4
+ BrowserUseHarnessConfig,
5
+ )
2
6
  from verifiers.v1.harnesses.claude_code import (
3
7
  ClaudeCodeHarness,
4
8
  ClaudeCodeHarnessConfig,
@@ -18,6 +22,8 @@ from verifiers.v1.harnesses.terminus_2 import Terminus2Harness, Terminus2Harness
18
22
  __all__ = [
19
23
  "BashHarness",
20
24
  "BashHarnessConfig",
25
+ "BrowserUseHarness",
26
+ "BrowserUseHarnessConfig",
21
27
  "ClaudeCodeHarness",
22
28
  "ClaudeCodeHarnessConfig",
23
29
  "CodexHarness",
@@ -0,0 +1,6 @@
1
+ from verifiers.v1.harnesses.browser_use.harness import (
2
+ BrowserUseHarness,
3
+ BrowserUseHarnessConfig,
4
+ )
5
+
6
+ __all__ = ["BrowserUseHarness", "BrowserUseHarnessConfig"]
@@ -0,0 +1,125 @@
1
+ import json
2
+ from pathlib import Path
3
+ from typing import Literal
4
+
5
+ from pydantic import model_validator
6
+
7
+ from verifiers.v1.clients import ModelContext
8
+ from verifiers.v1.configs.harness import HarnessConfig
9
+ from verifiers.v1.dialects.chat import message_to_wire
10
+ from verifiers.v1.harness import Harness
11
+ from verifiers.v1.runtimes import ProgramResult, Runtime
12
+ from verifiers.v1.task import TaskData
13
+ from verifiers.v1.trace import Trace
14
+
15
+ PROGRAM_SOURCE = (Path(__file__).resolve().parent / "program.py").read_text()
16
+
17
+ # The helper names and persistence rules the model needs to use the local tool.
18
+ BROWSER_SYSTEM_PROMPT = """You are a browser automation agent. Your `browser` tool executes Python code that controls a real Chromium over CDP through browser-harness; its helpers are pre-imported.
19
+
20
+ Rules of the tool:
21
+ - Each call runs in a fresh Python process: variables do NOT persist between calls. The browser does persist — tabs, cookies, and page state carry over.
22
+ - Use print() for anything you want to see. Filter in Python before printing; a raw AX tree or DOM dump is huge.
23
+ - The first navigation is new_tab(url), not goto_url(url). After navigating, call wait_for_load().
24
+
25
+ Core helpers: new_tab(url), goto_url(url), page_info(), js(expression), click_at_xy(x, y), type_text(text), press_key(key), fill_input(selector, text), scroll(x, y, dy), wait_for_load(), wait_for_element(selector), wait_for_network_idle(), list_tabs(), switch_tab(target), close_tab(), ensure_real_tab(), capture_screenshot(path), upload_file(selector, path), and raw cdp("Domain.method", ...).
26
+
27
+ Finding elements: prefer the accessibility tree over screenshots. cdp("Accessibility.getFullAXTree")["nodes"] has every element's role, name, and backendDOMNodeId — filter in Python before printing. For coordinates: q = cdp("DOM.getBoxModel", backendNodeId=n)["model"]["content"]; x, y = sum(q[0::2])/4, sum(q[1::2])/4, then click_at_xy(x, y) and verify with a targeted js(...) or page_info() check. Fall back to js(...) over the DOM when the AX tree lacks the element."""
28
+
29
+
30
+ class BrowserUseHarnessConfig(HarnessConfig):
31
+ browser: Literal["chromium", "cdp"] = "chromium"
32
+ """`chromium` launches locally; `cdp` attaches to `cdp_url` without owning it."""
33
+
34
+ cdp_url: str | None = None
35
+ """Rollout-scoped HTTP or WebSocket endpoint used with `browser = "cdp"`."""
36
+
37
+ @model_validator(mode="after")
38
+ def _require_cdp_url_iff_cdp(self) -> "BrowserUseHarnessConfig":
39
+ if self.browser == "cdp" and not self.cdp_url:
40
+ raise ValueError(
41
+ "browser='cdp' needs cdp_url set to a CDP endpoint to attach to"
42
+ )
43
+ if self.browser != "cdp" and self.cdp_url:
44
+ raise ValueError(
45
+ f"cdp_url is only valid with browser='cdp', not browser={self.browser!r}"
46
+ )
47
+ return self
48
+
49
+
50
+ class BrowserUseHarness(Harness[BrowserUseHarnessConfig]):
51
+ APPENDS_SYSTEM_PROMPT = True
52
+ SUPPORTS_MCP = True
53
+ SUPPORTS_RESUME = True
54
+ # The browser tool executes model-authored Python through a third-party daemon.
55
+ NEEDS_CONTAINER = True
56
+
57
+ async def setup(self, runtime: Runtime) -> None:
58
+ await runtime.prepare_uv_script(PROGRAM_SOURCE, self.config.resolved_env)
59
+
60
+ async def launch(
61
+ self,
62
+ ctx: ModelContext,
63
+ trace: Trace,
64
+ runtime: Runtime,
65
+ endpoint: str,
66
+ secret: str,
67
+ mcp_urls: dict[str, str],
68
+ data: TaskData,
69
+ ) -> ProgramResult:
70
+ system_prompt, prompt = self.resolve_prompt(data)
71
+ system_prompt = "\n\n".join(
72
+ p for p in (BROWSER_SYSTEM_PROMPT, system_prompt) if p
73
+ )
74
+ # Default resume replays the transcript. If there was no task system
75
+ # prompt, that transcript already contains this harness prompt.
76
+ replaying_browser_prompt = (
77
+ data.system_prompt is None
78
+ and prompt is not None
79
+ and not isinstance(prompt, str)
80
+ and any(
81
+ message.role == "system" and message.content == BROWSER_SYSTEM_PROMPT
82
+ for message in prompt
83
+ )
84
+ )
85
+ env = {**self.config.resolved_env}
86
+ state = f".vf-browser-{trace.id}"
87
+ args = [
88
+ f"--base-url={endpoint}",
89
+ f"--api-key={secret}",
90
+ f"--model={ctx.model}",
91
+ f"--browser={self.config.browser}",
92
+ # A resumed segment reuses this trace's browser and profile.
93
+ f"--state-dir={state}",
94
+ ]
95
+ if not replaying_browser_prompt:
96
+ args.append(f"--system-prompt={system_prompt}")
97
+ if self.config.cdp_url:
98
+ args.append(f"--cdp-url={self.config.cdp_url}")
99
+ if mcp_urls:
100
+ # The program connects to the tool servers over HTTP; hand it a standard
101
+ # `mcpServers` URL config (the `mcp` client itself comes from the uv deps).
102
+ args.append(
103
+ "--mcp-config="
104
+ + json.dumps(
105
+ {
106
+ "mcpServers": {
107
+ name: {"url": url} for name, url in mcp_urls.items()
108
+ }
109
+ }
110
+ )
111
+ )
112
+ if isinstance(prompt, str):
113
+ args.append(f"--prompt={prompt}")
114
+ elif prompt is not None:
115
+ # Base64 images can exceed exec limits, so hand Messages off through a file.
116
+ path = f".vf-initial-messages-{trace.id}.json"
117
+ await runtime.write(
118
+ path,
119
+ json.dumps([message_to_wire(m) for m in prompt]).encode(),
120
+ )
121
+ args.append(f"--initial-messages-file={path}")
122
+ program = await runtime.prepare_uv_script(
123
+ PROGRAM_SOURCE, self.config.resolved_env
124
+ )
125
+ return await runtime.run_program([*program, *args], env)
@@ -0,0 +1,402 @@
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "browser-harness==0.1.8",
5
+ # "openai",
6
+ # "mcp>=1.24.0,<2",
7
+ # "httpx",
8
+ # "tenacity",
9
+ # ]
10
+ # ///
11
+ """A chat loop whose one local tool drives a real Chromium over CDP.
12
+
13
+ Each tool call pipes the model's code to browser-harness, whose daemon holds the
14
+ CDP connection and pre-imports its page helpers. `chromium` launches and owns a
15
+ local browser; `cdp` attaches to an HTTP or WebSocket endpoint it does not own.
16
+ Trace-scoped state preserves tabs across resume and records owned process IDs.
17
+ """
18
+
19
+ import argparse
20
+ import asyncio
21
+ import json
22
+ import os
23
+ import re
24
+ import shutil
25
+ import subprocess
26
+ import sys
27
+ import time
28
+ import urllib.request
29
+ from contextlib import AsyncExitStack, asynccontextmanager, suppress
30
+ from pathlib import Path
31
+ from typing import Any, cast
32
+ from urllib.parse import urlsplit
33
+
34
+ import httpx
35
+ from openai import AsyncOpenAI
36
+ from tenacity import AsyncRetrying, stop_after_attempt, wait_exponential_jitter
37
+
38
+ MCP_CALL_ATTEMPTS = 6
39
+ MCP_TIMEOUT = httpx.Timeout(600.0, connect=5.0) # the OpenAI SDK client defaults
40
+
41
+ BROWSER_TOOL_TIMEOUT = 3600
42
+ """Matches the bash harness's command timeout."""
43
+
44
+ BROWSER_READY_TIMEOUT = 60
45
+ """The documented Playwright image announced CDP in under one second from a
46
+ cold container; one minute leaves ample runtime startup headroom."""
47
+
48
+ _DEVTOOLS_LINE = re.compile(r"DevTools listening on ws://127\.0\.0\.1:(\d+)/")
49
+
50
+ BROWSER_TOOL = {
51
+ "type": "function",
52
+ "function": {
53
+ "name": "browser",
54
+ "description": (
55
+ "Execute Python code that drives the browser through browser-harness. "
56
+ "Helpers are pre-imported; use print() to see values. Each call runs in "
57
+ "a fresh process: Python variables do not persist between calls, but the "
58
+ "browser (tabs, cookies, page state) does."
59
+ ),
60
+ "parameters": {
61
+ "type": "object",
62
+ "properties": {
63
+ "code": {
64
+ "type": "string",
65
+ "description": "The Python code to execute.",
66
+ }
67
+ },
68
+ "required": ["code"],
69
+ },
70
+ },
71
+ }
72
+
73
+
74
+ def find_browser() -> str:
75
+ """The Chromium binary to launch, where a machine keeps one.
76
+
77
+ `PLAYWRIGHT_BROWSERS_PATH` before PATH: an image that installs browsers
78
+ through Playwright puts nothing on PATH.
79
+ """
80
+ for key in ("BH_CHROME_PATH", "CHROME_PATH"):
81
+ candidate = os.environ.get(key)
82
+ if candidate and os.access(candidate, os.X_OK):
83
+ return candidate
84
+ registry = os.environ.get("PLAYWRIGHT_BROWSERS_PATH")
85
+ if registry:
86
+ builds = sorted(Path(registry).glob("chromium-*/chrome-linux*/chrome"))
87
+ if builds:
88
+ return str(builds[-1])
89
+ for name in (
90
+ "google-chrome-stable",
91
+ "google-chrome",
92
+ "chromium",
93
+ "chromium-browser",
94
+ ):
95
+ found = shutil.which(name)
96
+ if found:
97
+ return found
98
+ raise SystemExit(
99
+ "no Chromium/Chrome found; run on a browser-capable image "
100
+ "(e.g. mcr.microsoft.com/playwright/python) or set BH_CHROME_PATH"
101
+ )
102
+
103
+
104
+ def _endpoint_alive(endpoint: str) -> bool:
105
+ try:
106
+ # browser-harness uses five seconds for this same DevTools HTTP probe.
107
+ urllib.request.urlopen(f"{endpoint}/json/version", timeout=5).close()
108
+ return True
109
+ except OSError:
110
+ return False
111
+
112
+
113
+ def ensure_chromium(state_dir: Path) -> str:
114
+ """Reuse this trace's live Chromium or launch it."""
115
+ endpoint_file = state_dir / "cdp-endpoint"
116
+ if endpoint_file.exists():
117
+ endpoint = endpoint_file.read_text().strip()
118
+ if endpoint and _endpoint_alive(endpoint):
119
+ return endpoint
120
+
121
+ profile = state_dir / "profile"
122
+ profile.mkdir(parents=True, exist_ok=True)
123
+ log = state_dir / "browser.log"
124
+ with open(log, "wb") as stderr:
125
+ browser = subprocess.Popen(
126
+ [
127
+ find_browser(),
128
+ "--remote-debugging-port=0",
129
+ f"--user-data-dir={profile}",
130
+ "--headless",
131
+ "--no-first-run",
132
+ "--no-default-browser-check",
133
+ "--disable-dev-shm-usage",
134
+ "--no-sandbox",
135
+ ],
136
+ stdout=subprocess.DEVNULL,
137
+ stderr=stderr,
138
+ stdin=subprocess.DEVNULL,
139
+ start_new_session=True,
140
+ )
141
+ deadline = time.monotonic() + BROWSER_READY_TIMEOUT
142
+ while time.monotonic() < deadline and browser.poll() is None:
143
+ output = log.read_text(errors="replace")
144
+ if match := _DEVTOOLS_LINE.search(output):
145
+ endpoint = f"http://127.0.0.1:{match.group(1)}"
146
+ endpoint_file.write_text(endpoint)
147
+ return endpoint
148
+ time.sleep(0.1)
149
+ if browser.poll() is None:
150
+ browser.kill()
151
+ browser.wait()
152
+ tail = log.read_text(errors="replace")[-2000:]
153
+ raise SystemExit(
154
+ f"browser did not announce a DevTools port within {BROWSER_READY_TIMEOUT}s: "
155
+ f"{tail or '<no browser output>'}"
156
+ )
157
+
158
+
159
+ def run_browser(code: str, env: dict[str, str]) -> str:
160
+ """Run model code through the pinned browser-harness CLI."""
161
+ try:
162
+ result = subprocess.run(
163
+ [sys.executable, "-m", "browser_harness.run"],
164
+ input=code,
165
+ capture_output=True,
166
+ text=True,
167
+ timeout=BROWSER_TOOL_TIMEOUT,
168
+ env=env,
169
+ check=False,
170
+ )
171
+ return (result.stdout + result.stderr) or "(no output)"
172
+ except Exception as e: # noqa: BLE001 - tool failures are returned to the model
173
+ return f"error: {e}"
174
+
175
+
176
+ async def chat(
177
+ client: AsyncOpenAI,
178
+ model: str,
179
+ messages: list[dict[str, Any]],
180
+ tools: list[dict[str, Any]],
181
+ ):
182
+ completion = await client.chat.completions.create(
183
+ model=model,
184
+ messages=cast(Any, messages),
185
+ tools=cast(Any, tools or None),
186
+ )
187
+ return completion.choices[0].message
188
+
189
+
190
+ @asynccontextmanager
191
+ async def mcp_session(spec: dict):
192
+ """One fresh streamable-HTTP session to an MCP server, opened and closed within the caller's
193
+ task so AnyIO cancellation scopes stay correctly nested. A teardown failure after the body
194
+ completed is swallowed — the result is already in hand, and closing noise must not fail (or
195
+ replay) an already-answered call."""
196
+ from mcp import ClientSession
197
+ from mcp.client.streamable_http import (
198
+ create_mcp_http_client,
199
+ streamable_http_client,
200
+ )
201
+
202
+ stack = AsyncExitStack()
203
+ try:
204
+ http_client = await stack.enter_async_context(
205
+ create_mcp_http_client(
206
+ headers=spec.get("headers") or None, timeout=MCP_TIMEOUT
207
+ )
208
+ )
209
+ read, write, *_ = await stack.enter_async_context(
210
+ streamable_http_client(spec["url"], http_client=http_client)
211
+ )
212
+ session = await stack.enter_async_context(ClientSession(read, write))
213
+ await session.initialize()
214
+ yield session
215
+ finally:
216
+ with suppress(Exception):
217
+ await stack.aclose()
218
+
219
+
220
+ async def with_retry(call):
221
+ """Run one session-scoped operation, retrying transient failures with backoff. A call whose
222
+ response was lost may be replayed — MCP has no idempotency key, so tools should tolerate
223
+ at-least-once delivery (a tool that fails reports through its result, not an exception)."""
224
+ async for attempt in AsyncRetrying(
225
+ stop=stop_after_attempt(MCP_CALL_ATTEMPTS),
226
+ wait=wait_exponential_jitter(initial=0.5, max=30),
227
+ reraise=True,
228
+ ):
229
+ with attempt:
230
+ return await call()
231
+
232
+
233
+ async def connect_mcp(
234
+ config: dict, reserved: set[str]
235
+ ) -> tuple[list[dict], dict, dict]:
236
+ """Enumerate each configured MCP server's tools (a streamable-HTTP `url`); return (tool schemas,
237
+ dispatch mapping `<server>_<tool>` -> (server name, raw tool name), servers mapping name -> spec).
238
+ No session is held — a stateless-HTTP server is reconnected per call."""
239
+ tool_schemas: list[dict] = []
240
+ dispatch: dict[str, tuple] = {}
241
+ servers: dict[str, dict] = {}
242
+ for name, spec in config.get("mcpServers", {}).items():
243
+ servers[name] = spec
244
+
245
+ async def list_tools(spec: dict = spec):
246
+ async with mcp_session(spec) as session:
247
+ return (await session.list_tools()).tools
248
+
249
+ for tool in await with_retry(list_tools):
250
+ # A server named "" (TOOL_PREFIX = None) advertises its tools bare.
251
+ full = f"{name}_{tool.name}" if name else tool.name
252
+ if full in reserved or full in dispatch:
253
+ raise ValueError(
254
+ f"duplicate tool name {full!r}; keep MCP tool names qualified"
255
+ )
256
+ tool_schemas.append(
257
+ {
258
+ "type": "function",
259
+ "function": {
260
+ "name": full,
261
+ "description": tool.description or "",
262
+ "parameters": tool.inputSchema,
263
+ },
264
+ }
265
+ )
266
+ dispatch[full] = (name, tool.name)
267
+ return tool_schemas, dispatch, servers
268
+
269
+
270
+ def mcp_content_to_chat_content(blocks) -> str | list[dict]:
271
+ parts = []
272
+ for block in blocks:
273
+ if block.type == "text":
274
+ parts.append({"type": "text", "text": block.text})
275
+ elif block.type == "image":
276
+ url = f"data:{block.mimeType};base64,{block.data}"
277
+ parts.append({"type": "image_url", "image_url": {"url": url}})
278
+ else:
279
+ parts.append({"type": "text", "text": str(block)})
280
+ if not parts:
281
+ return str(blocks)
282
+ if all(part["type"] == "text" for part in parts):
283
+ return "\n".join(str(part["text"]) for part in parts)
284
+ return parts
285
+
286
+
287
+ async def call_mcp(
288
+ servers: dict, dispatch: dict, name: str, arguments: dict
289
+ ) -> str | list[dict]:
290
+ """Call a tool on a fresh session per attempt — see `with_retry` for the replay semantics.
291
+ The result is converted outside the retry so a conversion failure fails once."""
292
+ server_name, raw = dispatch[name]
293
+
294
+ async def call():
295
+ async with mcp_session(servers[server_name]) as session:
296
+ return await session.call_tool(raw, arguments)
297
+
298
+ result = await with_retry(call)
299
+ return mcp_content_to_chat_content(result.content)
300
+
301
+
302
+ def parse_args() -> argparse.Namespace:
303
+ parser = argparse.ArgumentParser()
304
+ parser.add_argument("--base-url", required=True)
305
+ parser.add_argument("--api-key", required=True)
306
+ parser.add_argument("--model", required=True)
307
+ parser.add_argument("--state-dir", required=True)
308
+ parser.add_argument("--browser", default="chromium")
309
+ parser.add_argument("--cdp-url", default="")
310
+ parser.add_argument("--system-prompt", default="")
311
+ parser.add_argument("--prompt", default="")
312
+ parser.add_argument("--initial-messages-file", default="")
313
+ parser.add_argument("--mcp-config", default="")
314
+ return parser.parse_args()
315
+
316
+
317
+ async def main() -> None:
318
+ args = parse_args()
319
+ initial = []
320
+ if args.initial_messages_file:
321
+ path = Path(args.initial_messages_file)
322
+ payload = path.read_bytes()
323
+ path.unlink()
324
+ initial = json.loads(payload)
325
+ state_dir = Path(args.state_dir)
326
+ state_dir.mkdir(parents=True, exist_ok=True)
327
+ endpoint = (
328
+ ensure_chromium(state_dir) if args.browser == "chromium" else args.cdp_url
329
+ )
330
+ browser_env = {
331
+ **os.environ,
332
+ "BH_HOME": str(state_dir / "bh-home"),
333
+ "BH_TELEMETRY": "0",
334
+ (
335
+ "BU_CDP_WS" if urlsplit(endpoint).scheme in {"ws", "wss"} else "BU_CDP_URL"
336
+ ): endpoint,
337
+ }
338
+ client = AsyncOpenAI(base_url=args.base_url, api_key=args.api_key)
339
+ config = json.loads(args.mcp_config or "{}")
340
+ tools = [BROWSER_TOOL]
341
+ reserved = {"browser"}
342
+ mcp_tools, dispatch, servers = (
343
+ await connect_mcp(config, reserved)
344
+ if config.get("mcpServers")
345
+ else ([], {}, {})
346
+ )
347
+ tools += mcp_tools
348
+ messages = (
349
+ [{"role": "system", "content": args.system_prompt}]
350
+ if args.system_prompt
351
+ else []
352
+ )
353
+ if initial:
354
+ messages.extend(initial)
355
+ elif args.prompt:
356
+ messages.append({"role": "user", "content": args.prompt})
357
+ while True:
358
+ message = await chat(client, args.model, messages, tools)
359
+ messages.append(message.model_dump(exclude_none=True))
360
+ if not message.tool_calls:
361
+ break
362
+ for call in message.tool_calls:
363
+ name = call.function.name
364
+ try:
365
+ tool_args = json.loads(call.function.arguments or "{}")
366
+ except json.JSONDecodeError as e:
367
+ messages.append(
368
+ {
369
+ "role": "tool",
370
+ "tool_call_id": call.id,
371
+ "content": f"error: invalid JSON in tool arguments ({e}); resend the call with valid JSON",
372
+ }
373
+ )
374
+ continue
375
+ # Valid JSON can still be a non-object (`[]`, `42`, `null`); the `.get(...)` calls
376
+ # below assume a dict, so reject anything else as a tool error rather than crashing.
377
+ if not isinstance(tool_args, dict):
378
+ messages.append(
379
+ {
380
+ "role": "tool",
381
+ "tool_call_id": call.id,
382
+ "content": f"error: tool arguments must be a JSON object, got {type(tool_args).__name__}; resend as an object",
383
+ }
384
+ )
385
+ continue
386
+ if name in dispatch:
387
+ content = await call_mcp(servers, dispatch, name, tool_args)
388
+ elif name == "browser":
389
+ content = await asyncio.to_thread(
390
+ run_browser,
391
+ tool_args.get("code", ""),
392
+ browser_env,
393
+ )
394
+ else:
395
+ content = f"error: unknown tool {name!r}"
396
+ messages.append(
397
+ {"role": "tool", "tool_call_id": call.id, "content": content}
398
+ )
399
+
400
+
401
+ if __name__ == "__main__":
402
+ asyncio.run(main())
@@ -22,7 +22,7 @@ from verifiers.v1.serve.types import (
22
22
  RunRequest,
23
23
  RunResponse,
24
24
  )
25
- from verifiers.v1.task import Task, task_data_cls
25
+ from verifiers.v1.task import Task
26
26
  from verifiers.v1.types import SamplingConfig
27
27
 
28
28
  logger = logging.getLogger(__name__)
@@ -39,7 +39,7 @@ class EnvServer:
39
39
  self.taskset_id = config.taskset.id
40
40
  self.env = load_environment(config)
41
41
  self.task_cls = type(self.env.taskset).task_type()
42
- self.data_cls = task_data_cls(self.task_cls)
42
+ self.data_cls = self.task_cls.data_type()
43
43
  # A dispatched task is its client-side model_dump(): a field excluded from
44
44
  # serialization would vanish on the wire and rebuild silently defaulted, so
45
45
  # refuse to serve such a taskset.
verifiers/v1/task.py CHANGED
@@ -1,25 +1,10 @@
1
- """Task data, configuration, behavior, and scoring.
2
-
3
- `TaskData` is the wire half: a frozen pydantic model carrying everything a rollout's
4
- row IS — the base fields plus your typed, task-specific fields. It rides on
5
- `trace.task.data`, is what `traces.jsonl` stores, and what tool servers receive
6
- over the `/task` channel. Subclass it per dataset.
7
-
8
- `Task` is the behavior half: runtime prep (`setup`/`finalize`), server declarations
9
- (`tools`), well-formedness (`validate`), and per-trace judgement
10
- (`@reward`/`@metric` methods plus the plugged judges from `config.judges`, run by
11
- `score`). Subclass per dataset and parameterize `Task[MyData, MyState, MyConfig]`
12
- (all three default); judgement that compares sibling traces lives on
13
- `Env.finalize` instead.
14
-
15
- A Task instance is shared across its rollouts (`-r n` runs hold the same instance),
16
- so hooks must not stash per-rollout state on `self` — that lives on the trace
17
- (`trace.state`).
18
-
19
- On the wire only the data travels (plus the producing class's name,
20
- `trace.task.type`): a saved row reads back as `WireTaskData` without importing the
21
- taskset; a re-scoring consumer (`replay`) rebuilds the declared `TaskData` type and
22
- wraps it in the declared `Task` — one task type per taskset.
1
+ """Task data + behavior.
2
+
3
+ `TaskData` is the wire half: a frozen pydantic model carrying the data which
4
+ initializes a task instance. Rides on `trace.task.data` in `traces.jsonl`.
5
+
6
+ `Task` is the behavior half: runtime prep (`setup`/`finalize`), tool declarations
7
+ (`tools`), and scoring (`@reward`/`@metric`) methods.
23
8
  """
24
9
 
25
10
  from __future__ import annotations
@@ -52,6 +37,8 @@ logger = logging.getLogger(__name__)
52
37
 
53
38
 
54
39
  class TaskResources(BaseModel):
40
+ """Optional resource limits for the task."""
41
+
55
42
  model_config = ConfigDict(frozen=True)
56
43
 
57
44
  cpu: float | None = None
@@ -70,31 +57,35 @@ class TaskTimeout(BaseModel):
70
57
  model_config = ConfigDict(frozen=True)
71
58
 
72
59
  setup: float | None = None
60
+ """Timeout (in seconds) for the task's setup hook."""
73
61
  agent: float | None = None
62
+ """Timeout (in seconds) for the agent's solve attempt."""
74
63
  finalize: float | None = None
64
+ """Timeout (in seconds) for the task's finalize hook."""
75
65
  scoring: float | None = None
66
+ """Timeout (in seconds) for the task's scoring."""
76
67
 
77
68
 
78
69
  class TaskData(BaseModel):
79
- """The task's wire half: one row's pure data, a frozen pydantic model. Subclass
80
- per dataset to add typed task-specific fields next to the base fields; behavior
81
- lives on `Task`, which wraps this (`self.data`)."""
82
-
83
70
  model_config = ConfigDict(frozen=True)
84
71
 
85
72
  idx: int | None = None
86
- """Dataset row index — set by tasksets (selection, resume, and grouping key
87
- on the eval path); `None` for ad-hoc tasks minted in scripts."""
73
+ """Taskset-autogenerated index."""
88
74
  name: str | None = None
75
+ """Optional human-readable task name."""
89
76
  description: str | None = None
77
+ """Optional human-readable task description."""
78
+
90
79
  prompt: str | Messages | None = None
91
- """Initial user prompt; `None` means the user opens the conversation — run the
92
- task through `agent.interaction()`, whose first `turn(message)` speaks first. (A
93
- default, not just optional: the wire drops `None`s — `traces.jsonl` rows for
94
- prompt-less tasks must read back.)"""
80
+ """Initial user prompt; unset if the user opens the conversation."""
95
81
  system_prompt: str | None = None
82
+ """Optional system prompt to prepend to the user prompt."""
83
+
96
84
  image: str | None = None
85
+ """Optional Docker image to use for the task. Only relevant for tasks that run in a container."""
97
86
  workdir: str | None = None
87
+ """Optional working directory to use for the task. Only relevant for tasks that run in a container."""
88
+
98
89
  network_allow: list[str] = Field(default_factory=lambda: ["*"])
99
90
  """Execution-time destinations requested by this task. `*` leaves the runtime
100
91
  allowlist unchanged; a concrete list replaces a wildcard or combines with existing
@@ -103,11 +94,13 @@ class TaskData(BaseModel):
103
94
  """Execution-time destinations denied by this task and combined with runtime
104
95
  blocks. Non-empty concrete allowlists cannot be combined with blocklists. Docker
105
96
  framework routes take precedence; ordinary Prime deny rules pass through unchanged."""
97
+
106
98
  artifacts: list[Artifact] = Field(default_factory=list)
107
99
  """Paths collected from one runtime and restored at the same locations in another,
108
100
  on top of the implicitly collected `/logs/artifacts/` convention dir. Declare
109
101
  runtime outputs that must cross that boundary. A declared path that is missing at
110
102
  collection time fails the rollout."""
103
+
111
104
  timeout: TaskTimeout = TaskTimeout()
112
105
  resources: TaskResources = TaskResources()
113
106
 
@@ -125,23 +118,10 @@ class WireTaskData(TaskData):
125
118
  model_config = ConfigDict(extra="allow")
126
119
 
127
120
 
128
- # No `default=`: an unparameterized `Trace`'s `task` field must serialize duck-typed
129
- # (a defaulted TypeVar narrows pydantic's serialization to the base `TaskData`, silently
130
- # dropping subclass fields from the wire).
131
121
  DataT = TypeVar("DataT", bound=TaskData)
132
122
  ConfigT = TypeVar("ConfigT", bound=TaskConfig, default=TaskConfig)
133
123
 
134
124
 
135
- def task_data_cls(cls: type) -> type[TaskData]:
136
- """Resolve a task's `TaskData` specialization through its MRO, else `TaskData`."""
137
- return concrete_type(cls, TaskData) or TaskData
138
-
139
-
140
- def task_config_cls(cls: type) -> type[TaskConfig]:
141
- """Resolve a task's `TaskConfig` specialization through its MRO, else `TaskConfig`."""
142
- return concrete_type(cls, TaskConfig) or TaskConfig
143
-
144
-
145
125
  def resolve_server_config(
146
126
  owner: str, config: BaseConfig, server_cls: type, *, sole: bool = True
147
127
  ) -> BaseConfig:
@@ -168,48 +148,20 @@ def resolve_server_config(
168
148
 
169
149
 
170
150
  class Task(Generic[DataT, StateT, ConfigT]):
171
- """Behavior, lifecycle, servers, and scoring for one `TaskData` row.
172
-
173
- Parameterize as `Task[MyData, MyState, MyConfig]`. Construction accepts the row
174
- and an optional config; omitting config builds the declared config type. One task
175
- instance is shared across a rollout group, so per-rollout state belongs on the trace.
176
- """
177
-
178
151
  NEEDS_CONTAINER: ClassVar[bool] = False
152
+ """Whether the task needs a containerized environment (isolated filesystem, ...)."""
179
153
 
180
154
  tools: ClassVar[tuple[type[Toolset], ...]] = ()
181
155
 
182
156
  def __init__(self, data: DataT, config: ConfigT | None = None) -> None:
183
157
  self.data = data
184
- self.config = config if config is not None else task_config_cls(type(self))()
158
+ self.config = config if config is not None else self.config_type()()
185
159
 
186
160
  def with_system_prompt(self, system_prompt: str) -> Self:
187
- """A shallow copy of this task with `data.system_prompt` overridden. Copies the
188
- instance instead of reconstructing via `type(self)(...)`, so a subclass with a
189
- non-`(data, config)` constructor or extra load-time state keeps it. Used to apply the
190
- config-layer / GEPA system prompt (see `TasksetConfig` and `verifiers.v1.gepa`)."""
191
161
  clone = copy.copy(self)
192
162
  clone.data = self.data.model_copy(update={"system_prompt": system_prompt})
193
163
  return clone
194
164
 
195
- def plugged_judges(self) -> list[Judge]:
196
- from verifiers.v1.loaders import load_judge
197
-
198
- return [load_judge(config) for config in self.config.judges]
199
-
200
- def server_config(self, server_cls: type) -> BaseConfig:
201
- """The config a declared server class (`tools`) is built with (see
202
- `resolve_server_config`). Override to pair explicitly."""
203
- return resolve_server_config(
204
- type(self).__name__,
205
- self.config,
206
- server_cls,
207
- sole=len(set(type(self).tools)) == 1,
208
- )
209
-
210
- def tool_servers(self) -> list[Toolset]:
211
- return [cls(self.server_config(cls)) for cls in type(self).tools]
212
-
213
165
  async def setup(self, trace: Trace, runtime: Runtime) -> None:
214
166
  return None
215
167
 
@@ -284,5 +236,29 @@ class Task(Generic[DataT, StateT, ConfigT]):
284
236
  for key, value in items:
285
237
  trace.record_reward(key, value, judge.config.weight)
286
238
 
239
+ @classmethod
240
+ def data_type(cls) -> type[TaskData]:
241
+ return concrete_type(cls, TaskData) or TaskData
242
+
243
+ @classmethod
244
+ def config_type(cls) -> type[TaskConfig]:
245
+ return concrete_type(cls, TaskConfig) or TaskConfig
246
+
247
+ def plugged_judges(self) -> list[Judge]:
248
+ from verifiers.v1.loaders import load_judge
249
+
250
+ return [load_judge(config) for config in self.config.judges]
251
+
252
+ def server_config(self, server_cls: type) -> BaseConfig:
253
+ return resolve_server_config(
254
+ type(self).__name__,
255
+ self.config,
256
+ server_cls,
257
+ sole=len(set(type(self).tools)) == 1,
258
+ )
259
+
260
+ def tool_servers(self) -> list[Toolset]:
261
+ return [cls(self.server_config(cls)) for cls in type(self).tools]
262
+
287
263
 
288
264
  TaskT = TypeVar("TaskT", bound=Task)
verifiers/v1/taskset.py CHANGED
@@ -103,8 +103,6 @@ class Taskset(ABC, Generic[TaskT, TasksetConfigT]):
103
103
  return concrete_type(cls, Task, origin=Taskset) or Task
104
104
 
105
105
  def server_config(self, server_cls: type) -> BaseConfig:
106
- """The config a `tools` entry is built with, resolved off `self.config` (the
107
- taskset config; see `resolve_server_config`). Override to pair explicitly."""
108
106
  return resolve_server_config(
109
107
  type(self).__name__,
110
108
  self.config,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: verifiers
3
- Version: 0.2.2.dev54
3
+ Version: 0.2.2.dev56
4
4
  Summary: Verifiers: Environments for LLM Reinforcement Learning
5
5
  Project-URL: Homepage, https://github.com/primeintellect-ai/verifiers
6
6
  Project-URL: Documentation, https://github.com/primeintellect-ai/verifiers
@@ -185,8 +185,8 @@ verifiers/v1/rollout.py,sha256=pmF4sgyHDRUUTnOxOWgBsPP8x6L_KFGaeR_dDKziANs,20470
185
185
  verifiers/v1/scoring.py,sha256=-R5Cog14r_tJ6Q_oOfGr5VPAm2CCUhofYZB6B9lm4wM,5787
186
186
  verifiers/v1/session.py,sha256=J6ZPuvsg6vMTJAs9dMUMtfdjCuvp6Hom877DVdKFKlY,6912
187
187
  verifiers/v1/state.py,sha256=pcpN2V6tX7rIO5XdtdUYay1j0ktEwrMtq7w1ApfsPdE,675
188
- verifiers/v1/task.py,sha256=N1EbU3UBu6LdSf9I8tIozxguz4Lh3rLU4YdTwXWAp9U,12182
189
- verifiers/v1/taskset.py,sha256=RPFkpRkeEyPX557_mK-JwraBuUKsguiCUKSFyotTclU,4636
188
+ verifiers/v1/task.py,sha256=pM2S4YU56jTuvvwHe00r1pBupQ42pvMUzpQhUXqpAPk,10232
189
+ verifiers/v1/taskset.py,sha256=5ffTlnmiN2GDePhonGSJ1a7iTseLPOC0DkwaVwf7uY4,4465
190
190
  verifiers/v1/trace.py,sha256=_bGHOrE6fRLGm0JYc0PrrrO3lyr-qqOF5Y1bHfViwR0,19347
191
191
  verifiers/v1/types.py,sha256=1PxamJspmoTc3OlFZAwH6o_2i_Tg9ZNvHxttIHWIxq8,8948
192
192
  verifiers/v1/acp/__init__.py,sha256=9dwH6fLopNndRmcpRSYC8ghzzMquaLfgh645QM-Dwic,2189
@@ -196,7 +196,7 @@ verifiers/v1/cli/debug.py,sha256=-jeEV_Q5tV8SOkWc1GdPZcXZWON_jU5gjeO4YoZm79o,114
196
196
  verifiers/v1/cli/gepa.py,sha256=hLIbS_4jBx0vvy4PXoePR5riFXcNvzQCMixZ-g2OR_U,4026
197
197
  verifiers/v1/cli/init.py,sha256=dVpX1YMz7DFmHgskAsPjP-HmVTGoZfC0ZUyE-T4I6l0,8322
198
198
  verifiers/v1/cli/output.py,sha256=pMS5Z0EBgyAVShNCAk9jVURNeLOaTfeRWpt0J8hHjq8,5890
199
- verifiers/v1/cli/replay.py,sha256=DiSEasbDvS-yjkkKhC6UDnMGcAPwtk7dv3NK2jM8fgA,10182
199
+ verifiers/v1/cli/replay.py,sha256=DAh9kB5PB-ppZLGhxdJwrCPch_Yky5HKhplwGFhKEz0,10164
200
200
  verifiers/v1/cli/resolve.py,sha256=OsNw4C3r9xOVFa-mminJFcex_bAsJ6EQ8K7A_H8u2kQ,4370
201
201
  verifiers/v1/cli/serve.py,sha256=_mdJaHVVe4pXzcpAot0ugcmiN3ra2gS4GrGmLghnX5M,2866
202
202
  verifiers/v1/cli/validate.py,sha256=lZ_wWnLgIWH5rUlMtwzvF3uS_cFZA4ZqBowpzdI4gos,10260
@@ -252,10 +252,13 @@ verifiers/v1/gepa/config.py,sha256=gFn8Re4GoeHJs2PZ-iw4jCEZ72AiM1lNgwaA0uvJlYw,4
252
252
  verifiers/v1/gepa/dataset.py,sha256=N2QYqUljHVuAdCbUuydEIlarvAWa6LFdGKu9qsOvjro,2186
253
253
  verifiers/v1/gepa/reflection.py,sha256=ptHhx0lcDLcWhWhXuslh9T8gPVNpnX5XLPtXoneW1yA,1054
254
254
  verifiers/v1/gepa/runner.py,sha256=-LZEt0lod6NKfyxg2dvOXZjfzTv3AWwendexd1De26c,6260
255
- verifiers/v1/harnesses/__init__.py,sha256=3fgfAMzFrNgu7RIO_evZPxipPdiskiHun5EKsdS4y6k,1301
255
+ verifiers/v1/harnesses/__init__.py,sha256=706ES37vrh_kCbctnbgkXIb1jBtO2ozZY5klBSg8ss0,1460
256
256
  verifiers/v1/harnesses/bash/__init__.py,sha256=IAV4eMMqDHSl-9ANb0Q3kxmBZ22SeHZFBM448X4gQio,140
257
257
  verifiers/v1/harnesses/bash/harness.py,sha256=ZtjhsANuK3vXkf9mRCi8-sBMyPebJMBNHa58vTd2Fm8,5284
258
258
  verifiers/v1/harnesses/bash/program.py,sha256=hGv3k9jwoabL045AGiZWiX76Cca3Juk58AaMYeJTEGo,15334
259
+ verifiers/v1/harnesses/browser_use/__init__.py,sha256=yxm2IG5TDLadxZEkX8SL26XWbcPcODXcrJfPfm1GqwU,171
260
+ verifiers/v1/harnesses/browser_use/harness.py,sha256=-P7CwMMkR7rLANAb6T4aOjAS4YuxzMPbm1MGvbIzbNI,5835
261
+ verifiers/v1/harnesses/browser_use/program.py,sha256=uk_nwTX_68bZckSFMkgtgwSkUK5HWBGqLTCDwxbt8P8,14287
259
262
  verifiers/v1/harnesses/claude_code/__init__.py,sha256=JkZQylMSA3o1fvBx_NM41y_umuahmOSqFjTrJ2hryTw,171
260
263
  verifiers/v1/harnesses/claude_code/harness.py,sha256=98k5T8d8nFQmxIU-ytkrkrrP6UNR5NxoGhVJRLVa-fI,4015
261
264
  verifiers/v1/harnesses/codex/__init__.py,sha256=ocyBvlpSO8c3pT6D1ebrQohoXYESQcCyPT5kN3j1-N4,132
@@ -305,7 +308,7 @@ verifiers/v1/runtimes/docker/egress.py,sha256=37UXgNX9gnoLxjMg4KZaJIGoApCAM6MK22
305
308
  verifiers/v1/serve/__init__.py,sha256=sr_zkDzAHnOcQm-QRm8xwJBmCMFD-xhKIFPaDZvMbUs,641
306
309
  verifiers/v1/serve/client.py,sha256=amUhf4cFJ1xCb8kw_AoVviwN543Wknx8LzImq1ZpaiQ,7057
307
310
  verifiers/v1/serve/pool.py,sha256=e9Nc3nQKEyV9YqyKHl_RuqQ84zWVa8z2J1rc3rfCadM,14828
308
- verifiers/v1/serve/server.py,sha256=VBOD3Gzq4p0ZD_8xgtG039i3JaefhOH0MmR6cxG56iY,9705
311
+ verifiers/v1/serve/server.py,sha256=IfJunpYX3MmNDToEcY-QHxDGfbZnK2i3C1-sgft6xfw,9687
309
312
  verifiers/v1/serve/types.py,sha256=y8Cf9wKOZRKDXcThFWVygTFHITJofOinGiIzwjQGCUE,2674
310
313
  verifiers/v1/tasksets/__init__.py,sha256=b62O4WDNbGfJH_4NjYmznn5otWovdfvUgJZyoIZyLh8,596
311
314
  verifiers/v1/tasksets/harbor/__init__.py,sha256=wwVGA8N7E2Q2qA5WGHuLRrn4DgG5oaRHrCS2RW3NXVY,195
@@ -330,8 +333,8 @@ verifiers/v1/utils/logging.py,sha256=OcMHA6NsYux3oIzjPuI95rDWmFBHNcHDjZeNIhXTX-Y
330
333
  verifiers/v1/utils/memory.py,sha256=ZkIvGk6uITAH5sKon65LifKPbvZr8mJ__PVc23FZpOQ,1835
331
334
  verifiers/v1/utils/sampling.py,sha256=52TJ5-Hmpvp4YSgKNR-LmAPVwm4RDcH-o2-BnbVTmYQ,965
332
335
  verifiers/v1/utils/version.py,sha256=-obEo_-l9-D8FLef4hYxncOe-uJpxrM1g2Hig_37Sgs,1607
333
- verifiers-0.2.2.dev54.dist-info/METADATA,sha256=kOTckyZa607Zo_MipBIfKbdhLJ1ePLbeHqOnPDm6OJ0,4545
334
- verifiers-0.2.2.dev54.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
335
- verifiers-0.2.2.dev54.dist-info/entry_points.txt,sha256=dF82JUYEFslR1AOW8LZfuBWeZeQoyX4wCRrduklg8-I,551
336
- verifiers-0.2.2.dev54.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
337
- verifiers-0.2.2.dev54.dist-info/RECORD,,
336
+ verifiers-0.2.2.dev56.dist-info/METADATA,sha256=W6ebWReoQGcUlZQMP5rxgoFLue_sm05XRa0MAqbZBwo,4545
337
+ verifiers-0.2.2.dev56.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
338
+ verifiers-0.2.2.dev56.dist-info/entry_points.txt,sha256=dF82JUYEFslR1AOW8LZfuBWeZeQoyX4wCRrduklg8-I,551
339
+ verifiers-0.2.2.dev56.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
340
+ verifiers-0.2.2.dev56.dist-info/RECORD,,