Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/yugos-evals/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,9 @@ harness=..., version=...)` returns a copy whose solver is Claude Code
release; samples, sandbox and scorer are unchanged. The harness runs inside the
task's sandbox and its model requests come back to the router, so the sandbox
needs no network and every turn is routed and metered as usual. The copy is a
separate source, `<source>@<harness>`, without difficulty labels.
separate source, `<source>@<harness>`, without difficulty labels. It drops the
task's message limit, which sizes the native agent's loop; the run's call, cost
and time limits bound a harness session.

Install the `harness` extra to use it. The harness release is fetched once on
the host and copied into the sandbox.
Expand Down
61 changes: 53 additions & 8 deletions packages/yugos-evals/src/yugos_evals/harnessed.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,16 @@
from importlib.metadata import version as installed_version

from inspect_ai import Task, task_with
from inspect_ai.model import GenerateInput
from inspect_ai.model import ContentText, GenerateInput
from inspect_ai.tool import ToolFunction, internal_tool_type

from yugos.inspect_engine.frozen import _task_builder

BUILDER = "yugos_evals.harnessed"
HARNESSES = ("claude_code", "codex_cli", "opencode")
# OpenCode formats requests as one model from its release's own catalog, which drops
# older models; the routed model still answers. This one is in current releases.
OPTIONS = {"opencode": {"opencode_model": "anthropic/claude-sonnet-4-6"}}
_RELEASE = re.compile(r"\d+(\.\d+)+")


Expand All @@ -28,24 +32,62 @@ def _check(harness: str, version: str) -> None:
raise ValueError("a harness is pinned to one exact release")


def _text_only(message):
"""The message with each attachment replaced by a note that it was left out."""
content = message.content
if isinstance(content, str) or all(part.type in ("text", "reasoning") for part in content):
return message
parts = [
part
if part.type in ("text", "reasoning")
else ContentText(text=f"[{part.type} omitted: this session's model reads text only]")
for part in content
]
return message.model_copy(update={"content": parts})


async def portable_request(model, messages, tools, tool_choice, config):
"""Drop the provider-private headers and body fields a harness adds to its requests.
"""Keep a harness's request to what any routed model can do inside the sandbox.

Provider-private headers and body fields are dropped: they carry session and cache
hints for the harness's own provider, the routed model may be any provider, and
the router protocol refuses them.

Tools the provider runs itself, such as web search, are dropped too. They run on
the provider's side with the network access the sandbox denies, and only for the
providers that offer them. The harness's own tools are untouched: one that needs
the network is still offered and fails as it would on a machine without it.

They carry session and cache hints for the harness's own provider; the routed
model may be any provider, and the router protocol refuses them.
An attachment, such as an image the harness read from disk, becomes a note saying
it was left out. The router protocol carries text only and refuses the request
otherwise, which ends the session with the harness reporting a failed model.
"""
if config.extra_body is None and config.extra_headers is None:
local = [tool for tool in tools if internal_tool_type(tool) is None]
text = [_text_only(message) for message in messages]
if (
len(local) == len(tools)
and all(new is old for new, old in zip(text, messages, strict=True))
and config.extra_body is None
and config.extra_headers is None
):
return None
named = isinstance(tool_choice, ToolFunction)
if not local and (named or tool_choice == "any"):
# The request required a tool and none is left: it is answered without one.
tool_choice = "none"
elif named and tool_choice.name not in {tool.name for tool in local}:
tool_choice = "auto"
portable = config.model_copy(update={"extra_body": None, "extra_headers": None})
return GenerateInput(messages, tools, tool_choice, portable)
return GenerateInput(text, local, tool_choice, portable)


def harness_agent(harness: str, version: str):
"""The named harness at one release, with its model requests made portable."""
_check(harness, version)
import inspect_swe

return getattr(inspect_swe, harness)(version=version, filter=portable_request)
options = OPTIONS.get(harness, {})
return getattr(inspect_swe, harness)(version=version, filter=portable_request, **options)


def build(*, options: dict, harness: str, version: str, builder: str, builder_args: dict) -> Task:
Expand All @@ -62,7 +104,9 @@ def harness_question(question, *, harness: str, version: str):
"""A frozen sandboxed question re-presented to a harness, without reloading it.

The copy is a separate source (`<source>@<harness>`) with no difficulty labels:
panel evidence for the task's own agent does not describe a harness.
panel evidence for the task's own agent does not describe a harness. The task's
message limit is dropped too: it sizes the native agent's loop, and a harness
session is bounded by the run's call, cost and time limits instead.
"""
_check(harness, version)
config = question.inspect_task
Expand Down Expand Up @@ -93,6 +137,7 @@ def harness_question(question, *, harness: str, version: str):
"builder": BUILDER,
"builder_args": builder_args,
"packages": packages,
"message_limit": None,
},
}
)
82 changes: 80 additions & 2 deletions packages/yugos-evals/tests/test_harnessed.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@

import pytest
from inspect_ai.dataset import MemoryDataset, Sample
from inspect_ai.model import ChatMessageUser, GenerateConfig
from inspect_ai.model import ChatMessageUser, ContentImage, ContentText, GenerateConfig
from inspect_ai.tool import INTERNAL_TOOL_TYPE, ToolFunction, ToolInfo

from yugos.evaluation import Question
from yugos.inference.chat import ModelInput
from yugos.inspect_engine import restore_tasks
from yugos_evals.catalog import entry, freeze_entry, load_task
from yugos_evals.harnessed import harness_question, portable_request
from yugos_evals.harnessed import harness_agent, harness_question, portable_request


@pytest.fixture
Expand Down Expand Up @@ -51,6 +52,31 @@ def test_harnessed_question_keeps_the_native_samples_sandbox_and_scorer(sandboxe
assert other.inspect_task != harnessed.inspect_task


def test_harness_session_is_not_cut_at_the_native_agents_message_limit(sandboxed):
limited = sandboxed.model_copy(
update={"inspect_task": {**sandboxed.inspect_task, "message_limit": 30}}
)
[(native, _)] = restore_tasks([limited])
[(task, _)] = restore_tasks([harness_question(limited, harness="codex_cli", version="0.80.0")])
# Thirty messages end a harness after about a dozen turns, before it can finish.
assert (native.message_limit, task.message_limit) == (30, None)


def test_opencode_is_given_a_model_its_release_can_resolve(monkeypatch):
import inspect_swe

seen = {}
monkeypatch.setattr(inspect_swe, "opencode", lambda **options: seen.update(options))
monkeypatch.setattr(inspect_swe, "claude_code", lambda **options: seen.update(options))
harness_agent("claude_code", "2.1.311")
assert "opencode_model" not in seen
harness_agent("opencode", "1.19.6")
# The inspect-swe default names a model newer OpenCode releases no longer list,
# which fails every session before its first request.
assert seen["opencode_model"] not in (None, "anthropic/claude-sonnet-4-5")
assert seen["version"] == "1.19.6" and seen["filter"] is portable_request


def test_harnessed_question_drops_evidence_measured_with_the_native_agent(sandboxed):
labelled = sandboxed.model_copy(update={"difficulty_decile": 3, "panel_solve_share": "0.5"})
harnessed = harness_question(labelled, harness="codex_cli", version="0.80.0")
Expand Down Expand Up @@ -103,3 +129,55 @@ def test_harness_requests_become_acceptable_to_the_router_protocol():
assert request.config.extra_body is None and request.config.extra_headers is None
plain = GenerateConfig(temperature=0)
assert asyncio.run(portable_request(None, messages, [], "auto", plain)) is None


def test_a_harness_request_keeps_only_tools_that_run_in_the_sandbox():
# Codex CLI declares web search as a tool its provider runs; Claude Code's own
# WebSearch tool asks for one in a request of its own. A provider that offers it
# would search the live web from a sandbox that has no network.
messages = [ChatMessageUser(content="fix the bug")]
shell = ToolInfo(name="exec_command", description="Run a command in the sandbox.")
search = ToolInfo(
name="web_search", description="Search the web.", options={INTERNAL_TOOL_TYPE: "web_search"}
)
plain = GenerateConfig(temperature=0)

_, tools, choice, _ = asyncio.run(
portable_request(None, messages, [shell, search], "auto", plain)
)
assert tools == [shell] and choice == "auto"
# A request that exists only to search is answered without a tool.
forced = ToolFunction(name="web_search")
_, tools, choice, _ = asyncio.run(portable_request(None, messages, [search], forced, plain))
assert tools == [] and choice == "none"
# So is one that required some tool: the router protocol refuses a required
# choice with no tool to choose.
filtered = asyncio.run(portable_request(None, messages, [search], "any", plain))
assert ModelInput.from_inspect(*filtered).tool_choice == "none"
# A forced tool that is gone leaves the choice among the tools that remain.
_, tools, choice, _ = asyncio.run(
portable_request(None, messages, [shell, search], forced, plain)
)
assert tools == [shell] and choice == "auto"
assert asyncio.run(portable_request(None, messages, [shell], "auto", plain)) is None


def test_a_harness_attachment_becomes_a_note_the_router_protocol_accepts():
# Claude Code answers a Read of an image file with the image itself.
read = ChatMessageUser(
content=[ContentText(text="plot.png:"), ContentImage(image="data:image/png;base64,AAAA")]
)
messages = [ChatMessageUser(content="fix the bug"), read]
plain = GenerateConfig(temperature=0)
with pytest.raises(ValueError, match="only text request content"):
ModelInput.from_inspect(messages, [], "auto", plain)

filtered = asyncio.run(portable_request(None, messages, [], "auto", plain))
request = ModelInput.from_inspect(*filtered)
assert request.messages[0].text == "fix the bug"
assert [part.text for part in request.messages[1].content] == [
"plot.png:",
"[image omitted: this session's model reads text only]",
]
# The harness's own record of the conversation is not rewritten.
assert read.content[1].type == "image"
58 changes: 57 additions & 1 deletion packages/yugos/src/yugos/inspect_engine/router_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import math
import time
import uuid
import weakref
from collections.abc import Awaitable, Callable
from contextvars import ContextVar
from dataclasses import dataclass
Expand Down Expand Up @@ -121,6 +122,35 @@ def __init__(self, message: str, *, retry_after: float | None = None) -> None:
}


def _calls(message: ChatMessageAssistant) -> list[tuple[str, str]]:
return [(call.id, call.function) for call in message.tool_calls or ()]


def restore_continuations(
input: list[ChatMessage], replies: dict[tuple[str, ...], ChatMessageAssistant]
) -> list[ChatMessage]:
"""Give each replayed tool-calling turn back the reply it came from.

A coding harness keeps its own transcript and rebuilds every request from it, so
its assistant turns arrive without the metadata that carries the provider's
reasoning state, and an empty reply arrives as placeholder text. A harness also
rewrites its own record of a call, such as filling in an argument's default, so
arguments are not compared: a turn making the same calls, by ID and function, as a
reply this sample was given is that reply, and is sent as the model wrote it.
"""
restored = []
for message in input:
if isinstance(message, ChatMessageAssistant) and not (message.metadata or {}).get(
PROVIDER_STATE_KEY
):
calls = _calls(message)
reply = replies.get(tuple(call[0] for call in calls))
if reply is not None and _calls(reply) == calls:
message = reply
restored.append(message)
return restored


def _output(reply: RouterReply, model: str, elapsed_s: float) -> ModelOutput:
tool_calls = [
ToolCall(id=call.id, function=call.function, arguments=call.arguments)
Expand Down Expand Up @@ -183,7 +213,33 @@ def record_model_time(seconds: float) -> None:


class _RouterInspectModel(Model):
async def generate(self, *args, **kwargs):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
# Tool-calling replies that carry provider state, by sample and call IDs.
self._replies: dict[int, dict[tuple[str, ...], ChatMessageAssistant]] = {}

def _sample_replies(self) -> dict[tuple[str, ...], ChatMessageAssistant]:
sample = store()
replies = self._replies.get(id(sample))
if replies is None:
replies = self._replies[id(sample)] = {}
# A sample's replies are dropped with its store.
weakref.finalize(sample, self._replies.pop, id(sample), None)
return replies

async def generate(self, input, *args, **kwargs):
# Restored here, before Inspect records the request, so the log shows the
# conversation the router was sent.
replies = self._sample_replies()
if not isinstance(input, str):
input = restore_continuations(input, replies)
output = await self._timed_generate(input, *args, **kwargs)
message = output.message if output.choices else None
if message and message.tool_calls and (message.metadata or {}).get(PROVIDER_STATE_KEY):
replies[tuple(call.id for call in message.tool_calls)] = message
return output

async def _timed_generate(self, *args, **kwargs):
# Inspect reconciles successful generations across every retry, while a
# terminal exception skips that reconciliation. Own the final adjustment
# around its complete generation so earlier callbacks cannot earn credit twice.
Expand Down
Loading