verifiers 0.3.2.dev24__py3-none-any.whl → 0.3.2.dev26__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.
verifiers/v1/__init__.py CHANGED
@@ -82,6 +82,13 @@ from verifiers.v1.runtimes import (
82
82
  RuntimeProcess,
83
83
  SubprocessConfig,
84
84
  )
85
+ from verifiers.v1.semantic import (
86
+ ACP_SEMANTIC_EDGES_METADATA_KEY,
87
+ ACPInfo,
88
+ ParentLink,
89
+ SemanticEdge,
90
+ SemanticEdgeSet,
91
+ )
85
92
  from verifiers.v1.state import State, StateT
86
93
  from verifiers.v1.task import Task, TaskData, TaskResources, TaskTimeout, WireTaskData
87
94
  from verifiers.v1.taskset import Taskset
@@ -226,6 +233,11 @@ __all__ = [ # noqa: RUF022 - grouped by public API area
226
233
  "EvalRunInfo",
227
234
  "EvalWorkInfo",
228
235
  "ModelCall",
236
+ "ACPInfo",
237
+ "ACP_SEMANTIC_EDGES_METADATA_KEY",
238
+ "ParentLink",
239
+ "SemanticEdge",
240
+ "SemanticEdgeSet",
229
241
  "PolicyEvent",
230
242
  "TrainRunInfo",
231
243
  "TrainWorkInfo",
@@ -16,6 +16,10 @@ from verifiers.v1.configs.harness import HarnessConfig
16
16
  from verifiers.v1.errors import HarnessError
17
17
  from verifiers.v1.harness import Harness, HarnessSession
18
18
  from verifiers.v1.runtimes import ProgramResult, Runtime, RuntimeProcess
19
+ from verifiers.v1.semantic import (
20
+ ACP_SEMANTIC_EDGES_METADATA_KEY,
21
+ SemanticEdgeSet,
22
+ )
19
23
  from verifiers.v1.task import TaskData
20
24
  from verifiers.v1.trace import Trace
21
25
  from verifiers.v1.types import Messages
@@ -67,6 +71,20 @@ class ACPHarness(Harness[ConfigT]):
67
71
  def acp_turn_result(self, trace: Trace, result: ACPTurn) -> None:
68
72
  """Consume the typed result of one ACP prompt."""
69
73
 
74
+ def acp_close_result(self, trace: Trace, response_metadata: dict[str, Any]) -> None:
75
+ """Consume extension metadata returned by `session/close`, when supported."""
76
+
77
+ def _consume_protocol_metadata(
78
+ self, trace: Trace, response_metadata: dict[str, Any]
79
+ ) -> None:
80
+ """Attach optional protocol extensions understood by every ACP harness."""
81
+ if ACP_SEMANTIC_EDGES_METADATA_KEY not in response_metadata:
82
+ return
83
+ edge_set = SemanticEdgeSet.model_validate(
84
+ response_metadata[ACP_SEMANTIC_EDGES_METADATA_KEY]
85
+ )
86
+ trace.add_semantic_edges(edge_set)
87
+
70
88
  @abstractmethod
71
89
  async def prepare_acp(
72
90
  self,
@@ -274,22 +292,30 @@ class ACPHarnessSession(HarnessSession):
274
292
  if stderr := self._stderr():
275
293
  detail = f"{detail}\n\nACP process stderr:\n{stderr}"
276
294
  raise RuntimeError(detail)
277
- cast(ACPHarness, self.harness).acp_turn_result(self.trace, turn)
295
+ harness = cast(ACPHarness, self.harness)
296
+ harness._consume_protocol_metadata(self.trace, turn.response_metadata)
297
+ harness.acp_turn_result(self.trace, turn)
278
298
  result = ProgramResult(exit_code=0, stdout=turn.reply, stderr="")
279
299
  _require_model_turn(self.trace, calls_before, result)
280
300
  return result
281
301
 
282
- async def _stop(self, *, graceful: bool) -> None:
302
+ async def _stop(self, *, graceful: bool) -> dict[str, Any]:
283
303
  process, self._process = self._process, None
284
304
  reader, self._reader = self._reader, None
285
305
  stderr_task, self._stderr_task = self._stderr_task, None
286
306
  if process is None:
287
- return
307
+ return {}
308
+ response_metadata: dict[str, Any] = {}
288
309
  try:
289
310
  if graceful and reader is not None:
290
311
  with contextlib.suppress(BaseException):
291
312
  await process.write(_packet({"operation": "shutdown"}))
292
- await asyncio.wait_for(reader.read(), timeout=10)
313
+ response = await asyncio.wait_for(reader.read(), timeout=10)
314
+ result = response.get("result")
315
+ if response.get("ok") and isinstance(result, dict):
316
+ metadata = result.get("response_metadata")
317
+ if isinstance(metadata, dict):
318
+ response_metadata = metadata
293
319
  for timeout, stop in (
294
320
  (10 if graceful else 0.1, None),
295
321
  (5, process.terminate),
@@ -309,6 +335,7 @@ class ACPHarnessSession(HarnessSession):
309
335
  stderr_task.cancel()
310
336
  with contextlib.suppress(BaseException):
311
337
  await stderr_task
338
+ return response_metadata
312
339
 
313
340
  async def close(self) -> None:
314
341
  if self._closed:
@@ -320,6 +347,10 @@ class ACPHarnessSession(HarnessSession):
320
347
 
321
348
  async def close_process() -> None:
322
349
  async with self._lock:
323
- await self._stop(graceful=True)
350
+ response_metadata = await self._stop(graceful=True)
351
+ if response_metadata:
352
+ harness = cast(ACPHarness, self.harness)
353
+ harness._consume_protocol_metadata(self.trace, response_metadata)
354
+ harness.acp_close_result(self.trace, response_metadata)
324
355
 
325
356
  await run_shielded(close_process())
@@ -225,7 +225,8 @@ class ACPSession:
225
225
  self.is_new = False
226
226
  return result
227
227
 
228
- async def close(self) -> None:
228
+ async def close(self) -> dict[str, Any]:
229
+ response_metadata: dict[str, Any] = {}
229
230
  try:
230
231
  if self.connection is not None and self.session_id is not None:
231
232
  session_capabilities = (
@@ -233,12 +234,16 @@ class ACPSession:
233
234
  )
234
235
  if session_capabilities and session_capabilities.close is not None:
235
236
  with suppress(Exception):
236
- await self.connection.close_session(session_id=self.session_id)
237
+ response = await self.connection.close_session(
238
+ session_id=self.session_id
239
+ )
240
+ response_metadata = dict(response.field_meta or {})
237
241
  finally:
238
242
  try:
239
243
  await self.stack.aclose()
240
244
  finally:
241
245
  self._reset()
246
+ return response_metadata
242
247
 
243
248
 
244
249
  async def read_packet(stream: asyncio.StreamReader) -> dict | None:
@@ -285,8 +290,10 @@ async def serve_stream() -> None:
285
290
  }
286
291
  elif operation == "shutdown":
287
292
  stop = True
288
- await session.close()
289
- response = {"ok": True}
293
+ response = {
294
+ "ok": True,
295
+ "result": {"response_metadata": await session.close()},
296
+ }
290
297
  else:
291
298
  raise ValueError(f"unknown ACP session operation: {operation!r}")
292
299
  except Exception as error: # noqa: BLE001 - serialize protocol failures
@@ -13,41 +13,45 @@ from verifiers.v1.configs.client import BaseClientConfig, resolve_api_key
13
13
  from verifiers.v1.dialects import Dialect
14
14
  from verifiers.v1.errors import model_error
15
15
  from verifiers.v1.graph import PendingTurn
16
+ from verifiers.v1.semantic import ACP_EXTENSION_HEADERS
16
17
  from verifiers.v1.types import Response, SamplingConfig
17
18
 
18
19
  # These fields describe the localhost request, its original bytes, or its connection. HTTPX
19
20
  # rebuilds the provider request from JSON; endpoint configuration and provider auth apply last.
20
- _BLOCKED_REQUEST_HEADERS = frozenset(
21
- {
22
- # The harness uses this rollout secret to authenticate with the localhost server.
23
- # The dialect adds the actual provider authorization after filtering.
24
- "authorization",
25
- # HTTPX recalculates these for the provider URL, JSON bytes, and supported decoders.
26
- "accept-encoding",
27
- "content-encoding",
28
- "content-length",
29
- "content-type",
30
- "host",
31
- "transfer-encoding",
32
- # These control only the localhost HTTP exchange.
33
- "expect",
34
- "keep-alive",
35
- "proxy-authorization",
36
- "proxy-connection",
37
- "te",
38
- "trailer",
39
- "upgrade",
40
- # Provider affinity must not compete with the rollout-wide session header below.
41
- "session_id",
42
- # The eval owns the model and sampling settings, so it changes those JSON fields before
43
- # sending upstream. Hashes and signatures calculated from the intercepted body are stale.
44
- "content-digest",
45
- "content-md5",
46
- "digest",
47
- "repr-digest",
48
- "signature",
49
- "signature-input",
50
- }
21
+ _BLOCKED_REQUEST_HEADERS = (
22
+ frozenset(
23
+ {
24
+ # The harness uses this rollout secret to authenticate with the localhost server.
25
+ # The dialect adds the actual provider authorization after filtering.
26
+ "authorization",
27
+ # HTTPX recalculates these for the provider URL, JSON bytes, and supported decoders.
28
+ "accept-encoding",
29
+ "content-encoding",
30
+ "content-length",
31
+ "content-type",
32
+ "host",
33
+ "transfer-encoding",
34
+ # These control only the localhost HTTP exchange.
35
+ "expect",
36
+ "keep-alive",
37
+ "proxy-authorization",
38
+ "proxy-connection",
39
+ "te",
40
+ "trailer",
41
+ "upgrade",
42
+ # Provider affinity must not compete with the rollout-wide session header below.
43
+ "session_id",
44
+ # The eval owns the model and sampling settings, so it changes those JSON fields before
45
+ # sending upstream. Hashes and signatures calculated from the intercepted body are stale.
46
+ "content-digest",
47
+ "content-md5",
48
+ "digest",
49
+ "repr-digest",
50
+ "signature",
51
+ "signature-input",
52
+ }
53
+ )
54
+ | ACP_EXTENSION_HEADERS
51
55
  )
52
56
 
53
57
 
verifiers/v1/graph.py CHANGED
@@ -1,11 +1,14 @@
1
1
  """Message-graph trajectory: store each message once, recover branches by walking.
2
2
 
3
3
  A rollout is a graph of `MessageNode`s — one per distinct message, each linked to its
4
- predecessor. The conversation is a path from a root to a leaf; branches (compaction,
5
- subagents) are simply multiple leaves, so branching falls out of the walk. Each node stores
6
- only the tokens it *adds* to the cumulative sequence, keeping size linear in turns and
7
- making a branch's training sample a cheap concat of node `token_ids`/`mask`/`logprobs` along
8
- its path.
4
+ predecessor. A conversation is a path from a root to a leaf; prompt divergence from
5
+ compaction, subagents, or other history rewrites produces multiple leaves, so branching
6
+ falls out of the walk. A branch often corresponds to one harness context window, but it is
7
+ a physical, exact-prefix training view rather than a semantic context identity: a prefix
8
+ break can split one context and prefix reuse can preserve an ancestral path. Each node
9
+ stores only the tokens it *adds* to the cumulative sequence, keeping size linear in turns
10
+ and making a branch's training sample a cheap concat of node
11
+ `token_ids`/`mask`/`logprobs` along its path.
9
12
 
10
13
  Token attribution (renderer client): the renderer reports, per prompt, each message's token
11
14
  span (`RenderedTokens.message_token_spans()`, carried on `TurnTokens.message_spans`). A new
@@ -29,6 +32,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_valid
29
32
  from pydantic.json_schema import SkipJsonSchema
30
33
  from renderers.base import MultiModalData, PlaceholderRange, RenderedTokens
31
34
 
35
+ from verifiers.v1.semantic import ParentLink
32
36
  from verifiers.v1.types import (
33
37
  AssistantMessage,
34
38
  KeptTokens,
@@ -68,6 +72,14 @@ class MessageNode(BaseModel):
68
72
 
69
73
  parent: int | None = None
70
74
  """Index into `Trace.nodes` of the predecessor message; None for a root."""
75
+ semantic_parents: list[ParentLink] = Field(default_factory=list)
76
+ """Additional harness-declared parents in the semantic execution graph.
77
+
78
+ Unlike ``parent``, these links do not imply an exact token prefix and therefore do
79
+ not affect physical branch construction. A list permits multiple parents of the same
80
+ type, supports incremental appends, and preserves their advertised wire order; edge
81
+ application prevents duplicate ``(node, type)`` links.
82
+ """
71
83
  message: Message
72
84
  """The message this node carries (system / user / assistant / tool)."""
73
85
  sampled: bool = False
@@ -1,5 +1,8 @@
1
1
  import os
2
2
 
3
+ from pydantic import PositiveInt
4
+ from pydantic_config import BaseConfig
5
+
3
6
  from verifiers.v1.clients import ModelContext
4
7
  from verifiers.v1.configs.harness import HarnessConfig
5
8
  from verifiers.v1.harness import Harness
@@ -24,6 +27,14 @@ SEARCH_PROMPT = (
24
27
  )
25
28
 
26
29
 
30
+ class CompactionConfig(BaseConfig):
31
+ """Context compaction policy for the bash agent loop."""
32
+
33
+ summarize_at_tokens: PositiveInt | None = None
34
+ """Compact at this token count. When unset, compact when 16k tokens remain below the
35
+ model context window when the provider advertises it."""
36
+
37
+
27
38
  class BashHarnessConfig(HarnessConfig):
28
39
  edit: bool = True
29
40
  """Offer the local `edit` tool (single-occurrence string replacement in a file) alongside
@@ -34,6 +45,9 @@ class BashHarnessConfig(HarnessConfig):
34
45
  eval environment; the key is handed to the program over argv (like the interception secret) so
35
46
  the agent's `bash` subprocesses don't inherit it."""
36
47
 
48
+ compaction: CompactionConfig | None = None
49
+ """Context compaction policy. Set an empty config to use automatic thresholds."""
50
+
37
51
 
38
52
  class BashHarness(Harness[BashHarnessConfig]):
39
53
  APPENDS_SYSTEM_PROMPT = True
@@ -69,6 +83,11 @@ class BashHarness(Harness[BashHarnessConfig]):
69
83
  args = ["--bash"]
70
84
  if tool_interception_url:
71
85
  args.append(f"--tool-interception-url={tool_interception_url}")
86
+ if self.config.compaction is not None:
87
+ args.append("--compaction")
88
+ threshold = self.config.compaction.summarize_at_tokens
89
+ if threshold is not None:
90
+ args.append(f"--summarize-at-tokens={threshold}")
72
91
  if self.config.edit:
73
92
  args.append("--edit")
74
93
  if self.config.search:
@@ -12,7 +12,7 @@ from pathlib import Path
12
12
  from typing import TYPE_CHECKING
13
13
 
14
14
  import httpx
15
- from openai import APIStatusError, AsyncOpenAI
15
+ from openai import APIError, APIStatusError, AsyncOpenAI
16
16
 
17
17
  if TYPE_CHECKING:
18
18
  # The harness bundles this module into the generated script before execution.
@@ -40,6 +40,92 @@ def is_context_overflow(error: APIStatusError) -> bool:
40
40
  )
41
41
 
42
42
 
43
+ RESERVE_TOKENS = 16_384
44
+ """Compact when this many tokens remain below the model context window."""
45
+
46
+ COMPACTION_ATTEMPTS = 3
47
+ """Checkpoint attempts before compaction fails: a rejected request falls back to the
48
+ last good snapshot; an empty or tool-calling reply is resampled."""
49
+
50
+ TOOL_OUTPUT_MAX_BYTES = 20_000
51
+ """Middle-out truncation budget for one tool result before it enters the conversation."""
52
+
53
+ CHECKPOINT_COMPACTION_PROMPT = """You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.
54
+
55
+ Include:
56
+ - Current progress and key decisions made
57
+ - Important context, constraints, or user preferences
58
+ - What remains to be done (clear next steps)
59
+ - Any critical data, examples, or references needed to continue
60
+
61
+ Be concise, structured, and focused on helping the next LLM seamlessly continue the work.
62
+
63
+ Reply with the summary as plain text. Do not call any tools - summarize from the conversation as it stands."""
64
+
65
+ POST_COMPACTION_FRAMING = """Another language model started to solve this problem and produced \
66
+ a summary of its thinking process. You also have access to the state of the tools that \
67
+ were used by that language model. Use this to build on the work \
68
+ that has already been done and avoid duplicating work. Here is \
69
+ the summary produced by the other language model, use the \
70
+ information in this summary to assist with your own analysis:"""
71
+
72
+ CONTEXT_OVERFLOW_MARKERS = (
73
+ # OpenAI error code "context_length_exceeded"; OpenRouter relays the raw body.
74
+ "context_length_exceeded",
75
+ # OpenAI Responses/Completions: "Your input exceeds the context window of this model".
76
+ "exceeds the context window",
77
+ # OpenAI chat: "Input tokens exceed the configured limit of N tokens. Please reduce
78
+ # the length of the messages."; Groq words it the same way.
79
+ "reduce the length of the messages",
80
+ # vLLM: "This model's maximum context length is N tokens"; the renderers pre-flight:
81
+ # "Prompt length (N) exceeds maximum context length (M)"; Mistral uses the same words.
82
+ "maximum context length",
83
+ # Anthropic: "prompt is too long: N tokens > M maximum".
84
+ "prompt is too long",
85
+ # Anthropic byte-size overflow: HTTP 413 {"type": "request_too_large"}.
86
+ "request_too_large",
87
+ # HTTP proxies reject an oversized body with 413 "Request Entity Too Large".
88
+ "request entity too large",
89
+ # Google: "The input token count (N) exceeds the maximum number of tokens allowed (M)".
90
+ "exceeds the maximum number of tokens",
91
+ # xAI: "This model's maximum prompt length is N but the request contains M tokens".
92
+ "maximum prompt length is",
93
+ )
94
+
95
+ CONTEXT_WINDOW_FIELDS = (
96
+ "max_model_len",
97
+ "context_length",
98
+ "context_window",
99
+ "max_context_length",
100
+ )
101
+
102
+
103
+ def default_threshold(context_window: int) -> int:
104
+ """Leave a fixed reserve below the window; small windows keep at least half."""
105
+ return max(context_window - RESERVE_TOKENS, context_window // 2)
106
+
107
+
108
+ async def discover_threshold(client: AsyncOpenAI, model: str) -> int | None:
109
+ """The compaction threshold, when the provider's model card advertises a context window.
110
+
111
+ `models.list()` keeps provider extensions in each card's `model_extra`; a raw
112
+ `cast_to` parse breaks on one Python version or another."""
113
+ try:
114
+ page = await client.models.list()
115
+ except APIError:
116
+ return None
117
+ for card in page.data:
118
+ if card.id != model:
119
+ continue
120
+ extra = card.model_extra or {}
121
+ for field in CONTEXT_WINDOW_FIELDS:
122
+ value = extra.get(field)
123
+ if isinstance(value, int) and not isinstance(value, bool) and value > 0:
124
+ return default_threshold(value)
125
+ break
126
+ return None
127
+
128
+
43
129
  BASH_TOOL = {
44
130
  "type": "function",
45
131
  "function": {
@@ -197,12 +283,171 @@ def run_edit(path: str, old_str: str, new_str: str) -> str:
197
283
 
198
284
 
199
285
  async def chat(
200
- client: AsyncOpenAI, model: str, messages: list[dict], tools: list[dict]
286
+ client: AsyncOpenAI,
287
+ model: str,
288
+ messages: list[dict],
289
+ tools: list[dict],
290
+ *,
291
+ tool_choice: str | None = None,
201
292
  ):
202
- completion = await client.chat.completions.create(
203
- model=model, messages=messages, tools=tools or None
293
+ kwargs = {"model": model, "messages": messages, "tools": tools or None}
294
+ if tools and tool_choice is not None:
295
+ kwargs["tool_choice"] = tool_choice
296
+ return await client.chat.completions.create(**kwargs)
297
+
298
+
299
+ class CompactionFailed(Exception):
300
+ """Every checkpoint attempt failed - the caller ends the run cleanly instead."""
301
+
302
+
303
+ def compactable(messages: list[dict]) -> bool:
304
+ """Whether compaction can reclaim anything - some history beyond the task exists."""
305
+ first_user = next(
306
+ (i for i, m in enumerate(messages) if m.get("role") == "user"), None
204
307
  )
205
- return completion.choices[0].message
308
+ return any(
309
+ m.get("role") != "system" and i != first_user for i, m in enumerate(messages)
310
+ )
311
+
312
+
313
+ def bound_tool_message(message: dict) -> dict:
314
+ """Bound a tool message before it enters the conversation - rewrites included."""
315
+ content = message.get("content")
316
+ if isinstance(content, str):
317
+ return {**message, "content": truncate_tool_output(content)}
318
+ # Multimodal results come back as content-part lists; only plain text is truncated.
319
+ return message
320
+
321
+
322
+ def truncate_tool_output(text: str) -> str:
323
+ """Keep the head and tail of an oversized tool result and say what was cut."""
324
+ data = text.encode("utf-8")
325
+ if len(data) <= TOOL_OUTPUT_MAX_BYTES:
326
+ return text
327
+ keep = TOOL_OUTPUT_MAX_BYTES // 2
328
+ head = data[:keep].decode("utf-8", errors="ignore")
329
+ tail = data[-keep:].decode("utf-8", errors="ignore")
330
+ return (
331
+ f"Warning: truncated output (original token count: {estimated_tokens(text)})\n"
332
+ f"Total output lines: {text.count(chr(10)) + 1}\n\n"
333
+ f"{head}\n[... {len(data) - 2 * keep} bytes truncated ...]\n{tail}"
334
+ )
335
+
336
+
337
+ def estimated_tokens(chars: str) -> int:
338
+ """Rough token count at four characters per token."""
339
+ return (len(chars) + 3) // 4
340
+
341
+
342
+ def context_tokens(completion) -> int:
343
+ usage = completion.usage
344
+ if usage is None:
345
+ return 0
346
+ return (usage.prompt_tokens or 0) + (usage.completion_tokens or 0)
347
+
348
+
349
+ class Compactor:
350
+ """Compact once and retry once when a model turn exhausts its context."""
351
+
352
+ def __init__(self, client, model, tools, enabled, threshold):
353
+ self.client = client
354
+ self.model = model
355
+ self.tools = tools
356
+ self.enabled = enabled
357
+ self.threshold = threshold
358
+ self.compacted = False
359
+ self.last_good = 0
360
+ """Message count of the newest state that passed a threshold check - by
361
+ definition a state with a full reserve of room, so a checkpoint over it fits."""
362
+
363
+ def reached(self, completion, extra_tokens: int = 0) -> bool:
364
+ return (
365
+ self.enabled
366
+ and self.threshold is not None
367
+ and context_tokens(completion) + extra_tokens >= self.threshold
368
+ )
369
+
370
+ def note_good(self, messages: list[dict]) -> None:
371
+ self.last_good = len(messages)
372
+
373
+ async def complete(self, messages: list[dict]):
374
+ try:
375
+ completion = await chat(self.client, self.model, messages, self.tools)
376
+ except APIStatusError as error:
377
+ if (
378
+ not self.enabled
379
+ or self.threshold is None
380
+ or not is_context_overflow(error)
381
+ ):
382
+ raise
383
+ if not compactable(messages):
384
+ if self.compacted:
385
+ # The conversation is already a compaction floor and still
386
+ # overflows - out of moves, end cleanly.
387
+ raise CompactionFailed(
388
+ "the compacted conversation still overflows"
389
+ ) from error
390
+ raise
391
+ else:
392
+ choice = completion.choices[0]
393
+ if not self.reached(completion):
394
+ # Usage-verified: this exact prompt was accepted with a full
395
+ # reserve of room, so it is a safe checkpoint fallback.
396
+ self.note_good(messages)
397
+ return completion, messages
398
+ if choice.finish_reason != "length" or not compactable(messages):
399
+ return completion, messages
400
+
401
+ messages = await self.compact(messages)
402
+ try:
403
+ completion = await chat(self.client, self.model, messages, self.tools)
404
+ except APIStatusError as error:
405
+ # The rebuilt conversation is sized to fit, so this is out of moves.
406
+ if is_context_overflow(error):
407
+ raise CompactionFailed(
408
+ "the rebuilt conversation still overflows"
409
+ ) from error
410
+ raise
411
+ return completion, messages
412
+
413
+ async def compact(self, messages: list[dict]) -> list[dict]:
414
+ # A rejected checkpoint falls back to the last good snapshot (which has a
415
+ # full reserve of room, so it fits); an empty or tool-calling reply is
416
+ # resampled. Reasoning is never part of the summary.
417
+ system = [message for message in messages if message.get("role") == "system"]
418
+ base = messages
419
+ for _ in range(COMPACTION_ATTEMPTS):
420
+ checkpoint = [
421
+ *base,
422
+ {"role": "user", "content": CHECKPOINT_COMPACTION_PROMPT},
423
+ ]
424
+ try:
425
+ completion = await chat(
426
+ self.client,
427
+ self.model,
428
+ checkpoint,
429
+ self.tools,
430
+ tool_choice="none",
431
+ )
432
+ except APIStatusError as error:
433
+ if not is_context_overflow(error):
434
+ raise
435
+ base = messages[: self.last_good]
436
+ continue
437
+ message = completion.choices[0].message
438
+ # Reasoning never enters the summary: only the reply's final text
439
+ # counts, so a reply that lives entirely in the reasoning channel
440
+ # is resampled like an empty one.
441
+ text = (message.content or "").strip()
442
+ if not message.tool_calls and text:
443
+ framed = POST_COMPACTION_FRAMING + "\n\n" + text
444
+ rebuilt = [*system, {"role": "user", "content": framed}]
445
+ self.note_good(rebuilt)
446
+ self.compacted = True
447
+ return rebuilt
448
+ raise CompactionFailed(
449
+ f"no usable summary after {COMPACTION_ATTEMPTS} attempts"
450
+ )
206
451
 
207
452
 
208
453
  async def run_tool_hook(
@@ -235,6 +480,8 @@ def parse_args() -> argparse.Namespace:
235
480
  parser.add_argument("--mcp-config", default="")
236
481
  parser.add_argument("--tool-interception-url", default="")
237
482
  parser.add_argument("--bash", action="store_true")
483
+ parser.add_argument("--compaction", action="store_true")
484
+ parser.add_argument("--summarize-at-tokens", type=int)
238
485
  parser.add_argument("--edit", action="store_true")
239
486
  parser.add_argument("--search", action="store_true")
240
487
  parser.add_argument("--serper-key", default="")
@@ -284,17 +531,35 @@ async def main() -> None:
284
531
  messages.extend(initial)
285
532
  elif args.prompt:
286
533
  messages.append({"role": "user", "content": args.prompt})
534
+ compactor = Compactor(
535
+ client,
536
+ args.model,
537
+ tools,
538
+ args.compaction,
539
+ args.summarize_at_tokens,
540
+ )
541
+ if compactor.enabled and compactor.threshold is None:
542
+ compactor.threshold = await discover_threshold(client, args.model)
543
+ # The initial conversation is the floor for checkpoint fallbacks: a first-turn
544
+ # checkpoint must never retry from an empty base.
545
+ compactor.note_good(messages)
287
546
  while True:
288
547
  try:
289
- message = await chat(client, args.model, messages, tools)
548
+ completion, messages = await compactor.complete(messages)
549
+ except CompactionFailed:
550
+ # The context is exhausted and could not be summarized: end the run
551
+ # cleanly with what the conversation holds - still a trainable sample.
552
+ break
290
553
  except APIStatusError as error:
291
554
  # Null cannot compact, so context exhaustion ends it with the transcript so far.
292
555
  if args.bash or not is_context_overflow(error):
293
556
  raise
294
557
  return
558
+ message = completion.choices[0].message
295
559
  messages.append(message.model_dump(exclude_none=True))
296
560
  if not message.tool_calls:
297
561
  break
562
+ tool_result_tokens = 0
298
563
  for call in message.tool_calls:
299
564
  name = call.function.name
300
565
  tool_message = {
@@ -313,7 +578,11 @@ async def main() -> None:
313
578
  tool_message,
314
579
  )
315
580
  if decision["action"] == "rewrite":
316
- messages.append(decision["message"])
581
+ rewritten = bound_tool_message(decision["message"])
582
+ messages.append(rewritten)
583
+ tool_result_tokens += estimated_tokens(
584
+ str(rewritten.get("content", ""))
585
+ )
317
586
  continue
318
587
  try:
319
588
  tool_args = json.loads(call.function.arguments or "{}")
@@ -346,6 +615,7 @@ async def main() -> None:
346
615
  else:
347
616
  content = f"error: unknown tool {name!r}"
348
617
  tool_message["content"] = content
618
+ tool_message = bound_tool_message(tool_message)
349
619
  if args.tool_interception_url:
350
620
  assert tool_client is not None
351
621
  decision = await run_tool_hook(
@@ -356,8 +626,14 @@ async def main() -> None:
356
626
  tool_message,
357
627
  )
358
628
  if decision["action"] == "rewrite":
359
- tool_message = decision["message"]
629
+ tool_message = bound_tool_message(decision["message"])
360
630
  messages.append(tool_message)
631
+ tool_result_tokens += estimated_tokens(str(tool_message["content"]))
632
+ if compactor.reached(completion, tool_result_tokens) and compactable(messages):
633
+ try:
634
+ messages = await compactor.compact(messages)
635
+ except CompactionFailed:
636
+ break
361
637
  if tool_client is not None:
362
638
  await tool_client.aclose()
363
639
 
@@ -1,9 +1,10 @@
1
1
  """RLM over ACP, with MCP tools exposed as pre-imported IPython skills."""
2
2
 
3
+ import hashlib
3
4
  import logging
4
5
  import random
5
6
  import shlex
6
- from typing import Literal
7
+ from typing import Any, Literal
7
8
 
8
9
  from pydantic import BaseModel, ConfigDict, Field, PositiveInt, model_validator
9
10
 
@@ -19,8 +20,7 @@ logger = logging.getLogger(__name__)
19
20
  BuiltinSkill = Literal["edit", "search"]
20
21
 
21
22
  RLM_REPO = "github.com/PrimeIntellect-ai/nano-rlm.git"
22
- RLM_DIR = "/tmp/vf-rlm"
23
- RLM_BIN = f"{RLM_DIR}/bin/rlm"
23
+ RLM_CACHE_DIR = "/tmp/vf-rlm"
24
24
  SKILLS_DIR = "/task/rlm-skills"
25
25
  RLM_STATE_DIR = ".vf-rlm"
26
26
  RLM_RUNTIME_METADATA_KEY = "ai.prime.rlm/runtime-v1"
@@ -36,7 +36,7 @@ class _SessionSnapshot(BaseModel):
36
36
 
37
37
  class RLMHarnessConfig(HarnessConfig):
38
38
  version: str = Field(
39
- default="d4ce3e10e63b359f4f3d432d58a77471e9e21fe7", min_length=1
39
+ default="4a6369611c06d3943ac40681f374a464feb706b9", min_length=1
40
40
  )
41
41
  """Git ref (branch, tag, or commit) of nano-rlm to install."""
42
42
  max_depth: int = 0
@@ -77,18 +77,26 @@ class RLMHarness(ACPHarness[RLMHarnessConfig]):
77
77
  async def setup(self, runtime: Runtime) -> None:
78
78
  # Before the installer: install.sh packages the skills it finds.
79
79
  await self.install_skills(runtime, SKILLS_DIR)
80
+ directory = self._install_dir()
81
+ binary = f"{directory}/bin/rlm"
82
+ checkout = f"{directory}/checkout"
83
+ ready = f"{directory}/.ready"
80
84
  # install.sh fetches curl/uv itself; add git only when the image lacks it.
81
85
  install = (
82
- "command -v git >/dev/null 2>&1 || "
86
+ f"rm -f {ready} && "
87
+ "(command -v git >/dev/null 2>&1 || "
83
88
  "{ apt-get update -qq && apt-get install -y -qq git; } && "
84
- f"rm -rf /tmp/rlm && git clone https://{RLM_REPO} /tmp/rlm && "
85
- f"git -C /tmp/rlm checkout {shlex.quote(self.config.version)} && "
86
- f"UV_INSTALL_DIR={RLM_DIR}/bin UV_TOOL_BIN_DIR={RLM_DIR}/bin "
87
- f"RLM_CHECKOUT_PATH=/tmp/rlm bash /tmp/rlm/install.sh"
89
+ f"rm -rf {checkout} && git clone https://{RLM_REPO} {checkout} && "
90
+ f"git -C {checkout} checkout {shlex.quote(self.config.version)} && "
91
+ f"UV_INSTALL_DIR={directory}/bin UV_TOOL_BIN_DIR={directory}/bin "
92
+ f"RLM_CHECKOUT_PATH={checkout} bash {checkout}/install.sh && "
93
+ f"touch {ready})"
88
94
  )
89
95
  logger.info("rlm: ensuring rlm is installed (version=%s)", self.config.version)
90
- ensure = shlex.quote(f"[ -x {RLM_BIN} ] || ({install})")
91
- guarded = f"mkdir -p {RLM_DIR} && flock {RLM_DIR}/install.lock sh -c {ensure}"
96
+ ensure = shlex.quote(f"[ -f {ready} ] && [ -x {binary} ] || ({install})")
97
+ guarded = (
98
+ f"mkdir -p {directory} && flock {directory}/install.lock sh -c {ensure}"
99
+ )
92
100
  env = self.config.resolved_env.copy()
93
101
  extra_uv_args = env.get("RLM_EXTRA_UV_ARGS", "")
94
102
  env["RLM_EXTRA_UV_ARGS"] = f"{extra_uv_args} --with mcp~=1.28".strip()
@@ -150,24 +158,35 @@ class RLMHarness(ACPHarness[RLMHarnessConfig]):
150
158
  system_prompt, prompt = self.resolve_prompt(data)
151
159
  return ACPConfig(
152
160
  env={**self.config.resolved_env, "RLM_HOME": self._home(trace)},
153
- command=[RLM_BIN, "--acp"],
161
+ command=[f"{self._install_dir()}/bin/rlm", "--acp"],
154
162
  prompt=prompt,
155
163
  session_meta=self._runtime_metadata(
156
164
  ctx, trace, runtime, endpoint, secret, data, system_prompt
157
165
  ),
158
166
  )
159
167
 
160
- def acp_turn_result(self, trace: Trace, result: ACPTurn) -> None:
168
+ def _consume_snapshot(self, trace: Trace, metadata: dict[str, Any]) -> None:
161
169
  snapshot = _SessionSnapshot.model_validate(
162
- result.response_metadata.get(RLM_SESSION_METADATA_KEY)
170
+ metadata.get(RLM_SESSION_METADATA_KEY)
163
171
  )
164
172
  if snapshot.session_id != trace.id:
165
173
  raise ValueError("RLM session snapshot does not match the rollout")
166
174
  trace.record_metrics(snapshot.metrics)
167
175
 
176
+ def acp_turn_result(self, trace: Trace, result: ACPTurn) -> None:
177
+ self._consume_snapshot(trace, result.response_metadata)
178
+
179
+ def acp_close_result(self, trace: Trace, response_metadata: dict[str, Any]) -> None:
180
+ if RLM_SESSION_METADATA_KEY in response_metadata:
181
+ self._consume_snapshot(trace, response_metadata)
182
+
168
183
  async def cleanup(self, trace: Trace, runtime: Runtime) -> None:
169
184
  await runtime.run(["rm", "-rf", f"{RLM_STATE_DIR}/{trace.id}"], {})
170
185
 
171
186
  @staticmethod
172
187
  def _home(trace: Trace) -> str:
173
188
  return f"{RLM_STATE_DIR}/{trace.id}/home"
189
+
190
+ def _install_dir(self) -> str:
191
+ cache_key = hashlib.sha256(self.config.version.encode()).hexdigest()
192
+ return f"{RLM_CACHE_DIR}-{cache_key}"
@@ -33,13 +33,15 @@ from dataclasses import dataclass
33
33
  from tempfile import SpooledTemporaryFile
34
34
  from typing import Literal
35
35
 
36
+ import httpx
36
37
  from aiohttp import web
37
38
  from pydantic import ValidationError
38
39
  from pydantic_core import PydanticSerializationError, from_json, to_json
39
40
 
40
41
  from verifiers.v1 import graph
41
42
  from verifiers.v1.clients import Client, resolve_client
42
- from verifiers.v1.configs.client import BaseClientConfig
43
+ from verifiers.v1.clients.base import join_url
44
+ from verifiers.v1.configs.client import BaseClientConfig, resolve_api_key
43
45
  from verifiers.v1.dialects import DIALECTS, Dialect
44
46
  from verifiers.v1.dialects.base import (
45
47
  PROVIDER_CAPABILITY_POLICY_CODE,
@@ -58,6 +60,7 @@ from verifiers.v1.interception.tunnel import (
58
60
  TunnelConfig,
59
61
  make_tunnel,
60
62
  )
63
+ from verifiers.v1.semantic import ACPInfo, extract_acp_info
61
64
  from verifiers.v1.session import IdempotentRequest, ReplayResponse, RolloutSession
62
65
  from verifiers.v1.trace import Error, ModelCall, PolicyEvent, TimeSpan
63
66
  from verifiers.v1.types import FinishReason, Request, Response, Usage
@@ -326,6 +329,7 @@ class InterceptionServer(Interception):
326
329
  app.router.add_post(route, self._handler_for(dialect))
327
330
  for aux in dialect.aux_routes:
328
331
  app.router.add_post(aux, self._aux_handler_for(dialect, aux))
332
+ app.router.add_get("/v1/models", self.handle_models)
329
333
  # Tool servers use a state-only capability; the model bearer cannot reach these.
330
334
  app.router.add_get("/state", self.handle_state_get)
331
335
  app.router.add_put("/state", self.handle_state_put)
@@ -421,6 +425,7 @@ class InterceptionServer(Interception):
421
425
  usage: "Usage | None" = None,
422
426
  error: BaseException | None = None,
423
427
  policy_paths: list[str] | None = None,
428
+ acp: ACPInfo | None = None,
424
429
  ) -> None:
425
430
  """Append one provider exchange to the trace's per-call records (`Trace.calls`):
426
431
  the model + effective settings that went upstream, timing, and — when the call
@@ -468,6 +473,7 @@ class InterceptionServer(Interception):
468
473
  )
469
474
  if policy_paths
470
475
  else None,
476
+ acp=acp,
471
477
  )
472
478
  )
473
479
 
@@ -491,7 +497,10 @@ class InterceptionServer(Interception):
491
497
  del raw
492
498
  body = dialect.apply_overrides(body, session.ctx.model, session.ctx.sampling)
493
499
  streaming = dialect.streaming(body)
494
- upstream_headers = dict(request.headers)
500
+ try:
501
+ acp, upstream_headers = extract_acp_info(request.headers)
502
+ except ValueError as error:
503
+ return web.json_response(dialect.error_body(str(error)), status=400)
495
504
  logger.debug(
496
505
  "intercept %s: id=%s stream=%s",
497
506
  request.path,
@@ -508,14 +517,18 @@ class InterceptionServer(Interception):
508
517
  replay_key: str | None = None
509
518
  binding = (request.path, req_hash)
510
519
  if idempotency_key:
511
- if streaming:
520
+ if streaming and acp is None:
512
521
  return web.json_response(
513
522
  dialect.error_body(
514
523
  "Idempotency-Key is not supported for streaming requests"
515
524
  ),
516
525
  status=400,
517
526
  )
518
- replay_key = f"explicit:{idempotency_key}"
527
+ if not streaming:
528
+ replay_key = f"explicit:{idempotency_key}"
529
+ # This key identifies the harness-to-interception hop. The server owns its
530
+ # replay semantics, and the body has since been rewritten with rollout model
531
+ # and sampling overrides, so never expose the local key to the provider.
519
532
  upstream_headers = {
520
533
  name: value
521
534
  for name, value in upstream_headers.items()
@@ -643,6 +656,8 @@ class InterceptionServer(Interception):
643
656
  turn=turn,
644
657
  inspect_response=inspect_response,
645
658
  policy_paths=policy_paths,
659
+ acp=acp,
660
+ upstream_headers=upstream_headers,
646
661
  )
647
662
 
648
663
  def serve(response: Response) -> web.Response:
@@ -757,6 +772,7 @@ class InterceptionServer(Interception):
757
772
  usage=call_response.usage if call_response else None,
758
773
  error=error,
759
774
  policy_paths=policy_paths,
775
+ acp=acp,
760
776
  )
761
777
  return serve(call_response)
762
778
 
@@ -773,6 +789,8 @@ class InterceptionServer(Interception):
773
789
  turn: graph.PendingTurn,
774
790
  inspect_response: bool,
775
791
  policy_paths: list[str] | None = None,
792
+ acp: ACPInfo | None = None,
793
+ upstream_headers: Mapping[str, str] | None = None,
776
794
  ) -> web.StreamResponse:
777
795
  """A streamed (SSE) model turn: relay the provider's stream through to the program,
778
796
  incrementally assembling the response to record on the trace (the only client that
@@ -788,7 +806,7 @@ class InterceptionServer(Interception):
788
806
  reply = await session.client.relay(
789
807
  dialect,
790
808
  body,
791
- headers=request.headers,
809
+ headers=upstream_headers,
792
810
  session_id=session.trace.id,
793
811
  )
794
812
  except RolloutError as e:
@@ -1017,6 +1035,7 @@ class InterceptionServer(Interception):
1017
1035
  usage=response.usage if response is not None else None,
1018
1036
  error=error,
1019
1037
  policy_paths=policy_paths,
1038
+ acp=acp,
1020
1039
  )
1021
1040
 
1022
1041
  async def handle_aux(
@@ -1053,6 +1072,41 @@ class InterceptionServer(Interception):
1053
1072
  return web.json_response(dialect.error_body(str(e)), status=502)
1054
1073
  return web.json_response(result)
1055
1074
 
1075
+ async def handle_models(self, request: web.Request) -> web.Response:
1076
+ """`GET /v1/models`: relay the upstream model listing so agent loops can read a
1077
+ provider context-window extension (e.g. vLLM's `max_model_len`). The path is shared
1078
+ by every dialect; only the auth carrier differs, so the bearer is tried per dialect.
1079
+ A pure relay from the session's endpoint config — never recorded on the trace, and a
1080
+ failure never fails the rollout."""
1081
+ for dialect in DIALECTS:
1082
+ session = self.sessions.get(dialect.secret(request.headers))
1083
+ if session is not None:
1084
+ break
1085
+ else:
1086
+ return web.json_response({"error": "unauthorized"}, status=401)
1087
+ session.adopt(asyncio.current_task())
1088
+ logger.debug("intercept models: id=%s", session.trace.id)
1089
+ config = session.ctx.client
1090
+ headers = dict(config.headers or {})
1091
+ headers.update(dialect.auth_headers(resolve_api_key(config)))
1092
+ try:
1093
+ # Finite read timeout: a hung provider must not stall threshold discovery
1094
+ # for the rollout's whole outer timeout - the loop falls back to no compaction.
1095
+ async with httpx.AsyncClient(
1096
+ timeout=httpx.Timeout(30.0, connect=5.0)
1097
+ ) as client:
1098
+ upstream = await client.get(
1099
+ join_url(config.base_url, "/v1/models"), headers=headers
1100
+ )
1101
+ except httpx.HTTPError as e:
1102
+ logger.warning("models call failed: id=%s %s", session.trace.id, e)
1103
+ return web.json_response(dialect.error_body(str(e)), status=502)
1104
+ return web.Response(
1105
+ body=upstream.content,
1106
+ status=upstream.status_code,
1107
+ content_type="application/json",
1108
+ )
1109
+
1056
1110
  def _session_for(
1057
1111
  self, request: web.Request, *, allow_service: bool = False
1058
1112
  ) -> RolloutSession | None:
@@ -0,0 +1,132 @@
1
+ """ACP semantic edges carried beside the physical training-message graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Mapping
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
9
+
10
+ ACP_REQUEST_ID_PATTERN = r"^[A-Za-z0-9._:-]{1,128}$"
11
+ EDGE_TYPE_PATTERN = r"^[A-Za-z][A-Za-z0-9._:-]{0,127}$"
12
+ """Semantic label syntax, for example ``subagent_return`` or ``vendor:review``."""
13
+
14
+ ACP_SEMANTIC_EDGES_METADATA_KEY = "ai.prime.acp/semantic-edges-v1"
15
+ ACP_MODEL_REQUEST_ID_HEADER = "X-ACP-Model-Request-ID"
16
+
17
+ ACP_EXTENSION_HEADERS = frozenset({ACP_MODEL_REQUEST_ID_HEADER.lower()})
18
+ """Private ACP extension headers consumed at interception and never sent upstream."""
19
+
20
+
21
+ class ACPInfo(BaseModel):
22
+ """Metadata advertised by an ACP harness for one intercepted model request."""
23
+
24
+ model_config = ConfigDict(extra="forbid", strict=True)
25
+
26
+ request_id: str = Field(pattern=ACP_REQUEST_ID_PATTERN)
27
+
28
+
29
+ class SemanticEdge(BaseModel):
30
+ """A harness-declared relationship between two logical model requests.
31
+
32
+ Request IDs are wire-level correlation handles. They let a harness describe the
33
+ relationship before it can know Verifiers-local message-node indexes.
34
+ """
35
+
36
+ model_config = ConfigDict(extra="forbid", strict=True)
37
+
38
+ source_request_id: str = Field(pattern=ACP_REQUEST_ID_PATTERN)
39
+ target_request_id: str = Field(pattern=ACP_REQUEST_ID_PATTERN)
40
+ type: str = Field(pattern=EDGE_TYPE_PATTERN)
41
+
42
+ @model_validator(mode="after")
43
+ def reject_self_edge(self) -> SemanticEdge:
44
+ if self.source_request_id == self.target_request_id:
45
+ raise ValueError("semantic edge cannot link a request to itself")
46
+ return self
47
+
48
+
49
+ class ParentLink(BaseModel):
50
+ """One semantic parent of a ``MessageNode``.
51
+
52
+ ``node`` is an index into the containing ``Trace.nodes``. The child is the
53
+ ``MessageNode`` carrying this link.
54
+ """
55
+
56
+ model_config = ConfigDict(extra="forbid", strict=True)
57
+
58
+ node: int = Field(ge=0)
59
+ type: str = Field(pattern=EDGE_TYPE_PATTERN)
60
+
61
+
62
+ class SemanticEdgeSet(BaseModel):
63
+ """A harness-published set of semantic edges over logical request IDs.
64
+
65
+ Edge labels are intentionally extensible. Initial harnesses use ``continuation``,
66
+ ``compaction``, ``subagent_call``, and ``subagent_return``; consumers must preserve
67
+ unknown labels.
68
+ """
69
+
70
+ model_config = ConfigDict(extra="forbid", strict=True)
71
+
72
+ edges: list[SemanticEdge]
73
+
74
+ @model_validator(mode="after")
75
+ def validate_edges(self) -> SemanticEdgeSet:
76
+ identities: set[tuple[str, str, str]] = set()
77
+ children: dict[str, list[str]] = {}
78
+ nodes: set[str] = set()
79
+ for edge in self.edges:
80
+ identity = (
81
+ edge.source_request_id,
82
+ edge.target_request_id,
83
+ edge.type,
84
+ )
85
+ if identity in identities:
86
+ raise ValueError(f"duplicate semantic edge: {identity!r}")
87
+ identities.add(identity)
88
+ children.setdefault(edge.source_request_id, []).append(
89
+ edge.target_request_id
90
+ )
91
+ nodes.update((edge.source_request_id, edge.target_request_id))
92
+
93
+ indegree = dict.fromkeys(nodes, 0)
94
+ for targets in children.values():
95
+ for target in targets:
96
+ indegree[target] += 1
97
+
98
+ stack = [node for node, degree in indegree.items() if degree == 0]
99
+ visited = 0
100
+ while stack:
101
+ node = stack.pop()
102
+ visited += 1
103
+ for child in children.get(node, ()):
104
+ indegree[child] -= 1
105
+ if indegree[child] == 0:
106
+ stack.append(child)
107
+ if visited != len(nodes):
108
+ raise ValueError("semantic edge cycle detected")
109
+ return self
110
+
111
+
112
+ def extract_acp_info(
113
+ headers: Mapping[str, str],
114
+ ) -> tuple[ACPInfo | None, dict[str, str]]:
115
+ """Parse ACP request metadata and remove its private transport header.
116
+
117
+ The semantic edge set arrives independently in ACP metadata. Ordinary requests
118
+ without the private correlation header remain unchanged.
119
+ """
120
+
121
+ forwarded = {
122
+ name: value
123
+ for name, value in headers.items()
124
+ if name.lower() not in ACP_EXTENSION_HEADERS
125
+ }
126
+ normalized = {name.lower(): value for name, value in headers.items()}
127
+ request_id = normalized.get(ACP_MODEL_REQUEST_ID_HEADER.lower())
128
+ if request_id is None:
129
+ return None, forwarded
130
+ if re.fullmatch(ACP_REQUEST_ID_PATTERN, request_id) is None:
131
+ raise ValueError(f"{ACP_MODEL_REQUEST_ID_HEADER} is not a valid ACP request ID")
132
+ return ACPInfo(request_id=request_id), forwarded
verifiers/v1/trace.py CHANGED
@@ -19,6 +19,11 @@ from verifiers.v1.configs.agent import AgentConfig, WireAgentConfig
19
19
  from verifiers.v1.errors import ProviderError
20
20
  from verifiers.v1.graph import MessageNode
21
21
  from verifiers.v1.runtimes import RuntimeInfo
22
+ from verifiers.v1.semantic import (
23
+ ACPInfo,
24
+ ParentLink,
25
+ SemanticEdgeSet,
26
+ )
22
27
  from verifiers.v1.state import State, StateT
23
28
  from verifiers.v1.task import DataT, WireTaskData
24
29
  from verifiers.v1.types import (
@@ -171,6 +176,8 @@ class ModelCall(BaseModel):
171
176
  """The failure that ended this call, coupled to the exchange that caused it."""
172
177
  policy: PolicyEvent | None = None
173
178
  """Policy mediation applied to the request before this call."""
179
+ acp: ACPInfo | None = None
180
+ """Metadata advertised by the ACP harness for this model request."""
174
181
 
175
182
 
176
183
  def min_new_input_tokens(calls: Iterable[ModelCall]) -> Iterator[tuple[ModelCall, int]]:
@@ -188,7 +195,7 @@ def min_new_input_tokens(calls: Iterable[ModelCall]) -> Iterator[tuple[ModelCall
188
195
 
189
196
 
190
197
  class Branch(BaseModel):
191
- """A root-to-leaf graph path; each branch becomes one training sample."""
198
+ """A root-to-leaf message-graph path; each branch becomes one training sample."""
192
199
 
193
200
  index: int
194
201
  nodes: list[MessageNode]
@@ -387,7 +394,7 @@ class Trace(BaseModel, Generic[DataT, StateT, AgentConfigT]):
387
394
  """The tools advertised to the agent, automatically recorded from last intercepted turn."""
388
395
 
389
396
  nodes: list[MessageNode] = Field(default_factory=list)
390
- """The message graph; branches are derived views and storage stays linear in turns."""
397
+ """The message graph, including physical and semantic parent links."""
391
398
  calls: list[ModelCall] = Field(default_factory=list)
392
399
  """Every model call; automatically recorded at intercept time + linked into `nodes`."""
393
400
  mm_token_type_id_map: dict[int, int] = Field(default_factory=dict)
@@ -493,6 +500,72 @@ class Trace(BaseModel, Generic[DataT, StateT, AgentConfigT]):
493
500
  )
494
501
  return branches
495
502
 
503
+ def add_semantic_edges(self, edge_set: SemanticEdgeSet) -> None:
504
+ """Add newly advertised ACP edges; cumulative replays are idempotent."""
505
+ node_by_request: dict[str, int] = {}
506
+ for call in self.calls:
507
+ if call.acp is None or call.node is None:
508
+ continue
509
+ if not 0 <= call.node < len(self.nodes):
510
+ raise ValueError(f"model call has invalid message node {call.node}")
511
+ if not self.nodes[call.node].sampled:
512
+ raise ValueError(f"model call node {call.node} is not sampled")
513
+ # SDK retries are sequential. If more than one attempt commits, the last
514
+ # sampled response is the logical request result consumed by the harness.
515
+ node_by_request[call.acp.request_id] = call.node
516
+
517
+ resolved_identities: set[tuple[int, int, str]] = set()
518
+ additions: list[tuple[int, ParentLink]] = []
519
+ pending_parents: dict[int, list[ParentLink]] = {}
520
+ for edge in edge_set.edges:
521
+ endpoints: list[int] = []
522
+ for request_id in (
523
+ edge.source_request_id,
524
+ edge.target_request_id,
525
+ ):
526
+ node = node_by_request.get(request_id)
527
+ if node is None:
528
+ raise ValueError(
529
+ f"semantic edge request {request_id!r} has no committed message node"
530
+ )
531
+ endpoints.append(node)
532
+ source, target = endpoints
533
+ if source == target:
534
+ raise ValueError("semantic edge resolves to the same message node")
535
+ identity = (source, target, edge.type)
536
+ if identity in resolved_identities:
537
+ raise ValueError(f"duplicate resolved semantic edge: {identity!r}")
538
+ resolved_identities.add(identity)
539
+ link = ParentLink(node=source, type=edge.type)
540
+ if link in self.nodes[target].semantic_parents:
541
+ continue
542
+
543
+ # Adding source -> target creates a cycle exactly when target is already an
544
+ # ancestor of source. Walk parent links directly so existing nodes and links
545
+ # are never rebuilt as cumulative ACP edge sets arrive.
546
+ stack = [source]
547
+ visited: set[int] = set()
548
+ while stack:
549
+ node_id = stack.pop()
550
+ if node_id == target:
551
+ raise ValueError(
552
+ "semantic edges create a cycle in the message graph"
553
+ )
554
+ if node_id in visited:
555
+ continue
556
+ visited.add(node_id)
557
+ node = self.nodes[node_id]
558
+ if node.parent is not None:
559
+ stack.append(node.parent)
560
+ stack.extend(parent.node for parent in node.semantic_parents)
561
+ stack.extend(parent.node for parent in pending_parents.get(node_id, ()))
562
+
563
+ additions.append((target, link))
564
+ pending_parents.setdefault(target, []).append(link)
565
+
566
+ for target, link in additions:
567
+ self.nodes[target].semantic_parents.append(link)
568
+
496
569
  @property
497
570
  def messages(self) -> Messages:
498
571
  """Messages on the final branch."""
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: verifiers
3
- Version: 0.3.2.dev24
3
+ Version: 0.3.2.dev26
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
@@ -21,7 +21,7 @@ Classifier: Programming Language :: Python :: 3.13
21
21
  Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
22
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
23
  Requires-Python: <3.14,>=3.11
24
- Requires-Dist: aiohttp>=3.14.0
24
+ Requires-Dist: aiohttp>=3.14.1
25
25
  Requires-Dist: anthropic>=0.78.0
26
26
  Requires-Dist: datasets<6.0.0,>=3.3.0
27
27
  Requires-Dist: gepa>=0.0.6
@@ -1,21 +1,22 @@
1
1
  verifiers/__init__.py,sha256=yDYsckVQbUkwoh9mU_hBeCLGvS_aWgAxuoNm5LxQpDI,517
2
- verifiers/v1/__init__.py,sha256=AnXz2IG12salvxlOZvxFpG_3v9cvRc7B2DYuH_ORiD4,8090
2
+ verifiers/v1/__init__.py,sha256=AYjjpOBfpSlWZRN51V1KaxMYMBWSZhBEIOzvNk23pxg,8348
3
3
  verifiers/v1/agent.py,sha256=AfjyYmcGpVaOlZkElIz1JZeNRQuZsE_KMZ-LV3uLvzA,31644
4
4
  verifiers/v1/env.py,sha256=CEhzjojhg5jqbOYruUnc5U7TtgDHDSx8NiiFA0qfbt8,18234
5
5
  verifiers/v1/episode.py,sha256=uStvI4WqgJT50hmHIB55m5B-ASqqLz-fZ-ynBz9uzEY,5474
6
6
  verifiers/v1/errors.py,sha256=uQySmCUrjDYFkBIii1vBFPiEcPFPQZ9EGpas_6HvcQI,5279
7
- verifiers/v1/graph.py,sha256=W5JkeUQwtYwQY8pyI2YN6Ci7G8D4PFktfKf2PxzhuwE,34996
7
+ verifiers/v1/graph.py,sha256=09uysIuX7kHCt9XRndpACkQtWocgVbtiLewcEmnzmD4,35787
8
8
  verifiers/v1/harness.py,sha256=ziECqEBWV34UWbLlxrkhY6MwkbVYkoXBOoaY7mZxwTs,14753
9
9
  verifiers/v1/judge.py,sha256=Pvr0C41ah1qkNSZ0WXdkDvBMfv5YSfY1REHncwlJ8cg,9346
10
10
  verifiers/v1/rollout.py,sha256=EnF3RuBfMyKNjJIs0LZaImkSvfe9LYLXc8dYP-1a2Ew,23628
11
+ verifiers/v1/semantic.py,sha256=wssvBSEpY_tgzpFUADG9-N4HkDXgCZvNQ1pdf6qAsS0,4680
11
12
  verifiers/v1/session.py,sha256=xM7JJJVJACk0JfH9RAN1Ts8gJJKr2tGGRiIgQTrdieY,18692
12
13
  verifiers/v1/state.py,sha256=EckF2bWp-vV4b1jYJ9sLI5xrfGuI5spIgYYwW926toI,595
13
14
  verifiers/v1/task.py,sha256=vaVkBu00riiNU1Ke4NeeY2NQTXxOguz9d6NLe55hO_Q,11468
14
15
  verifiers/v1/taskset.py,sha256=fp2E0IEhL_Ybj9cegZwljfTmW27p_30zTWHFKw_kXE4,4374
15
- verifiers/v1/trace.py,sha256=gA0vYHsssYpoc2Kc5WXc-xRIR7xpY0njrNkTddmYMvQ,25095
16
+ verifiers/v1/trace.py,sha256=ABAr9hxpLiAwVOb4h6djAom9DJbOy4BuDqvx0wJDUDY,28439
16
17
  verifiers/v1/types.py,sha256=a1wqL8T7KQg9WxkaDIZpmOyU6xT2VeSr1K4SWiW8ef4,9660
17
- verifiers/v1/acp/__init__.py,sha256=t91yf1NmVvYiUbHCV-ApxcqFFT89JRNYpruu04k6Wco,11205
18
- verifiers/v1/acp/runner.py,sha256=6Y7yTWP560IWrRijlnsB_t3lR79oRilrRoISXX4lXjc,10781
18
+ verifiers/v1/acp/__init__.py,sha256=wUPZVYBFjJuOnIIoYONBFuA04A1DJf_dOyKY3QwK37Q,12722
19
+ verifiers/v1/acp/runner.py,sha256=gMXFmsVg2qD0Zhrx7kvC6Me2Z-wsfBamRIO0i45UW8g,11097
19
20
  verifiers/v1/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
21
  verifiers/v1/cli/debug.py,sha256=x3bqOwwbwwfwQQpxHrZeKdxsW3ZVtUT9cAn_r4aOro4,11631
21
22
  verifiers/v1/cli/gepa.py,sha256=7YpppEMeuY2m1X5szGkybzTHztnIs83CvnSizhiEC-w,4210
@@ -37,7 +38,7 @@ verifiers/v1/cli/eval/runner.py,sha256=tZDPWzd6U7-5N43HGRlV7p-RnUiDleYwMUBVHzWH7
37
38
  verifiers/v1/clients/__init__.py,sha256=Ysig0tE_0E4Jsfgfes1XHN-fK1s_RCXdqZD6E7lK4PU,507
38
39
  verifiers/v1/clients/base.py,sha256=PoDw4GMqrfuPTFVK6n2jDmlD0_lJ5zTrYcNio5yq6K8,1691
39
40
  verifiers/v1/clients/client.py,sha256=zqC_AkiD9pl0kxxIbupNiehbS-YnVdp3EMZ0LOHTd8U,3125
40
- verifiers/v1/clients/eval.py,sha256=-OcYUqlj8dBRjyuffMvymc1fMfZcjo-p5q8ZSMvDGzY,8106
41
+ verifiers/v1/clients/eval.py,sha256=cJucyUFsbF1JlG8nF0Tlw2EBMSoAF0YMklgYiOSoNpg,8322
41
42
  verifiers/v1/clients/train.py,sha256=ZNbEU8WPZ6xI1hho7MiIjleZOswt2lOUGkIUQqpe8gM,18803
42
43
  verifiers/v1/configs/__init__.py,sha256=X7u6X7B3ieD1HZl79Tv1kg-yPHbT0QLvAebaGqxVtvA,317
43
44
  verifiers/v1/configs/agent.py,sha256=L5P6ombAi4U5wwsspMHAuM8111sB9AVdm8q6B5iV1lw,3251
@@ -82,7 +83,7 @@ verifiers/v1/harnesses/__init__.py,sha256=0FVi-mPF36fF0vpLY4H2vbK3U_om1Svz3KgJ3i
82
83
  verifiers/v1/harnesses/node.py,sha256=_-7NofTl-TNuwgEg8qxrD28shlQuyBWgiVHwCCwbdVo,2410
83
84
  verifiers/v1/harnesses/standalone.py,sha256=4y5Mg0fFCdCBLIxbTIpfiNbJFqbM2kPrD4_K_W5SIYI,2358
84
85
  verifiers/v1/harnesses/bash/__init__.py,sha256=IAV4eMMqDHSl-9ANb0Q3kxmBZ22SeHZFBM448X4gQio,140
85
- verifiers/v1/harnesses/bash/harness.py,sha256=MrcdKawd8i5WwnJwPIeRoiAJVxJNNNQT0L6eT1HIvsE,4479
86
+ verifiers/v1/harnesses/bash/harness.py,sha256=i2dbMkJlWT-JZ0lsxWtDy6TGpcKVNd8MAv56PDJJbPE,5245
86
87
  verifiers/v1/harnesses/browser_use/__init__.py,sha256=yxm2IG5TDLadxZEkX8SL26XWbcPcODXcrJfPfm1GqwU,171
87
88
  verifiers/v1/harnesses/browser_use/harness.py,sha256=gISpaGOSHVdSjD41nTEhD0tO8IYim3Ro8MRV4LV_8PQ,4880
88
89
  verifiers/v1/harnesses/browser_use/program.py,sha256=j9umhpD95poj3Emxp-uMEBHlIO_JWDbK5gGL6XMOTrA,9813
@@ -99,7 +100,7 @@ verifiers/v1/harnesses/mini_swe_agent/__init__.py,sha256=1OBu2Y-XqL72-dGhFdgB6sr
99
100
  verifiers/v1/harnesses/mini_swe_agent/harness.py,sha256=7HHismhmfCtahlLtQdQyp_fTKidHfco-MdeWp7B9xCo,2522
100
101
  verifiers/v1/harnesses/mini_swe_agent/program.py,sha256=Beej-JLIgSqnqIqB746oKU6kJYcynvppIbmwGa3nJJ0,167
101
102
  verifiers/v1/harnesses/minimal/__init__.py,sha256=f_dKnFqgeypSh3t7EoPpx0lvosvn1UbsR6_zLpiSsBM,224
102
- verifiers/v1/harnesses/minimal/program.py,sha256=yRzE93K0GbXm79F_2sBs9HfvYG6NGwiv9h7QQXdOpTY,13391
103
+ verifiers/v1/harnesses/minimal/program.py,sha256=Y8sUZjwyu05ZnLuQtdmUr6DMsAJYBqk03yP1DhZJ2K0,24810
103
104
  verifiers/v1/harnesses/null/__init__.py,sha256=XDeKOPeoXUQi9US9_Z3_yH9YaZ4EiOMKJmUtNNdtD7s,127
104
105
  verifiers/v1/harnesses/null/harness.py,sha256=2BhzTmA8suBW6p_8kWksX7GHWhvsblJZp1_yb57R09M,1342
105
106
  verifiers/v1/harnesses/openclaw/__init__.py,sha256=kNyfPB1sGwEf4K3mTfKN0VEyxun3SGvNpvArVKvH-x8,160
@@ -111,14 +112,14 @@ verifiers/v1/harnesses/pool/harness.py,sha256=HKAogPbyLK5QpvPQ1teHOh_IyRQX-or2JF
111
112
  verifiers/v1/harnesses/prime_agent/__init__.py,sha256=xfPC4RrlnyYWaf38tPAOZq4YL6M55lMpj5BoRLmaK8I,171
112
113
  verifiers/v1/harnesses/prime_agent/harness.py,sha256=byplbbIOFACCn2BvVZAxBSHdaPKBGERYz_hA1rgBj0E,11205
113
114
  verifiers/v1/harnesses/rlm/__init__.py,sha256=hwx51xTdEWzzYgMj-p4ETNcptoub3IPMDbEdJ4uB8Ns,122
114
- verifiers/v1/harnesses/rlm/harness.py,sha256=rQDME1GaYcApf7Giqt2ZyBQCBhuXvwLR-X-ofAbfWPo,6860
115
+ verifiers/v1/harnesses/rlm/harness.py,sha256=OpbPCObGg9BQnNw9njI5iLELRGwoMySMrsE9WbhFWHA,7666
115
116
  verifiers/v1/harnesses/terminus_2/__init__.py,sha256=l1pwfg1HyVDEqT9efdnFWcXqaZwtKwe7TrplkyxZSA0,166
116
117
  verifiers/v1/harnesses/terminus_2/harness.py,sha256=kXKhi-aqqsoXGnvet0Tq_v7LYYpRYEzARyQL2MTEGWs,3101
117
118
  verifiers/v1/harnesses/terminus_2/program.py,sha256=X8MZdyItU3gbXGXnGOlJ9LWcUTnqIDaxlhkZvoRiqKY,2703
118
119
  verifiers/v1/interception/__init__.py,sha256=5Kvo7tcBUVaa65s9A1NiOH3CPpzw-P5btXwxB4Nbbvs,4251
119
120
  verifiers/v1/interception/base.py,sha256=Mg16Y104lyZilF9shdivdqYoqz4OYp978i_myyrulu8,2529
120
121
  verifiers/v1/interception/pool.py,sha256=sk_zcdTV8EVRuzqlYMXxon_42tSDAlFvwcyOO2EF7hw,6473
121
- verifiers/v1/interception/server.py,sha256=cyg4ndvny4Y0iZL2OsoIE9oWdgoQsG0jdfmoH2dGCaE,49320
122
+ verifiers/v1/interception/server.py,sha256=2WBh7HQAF8wQvL5jui03i2dVjyKwewwTAzmdn0eH2gg,52079
122
123
  verifiers/v1/interception/tool.py,sha256=ZyZPxLYM_HsGkz-ZbCREQVGtiKZK9lQLChBNF_bBuuc,259
123
124
  verifiers/v1/interception/tunnel/__init__.py,sha256=eVNZJszj6myrKhx9jmJz7VRd9qlfj0AUvUZwI2bXEj8,893
124
125
  verifiers/v1/interception/tunnel/base.py,sha256=DZB6uPLwM4Qy7n7m0vKeyg-Px87MhsmpYTpe2vpPEng,1998
@@ -183,8 +184,8 @@ verifiers/v1/utils/prime.py,sha256=UTYRjp9cbjNb6CVmBHda-1wWZAIIfxNOmTyNuT7_wL4,9
183
184
  verifiers/v1/utils/retries.py,sha256=Y2ZgrAjn-qNkRKZP_RVNL_7EK0iaRcZeCa404lpGYi4,5417
184
185
  verifiers/v1/utils/score.py,sha256=493yJVMw8teCu9JxapxMFPFzI0hNUqdo0Y2nGW4kckk,6200
185
186
  verifiers/v1/utils/version.py,sha256=-obEo_-l9-D8FLef4hYxncOe-uJpxrM1g2Hig_37Sgs,1607
186
- verifiers-0.3.2.dev24.dist-info/METADATA,sha256=ubhsm2wGxJo5JbBqs2ZHTZU6MMbo60B1ZTC3bHcd0pU,4144
187
- verifiers-0.3.2.dev24.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
188
- verifiers-0.3.2.dev24.dist-info/entry_points.txt,sha256=uqQje0TMsr7k6nXlWxlPs13Si0evb3pVCEDF6c-YL80,241
189
- verifiers-0.3.2.dev24.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
190
- verifiers-0.3.2.dev24.dist-info/RECORD,,
187
+ verifiers-0.3.2.dev26.dist-info/METADATA,sha256=4LpEYT-3m6c9gQ3fNSMy3nAMjSvfjVfnNhtZ6g15Luo,4144
188
+ verifiers-0.3.2.dev26.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
189
+ verifiers-0.3.2.dev26.dist-info/entry_points.txt,sha256=uqQje0TMsr7k6nXlWxlPs13Si0evb3pVCEDF6c-YL80,241
190
+ verifiers-0.3.2.dev26.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
191
+ verifiers-0.3.2.dev26.dist-info/RECORD,,