diff --git a/packages/yugos-evals/README.md b/packages/yugos-evals/README.md index 915f1f0..9568ffd 100644 --- a/packages/yugos-evals/README.md +++ b/packages/yugos-evals/README.md @@ -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, `@`, without difficulty labels. +separate source, `@`, 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. diff --git a/packages/yugos-evals/src/yugos_evals/harnessed.py b/packages/yugos-evals/src/yugos_evals/harnessed.py index 2543b97..0ad2884 100644 --- a/packages/yugos-evals/src/yugos_evals/harnessed.py +++ b/packages/yugos-evals/src/yugos_evals/harnessed.py @@ -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+)+") @@ -28,16 +32,53 @@ 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): @@ -45,7 +86,8 @@ def harness_agent(harness: str, version: str): _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: @@ -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 (`@`) 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 @@ -93,6 +137,7 @@ def harness_question(question, *, harness: str, version: str): "builder": BUILDER, "builder_args": builder_args, "packages": packages, + "message_limit": None, }, } ) diff --git a/packages/yugos-evals/tests/test_harnessed.py b/packages/yugos-evals/tests/test_harnessed.py index ecc8cb7..7f8dac2 100644 --- a/packages/yugos-evals/tests/test_harnessed.py +++ b/packages/yugos-evals/tests/test_harnessed.py @@ -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 @@ -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") @@ -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" diff --git a/packages/yugos/src/yugos/inspect_engine/router_model.py b/packages/yugos/src/yugos/inspect_engine/router_model.py index 9e9c3e2..a1d7c97 100644 --- a/packages/yugos/src/yugos/inspect_engine/router_model.py +++ b/packages/yugos/src/yugos/inspect_engine/router_model.py @@ -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 @@ -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) @@ -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. diff --git a/packages/yugos/tests/test_inspect_router.py b/packages/yugos/tests/test_inspect_router.py index 9ece350..6588f3c 100644 --- a/packages/yugos/tests/test_inspect_router.py +++ b/packages/yugos/tests/test_inspect_router.py @@ -1,6 +1,7 @@ import asyncio import json import threading +from dataclasses import replace from decimal import Decimal from types import SimpleNamespace @@ -11,7 +12,14 @@ from inspect_ai import Task # noqa: E402 from inspect_ai.dataset import MemoryDataset, Sample # noqa: E402 from inspect_ai.log import read_eval_log # noqa: E402 -from inspect_ai.model import GenerateConfig, ModelOutput, RetryDecision # noqa: E402 +from inspect_ai.model import ( # noqa: E402 + ChatMessageAssistant, + ChatMessageTool, + GenerateConfig, + ModelOutput, + RetryDecision, + get_model, +) from inspect_ai.scorer import includes # noqa: E402 from inspect_ai.solver import generate, solver, use_tools # noqa: E402 from inspect_ai.tool import tool # noqa: E402 @@ -19,6 +27,7 @@ from inspect_fakes import ScriptedRouter, exact_question, pack_task, reply, run # noqa: E402 from yugos.inference.calls import QuestionLimitExceeded # noqa: E402 +from yugos.inference.chat import ProviderState, provider_state # noqa: E402 from yugos.inspect_engine import ( # noqa: E402 QUESTION_EXHAUSTED, JsonlReceipts, @@ -143,6 +152,67 @@ async def client(call): assert event.output.time is not None and event.output.time >= 0 +def test_a_harness_replayed_turn_gets_its_reasoning_state_back(tmp_path): + # A coding harness rebuilds each request from its own transcript: the assistant + # turn returns without metadata, an empty reply returns as placeholder text, and + # a call's arguments can return rewritten, such as with a default filled in. + state = ProviderState( + provider_id="google", + model_id="m", + effort="medium", + data={"api": "google", "message": {"role": "assistant", "content": ""}}, + ) + requests = {"faithful": [], "rewritten": [], "other": []} + + async def client(call): + requests[call.scope.sample_id].append(call.request) + if len(requests[call.scope.sample_id]) == 1: + return RouterReply( + tool_calls=( + RouterToolCall(id="t1", function="lookup", arguments={"city": "Oslo"}), + ), + provider_state=state, + finish_reason="tool_calls", + ) + return reply("sunny") + + @solver + def replaying_harness(): + async def solve(sample, generate): + model = get_model() + first = (await model.generate(sample.messages)).message + calls = first.tool_calls + if sample.sample_id == "rewritten": + calls = [replace(calls[0], arguments={"city": "Oslo", "units": "metric"})] + if sample.sample_id == "other": + calls = [replace(calls[0], function="forecast")] + replayed = ChatMessageAssistant(content="(no content)", tool_calls=calls) + result = ChatMessageTool(content="sunny", tool_call_id="t1") + sample.output = await model.generate([*sample.messages, replayed, result]) + return sample + + return solve + + task = pack_task([exact_question(name, "sunny") for name in requests], name="pack") + task.solver = replaying_harness() + log = run_competition_eval( + task, router_model(client, submission_id="sub"), log_dir=str(tmp_path), display="none" + ) + assert not any(sample.error for sample in log.samples) + + faithful, rewritten, other = (requests[name][1].messages[-2] for name in requests) + for restored in (faithful, rewritten): + # The turn is sent as the model wrote it, not as the harness recorded it. + assert provider_state(restored) == state and restored.text == "" + assert restored.tool_calls[0].arguments == {"city": "Oslo"} + # A turn calling another function is not the reply the state belongs to. + assert provider_state(other) is None and other.text == "(no content)" + # The log records the request the router was sent. + [sample] = [sample for sample in log.samples if sample.id == "faithful"] + logged = [event for event in sample.events if event.event == "model"][1].input[-2] + assert provider_state(logged) == state and logged.text == "" + + def test_only_infrastructure_unavailability_is_retried(): # Catches retrying a miner failure (a second attempt) or failing on a transient outage. api = RouterModel("sub", client=None)