verifiers 0.4.2.dev60__py3-none-any.whl → 0.4.2.dev63__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.
Files changed (44) hide show
  1. verifiers/v1/__init__.py +3 -3
  2. verifiers/v1/agent.py +30 -3
  3. verifiers/v1/cli/debug.py +10 -3
  4. verifiers/v1/cli/validate.py +7 -1
  5. verifiers/v1/configs/runtime.py +10 -19
  6. verifiers/v1/env.py +20 -18
  7. verifiers/v1/envs/agentic_judge/env.py +8 -3
  8. verifiers/v1/envs/best_of_n_judge/env.py +13 -2
  9. verifiers/v1/grading.py +10 -4
  10. verifiers/v1/harness.py +7 -1
  11. verifiers/v1/harnesses/bash/harness.py +1 -0
  12. verifiers/v1/harnesses/browser_use/harness.py +1 -0
  13. verifiers/v1/harnesses/null/harness.py +1 -0
  14. verifiers/v1/harnesses/utils/core.py +57 -7
  15. verifiers/v1/interception/__init__.py +5 -7
  16. verifiers/v1/interception/server.py +131 -1
  17. verifiers/v1/mcp/launch.py +303 -99
  18. verifiers/v1/mcp/toolset.py +8 -10
  19. verifiers/v1/rollout.py +1 -0
  20. verifiers/v1/runtimes/__init__.py +10 -3
  21. verifiers/v1/runtimes/backends/custom.py +12 -7
  22. verifiers/v1/runtimes/backends/docker.py +13 -2
  23. verifiers/v1/runtimes/backends/prime.py +13 -0
  24. verifiers/v1/runtimes/backends/subprocess.py +223 -0
  25. verifiers/v1/runtimes/base.py +53 -28
  26. verifiers/v1/runtimes/private_network.py +2 -3
  27. verifiers/v1/runtimes/runtime.py +13 -2
  28. verifiers/v1/runtimes/strategies.py +2 -2
  29. verifiers/v1/session.py +5 -0
  30. verifiers/v1/submission.py +13 -4
  31. verifiers/v1/task.py +4 -1
  32. verifiers/v1/tasksets/harbor/taskset.py +5 -1
  33. verifiers/v1/tasksets/nemo_gym/server.py +8 -21
  34. verifiers/v1/tasksets/nemo_gym/taskset.py +30 -77
  35. verifiers/v1/utils/artifacts.py +7 -0
  36. verifiers/v1/utils/compile.py +62 -9
  37. verifiers/v1/utils/git.py +1 -1
  38. {verifiers-0.4.2.dev60.dist-info → verifiers-0.4.2.dev63.dist-info}/METADATA +1 -1
  39. {verifiers-0.4.2.dev60.dist-info → verifiers-0.4.2.dev63.dist-info}/RECORD +42 -43
  40. verifiers/v1/mcp/packages.py +0 -287
  41. verifiers/v1/runtimes/backends/cli.py +0 -51
  42. {verifiers-0.4.2.dev60.dist-info → verifiers-0.4.2.dev63.dist-info}/WHEEL +0 -0
  43. {verifiers-0.4.2.dev60.dist-info → verifiers-0.4.2.dev63.dist-info}/entry_points.txt +0 -0
  44. {verifiers-0.4.2.dev60.dist-info → verifiers-0.4.2.dev63.dist-info}/licenses/LICENSE +0 -0
verifiers/v1/__init__.py CHANGED
@@ -47,7 +47,7 @@ if TYPE_CHECKING:
47
47
  PrimeConfig,
48
48
  PrimeVolume,
49
49
  RuntimeConfig,
50
- SandboxConfig,
50
+ SubprocessConfig,
51
51
  )
52
52
  from verifiers.v1.configs.sampling import Sampling, SamplingConfig
53
53
  from verifiers.v1.configs.scoring import ScoringConfig
@@ -262,7 +262,6 @@ _NAME_TO_MODULE = {
262
262
  "ModelRoute": "verifiers.v1.clients",
263
263
  "RouteRejected": "verifiers.v1.clients",
264
264
  "NetworkPolicyConfig": "verifiers.v1.configs.runtime",
265
- "SandboxConfig": "verifiers.v1.configs.runtime",
266
265
  "PATCH_CAP_BYTES": "verifiers.v1.utils.git",
267
266
  "ParentLink": "verifiers.v1.semantic",
268
267
  "PolicyEvent": "verifiers.v1.trace",
@@ -306,6 +305,7 @@ _NAME_TO_MODULE = {
306
305
  "State": "verifiers.v1.state",
307
306
  "StateT": "verifiers.v1.state",
308
307
  "StopFunctionConfig": "verifiers.v1.configs.task",
308
+ "SubprocessConfig": "verifiers.v1.configs.runtime",
309
309
  "SystemMessage": "verifiers.v1.types",
310
310
  "TRACE_VERSION": "verifiers.v1.trace",
311
311
  "Task": "verifiers.v1.task",
@@ -496,11 +496,11 @@ __all__ = [ # noqa: RUF022 - grouped by public API area
496
496
  "RuntimeConfig",
497
497
  "RuntimeInfo",
498
498
  "ProgramResult",
499
+ "SubprocessConfig",
499
500
  "DockerConfig",
500
501
  "BindMount",
501
502
  "CustomRuntimeConfig",
502
503
  "NetworkPolicyConfig",
503
- "SandboxConfig",
504
504
  "PrimeConfig",
505
505
  "PrimeVolume",
506
506
  "Env",
verifiers/v1/agent.py CHANGED
@@ -38,6 +38,7 @@ from verifiers.v1.rollout import Rollout, RolloutTimeouts
38
38
  from verifiers.v1.runtimes import (
39
39
  Runtime,
40
40
  RuntimeConfig,
41
+ backend_cls,
41
42
  provision_backend,
42
43
  runtime_is_local,
43
44
  )
@@ -95,6 +96,16 @@ def resolve_rollout_timeouts(timeout: TimeoutConfig, task: Task) -> RolloutTimeo
95
96
  )
96
97
 
97
98
 
99
+ def _check_artifact_runtime(runtime_config: RuntimeConfig) -> None:
100
+ """Artifact collection reads the task's paths out of the box, so the box needs a
101
+ filesystem of its own."""
102
+ if not backend_cls(runtime_config).SUPPORTS_TASK_IMAGES:
103
+ raise TypeError(
104
+ "artifact collection requires a runtime with its own filesystem; the "
105
+ f"{runtime_config.type} runtime cannot run images"
106
+ )
107
+
108
+
98
109
  def _check_borrowed_placement(
99
110
  task: Task, runtime: Runtime, base_config: RuntimeConfig
100
111
  ) -> None:
@@ -135,7 +146,13 @@ def _check_borrowed_placement(
135
146
  )
136
147
  if task.data.image is None:
137
148
  return
138
- box_image = runtime.config.image
149
+ if not runtime.backend.SUPPORTS_TASK_IMAGES:
150
+ raise TypeError(
151
+ f"task {task.data.idx!r} requires image {task.data.image!r}, but the "
152
+ f"borrowed {runtime.type} runtime cannot run images; borrow a container "
153
+ "box (e.g. agent.provision(task)) or drop the task's image"
154
+ )
155
+ box_image = getattr(runtime.config, "image", None)
139
156
  if box_image != task.data.image:
140
157
  logger.warning(
141
158
  "Running task %s in borrowed box %s on its image - the task requires %s "
@@ -592,6 +609,7 @@ class Agent:
592
609
  self.trainable: bool = True
593
610
  self._entered = False
594
611
  self._server: InterceptionServer | None = None
612
+ self._warned_resources: set[tuple[str, str]] = set()
595
613
 
596
614
  async def __aenter__(self) -> Self:
597
615
  if self._entered:
@@ -747,6 +765,8 @@ class Agent:
747
765
  attempt: int,
748
766
  ) -> Trace:
749
767
  params = self._rollout_params(task, runtime, dict(shared_tools or {}), route)
768
+ if collect_artifacts:
769
+ _check_artifact_runtime(params["runtime_config"])
750
770
  run = Rollout(
751
771
  task=task,
752
772
  on_trace=on_trace,
@@ -815,6 +835,8 @@ class Agent:
815
835
  params = self._rollout_params(
816
836
  task, runtime, dict(tools or {}), route or ModelRoute(self.ctx)
817
837
  )
838
+ if collect_artifacts:
839
+ _check_artifact_runtime(params["runtime_config"])
818
840
  run = Rollout(
819
841
  task=task,
820
842
  has_user=True,
@@ -866,7 +888,9 @@ class Agent:
866
888
  runtime_config = runtime.config
867
889
  run_is_local = runtime.is_local
868
890
  else:
869
- runtime_config = resolve_runtime_config(self.runtime_config, task)
891
+ runtime_config = resolve_runtime_config(
892
+ self.runtime_config, task, self._warned_resources
893
+ )
870
894
  run_is_local = runtime_is_local(runtime_config)
871
895
  validate_pairing(
872
896
  harness,
@@ -892,7 +916,7 @@ class Agent:
892
916
  """Provision (and on exit tear down) a box from this agent's runtime
893
917
  policy, resolved for `task` when given; share it via `run(..., runtime=runtime)`."""
894
918
  config = (
895
- resolve_runtime_config(self.runtime_config, task)
919
+ resolve_runtime_config(self.runtime_config, task, self._warned_resources)
896
920
  if task is not None
897
921
  else self.runtime_config
898
922
  )
@@ -923,8 +947,11 @@ class _EpisodeAgent(Agent):
923
947
  completed: list[Trace],
924
948
  on_trace: Callable[[Trace], None] | None,
925
949
  on_discard: Callable[[Trace], None] | None,
950
+ warned_resources: set,
926
951
  ) -> None:
927
952
  super().__init__(config, interception=interception)
953
+ # Resource warnings dedupe env-wide, not per episode.
954
+ self._warned_resources = warned_resources
928
955
  self._name = name
929
956
  self._shared_tools = shared_tools
930
957
  self._task_cls = task_cls
verifiers/v1/cli/debug.py CHANGED
@@ -39,7 +39,7 @@ logger = get_logger(__name__)
39
39
 
40
40
  USAGE = (
41
41
  "usage: uv run vf-debug [<taskset-id>] (--command <cmd> | --script-path <path>) "
42
- "[--runtime.type docker] [options] [@ file.toml]\n"
42
+ "[--runtime.type subprocess] [options] [@ file.toml]\n"
43
43
  " runs setup, then one command or uploaded host script, and saves traces"
44
44
  )
45
45
 
@@ -173,8 +173,9 @@ async def run_action(runtime: Runtime, config: DebugConfig) -> dict[str, Any]:
173
173
  **(await run_timed(runtime.run(["sh", "-lc", config.command], {}), config)),
174
174
  }
175
175
  assert config.script_path is not None
176
- # Keep the script outside the task workdir so it doesn't appear in the repo
177
- # state being inspected; the runtime name separates concurrent runs.
176
+ # /tmp keyed by the (run-unique) runtime name: outside the task workdir so the script
177
+ # doesn't show up in the repo state being inspected, and never shared between runs on
178
+ # the subprocess runtime, where an absolute path is a host path.
178
179
  remote_path = f"/tmp/{runtime.name}-script.sh"
179
180
  quoted = shlex.quote(remote_path)
180
181
  command = f"chmod +x {quoted} && {quoted}"
@@ -274,6 +275,12 @@ async def run_debug(config: DebugConfig) -> list[Trace]:
274
275
  f"{type(taskset).__name__} is infinite - bound the run with -n"
275
276
  )
276
277
  tasks = list(taskset)
278
+ if isinstance(config.runtime, vf.SubprocessConfig) and any(
279
+ type(t).NEEDS_CONTAINER or t.data.image for t in tasks
280
+ ):
281
+ raise SystemExit(
282
+ "taskset needs a container runtime to debug - pass --runtime.type docker (or prime)"
283
+ )
277
284
 
278
285
  out = output_path(config)
279
286
  save_config(config, out, "debug.json")
@@ -63,7 +63,7 @@ ResultRow = dict[str, Any]
63
63
 
64
64
  USAGE = (
65
65
  "usage: uv run vf-validate [<taskset-id>] [--only-setup | --only-gold | --only-noop] "
66
- "[-o <output-dir>] [--runtime.type docker] [options] [@ file.toml]\n"
66
+ "[-o <output-dir>] [--runtime.type subprocess] [options] [@ file.toml]\n"
67
67
  " uv run vf-validate @ <run-dir>/configs/validate.json --resume (re-run missing/errored/timed-out tasks)\n"
68
68
  " runs persisted gold and noop (untouched scoring) checks per task (no agent)"
69
69
  )
@@ -448,6 +448,12 @@ async def run_validate(config: ValidateConfig) -> list[dict]:
448
448
  f"{type(taskset).__name__} is infinite - bound the run with -n"
449
449
  )
450
450
  tasks = list(taskset)
451
+ if isinstance(config.runtime, vf.SubprocessConfig) and any(
452
+ type(t).NEEDS_CONTAINER or t.data.image for t in tasks
453
+ ):
454
+ raise SystemExit(
455
+ "taskset needs a container runtime to validate - pass --runtime.type docker (or prime)"
456
+ )
451
457
  mode = validation_mode(config)
452
458
  checks = "gold+noop" if mode == "all" else mode
453
459
  out = output_path(config)
@@ -152,28 +152,17 @@ class NetworkPolicyConfig(BaseConfig):
152
152
  return type(self).model_validate({**values, "allow": allow, "block": block})
153
153
 
154
154
 
155
- class SandboxConfig(BaseConfig):
156
- """What every runtime provisions: a task image with a working directory and the
157
- resources `TaskData.resources` requests. Network policy support is declared by also
158
- inheriting `NetworkPolicyConfig`."""
155
+ class SubprocessConfig(BaseConfig):
156
+ type: Literal["subprocess"] = "subprocess"
159
157
 
158
+
159
+ class DockerConfig(NetworkPolicyConfig):
160
+ type: Literal["docker"] = "docker"
160
161
  image: str = "python:3.11-slim"
161
162
  workdir: str | None = None
162
163
  """Working directory override; None uses the task's workdir, or /app."""
163
164
  # TaskData.resources uses these units; non-default runtime config values take precedence.
164
165
  cpu: float | None = None
165
- """CPU cores. None = the provider's default."""
166
- memory: float | None = None
167
- """Memory limit in GB. None = the provider's default."""
168
- gpu: str | None = None
169
- """GPU spec, e.g. "A100" or "A100:2" (a bare count = provider-chosen type)."""
170
- disk: float | None = None
171
- """Disk in GB. None = the provider's default."""
172
-
173
-
174
- class DockerConfig(SandboxConfig, NetworkPolicyConfig):
175
- type: Literal["docker"] = "docker"
176
- cpu: float | None = None
177
166
  """Pin the container to this many CPU cores. None = unlimited."""
178
167
  memory: float | None = None
179
168
  """Hard memory limit in GB. None = unlimited."""
@@ -200,13 +189,15 @@ class PrimeVolume(BaseConfig):
200
189
  read_only: bool = True
201
190
 
202
191
 
203
- class PrimeConfig(SandboxConfig, NetworkPolicyConfig):
192
+ class PrimeConfig(NetworkPolicyConfig):
204
193
  type: Literal["prime"] = "prime"
205
194
  image: str = "python:3.11-slim"
206
195
  """Docker image to run. Any pullable ref works: on the first use of an image, the
207
196
  platform auto-builds the VM image that the sandbox needs from it (~10 minutes)
208
197
  and caches the result, so later sandboxes on the same ref start in
209
198
  seconds."""
199
+ workdir: str | None = None
200
+ """Working directory override; None uses the task's workdir, or /app."""
210
201
  region: str | None = None
211
202
  """Region to provision in (None = provider-chosen)."""
212
203
  labels: list[str] = Field(default_factory=list)
@@ -255,7 +246,7 @@ class PrimeConfig(SandboxConfig, NetworkPolicyConfig):
255
246
  return self
256
247
 
257
248
 
258
- class CustomRuntimeConfig(SandboxConfig):
249
+ class CustomRuntimeConfig(BaseConfig):
259
250
  type: Literal["custom"] = "custom"
260
251
  import_path: str
261
252
  """Dotted path to a `RuntimeBackend` subclass, e.g. `my_package.runtime.MyBackend`."""
@@ -284,7 +275,7 @@ class CustomRuntimeConfig(SandboxConfig):
284
275
  # Serialized by the runtime type, so a custom runtime's typed config keeps its fields.
285
276
  RuntimeConfig = SerializeAsAny[
286
277
  Annotated[
287
- DockerConfig | PrimeConfig | CustomRuntimeConfig,
278
+ SubprocessConfig | DockerConfig | PrimeConfig | CustomRuntimeConfig,
288
279
  Field(discriminator="type"),
289
280
  ]
290
281
  ]
verifiers/v1/env.py CHANGED
@@ -30,8 +30,7 @@ from verifiers.v1.interception import (
30
30
  requires_tunnel,
31
31
  )
32
32
  from verifiers.v1.mcp import SharedToolServer, serve_shared
33
- from verifiers.v1.mcp.launch import check_reachable, tool_runtime
34
- from verifiers.v1.runtimes import RuntimeConfig, runtime_is_local
33
+ from verifiers.v1.runtimes import SubprocessConfig, runtime_is_local
35
34
  from verifiers.v1.task import Task
36
35
  from verifiers.v1.trace import Error, Trace, TraceTask
37
36
  from verifiers.v1.utils.format import format_time
@@ -132,10 +131,27 @@ class Env(ABC, Generic[ConfigT]):
132
131
  if key not in loaded:
133
132
  loaded[key] = load_harness(cfg)
134
133
  self._harnesses[name] = loaded[key]
134
+ warned: set[str] = set()
135
+ for name, harness in self._harnesses.items():
136
+ # Warn once per distinct harness; tool-less chat loops are exempt.
137
+ if (
138
+ harness.EXECUTES_CODE
139
+ and isinstance(self._agent_specs[name].runtime, SubprocessConfig)
140
+ and harness.config.id not in warned
141
+ ):
142
+ warned.add(harness.config.id)
143
+ logger.warning(
144
+ "Harness %r is running in the subprocess runtime on the local system. "
145
+ "Local files and settings may affect the evaluation; use subprocess only "
146
+ "for debugging. Use --env.<role>.runtime.type docker or prime "
147
+ "for an isolated run.",
148
+ harness.config.id,
149
+ )
135
150
  # Serving resources, live only inside `serving()`; the env's agents borrow them.
136
151
  self._shared_tools: dict[str, SharedToolServer] = {}
137
152
  self._interception: Interception | None = None
138
153
  # Resource warnings dedupe env-wide (agents are per-episode).
154
+ self._warned_resources: set = set()
139
155
 
140
156
  # --- the multi-agent surface (override these) ------------------------------
141
157
 
@@ -215,6 +231,7 @@ class Env(ABC, Generic[ConfigT]):
215
231
  completed=completed,
216
232
  on_trace=on_trace,
217
233
  on_discard=on_discard,
234
+ warned_resources=self._warned_resources,
218
235
  )
219
236
 
220
237
  agents = Agents(self.config, make)
@@ -436,26 +453,11 @@ class Env(ABC, Generic[ConfigT]):
436
453
  ]
437
454
  return requires_tunnel(self._runs_local(), configs, shared.values())
438
455
 
439
- def tool_provider(self) -> RuntimeConfig:
440
- """The runtime shared servers default to: the roles' provider, or a remote role's
441
- when roles mix providers, since a local server cannot serve a remote harness."""
442
- runtimes = [spec.runtime for spec in self._agent_specs.values()]
443
- remote = [config for config in runtimes if not runtime_is_local(config)]
444
- return (remote or runtimes)[0]
445
-
446
456
  @contextlib.asynccontextmanager
447
457
  async def shared_tools(self):
448
458
  servers = self.taskset.toolsets(self.taskset.config)
449
459
  if not servers:
450
460
  yield {}
451
461
  return
452
- provider = self.tool_provider()
453
- for server in servers:
454
- if not server.config.url:
455
- check_reachable(
456
- server.server_name,
457
- tool_runtime(server.config, provider),
458
- self._runs_local(),
459
- )
460
- async with serve_shared(servers, provider) as shared:
462
+ async with serve_shared(servers, harness_is_local=self._runs_local()) as shared:
461
463
  yield shared
@@ -117,7 +117,10 @@ HINT_SECTION = """\
117
117
  class JudgeTask(vf.Task):
118
118
  """The judge's verdict task: the solver task's world mirrored onto the minted
119
119
  row, the trace record written (and any stale verdict removed) before the
120
- judge starts, verdict scraped off the live box after it exits."""
120
+ judge starts, verdict scraped off the live box after it exits. `NEEDS_CONTAINER`
121
+ keeps `Agent.run`'s per-task backstop aligned with the judge's declared need."""
122
+
123
+ NEEDS_CONTAINER = True
121
124
 
122
125
  def __init__(
123
126
  self,
@@ -272,8 +275,8 @@ class AgenticJudgeEnv(vf.Env[AgenticJudgeEnvConfig]):
272
275
  config.task.criteria()
273
276
 
274
277
  def _check_agents(self) -> None:
275
- """Refuse an impossible judge at construction, not after burning a full
276
- solver run."""
278
+ """The judge executes real code, never on the host — refuse an impossible
279
+ pairing at construction, not after burning a full solver run."""
277
280
  judge = self._harnesses["judge"]
278
281
  if not judge.EXECUTES_CODE:
279
282
  raise ValueError(
@@ -314,6 +317,8 @@ class AgenticJudgeEnv(vf.Env[AgenticJudgeEnvConfig]):
314
317
  workspace = (
315
318
  policy.runtime if policy.mode == "isolated" else None
316
319
  ) or self.config.solver.runtime
320
+ if isinstance(workspace, vf.SubprocessConfig):
321
+ raise TypeError("agentic judging requires a container scoring workspace")
317
322
  validate_pairing(self._harnesses["judge"], JudgeTask, workspace)
318
323
 
319
324
  async def judge(solution: vf.Trace, runtime: vf.Runtime) -> None:
@@ -25,6 +25,7 @@ from verifiers.v1.envs.agentic_judge.env import (
25
25
  TextSource,
26
26
  )
27
27
  from verifiers.v1.envs.best_of_n import BestOfNEnv, BestOfNEnvConfig
28
+ from verifiers.v1.runtimes import backend_cls
28
29
  from verifiers.v1.utils.artifacts import _validate_restore
29
30
 
30
31
  ATTEMPTS_DIR = "/tmp/attempts"
@@ -119,7 +120,9 @@ class Ranking(BaseModel):
119
120
  class RankTask(vf.Task):
120
121
  """One judge's ranking task: every attempt's record and artifacts uploaded
121
122
  under its label before the judge starts, the ranking scraped off the box after
122
- it exits."""
123
+ it exits. `NEEDS_CONTAINER`: the judge executes code, never on the host."""
124
+
125
+ NEEDS_CONTAINER = True
123
126
 
124
127
  def __init__(self, data: vf.TaskData, labels: dict[str, vf.Trace]) -> None:
125
128
  super().__init__(data)
@@ -243,15 +246,23 @@ class BestOfNJudgeEnv(BestOfNEnv, vf.Env[BestOfNJudgeEnvConfig]):
243
246
  "best-of-n-judge requires a judge harness that can execute code, but "
244
247
  f"harness {judge.config.id!r} is a tool-less chat loop"
245
248
  )
249
+ if not backend_cls(config.judge.runtime).SUPPORTS_TASK_IMAGES:
250
+ raise ValueError(
251
+ "best-of-n-judge requires a container judge runtime: "
252
+ "--env.judge.runtime.type docker|prime"
253
+ )
246
254
 
247
255
  async def setup(self, agents: vf.Agents) -> None:
248
256
  # The judges grade the policy; their tokens are never training data.
249
257
  agents.judge.trainable = False
250
258
 
251
259
  async def run(self, task: vf.Task, agents: vf.Agents) -> None:
260
+ # Artifacts need a runtime with its own filesystem; a subprocess attempt
261
+ # is ranked on its trace alone.
262
+ collect = backend_cls(self.config.agent.runtime).SUPPORTS_TASK_IMAGES
252
263
  async with asyncio.TaskGroup() as tg:
253
264
  runs = [
254
- tg.create_task(agents.agent.run(task, collect_artifacts=True))
265
+ tg.create_task(agents.agent.run(task, collect_artifacts=collect))
255
266
  for _ in range(self.config.n)
256
267
  ]
257
268
  attempts = [run.result() for run in runs]
verifiers/v1/grading.py CHANGED
@@ -13,6 +13,7 @@ from verifiers.v1.runtimes import (
13
13
  PrimeConfig,
14
14
  Runtime,
15
15
  RuntimeConfig,
16
+ backend_cls,
16
17
  )
17
18
  from verifiers.v1.task import Task
18
19
  from verifiers.v1.trace import Error, Trace
@@ -56,21 +57,26 @@ def verifier_runtime(
56
57
  # A task without its own image/workdir inherits the actual workspace's values,
57
58
  # including a Compose image or split execution configuration.
58
59
  task = task.with_data(
59
- image=task.data.image or solver_runtime.config.image,
60
- workdir=task.data.workdir or solver_runtime.config.workdir,
60
+ image=task.data.image or getattr(solver_runtime.config, "image", None),
61
+ workdir=task.data.workdir or getattr(solver_runtime.config, "workdir", None),
61
62
  )
62
63
  if policy.network is not None:
63
64
  task = task.with_data(network=policy.network)
64
65
  config = resolve_runtime_config(source, task)
65
66
  if policy.runtime is not None and "image" in policy.runtime.model_fields_set:
66
67
  config = config.model_copy(update={"image": policy.runtime.image})
68
+ if not backend_cls(config).SUPPORTS_TASK_IMAGES:
69
+ raise TaskError(
70
+ f"isolated verification requires an isolated filesystem; the "
71
+ f"{config.type} runtime cannot run images"
72
+ )
67
73
  relative = [
68
74
  a.source
69
75
  for a in task.data.artifacts
70
76
  if not PurePosixPath(a.source).is_absolute()
71
77
  ]
72
- solver_dir = PurePosixPath(solver_runtime.config.workdir or "/app")
73
- grader_dir = PurePosixPath(config.workdir or "/app")
78
+ solver_dir = PurePosixPath(getattr(solver_runtime.config, "workdir", "/") or "/app")
79
+ grader_dir = PurePosixPath(getattr(config, "workdir", "/") or "/app")
74
80
  if relative and solver_dir != grader_dir:
75
81
  raise TaskError(
76
82
  f"cannot restore relative artifacts {relative!r} from {solver_dir} into {grader_dir}; use matching workdirs or absolute paths"
verifiers/v1/harness.py CHANGED
@@ -56,11 +56,17 @@ class Harness(ABC, Generic[ConfigT]):
56
56
  EXECUTES_CODE: ClassVar[bool] = True
57
57
  """Whether the program hands the model local execution in the runtime — true for
58
58
  every real harness; the tool-less chat loops (`null`) override to False. Read
59
- where model-directed execution changes the rules, e.g. the judge envs."""
59
+ where model-directed execution changes the rules: the subprocess-on-host
60
+ warning, the judge env's sandbox requirement."""
60
61
  SUPPORTS_SKILLS: ClassVar[bool] = False
61
62
  """Whether the program discovers SKILL.md skills — it calls
62
63
  `install_skills` with a run-scoped discovery location; configuring
63
64
  `skills` on a harness without support is rejected up front."""
65
+ NEEDS_CONTAINER: ClassVar[bool] = True
66
+ """Whether the program must run in a container runtime: True for every harness
67
+ that installs and drives a third-party program — on the host (subprocess) it
68
+ leaks host state (auth, config, processes) both ways. Only the minimal
69
+ in-house loops (`bash`, `null`) override to False."""
64
70
 
65
71
  def __init__(self, config: ConfigT) -> None:
66
72
  self.config = config
@@ -53,6 +53,7 @@ class BashHarness(Harness[BashHarnessConfig]):
53
53
  SUPPORTS_MCP = True
54
54
  SUPPORTS_RESUME = True
55
55
  SUPPORTS_TOOL_INTERCEPTION = True
56
+ NEEDS_CONTAINER = False
56
57
 
57
58
  async def setup(self, runtime: Runtime) -> None:
58
59
  await runtime.prepare_uv_script(CHAT_PROGRAM_SOURCE, self.config.resolved_env)
@@ -57,6 +57,7 @@ class BrowserUseHarness(Harness[BrowserUseHarnessConfig]):
57
57
  SUPPORTS_MCP = True
58
58
  SUPPORTS_RESUME = True
59
59
  # The browser tool executes model-authored Python through a third-party daemon.
60
+ NEEDS_CONTAINER = True
60
61
 
61
62
  async def setup(self, runtime: Runtime) -> None:
62
63
  await runtime.prepare_uv_script(PROGRAM_SOURCE, self.config.resolved_env)
@@ -28,6 +28,7 @@ class NullHarness(Harness[NullHarnessConfig]):
28
28
  SUPPORTS_RESUME = True
29
29
  SUPPORTS_TOOL_INTERCEPTION = True
30
30
  EXECUTES_CODE = False
31
+ NEEDS_CONTAINER = False
31
32
 
32
33
  async def setup(self, runtime: Runtime) -> None:
33
34
  await runtime.prepare_uv_script(CHAT_PROGRAM_SOURCE, self.config.resolved_env)
@@ -4,7 +4,10 @@ import argparse
4
4
  import asyncio
5
5
  import json
6
6
  import logging
7
+ import os
8
+ import selectors
7
9
  import subprocess
10
+ import time
8
11
  import traceback
9
12
  from contextlib import AsyncExitStack
10
13
  from pathlib import Path
@@ -32,6 +35,7 @@ from tenacity import (
32
35
  if TYPE_CHECKING:
33
36
  # The harness bundles this module into the generated script before execution.
34
37
  from verifiers.v1.harnesses.utils.compaction import ( # noqa: TC004
38
+ TOOL_OUTPUT_MAX_BYTES,
35
39
  Compactor,
36
40
  bound_tool_message,
37
41
  compactable,
@@ -183,16 +187,62 @@ def run_search(
183
187
  return f"search failed ({e}). Try again or rephrase the query."
184
188
 
185
189
 
190
+ class _BashOutput:
191
+ def __init__(self) -> None:
192
+ self.head = b""
193
+ self.tail = b""
194
+ self.size = 0
195
+
196
+ def add(self, chunk: bytes) -> None:
197
+ self.head += chunk[: max(0, TOOL_OUTPUT_MAX_BYTES - len(self.head))]
198
+ self.tail = (self.tail + chunk)[-TOOL_OUTPUT_MAX_BYTES:]
199
+ self.size += len(chunk)
200
+
201
+
186
202
  def run_bash(command: str) -> str:
187
203
  try:
188
- result = subprocess.run(
204
+ with subprocess.Popen(
189
205
  ["bash", "-c", command],
190
- capture_output=True,
191
- text=True,
192
- timeout=3600,
193
- check=False,
194
- )
195
- return result.stdout + result.stderr
206
+ stdout=subprocess.PIPE,
207
+ stderr=subprocess.PIPE,
208
+ ) as process:
209
+ stdout, stderr = _BashOutput(), _BashOutput()
210
+ deadline = time.monotonic() + 3600
211
+ try:
212
+ with selectors.DefaultSelector() as selector:
213
+ assert process.stdout is not None and process.stderr is not None
214
+ selector.register(process.stdout, selectors.EVENT_READ, stdout)
215
+ selector.register(process.stderr, selectors.EVENT_READ, stderr)
216
+ while selector.get_map():
217
+ remaining = deadline - time.monotonic()
218
+ if remaining <= 0:
219
+ raise subprocess.TimeoutExpired(process.args, 3600)
220
+ for key, _ in selector.select(remaining):
221
+ chunk = os.read(key.fd, 8192)
222
+ if chunk:
223
+ key.data.add(chunk)
224
+ else:
225
+ selector.unregister(key.fileobj)
226
+ process.wait(timeout=max(0, deadline - time.monotonic()))
227
+ finally:
228
+ # Do not communicate() here: descendants may still hold the pipes.
229
+ if process.returncode is None:
230
+ process.kill()
231
+ process.wait()
232
+ size = stdout.size + stderr.size
233
+ if size <= TOOL_OUTPUT_MAX_BYTES:
234
+ text = "".join(
235
+ output.head.decode().replace("\r\n", "\n").replace("\r", "\n")
236
+ for output in (stdout, stderr)
237
+ )
238
+ else:
239
+ marker = f"\n[... bash output truncated; {size} bytes total ...]\n"
240
+ keep = (TOOL_OUTPUT_MAX_BYTES - len(marker.encode())) // 2
241
+ # Preserve stdout-then-stderr ordering, including when just one is large.
242
+ head = (stdout.head + stderr.head)[:keep].decode(errors="ignore")
243
+ tail = (stdout.tail + stderr.tail)[-keep:].decode(errors="ignore")
244
+ text = head + marker + tail
245
+ return text.replace("\r\n", "\n").replace("\r", "\n")
196
246
  except Exception as e: # noqa: BLE001 - tool failures are returned to the model
197
247
  return f"error: {e}"
198
248
 
@@ -32,21 +32,19 @@ def requires_tunnel(
32
32
  """Whether the interception must be exposed via a tunnel — some consumer is off the
33
33
  host network: the harness itself, a live `shared` server in a remote runtime, or a
34
34
  tool server config placing one there (each reaches the `/state` channel from
35
- its own runtime). A server without a runtime of its own shares the harness's
36
- locality, as do task-format adapters. Skipped as non-consumers: a config-`url`
37
- server (external — it connects out), and an `external` shared server (outside the
38
- state machinery entirely). False means every consumer reaches the server at
39
- localhost."""
35
+ its own runtime). Task-format adapters share the harness's locality. Skipped as
36
+ non-consumers: a config-`url` server (external —
37
+ it connects out), and an `external` shared server (outside the state machinery
38
+ entirely). False means every consumer reaches the server at localhost."""
40
39
  from verifiers.v1.mcp.toolset import BaseToolsetConfig
41
40
 
42
41
  if not harness_is_local:
43
42
  return True
44
- if any(s.runtime is not None and not s.runtime.is_local for s in shared):
43
+ if any(not s.external and not s.local for s in shared):
45
44
  return True
46
45
  return any(
47
46
  isinstance(config, BaseToolsetConfig)
48
47
  and not config.url
49
- and config.runtime is not None
50
48
  and not runtime_is_local(config.runtime)
51
49
  for config in server_configs
52
50
  )