From 8b2984d40c046e89c02ed8bd3256d476c446d3d8 Mon Sep 17 00:00:00 2001 From: Pratyush Singhal Date: Mon, 23 Nov 2026 19:28:56 +0530 Subject: [PATCH 1/2] opencode: configurable output-token cap and a clear error at the cap opencode caps each model request at 32,000 output tokens unless told otherwise, and the bridge's model entry declares no limit. Reasoning models at high effort spend most of that on reasoning, the last step ends with reason "length", and the turn failed with the uninformative "opencode exited with code 0 without completing". Add an optional max_output_tokens to the agent-config. When set, the bridge puts limit.output on the generated model entry and sets OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX for the CLI, since opencode uses the smaller of the two. Unset keeps today's behaviour. When a turn doesn't complete and its last step stopped for "length", fail with error_code output_token_limit and a message giving the step's reasoning and text token counts. Error events still take precedence. Co-Authored-By: Claude Opus 5.5 --- .../agents/agents/opencode/README.md | 2 +- .../agents/agents/opencode/a2a_server.py | 3 ++ .../agents/agents/opencode/opencode_bridge.py | 42 ++++++++++++++++-- .../agents/opencode/test_message_contract.py | 6 +-- .../opencode/test_opencode_bridge_config.py | 37 +++++++++++++++- .../opencode/test_opencode_bridge_events.py | 43 +++++++++++++++++++ 6 files changed, 125 insertions(+), 8 deletions(-) diff --git a/src/agent_env/agents/agents/opencode/README.md b/src/agent_env/agents/agents/opencode/README.md index 4a464cfc7..26173a9ed 100644 --- a/src/agent_env/agents/agents/opencode/README.md +++ b/src/agent_env/agents/agents/opencode/README.md @@ -34,7 +34,7 @@ disk: | Extension | Implementation | |---|---| -| `agent-config/v1` | `OpenCodeConfig`: `model`, `effort` (the provider's `reasoningEffort`), `system_prompt`, `output_format` (a JSON schema the answer is checked against), `project_id`, `task_id`, `timeout_seconds` (1800 by default), `max_turns` (the steps, model requests, a task may make, as Claude Code's `--max-turns`: once the last one asks for another, the CLI is killed and the task fails with `Reached maximum number of turns (N)`. OpenCode v1's own `steps` limit isn't used, since it doesn't stop a model that keeps calling tools), `builtin_tools` (below) | +| `agent-config/v1` | `OpenCodeConfig`: `model`, `effort` (the provider's `reasoningEffort`), `max_output_tokens` (the output tokens, reasoning included, one model request may produce, 32,000 by default; it sets the model's `limit.output` and `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX`, since OpenCode takes the smaller of the two. A task whose last step stops at the cap fails with `output_token_limit`), `system_prompt`, `output_format` (a JSON schema the answer is checked against), `project_id`, `task_id`, `timeout_seconds` (1800 by default), `max_turns` (the steps, model requests, a task may make, as Claude Code's `--max-turns`: once the last one asks for another, the CLI is killed and the task fails with `Reached maximum number of turns (N)`. OpenCode v1's own `steps` limit isn't used, since it doesn't stop a model that keeps calling tools), `builtin_tools` (below) | | `mcp-config/v1` | SDK default; each server passed to the task's CLI | | `skill-config/v1` | inline and bundle skills installed as `$XDG_CONFIG_HOME/opencode/skills//`, where OpenCode finds them | | `trajectory/v1` | the task's `opencode run --format json` events, live while it runs (format `opencode-events/1`) | diff --git a/src/agent_env/agents/agents/opencode/a2a_server.py b/src/agent_env/agents/agents/opencode/a2a_server.py index 462c52544..a7e2e593c 100644 --- a/src/agent_env/agents/agents/opencode/a2a_server.py +++ b/src/agent_env/agents/agents/opencode/a2a_server.py @@ -134,6 +134,8 @@ def _changelog_backup_exclusions() -> list[str]: class OpenCodeConfig(AgentConfig): model: str | None = None effort: str | None = None + # The output tokens, reasoning included, one model request may produce; None keeps OpenCode's 32,000. + max_output_tokens: int | None = Field(default=None, gt=0) system_prompt: str | None = None output_format: dict[str, Any] | None = None project_id: str | None = None @@ -376,6 +378,7 @@ def record(event: dict) -> None: session_id=session_id, model=request.config.model, effort=request.config.effort, + max_output_tokens=request.config.max_output_tokens, mcp_servers=dict(request.mcp_servers), system_prompt=request.config.system_prompt, output_format=request.config.output_format, diff --git a/src/agent_env/agents/agents/opencode/opencode_bridge.py b/src/agent_env/agents/agents/opencode/opencode_bridge.py index 4bbc97803..7e6d229ca 100644 --- a/src/agent_env/agents/agents/opencode/opencode_bridge.py +++ b/src/agent_env/agents/agents/opencode/opencode_bridge.py @@ -45,6 +45,10 @@ ROLE_HEADER = "AgentEnv-Role" # What agent-env gives an agent for [model.headers]: a JSON object of header names to values. MODEL_HEADERS_ENV = "LITELLM_EXTRA_HEADERS" +# OpenCode's experimental flag for its output-token cap (32,000 by default), checked against opencode-ai 1.17.18. The +# CLI caps a step at min(the model's limit.output, this value), so limit.output alone can't raise the cap. A name the +# CLI doesn't know is ignored without an error, so recheck it on every opencode-ai upgrade. +OUTPUT_TOKEN_MAX_ENV = "OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX" # Root under which each A2A context_id gets its own OpenCode data dir; lives # under $HOME so host-mode instances don't share session state. @@ -282,6 +286,7 @@ def _build_config( environ: Mapping[str, str] = os.environ, instructions: list[str] | None = None, builtin_tools: OpenCodeTools | None = None, + max_output_tokens: int | None = None, ) -> dict: """Assemble the inline OpenCode config passed via OPENCODE_CONFIG_CONTENT. @@ -324,6 +329,8 @@ def _build_config( "additional_drop_params": ["tool_choice"], **({"reasoningEffort": effort} if effort else {}), }, + # Output only: a limit.context would turn on OpenCode's auto-compaction. + **({"limit": {"output": max_output_tokens}} if max_output_tokens else {}), }}, } }, @@ -458,6 +465,7 @@ async def _run_opencode( workspace: str = "/app", max_turns: int | None = None, base_url: str | None = None, + max_output_tokens: int | None = None, ) -> OpencodeResult: """Run one `opencode run` turn in ``workspace``, its provider calling ``base_url``, the endpoint's when None. ``event_callback`` gets each JSON event as the CLI prints it: exactly the events of the returned trajectory, in order. ``builtin_tools`` selects the CLI's own tools, as @@ -465,7 +473,10 @@ async def _run_opencode( ``max_turns`` bounds the turn's steps, OpenCode's model requests, as ``--max-turns`` bounds Claude Code's: once the last step it allows asks for another, the CLI is killed and the turn fails. OpenCode v1's own ``steps`` limit - only asks the model to stop, and still offers it every tool (anomalyco/opencode#55921).""" + only asks the model to stop, and still offers it every tool (anomalyco/opencode#55921). + + ``max_output_tokens`` raises or lowers the output tokens, reasoning included, one model request may produce; None + keeps OpenCode's default of 32,000.""" model = model or DEFAULT_MODEL attribution = _attribution_headers(project_id, task_id) if attribution: @@ -484,7 +495,8 @@ async def _run_opencode( config = _build_config(model, mcp_servers, provider_headers(os.environ, attribution), role, effort, environ={**os.environ, "LITELLM_BASE_URL": base_url} if base_url else os.environ, - instructions=instructions, builtin_tools=builtin_tools) + instructions=instructions, builtin_tools=builtin_tools, + max_output_tokens=max_output_tokens) # Resume a specific session by id (multi-turn continuity). `--continue` # does NOT replay history to the model; `-s ` does. First turn @@ -507,6 +519,7 @@ async def _run_opencode( env = { **cli_env(context_id, mcp_servers=mcp_servers, clock_armed=clock_armed()), "OPENCODE_CONFIG_CONTENT": json.dumps(config), + **({OUTPUT_TOKEN_MAX_ENV: str(max_output_tokens)} if max_output_tokens else {}), } logger.info(f"Running opencode (session={session_id}, model={model}, effort={effort}, ctx={context_id[:12]}, mcp={list((mcp_servers or {}).keys())})") @@ -655,6 +668,8 @@ def __init__(self, event_callback: Callable[[dict], None] | None = None) -> None self.tool_calls: set[str] = set() self.steps: set[str] = set() self.last_step_continues = False + self.last_step_reason: object = None + self.last_step_tokens: dict | None = None self.session_id: str | None = None self.completed = False self.event_errors: list[str] = [] @@ -740,6 +755,9 @@ def on_line(self, line: str) -> None: reason = (part or event).get("reason") self.steps.add(str((part or event).get("id") or f"step-{len(self.steps)}")) self.last_step_continues = reason in _CONTINUING_STEP_REASONS + self.last_step_reason = reason + tokens = (part or event).get("tokens") + self.last_step_tokens = tokens if isinstance(tokens, dict) else None if reason == "stop": self.completed = True @@ -758,11 +776,17 @@ def result(self, stderr: bytes, returncode: int | None) -> OpencodeResult: # file's modality is unsupported but the model still answered), so we only # surface an error when no terminal stop was emitted. err: str | None = None + error_code = self.error_code if not self.completed: stderr_text = stderr.decode(errors="replace").strip() details = "\n".join(self.event_errors) + # Ahead of stderr: a step cut off at the cap exits 0 with no error event, and any stderr is incidental. + length = self._output_limit_error() if not details else None + if length: + error_code = "output_token_limit" err = ( details + or length or stderr_text or f"opencode exited with code {returncode} without completing" )[:ERROR_MESSAGE_LIMIT] @@ -774,9 +798,21 @@ def result(self, stderr: bytes, returncode: int | None) -> OpencodeResult: session_id=self.session_id, trajectory=self.trajectory, error=err, - error_code=self.error_code if err else None, + error_code=error_code if err else None, ) + def _output_limit_error(self) -> str | None: + """The error for a turn whose last step stopped at the output-token cap, with the step's token counts when its + event has them: opencode-ai 1.17.18's step-finish ``tokens`` counts ``reasoning`` apart from ``output``.""" + if self.last_step_reason != "length": + return None + tokens = self.last_step_tokens or {} + reasoning, text = tokens.get("reasoning"), tokens.get("output") + counts = (f" ({reasoning + text} tokens: {reasoning} reasoning + {text} text)" + if isinstance(reasoning, int) and isinstance(text, int) else "") + return (f"model hit the output token cap{counts} before finishing; " + "raise max_output_tokens in the opencode agent config") + _TAGS_HEADER = "x-litellm-tags" diff --git a/tst/unit/agents/opencode/test_message_contract.py b/tst/unit/agents/opencode/test_message_contract.py index c19d316d6..1920a9fb4 100644 --- a/tst/unit/agents/opencode/test_message_contract.py +++ b/tst/unit/agents/opencode/test_message_contract.py @@ -181,17 +181,17 @@ async def test_a_turn_gets_the_sdks_peer_tools_with_its_registered_servers(monke @pytest.mark.asyncio async def test_the_turns_config_and_workspace_reach_the_cli(oc, turns, folders): config = {"model": "provider/model", "effort": "high", "system_prompt": "be brief", "project_id": "p-1", - "task_id": "t-1", "role": "solver", "timeout_seconds": 42, "max_turns": 45} + "task_id": "t-1", "role": "solver", "timeout_seconds": 42, "max_turns": 45, "max_output_tokens": 64000} async with oc.client() as client: assert (await client.post("/ext/agent-config", json=config)).status_code == 200 await oc.send(client, "go") (call,) = turns.calls assert {key: call[key] for key in ("prompt", "model", "effort", "system_prompt", "project_id", "task_id", "role", - "timeout_s", "workspace", "max_turns")} == { + "timeout_s", "workspace", "max_turns", "max_output_tokens")} == { "prompt": "go", "model": "provider/model", "effort": "high", "system_prompt": "be brief", "project_id": "p-1", "task_id": "t-1", "role": "solver", "timeout_s": 42, "workspace": str(folders), - "max_turns": 45} + "max_turns": 45, "max_output_tokens": 64000} @pytest.mark.asyncio diff --git a/tst/unit/agents/opencode/test_opencode_bridge_config.py b/tst/unit/agents/opencode/test_opencode_bridge_config.py index 0b73dd5c5..a1e995c1a 100644 --- a/tst/unit/agents/opencode/test_opencode_bridge_config.py +++ b/tst/unit/agents/opencode/test_opencode_bridge_config.py @@ -14,7 +14,7 @@ import pytest -from tst.unit.agents.opencode.agent import model_relay, opencode_bridge +from tst.unit.agents.opencode.agent import a2a_server, model_relay, opencode_bridge from tst.unit.agents.opencode.fake_cli import FakeCLI _build_config = opencode_bridge._build_config @@ -215,3 +215,38 @@ async def relay(upstream, calls, **kwargs): "tool_call_count": 0, "input_tokens": 19489, "output_tokens": 105, "total_tokens": 19594, "cache_read_tokens": 9342, "cache_write_tokens": 9539, "input_includes_cache": True, "provider_details": {"model_calls": 3}} + + +def test_max_output_tokens_sets_the_models_output_limit_alone(): + entry = _model_entry(_build_config(MODEL, None, {}, None, max_output_tokens=64000)) + # No context limit, which would turn on OpenCode's auto-compaction. + assert entry["limit"] == {"output": 64000} + + +def test_no_max_output_tokens_omits_the_limit(): + assert "limit" not in _model_entry(_build_config(MODEL, None, {}, None)) + + +def test_max_output_tokens_also_reaches_the_cli_as_its_output_cap(spawned): + """OpenCode caps a step at min(limit.output, the variable), so the limit alone can't raise it past 32,000.""" + asyncio.run(opencode_bridge.run_opencode(prompt="go", context_id="ctx", model="m", max_output_tokens=64000)) + + ((_argv, env),) = spawned + assert env["OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX"] == "64000" + assert _model_entry(json.loads(env["OPENCODE_CONFIG_CONTENT"]), "m")["limit"] == {"output": 64000} + + +def test_a_turn_with_no_max_output_tokens_sets_no_output_cap(monkeypatch, spawned): + monkeypatch.delenv("OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX", raising=False) + + asyncio.run(opencode_bridge.run_opencode(prompt="go", context_id="ctx", model="m")) + + ((_argv, env),) = spawned + assert "OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX" not in env + assert "limit" not in _model_entry(json.loads(env["OPENCODE_CONFIG_CONTENT"]), "m") + + +@pytest.mark.parametrize("value", [0, -1]) +def test_the_config_refuses_a_max_output_tokens_that_is_not_positive(value): + with pytest.raises(ValueError): + a2a_server.OpenCodeConfig(max_output_tokens=value) diff --git a/tst/unit/agents/opencode/test_opencode_bridge_events.py b/tst/unit/agents/opencode/test_opencode_bridge_events.py index f97c61b17..bab957f0a 100644 --- a/tst/unit/agents/opencode/test_opencode_bridge_events.py +++ b/tst/unit/agents/opencode/test_opencode_bridge_events.py @@ -95,3 +95,46 @@ async def fake_subprocess(*_args, **_kwargs): else: assert result.structured_output is None assert len(result.trajectory) == 2 + + +def _step_finish(reason: str, **part) -> dict: + return {"type": "step_finish", "part": {"type": "step-finish", "reason": reason, **part}} + + +# A prod turn's last step at opencode-ai 1.17.18's default cap of 32,000: `output` counts the text alone. +_CAPPED_TOKENS = {"total": 128270, "input": 13981, "output": 2, "reasoning": 31998, "cache": {"write": 0, "read": 82289}} + + +def test_a_turn_cut_off_at_the_output_cap_fails_with_its_token_counts(): + result = _parse_events(_jsonl(_step_finish("tool-calls"), _step_finish("length", tokens=_CAPPED_TOKENS)), b"", 0) + + assert result.error_code == "output_token_limit" + assert result.error == ("model hit the output token cap (32000 tokens: 31998 reasoning + 2 text) before " + "finishing; raise max_output_tokens in the opencode agent config") + + +def test_the_output_cap_error_wins_over_stderr_and_does_without_token_counts(): + result = _parse_events(_jsonl(_step_finish("length")), b"some log line\n", 0) + + assert result.error_code == "output_token_limit" + assert result.error.startswith("model hit the output token cap before finishing;") + + +def test_an_error_event_wins_over_the_output_cap(): + error = {"type": "error", "error": {"name": "APIError", "data": {"message": "boom", "statusCode": 500}}} + + result = _parse_events(_jsonl(_step_finish("length", tokens=_CAPPED_TOKENS), error), b"", 0) + + assert (result.error, result.error_code) == ("APIError: boom", "500") + + +def test_a_stopped_turn_is_unaffected_by_an_earlier_cut_off_step(): + result = _parse_events(_jsonl(_step_finish("length", tokens=_CAPPED_TOKENS), _step_finish("stop")), b"", 0) + + assert (result.error, result.error_code) == (None, None) + + +def test_a_turn_ending_on_another_reason_keeps_the_generic_error(): + result = _parse_events(_jsonl(_step_finish("content-filter")), b"", 0) + + assert (result.error, result.error_code) == ("opencode exited with code 0 without completing", None) From 292885dd526605bc9ee653e4d9b475b93b01061e Mon Sep 17 00:00:00 2001 From: Pratyush Singhal Date: Mon, 23 Nov 2026 19:55:07 +0530 Subject: [PATCH 2/2] prompt_agent: pass max_output_tokens to the agent config The opencode agent's max_output_tokens setting had no caller: prompt_agent sends a fixed set of agent-config fields, and negotiation drops the rest, so a task could not raise opencode's output-token cap. Add max_output_tokens to prompt_agent and always_on the way max_thinking_tokens is plumbed: a user-scoped step field, round-tripped through to_dict/from_dict, replaced by a run's agent_max_output_tokens override, and sent in the agent config. Only agents whose card accepts the field receive it. The opencode cap error now points at the prompt_agent step's field. Co-Authored-By: Claude Opus 5.5 --- .../agents/agents/opencode/README.md | 2 +- .../agents/agents/opencode/opencode_bridge.py | 2 +- .../task_step/task_steps/always_on.py | 9 +- .../task_step/task_steps/prompt_agent.py | 10 ++- .../opencode/test_opencode_bridge_events.py | 2 +- tst/unit/task_step/always_on_harness.py | 3 +- .../test_always_on_agent_and_gateway.py | 16 ++++ .../test_prompt_agent_max_output_tokens.py | 85 +++++++++++++++++++ 8 files changed, 119 insertions(+), 10 deletions(-) create mode 100644 tst/unit/task_step/test_prompt_agent_max_output_tokens.py diff --git a/src/agent_env/agents/agents/opencode/README.md b/src/agent_env/agents/agents/opencode/README.md index 26173a9ed..6a9584cb3 100644 --- a/src/agent_env/agents/agents/opencode/README.md +++ b/src/agent_env/agents/agents/opencode/README.md @@ -34,7 +34,7 @@ disk: | Extension | Implementation | |---|---| -| `agent-config/v1` | `OpenCodeConfig`: `model`, `effort` (the provider's `reasoningEffort`), `max_output_tokens` (the output tokens, reasoning included, one model request may produce, 32,000 by default; it sets the model's `limit.output` and `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX`, since OpenCode takes the smaller of the two. A task whose last step stops at the cap fails with `output_token_limit`), `system_prompt`, `output_format` (a JSON schema the answer is checked against), `project_id`, `task_id`, `timeout_seconds` (1800 by default), `max_turns` (the steps, model requests, a task may make, as Claude Code's `--max-turns`: once the last one asks for another, the CLI is killed and the task fails with `Reached maximum number of turns (N)`. OpenCode v1's own `steps` limit isn't used, since it doesn't stop a model that keeps calling tools), `builtin_tools` (below) | +| `agent-config/v1` | `OpenCodeConfig`: `model`, `effort` (the provider's `reasoningEffort`), `max_output_tokens` (prompt_agent's field of that name: the output tokens, reasoning included, one model request may produce, 32,000 by default; it sets the model's `limit.output` and `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX`, since OpenCode takes the smaller of the two. A task whose last step stops at the cap fails with `output_token_limit`), `system_prompt`, `output_format` (a JSON schema the answer is checked against), `project_id`, `task_id`, `timeout_seconds` (1800 by default), `max_turns` (the steps, model requests, a task may make, as Claude Code's `--max-turns`: once the last one asks for another, the CLI is killed and the task fails with `Reached maximum number of turns (N)`. OpenCode v1's own `steps` limit isn't used, since it doesn't stop a model that keeps calling tools), `builtin_tools` (below) | | `mcp-config/v1` | SDK default; each server passed to the task's CLI | | `skill-config/v1` | inline and bundle skills installed as `$XDG_CONFIG_HOME/opencode/skills//`, where OpenCode finds them | | `trajectory/v1` | the task's `opencode run --format json` events, live while it runs (format `opencode-events/1`) | diff --git a/src/agent_env/agents/agents/opencode/opencode_bridge.py b/src/agent_env/agents/agents/opencode/opencode_bridge.py index 7e6d229ca..ed9739587 100644 --- a/src/agent_env/agents/agents/opencode/opencode_bridge.py +++ b/src/agent_env/agents/agents/opencode/opencode_bridge.py @@ -811,7 +811,7 @@ def _output_limit_error(self) -> str | None: counts = (f" ({reasoning + text} tokens: {reasoning} reasoning + {text} text)" if isinstance(reasoning, int) and isinstance(text, int) else "") return (f"model hit the output token cap{counts} before finishing; " - "raise max_output_tokens in the opencode agent config") + "raise max_output_tokens on the prompt_agent step") _TAGS_HEADER = "x-litellm-tags" diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index d449ecce8..52ad8b3f0 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -223,8 +223,8 @@ def __init__(self, id: str, version: Optional[int], *, user_sim: str, end_time: scheduled_checks: Optional[bool] = None, scheduled_check_min_interval: str = CHECK_MIN_INTERVAL, contact_replies_in_parallel: bool = True, time_budget_seconds: Optional[float] = None, model: Optional[str] = None, model_params: Optional[dict] = None, effort: Optional[str] = None, - max_thinking_tokens: Optional[int] = None, harness: Optional[str] = None, - trajectory_output_prefix: Optional[str] = None, **prompt_fields: Any): + max_thinking_tokens: Optional[int] = None, max_output_tokens: Optional[int] = None, + harness: Optional[str] = None, trajectory_output_prefix: Optional[str] = None, **prompt_fields: Any): for unsupported in ("max_conversation_turns", "user_agent_name", "user_a2a_url", "post_turn_hooks", "user_output_format", "user_model", "snapshot_config"): prompt_fields.pop(unsupported, None) @@ -237,7 +237,7 @@ def __init__(self, id: str, version: Optional[int], *, user_sim: str, end_time: prompt_fields["prompt"] = "" # for prompt_agent's check; unset again below super().__init__(id, version, max_conversation_turns=max(1, int(max_wakes)), model=model, model_params=model_params, effort=effort, max_thinking_tokens=max_thinking_tokens, - harness=harness, trajectory_output_prefix=trajectory_output_prefix, **prompt_fields) + max_output_tokens=max_output_tokens, harness=harness, trajectory_output_prefix=trajectory_output_prefix, **prompt_fields) self.prompt = None if not user_sim: raise ValueError("always_on needs user_sim, the agent_name of a deploy_user_sim_agent step") @@ -266,7 +266,7 @@ def __init__(self, id: str, version: Optional[int], *, user_sim: str, end_time: "scheduled_checks", "scheduled_check_min_interval", "contact_replies_in_parallel", "time_budget_seconds") _PROMPT_FIELDS = ("prompt", "parts", "prompt_id", "agent_name", "timeout_seconds", "trajectory_output_prefix", "model", "model_params", "system_prompt", "max_turns", "output_format", "max_thinking_tokens", - "effort", "harness", "agentenv_tools", "poll_interval_seconds", "context_id") + "max_output_tokens", "effort", "harness", "agentenv_tools", "poll_interval_seconds", "context_id") def settle_cap_seconds(self, contact_seconds: float = CONTACT_TIMEOUT_DEFAULT_SECONDS) -> float: """The longest one settle waits, whatever is still at work (queued fires, nl actions in a row): the longest @@ -589,6 +589,7 @@ async def _configure_agents(self) -> None: "harness": ctx.agent_harness or step.harness, "max_turns": overrides.get("agent_max_turns") or step.max_turns, "max_thinking_tokens": overrides.get("agent_max_thinking_tokens") or step.max_thinking_tokens, + "max_output_tokens": overrides.get("agent_max_output_tokens") or step.max_output_tokens, "output_format": step.output_format, "timeout_seconds": step.timeout_seconds, "task_id": ctx.metadata.get("task_id"), "agentenv_tools": step.agentenv_tools, "builtin_tools": card.get("builtin_tools")} diff --git a/src/agent_env/task_step/task_steps/prompt_agent.py b/src/agent_env/task_step/task_steps/prompt_agent.py index 5af87308b..5ace00947 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -175,7 +175,8 @@ class PromptAgentTaskStep(TaskStep): ) # user_a2a_url stays the task's: setting it is also what tells a human counterpart from a simulator. field_scopes = {**TaskStep.field_scopes, **dict.fromkeys( - ("model", "model_params", "effort", "max_thinking_tokens", "harness", "user_model", "trajectory_output_prefix"), + ("model", "model_params", "effort", "max_thinking_tokens", "max_output_tokens", "harness", "user_model", + "trajectory_output_prefix"), FieldScope.USER)} DEFAULT_PROMPT_TIMEOUT_SECONDS: ClassVar[int] = 600 DEFAULT_POLL_INTERVAL_SECONDS: ClassVar[int] = 2 @@ -196,6 +197,7 @@ def __init__( max_turns: Optional[int] = None, output_format: Optional[dict[str, Any]] = None, max_thinking_tokens: Optional[int] = None, + max_output_tokens: Optional[int] = None, effort: Optional[str] = None, harness: Optional[str] = None, agentenv_tools: Optional[list[str]] = None, @@ -246,6 +248,7 @@ def __init__( self.max_turns = max_turns self.output_format = output_format self.max_thinking_tokens = max_thinking_tokens + self.max_output_tokens = max_output_tokens self.effort = effort self.harness = harness self.agentenv_tools = agentenv_tools @@ -302,6 +305,7 @@ def to_dict(self) -> dict: base["max_turns"] = self.max_turns base["output_format"] = self.output_format base["max_thinking_tokens"] = self.max_thinking_tokens + base["max_output_tokens"] = self.max_output_tokens base["effort"] = self.effort base["harness"] = self.harness base["agentenv_tools"] = self.agentenv_tools @@ -338,6 +342,7 @@ def from_dict(cls, data: dict) -> PromptAgentTaskStep: max_turns=data.get("max_turns"), output_format=data.get("output_format"), max_thinking_tokens=data.get("max_thinking_tokens"), + max_output_tokens=data.get("max_output_tokens"), effort=data.get("effort"), harness=data.get("harness"), agentenv_tools=data.get("agentenv_tools"), @@ -548,13 +553,14 @@ async def _converse( harness = context.agent_harness or self.harness overrides = context.metadata.get("user_overrides", {}) max_thinking_tokens = overrides.get("agent_max_thinking_tokens") or self.max_thinking_tokens + max_output_tokens = overrides.get("agent_max_output_tokens") or self.max_output_tokens max_turns = overrides.get("agent_max_turns") or self.max_turns card = agent.a2a_card or {} desired_config = { "model": model, "system_prompt": system_prompt, "effort": effort, "harness": harness, "max_turns": max_turns, - "max_thinking_tokens": max_thinking_tokens, + "max_thinking_tokens": max_thinking_tokens, "max_output_tokens": max_output_tokens, "output_format": self.output_format, "timeout_seconds": self.timeout_seconds, "task_id": context.metadata.get("task_id"), "agentenv_tools": self.agentenv_tools, diff --git a/tst/unit/agents/opencode/test_opencode_bridge_events.py b/tst/unit/agents/opencode/test_opencode_bridge_events.py index bab957f0a..51ff6d0b0 100644 --- a/tst/unit/agents/opencode/test_opencode_bridge_events.py +++ b/tst/unit/agents/opencode/test_opencode_bridge_events.py @@ -110,7 +110,7 @@ def test_a_turn_cut_off_at_the_output_cap_fails_with_its_token_counts(): assert result.error_code == "output_token_limit" assert result.error == ("model hit the output token cap (32000 tokens: 31998 reasoning + 2 text) before " - "finishing; raise max_output_tokens in the opencode agent config") + "finishing; raise max_output_tokens on the prompt_agent step") def test_the_output_cap_error_wins_over_stderr_and_does_without_token_counts(): diff --git a/tst/unit/task_step/always_on_harness.py b/tst/unit/task_step/always_on_harness.py index 6e54277ed..4a86bbd5c 100644 --- a/tst/unit/task_step/always_on_harness.py +++ b/tst/unit/task_step/always_on_harness.py @@ -33,7 +33,8 @@ # An agent card whose agent-config extension takes the settings the step sends. CONFIG_CARD = {"capabilities": {"extensions": [{"uri": A2AAgent.EXT_AGENT_CONFIG, "params": { "endpoint": "/ext/agent-config", "methods": {"set": {"request": {"supported": [ - "model", "system_prompt", "effort", "output_format", "timeout_seconds", "max_turns"]}}}}}]}} + "model", "system_prompt", "effort", "output_format", "timeout_seconds", "max_turns", + "max_output_tokens"]}}}}}]}} diff --git a/tst/unit/task_step/test_always_on_agent_and_gateway.py b/tst/unit/task_step/test_always_on_agent_and_gateway.py index 4a42f3ad2..3ff64f9f5 100644 --- a/tst/unit/task_step/test_always_on_agent_and_gateway.py +++ b/tst/unit/task_step/test_always_on_agent_and_gateway.py @@ -42,6 +42,22 @@ async def test_the_rules_go_in_the_system_prompt_when_the_agent_takes_it(monkeyp assert rig.record(ctx)["settings"]["rules_via"] == "system_prompt" +@pytest.mark.asyncio +@pytest.mark.parametrize("overrides, sent", [({}, 64000), ({"agent_max_output_tokens": 96000}, 96000)]) +async def test_the_step_s_max_output_tokens_reaches_the_agent_and_a_run_s_override_wins(monkeypatch, tmp_path, + overrides, sent): + rig = Rig(monkeypatch, tmp_path, takes_config=True) + await rig.arm() + ctx = rig.context() + ctx.metadata["user_overrides"] = overrides + step = rig.step(max_output_tokens=64000) + await rig.run(step, ctx) + + [(_, fields)] = [(u, f) for u, f in rig.configs if u.startswith(SOLVER)] + assert fields["max_output_tokens"] == sent + assert ao.AlwaysOnTaskStep.from_dict(step.to_dict()).max_output_tokens == 64000 + + @pytest.mark.asyncio async def test_the_step_s_context_id_is_the_agent_s_session(monkeypatch, tmp_path): def agent(n, texts, rig): diff --git a/tst/unit/task_step/test_prompt_agent_max_output_tokens.py b/tst/unit/task_step/test_prompt_agent_max_output_tokens.py new file mode 100644 index 000000000..543a3ff29 --- /dev/null +++ b/tst/unit/task_step/test_prompt_agent_max_output_tokens.py @@ -0,0 +1,85 @@ +"""prompt_agent's max_output_tokens: stored with the step, replaced by a run's agent_max_output_tokens, and sent in the +agent config only to an agent whose card takes it.""" + +from unittest.mock import MagicMock + +import pytest +from a2a.types import TaskState + +from agent_env.a2a_agent import A2AAgent +from agent_env.task_step.context import DeployedAgent, TaskStepContext +from agent_env.task_step.task_steps import prompt_agent as pa_mod +from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep + + +@pytest.fixture +def posted(monkeypatch): + """Mocks the turn's HTTP and store boundary, and collects each agent config posted.""" + cfg = MagicMock() + cfg.get_model_params.return_value = {} + cfg.get_model_for_role.return_value = None + monkeypatch.setattr(pa_mod, "get_config", lambda: cfg) + for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): + monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None) + configs = [] + + async def post_agent_config(url, fields, headers=None): + configs.append(fields) + + async def send(url, parts, message_id, context_id, timeout): + return f"task-{message_id}", None + + async def poll(url, task_id, timeout, interval, **_): + return {"status": {"state": TaskState.completed, "message": {"parts": [{"kind": "text", "text": "done"}]}}} + + monkeypatch.setattr(pa_mod.protocol, "post_agent_config", post_agent_config) + monkeypatch.setattr(pa_mod.protocol, "send_a2a_message", send) + monkeypatch.setattr(pa_mod.protocol, "poll_a2a_task", poll) + return configs + + +def _context(supported: list[str], overrides: dict | None = None) -> TaskStepContext: + card = {"capabilities": {"extensions": [{"uri": A2AAgent.EXT_AGENT_CONFIG, "params": { + "endpoint": "/ext/agent-config", "methods": {"set": {"request": {"supported": supported}}}}}]}} + context = TaskStepContext(instance_id="ti-1", metadata={"user_overrides": overrides} if overrides else {}) + context.deployed_agents.append(DeployedAgent(agent_name="solver", api_url="http://solver", a2a_url="http://solver", + a2a_card=card)) + return context + + +def _step(**fields) -> PromptAgentTaskStep: + return PromptAgentTaskStep.from_dict({"id": "p", "version": 1, "prompt": "go", "agent_name": "solver", **fields}) + + +def test_max_output_tokens_round_trips(): + assert PromptAgentTaskStep.from_dict(_step(max_output_tokens=64000).to_dict()).max_output_tokens == 64000 + assert _step().max_output_tokens is None + + +@pytest.mark.asyncio +async def test_the_steps_max_output_tokens_reaches_an_agent_that_takes_it(posted): + await _step(max_output_tokens=64000).execute(_context(["model", "max_output_tokens"])) + + assert [fields.get("max_output_tokens") for fields in posted] == [64000] + + +@pytest.mark.asyncio +async def test_a_runs_override_replaces_the_steps_max_output_tokens(posted): + await _step(max_output_tokens=64000).execute( + _context(["model", "max_output_tokens"], {"agent_max_output_tokens": 96000})) + + assert [fields.get("max_output_tokens") for fields in posted] == [96000] + + +@pytest.mark.asyncio +async def test_an_agent_whose_card_does_not_take_it_is_not_sent_max_output_tokens(posted): + await _step(max_output_tokens=64000, model="m").execute(_context(["model"])) + + assert posted and all("max_output_tokens" not in fields for fields in posted) + + +@pytest.mark.asyncio +async def test_an_unset_max_output_tokens_is_not_sent(posted): + await _step(model="m").execute(_context(["model", "max_output_tokens"])) + + assert posted and all("max_output_tokens" not in fields for fields in posted)