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
2 changes: 1 addition & 1 deletion src/agent_env/agents/agents/opencode/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>/`, where OpenCode finds them |
| `trajectory/v1` | the task's `opencode run --format json` events, live while it runs (format `opencode-events/1`) |
Expand Down
3 changes: 3 additions & 0 deletions src/agent_env/agents/agents/opencode/a2a_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
42 changes: 39 additions & 3 deletions src/agent_env/agents/agents/opencode/opencode_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 {}),
}},
}
},
Expand Down Expand Up @@ -468,14 +475,18 @@ 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
``_permission`` describes; the tools of ``mcp_servers`` stay offered with any selection.

``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:
Expand All @@ -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 <session_id>` does. First turn
Expand All @@ -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())})")
Expand Down Expand Up @@ -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] = []
Expand Down Expand Up @@ -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

Expand All @@ -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]
Expand All @@ -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"

Expand Down
9 changes: 5 additions & 4 deletions src/agent_env/task_step/task_steps/always_on.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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")
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")}
Expand Down
10 changes: 8 additions & 2 deletions src/agent_env/task_step/task_steps/prompt_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions tst/unit/agents/opencode/test_message_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 36 additions & 1 deletion tst/unit/agents/opencode/test_opencode_bridge_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Loading
Loading