diff --git a/src/agent_env/agents/agents/opencode/README.md b/src/agent_env/agents/agents/opencode/README.md index 4a464cfc7..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`), `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/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 67c2b465c..025cd3107 100644 --- a/src/agent_env/agents/agents/opencode/opencode_bridge.py +++ b/src/agent_env/agents/agents/opencode/opencode_bridge.py @@ -47,6 +47,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. @@ -287,6 +291,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, armed: bool = False, ) -> dict: """Assemble the inline OpenCode config passed via OPENCODE_CONFIG_CONTENT. @@ -331,6 +336,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 {}), }}, } }, @@ -468,6 +475,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 @@ -475,7 +483,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: @@ -495,7 +506,8 @@ async def _run_opencode( armed = clock_armed() 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, armed=armed) + instructions=instructions, builtin_tools=builtin_tools, + max_output_tokens=max_output_tokens, armed=armed) # Resume a specific session by id (multi-turn continuity). `--continue` # does NOT replay history to the model; `-s ` does. First turn @@ -518,6 +530,7 @@ async def _run_opencode( env = { **cli_env(context_id, mcp_servers=mcp_servers, clock_armed=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())})") @@ -666,6 +679,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] = [] @@ -751,6 +766,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 @@ -769,11 +787,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] @@ -785,9 +809,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 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 ed9d4d98a..e503ae082 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_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 83edd80bd..1adb39ed5 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 @@ -226,3 +226,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..51ff6d0b0 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 on the prompt_agent step") + + +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) 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)