From b6cf192a3d2f8a8a41e5812c358826cf95c2f6a7 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sat, 21 Nov 2026 16:21:58 -0800 Subject: [PATCH 1/8] fix(agents): OpenCode keeps its sessions on the env's clock at any date OpenCode orders a session's messages by when they were written and takes no time before 1970, so on the env's clock a set behind earlier messages scrambled the history and broke the next turn, and a clock in 1950 broke every turn. Its bridge now starts the CLI on real time, so the commands it runs still read the env's time, and an OpenCode plugin puts the env's date, read from a command, in the prompt's date line and the websearch tool's year. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/README.md | 4 + .../agents/agents/opencode/Dockerfile | 2 +- .../agents/agents/opencode/env_date.js | 32 ++++++ .../agents/agents/opencode/install.sh | 2 +- .../agents/agents/opencode/opencode_bridge.py | 10 +- tst/unit/agents/opencode/test_env_clock.py | 101 +++++++++++++++++- .../test_opencode_bridge_builtin_tools.py | 3 +- 7 files changed, 147 insertions(+), 7 deletions(-) create mode 100644 src/agent_env/agents/agents/opencode/env_date.js diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index e174e5c8e..4aa815c89 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -49,6 +49,10 @@ The A2A server starts with the real-time marker, so it and its records stay on r follower's config, which the server writes; `deploy_agent` does the same for an agent it deploys while that clock is armed. From then on the CLI, its own "Today's date is" line included, and every command the model runs read the env's time, and a clock write that waits for followers waits for the agent. +- **OpenCode's CLI on real time.** OpenCode orders a session's messages by when they were written and takes no time + before 1970, so a clock set behind a session's messages broke it. Its bridge starts the CLI with the real-time marker + instead: the commands it runs read the env's time, and its plugin, `env_date.js`, puts the env's date, read from a + command, in the prompt's "Today's date" line and the websearch tool's year, failing the turn when it can't read it. - **For the rest of the run.** An agent that follows goes on following: a later `sync_env_clock` without `agent_clock` re-arms the clock it follows, and only agents that never followed keep real time. - **Through the egress proxy.** While the agent follows an armed clock, the CLI goes out through the egress proxy, which diff --git a/src/agent_env/agents/agents/opencode/Dockerfile b/src/agent_env/agents/agents/opencode/Dockerfile index 1b18c8479..21aa523ab 100644 --- a/src/agent_env/agents/agents/opencode/Dockerfile +++ b/src/agent_env/agents/agents/opencode/Dockerfile @@ -39,7 +39,7 @@ RUN npm ci --ignore-scripts --omit=dev --no-audit --no-fund --loglevel=error && COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt # install.sh and run.sh are install/v1's: in the image, so they stay in its build context. -COPY a2a_server.py opencode_bridge.py opencode_kit.py entrypoint.sh install.sh run.sh ./ +COPY a2a_server.py opencode_bridge.py opencode_kit.py env_date.js entrypoint.sh install.sh run.sh ./ # Every clocked agent's egress rule, which the bridge imports, the clock page's format it reads, and the model relay # that counts the turn's model calls (shared_sources.toml). COPY agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py ./ diff --git a/src/agent_env/agents/agents/opencode/env_date.js b/src/agent_env/agents/agents/opencode/env_date.js new file mode 100644 index 000000000..e3004b571 --- /dev/null +++ b/src/agent_env/agents/agents/opencode/env_date.js @@ -0,0 +1,32 @@ +// OpenCode's plugin for the env's date. The bridge starts the CLI on real time, so a session's records sort in the +// order they were written at any date the env's clock shows; what the CLI starts, a command, reads the env's time, so +// the date the CLI tells the model is read the same way. A read that fails fails the turn rather than show real time. +import { execFileSync } from "node:child_process" + +const ENV_DATE = /([\s\S]*?\n {2}Today's date: )[^\n]*/ +const SEARCH_YEAR = /The current year is -?\d+\./ + +function envNow() { + const { AGENTENV_REAL_TIME: _, ...env } = process.env + const [seconds, nanoseconds] = execFileSync("date", ["+%s %N"], { encoding: "utf8", env }).trim().split(" ") + const now = new Date(Number(seconds) * 1000 + Math.floor(Number(nanoseconds) / 1e6)) + if (Number.isNaN(now.getTime())) throw new Error(`the env's date: unreadable "${seconds} ${nanoseconds}"`) + return now +} + +export default { + id: "agentenv-env-date", + server: async () => ({ + "experimental.chat.system.transform": async (_input, output) => { + const today = envNow().toDateString() + output.system.forEach((part, i) => { + output.system[i] = part.replace(ENV_DATE, (_match, head) => head + today) + }) + }, + "tool.definition": async (input, output) => { + if (input.toolID !== "websearch") return + const year = envNow().getFullYear() + output.description = output.description.replace(SEARCH_YEAR, () => `The current year is ${year}.`) + }, + }), +} diff --git a/src/agent_env/agents/agents/opencode/install.sh b/src/agent_env/agents/agents/opencode/install.sh index 2eb3d29a6..2cd09c69e 100755 --- a/src/agent_env/agents/agents/opencode/install.sh +++ b/src/agent_env/agents/agents/opencode/install.sh @@ -24,7 +24,7 @@ START_TIMEOUT_S=120 STOP_TIMEOUT_S=10 dockerfile_arg() { sed -n "s/^ARG $1=//p" "$here/Dockerfile"; } NODE_VERSION=$(dockerfile_arg NODE_VERSION) -AGENT_FILES="a2a_server.py opencode_bridge.py opencode_kit.py requirements.txt run.sh agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py" +AGENT_FILES="a2a_server.py opencode_bridge.py opencode_kit.py env_date.js requirements.txt run.sh agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py" # put SRC DEST replaces DEST by a rename, so a binary an earlier install's agent still runs can be replaced; put_dir SRC # DEST copies a folder to DEST, which isn't there. diff --git a/src/agent_env/agents/agents/opencode/opencode_bridge.py b/src/agent_env/agents/agents/opencode/opencode_bridge.py index 4bbc97803..d4c9745db 100644 --- a/src/agent_env/agents/agents/opencode/opencode_bridge.py +++ b/src/agent_env/agents/agents/opencode/opencode_bridge.py @@ -45,6 +45,8 @@ 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" +# The CLI's plugin that tells the model the env's date (env_date.js), beside this file in the image and in an install. +ENV_DATE_PLUGIN = Path(__file__).with_name("env_date.js") # 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. @@ -104,9 +106,12 @@ def cli_env(context_id: str, environ: Mapping[str, str] = os.environ, *, mcp_ser clock_armed: bool = False) -> dict[str, str]: """The CLI's environment for ``context_id``: this process's, with the context's own data and state dirs, and on an armed clock the egress proxy (``egress_env``) for the model endpoint and the env's MCP servers, which the CLI - connects to itself.""" + connects to itself. The CLI starts on real time: it orders a session's messages by when they were written and + takes no time before 1970, so on the env's clock a set behind them broke the session. What it starts, the model's + commands, reads the env's time, as does the date its plugin tells the model (``ENV_DATE_PLUGIN``).""" urls = [environ.get("LITELLM_BASE_URL", ""), *(info["url"] for info in (mcp_servers or {}).values())] - return {**environ, **_context_xdg(context_id), **egress_env(environ, urls, armed=clock_armed)} + return {**environ, **_context_xdg(context_id), **egress_env(environ, urls, armed=clock_armed), + "AGENTENV_REAL_TIME": "1"} async def _communicate(*cmd: str, env: Mapping[str, str], timeout_s: int) -> tuple[int, bytes, bytes]: @@ -333,6 +338,7 @@ def _build_config( # selects otherwise. "permission": _permission(builtin_tools, mcp_servers), "autoupdate": False, + "plugin": [ENV_DATE_PLUGIN.as_uri()], } if instructions: config["instructions"] = list(instructions) diff --git a/tst/unit/agents/opencode/test_env_clock.py b/tst/unit/agents/opencode/test_env_clock.py index 67d69e5f9..7b8510fd4 100644 --- a/tst/unit/agents/opencode/test_env_clock.py +++ b/tst/unit/agents/opencode/test_env_clock.py @@ -1,10 +1,15 @@ """OpenCode on the env's clock: its bridge hands the shared egress rule (tst/unit/agents/test_agent_egress.py) the model endpoint's URL and every MCP server's, which the CLI connects to itself, so on an armed clock it goes out through the image's egress proxy, and to loopback, the hosts NO_PROXY names and plain-HTTP hosts directly; unarmed, it goes out -as before. What every clocked image shares is checked in tst/unit/agents/test_agent_clock_images.py.""" +as before. The CLI itself runs on real time and its plugin (env_date.js) tells the model the env's date, which it reads +from a command as the model's own commands do. What every clocked image shares is checked in +tst/unit/agents/test_agent_clock_images.py.""" from __future__ import annotations +import json +import re +import shutil import subprocess import pytest @@ -37,7 +42,99 @@ def test_without_the_proxy_or_an_armed_clock_the_cli_goes_out_directly_as_before env = opencode_bridge.cli_env("ctx", environ, clock_armed=armed) assert not {"HTTPS_PROXY", "NO_PROXY"} & set(env) - assert set(env) == {*environ, "XDG_DATA_HOME", "XDG_STATE_HOME"} + assert set(env) == {*environ, "XDG_DATA_HOME", "XDG_STATE_HOME", "AGENTENV_REAL_TIME"} + + +@pytest.mark.parametrize("armed", [True, False]) +def test_the_cli_starts_on_real_time_so_its_sessions_keep_their_order_at_any_env_date(armed): + """libfaketime takes the marker out of the CLI's environment, so what the CLI starts reads the env's time.""" + env = opencode_bridge.cli_env("ctx", {agent_egress.EGRESS_PROXY_ENV: PROXY}, clock_armed=armed) + + assert env["AGENTENV_REAL_TIME"] == "1" + + +def test_every_turn_loads_the_date_plugin_which_the_image_and_an_install_carry_beside_the_bridge(): + config = opencode_bridge._build_config("m", None, {}, None) + + assert config["plugin"] == [(AGENT_DIR / "env_date.js").as_uri()] + assert opencode_bridge.ENV_DATE_PLUGIN == AGENT_DIR / "env_date.js" and opencode_bridge.ENV_DATE_PLUGIN.is_file() + assert re.search(r"^COPY .*\benv_date\.js\b.* \./$", (AGENT_DIR / "Dockerfile").read_text(), re.MULTILINE) + assert "env_date.js" in re.search(r'^AGENT_FILES="([^"]+)"$', (AGENT_DIR / "install.sh").read_text(), + re.MULTILINE).group(1).split() + + +# OpenCode's system prompt as its SystemPrompt.environment writes it (opencode-ai 1.17.18, src/session/system.ts). +SYSTEM = ("You are OpenCode, the best coding agent on the planet.\n" + "You are powered by the model named m. The exact model ID is litellm/m\n" + "Here is some useful information about the environment you are running in:\n\n" + " Working directory: /app\n Workspace root folder: /app\n Is directory a git repo: no\n" + " Platform: linux\n Today's date: Sat Nov 21 2026\n\n" + "The task's notes say: Today's date: as written") +HARNESS = """ +const plugin = (await import(process.argv[1])).default +const hooks = await plugin.server({}) +const out = { system: JSON.parse(process.argv[2]) } +const search = { description: "Searches the web. The current year is 2026. You MUST use this year.", parameters: {} } +const other = { description: "The current year is 2026.", parameters: {} } +try { + await hooks["experimental.chat.system.transform"]({ model: {} }, out) + await hooks["tool.definition"]({ toolID: "websearch" }, search) + await hooks["tool.definition"]({ toolID: "bash" }, other) +} catch (error) { + console.log(JSON.stringify({ error: String(error.message) })) + process.exit(0) +} +console.log(JSON.stringify({ id: plugin.id, system: out.system, search: search.description, other: other.description })) +""" + + +def _plugin(tmp_path, date_out: str | None, system: list[str] = [SYSTEM]) -> tuple[dict, str]: + """The plugin run by node as the CLI's Bun runs it, with a ``date`` that prints ``date_out`` (fails when None) + and records the environment it got.""" + node = shutil.which("node") + assert node, "node runs the CLI plugin's test" + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + (bin_dir / "date").write_text('#!/bin/sh\nenv > "$FAKE_DATE_ENV"\n[ "$1" = "+%s %N" ] || exit 2\n' + '[ -n "$FAKE_DATE_OUT" ] || exit 1\necho "$FAKE_DATE_OUT"\n') + (bin_dir / "date").chmod(0o755) + plugin = tmp_path / "env_date.mjs" + shutil.copy(AGENT_DIR / "env_date.js", plugin) + env = {"PATH": f"{bin_dir}:/usr/bin:/bin", "TZ": "UTC", "AGENTENV_REAL_TIME": "1", + "FAKE_DATE_ENV": str(tmp_path / "date.env"), **({"FAKE_DATE_OUT": date_out} if date_out else {})} + done = subprocess.run([node, "--input-type=module", "-e", HARNESS, plugin.as_uri(), json.dumps(system)], + capture_output=True, text=True, env=env, timeout=30, check=True) + return json.loads(done.stdout), (tmp_path / "date.env").read_text() + + +@pytest.mark.parametrize("date_out, today, year", [ + ("1801742400 000000000", "Thu Feb 04 2027", 2027), + ("7258161600 250000000", "Wed Jan 01 2200", 2200), + ("-631108800 000000000", "Sun Jan 01 1950", 1950), + # Half a second before 1950: date prints the second below and a positive fraction. + ("-631152001 500000000", "Sat Dec 31 1949", 1949), +]) +def test_the_plugin_tells_the_model_the_env_date_a_command_reads(tmp_path, date_out, today, year): + result, child_env = _plugin(tmp_path, date_out) + + assert result["id"] == "agentenv-env-date" + assert result["system"] == [SYSTEM.replace("Today's date: Sat Nov 21 2026", f"Today's date: {today}")] + assert result["search"] == f"Searches the web. The current year is {year}. You MUST use this year." + assert result["other"] == "The current year is 2026." + assert "AGENTENV_REAL_TIME" not in child_env and "TZ=UTC" in child_env + + +def test_the_plugin_leaves_a_prompt_without_the_env_block_alone(tmp_path): + system = ["You are a subagent.\nToday's date: whatever the task says"] + + assert _plugin(tmp_path, "1801742400 000000000", system)[0]["system"] == system + + +@pytest.mark.parametrize("date_out", [None, "not a time"]) +def test_a_date_the_plugin_cant_read_fails_the_turn_rather_than_show_real_time(tmp_path, date_out): + result, _ = _plugin(tmp_path, date_out) + + assert result["error"] @pytest.mark.parametrize("base_url, direct", [("http://10.0.0.5:4000", True), ("https://litellm.example.com", False)]) diff --git a/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py b/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py index 75bee09fe..63ad2e5a9 100644 --- a/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py +++ b/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py @@ -49,7 +49,7 @@ async def _exec(*cmd, **kwargs): def test_no_selection_leaves_the_config_and_argv_as_they_were(monkeypatch, spawned): """The whole config and argv of a turn without a selection, as origin/main builds them, except that the prompt - goes on stdin rather than as the positional message.""" + goes on stdin rather than as the positional message and the date plugin is loaded.""" monkeypatch.setenv("LITELLM_BASE_URL", "https://gateway.example") monkeypatch.delenv("LITELLM_EXTRA_HEADERS", raising=False) @@ -72,6 +72,7 @@ def test_no_selection_leaves_the_config_and_argv_as_they_were(monkeypatch, spawn "model": "litellm/m", "permission": {"*": "allow", "question": "deny"}, "autoupdate": False, + "plugin": [opencode_bridge.ENV_DATE_PLUGIN.as_uri()], "mcp": {"env": {"type": "remote", "url": "https://gw/mcp", "enabled": True}}, }) From 7b00c0a48bc182ed8e17b9fe9dcdcde4f96bae88 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 22 Nov 2026 08:15:36 -0800 Subject: [PATCH 2/8] fix(agents): OpenCode's model relay, not a CLI plugin, tells the model the env's date An OpenCode plugin makes every CLI start wait on OpenCode installing its plugin package from npm, which hangs every turn where npm can't be reached and writes the package into a workspace's .opencode folder, and a plugin that doesn't load tells the model the real date without a word. The turn's model relay, which every model call the CLI makes goes through, now puts the env's date in each call while the clock is armed, refusing a call whose date it can't read or whose env block it doesn't know. The CLI starts on real time only where the image follows the clock. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/README.md | 8 +- .../agents/agents/opencode/Dockerfile | 2 +- .../agents/agents/opencode/env_date.js | 32 --- .../agents/agents/opencode/install.sh | 2 +- .../agents/agents/opencode/opencode_bridge.py | 92 ++++++++- .../utils/model_relay/model_relay.py | 23 ++- tst/unit/agents/opencode/test_env_clock.py | 182 +++++++++++------- .../test_opencode_bridge_builtin_tools.py | 3 +- tst/unit/agents/test_model_relay.py | 30 +++ 9 files changed, 253 insertions(+), 121 deletions(-) delete mode 100644 src/agent_env/agents/agents/opencode/env_date.js diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index 4aa815c89..d84731cc1 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -50,9 +50,11 @@ The A2A server starts with the real-time marker, so it and its records stay on r armed. From then on the CLI, its own "Today's date is" line included, and every command the model runs read the env's time, and a clock write that waits for followers waits for the agent. - **OpenCode's CLI on real time.** OpenCode orders a session's messages by when they were written and takes no time - before 1970, so a clock set behind a session's messages broke it. Its bridge starts the CLI with the real-time marker - instead: the commands it runs read the env's time, and its plugin, `env_date.js`, puts the env's date, read from a - command, in the prompt's "Today's date" line and the websearch tool's year, failing the turn when it can't read it. + before 1970, so a clock set behind a session's messages broke it. Where the image follows the clock, its bridge + starts the CLI with the real-time marker instead, so the commands it runs read the env's time, and the turn's model + relay puts the env's date, read from `date` as those commands read it, in the prompt's "Today's date" line and the + websearch tool's year while the clock is armed. A call whose date can't be read, or whose `` block has no date + line the relay knows, is refused, failing the turn rather than telling the model the real date. - **For the rest of the run.** An agent that follows goes on following: a later `sync_env_clock` without `agent_clock` re-arms the clock it follows, and only agents that never followed keep real time. - **Through the egress proxy.** While the agent follows an armed clock, the CLI goes out through the egress proxy, which diff --git a/src/agent_env/agents/agents/opencode/Dockerfile b/src/agent_env/agents/agents/opencode/Dockerfile index 21aa523ab..1b18c8479 100644 --- a/src/agent_env/agents/agents/opencode/Dockerfile +++ b/src/agent_env/agents/agents/opencode/Dockerfile @@ -39,7 +39,7 @@ RUN npm ci --ignore-scripts --omit=dev --no-audit --no-fund --loglevel=error && COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt # install.sh and run.sh are install/v1's: in the image, so they stay in its build context. -COPY a2a_server.py opencode_bridge.py opencode_kit.py env_date.js entrypoint.sh install.sh run.sh ./ +COPY a2a_server.py opencode_bridge.py opencode_kit.py entrypoint.sh install.sh run.sh ./ # Every clocked agent's egress rule, which the bridge imports, the clock page's format it reads, and the model relay # that counts the turn's model calls (shared_sources.toml). COPY agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py ./ diff --git a/src/agent_env/agents/agents/opencode/env_date.js b/src/agent_env/agents/agents/opencode/env_date.js deleted file mode 100644 index e3004b571..000000000 --- a/src/agent_env/agents/agents/opencode/env_date.js +++ /dev/null @@ -1,32 +0,0 @@ -// OpenCode's plugin for the env's date. The bridge starts the CLI on real time, so a session's records sort in the -// order they were written at any date the env's clock shows; what the CLI starts, a command, reads the env's time, so -// the date the CLI tells the model is read the same way. A read that fails fails the turn rather than show real time. -import { execFileSync } from "node:child_process" - -const ENV_DATE = /([\s\S]*?\n {2}Today's date: )[^\n]*/ -const SEARCH_YEAR = /The current year is -?\d+\./ - -function envNow() { - const { AGENTENV_REAL_TIME: _, ...env } = process.env - const [seconds, nanoseconds] = execFileSync("date", ["+%s %N"], { encoding: "utf8", env }).trim().split(" ") - const now = new Date(Number(seconds) * 1000 + Math.floor(Number(nanoseconds) / 1e6)) - if (Number.isNaN(now.getTime())) throw new Error(`the env's date: unreadable "${seconds} ${nanoseconds}"`) - return now -} - -export default { - id: "agentenv-env-date", - server: async () => ({ - "experimental.chat.system.transform": async (_input, output) => { - const today = envNow().toDateString() - output.system.forEach((part, i) => { - output.system[i] = part.replace(ENV_DATE, (_match, head) => head + today) - }) - }, - "tool.definition": async (input, output) => { - if (input.toolID !== "websearch") return - const year = envNow().getFullYear() - output.description = output.description.replace(SEARCH_YEAR, () => `The current year is ${year}.`) - }, - }), -} diff --git a/src/agent_env/agents/agents/opencode/install.sh b/src/agent_env/agents/agents/opencode/install.sh index 2cd09c69e..2eb3d29a6 100755 --- a/src/agent_env/agents/agents/opencode/install.sh +++ b/src/agent_env/agents/agents/opencode/install.sh @@ -24,7 +24,7 @@ START_TIMEOUT_S=120 STOP_TIMEOUT_S=10 dockerfile_arg() { sed -n "s/^ARG $1=//p" "$here/Dockerfile"; } NODE_VERSION=$(dockerfile_arg NODE_VERSION) -AGENT_FILES="a2a_server.py opencode_bridge.py opencode_kit.py env_date.js requirements.txt run.sh agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py" +AGENT_FILES="a2a_server.py opencode_bridge.py opencode_kit.py requirements.txt run.sh agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py" # put SRC DEST replaces DEST by a rename, so a binary an earlier install's agent still runs can be replaced; put_dir SRC # DEST copies a folder to DEST, which isn't there. diff --git a/src/agent_env/agents/agents/opencode/opencode_bridge.py b/src/agent_env/agents/agents/opencode/opencode_bridge.py index d4c9745db..8655fca16 100644 --- a/src/agent_env/agents/agents/opencode/opencode_bridge.py +++ b/src/agent_env/agents/agents/opencode/opencode_bridge.py @@ -23,6 +23,7 @@ import re import signal import threading +import time from collections.abc import Callable, Mapping from dataclasses import dataclass, field from datetime import datetime, timezone @@ -34,7 +35,8 @@ from agent_egress import clock_armed, egress_env from agentenv_protocol.a2a_agent import Usage -from model_relay import Calls, model_relay +from agentenv_protocol.a2a_agent.clock import follows +from model_relay import Calls, Refusal, model_relay logger = logging.getLogger(__name__) @@ -45,8 +47,13 @@ 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" -# The CLI's plugin that tells the model the env's date (env_date.js), beside this file in the image and in an install. -ENV_DATE_PLUGIN = Path(__file__).with_name("env_date.js") +# Where the CLI, on real time, puts its own date in a model call: the block's line in its system prompt and the +# websearch tool's year, as TOOLS_CLI_VERSION writes them (src/session/system.ts, src/tool/websearch.txt). +_ENV_DATE = re.compile(r"(\n(?: [^\n]*\n)*? Today's date: )[^\n]*") +_SEARCH_YEAR = re.compile(r"The current year is -?\d+\.") +_DATE_TIMEOUT_S = 5 +_DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") +_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") # 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. @@ -106,12 +113,13 @@ def cli_env(context_id: str, environ: Mapping[str, str] = os.environ, *, mcp_ser clock_armed: bool = False) -> dict[str, str]: """The CLI's environment for ``context_id``: this process's, with the context's own data and state dirs, and on an armed clock the egress proxy (``egress_env``) for the model endpoint and the env's MCP servers, which the CLI - connects to itself. The CLI starts on real time: it orders a session's messages by when they were written and - takes no time before 1970, so on the env's clock a set behind them broke the session. What it starts, the model's - commands, reads the env's time, as does the date its plugin tells the model (``ENV_DATE_PLUGIN``).""" + connects to itself. Where the image follows the env's clock, the CLI starts on real time: it orders a session's + messages by when they were written and takes no time before 1970, so on the env's clock a set behind them broke + the session. What it starts, the model's commands, reads the env's time, and the relay puts the env's date in the + model calls (``env_date_rewrite``).""" urls = [environ.get("LITELLM_BASE_URL", ""), *(info["url"] for info in (mcp_servers or {}).values())] return {**environ, **_context_xdg(context_id), **egress_env(environ, urls, armed=clock_armed), - "AGENTENV_REAL_TIME": "1"} + **({"AGENTENV_REAL_TIME": "1"} if follows() else {})} async def _communicate(*cmd: str, env: Mapping[str, str], timeout_s: int) -> tuple[int, bytes, bytes]: @@ -129,6 +137,70 @@ async def _communicate(*cmd: str, env: Mapping[str, str], timeout_s: int) -> tup return proc.returncode, out, err +async def _env_today() -> tuple[str, int]: + """The env's date, as the CLI's ``Date.toDateString()`` writes one in this zone, and its year, read from ``date``, + which libfaketime fakes for what this server starts, as for the model's commands.""" + environ = {name: value for name, value in os.environ.items() if name != "AGENTENV_REAL_TIME"} + try: + code, out, err = await _communicate("date", "+%s %N", env=environ, timeout_s=_DATE_TIMEOUT_S) + seconds, _ = out.decode().split() + day = time.localtime(int(seconds)) + except (OSError, ValueError, OverflowError, TimeoutError) as exc: + raise Refusal(f"the env's date couldn't be read for the model: {type(exc).__name__}: {exc}") from exc + if code != 0: + raise Refusal(f"the env's date couldn't be read for the model: date exited {code}: " + f"{err.decode(errors='replace')[:200]}") + return f"{_DAYS[day.tm_wday]} {_MONTHS[day.tm_mon - 1]} {day.tm_mday:02d} {day.tm_year:04d}", day.tm_year + + +def _texts(request: dict, roles: tuple[str, ...]): + """Each text of the request's messages in ``roles``, as (holder, key).""" + for message in request.get("messages") or []: + if not isinstance(message, dict) or message.get("role") not in roles: + continue + content = message.get("content") + if isinstance(content, str): + yield message, "content" + elif isinstance(content, list): + yield from ((part, "text") for part in content if isinstance(part, dict) and isinstance(part.get("text"), str)) + + +def _search_descriptions(request: dict): + for tool in request.get("tools") or []: + function = tool.get("function") if isinstance(tool, dict) else None + if isinstance(function, dict) and function.get("name") == "websearch" \ + and isinstance(function.get("description"), str): + yield function, "description" + + +async def env_date_rewrite(body: bytes) -> bytes: + """A model call as the CLI, on real time, wrote it, with the env's date where the CLI put its own, while this agent + follows an armed clock; as written otherwise, when the two dates are one. A system prompt whose block has no + date line this knows, or a date that can't be read, refuses the call, so the model is never told the real date on + the env's clock.""" + if not clock_armed(): + return body + try: + request = json.loads(body) + except ValueError: + return body + if not isinstance(request, dict): + return body + system = [(holder, key) for holder, key in _texts(request, ("system", "developer")) if "\n" in holder[key]] + search = [(holder, key) for holder, key in _search_descriptions(request) if _SEARCH_YEAR.search(holder[key])] + if not system and not search: + return body + if any(not _ENV_DATE.search(holder[key]) for holder, key in system): + raise Refusal("OpenCode's block has no date line this agent knows, so the model can't be told the env's " + "date") + today, year = await _env_today() + for holder, key in system: + holder[key] = _ENV_DATE.sub(lambda match: match.group(1) + today, holder[key], count=1) + for holder, key in search: + holder[key] = _SEARCH_YEAR.sub(f"The current year is {year}.", holder[key], count=1) + return json.dumps(request, ensure_ascii=False, separators=(",", ":")).encode() + + async def export_session(context_id: str, session_id: str, timeout_s: int = _CLI_TIMEOUT_S) -> bytes: """`opencode export ` for the given context: the transcript JSON bytes.""" env = cli_env(context_id, clock_armed=clock_armed()) @@ -338,7 +410,6 @@ def _build_config( # selects otherwise. "permission": _permission(builtin_tools, mcp_servers), "autoupdate": False, - "plugin": [ENV_DATE_PLUGIN.as_uri()], } if instructions: config["instructions"] = list(instructions) @@ -437,9 +508,10 @@ def _descendants(pid: int) -> list[int]: async def run_opencode(prompt: str, context_id: str, **kwargs) -> OpencodeResult: """Run one turn, ``_run_opencode``'s, with OpenCode's provider pointed at a model relay of the turn's own, which counts every model call the CLI makes: its steps', its subagents' sessions', its compaction's, its title's and its - answered retries'. The turn's usage is theirs, a call answered without usage counted as unreported.""" + answered retries'. The turn's usage is theirs, a call answered without usage counted as unreported. The relay + puts the env's date in each call (``env_date_rewrite``).""" calls = Calls() - async with model_relay(_base_url(os.environ).removesuffix("/v1"), calls) as relay: + async with model_relay(_base_url(os.environ).removesuffix("/v1"), calls, rewrite=env_date_rewrite) as relay: result = await _run_opencode(prompt, context_id, base_url=relay, **kwargs) result.usage = calls.usage(result.tool_call_count) return result diff --git a/src/agent_env/utils/model_relay/model_relay.py b/src/agent_env/utils/model_relay/model_relay.py index a0c35c1d3..84cdb5139 100644 --- a/src/agent_env/utils/model_relay/model_relay.py +++ b/src/agent_env/utils/model_relay/model_relay.py @@ -7,7 +7,7 @@ import contextlib import json import secrets -from collections.abc import AsyncIterator, Mapping +from collections.abc import AsyncIterator, Awaitable, Callable, Mapping from contextlib import asynccontextmanager from dataclasses import dataclass, field from typing import Any @@ -27,6 +27,10 @@ _COUNTS = ("input_tokens", "output_tokens", "total_tokens", "cache_read_tokens", "cache_write_tokens") +class Refusal(Exception): + """A model call the relay answers itself, with this reason, rather than forward.""" + + @dataclass class Calls: """The model calls a relay forwarded: each answered call's usage, read as ``Usage.from_model_response`` reads one, @@ -138,13 +142,16 @@ def answer_usage(answer: bytes) -> Usage | None: @asynccontextmanager async def model_relay(upstream: str, calls: Calls, *, headers: Mapping[str, str] | None = None, - models: list[str] | None = None) -> AsyncIterator[str]: + models: list[str] | None = None, + rewrite: Callable[[bytes], Awaitable[bytes]] | None = None) -> AsyncIterator[str]: """Serve a relay to ``upstream``, the endpoint's API root, on loopback, and yield its root, which takes the endpoint's paths after it (``/v1/chat/completions``). Its path names a token of its own, so a process left from another turn reaches no other turn's relay. Each model call it forwards is added to ``calls`` once its answer has ended, read to its end even when the CLI hung up. ``headers`` replace the CLI's own on every request, so the endpoint's credentials need never reach the CLI; without them, the CLI's are forwarded. ``models`` is the list a - ``GET .../models`` is answered with, sparing a CLI that lists them the endpoint's whole catalog.""" + ``GET .../models`` is answered with, sparing a CLI that lists them the endpoint's whole catalog. ``rewrite`` takes + each model call's request body and gives the one to forward; a ``Refusal`` it raises is the call's answer, a 400, + which no CLI retries, and the call goes no further.""" token = secrets.token_hex(16) async with ClientSession(timeout=ClientTimeout(total=None)) as client: async def forward(request: web.Request) -> web.StreamResponse: @@ -161,8 +168,16 @@ async def forward(request: web.Request) -> web.StreamResponse: call = request.method == "POST" and path.rstrip("/").endswith(_CALL_ROUTES) status, reader = None, AnswerReader() try: + body = await request.read() + if call and rewrite is not None: + try: + body = await rewrite(body) + except Refusal as exc: + status = 400 + return web.json_response({"error": {"message": str(exc), "type": "invalid_request_error"}}, + status=status) async with client.request(request.method, f"{upstream}/{path}", params=request.query, - data=await request.read(), headers=outgoing) as answer: + data=body, headers=outgoing) as answer: status = answer.status reader = AnswerReader(stream=answer.content_type == "text/event-stream") response = web.StreamResponse(status=answer.status, headers={ diff --git a/tst/unit/agents/opencode/test_env_clock.py b/tst/unit/agents/opencode/test_env_clock.py index 7b8510fd4..78be8617b 100644 --- a/tst/unit/agents/opencode/test_env_clock.py +++ b/tst/unit/agents/opencode/test_env_clock.py @@ -1,16 +1,18 @@ """OpenCode on the env's clock: its bridge hands the shared egress rule (tst/unit/agents/test_agent_egress.py) the model endpoint's URL and every MCP server's, which the CLI connects to itself, so on an armed clock it goes out through the image's egress proxy, and to loopback, the hosts NO_PROXY names and plain-HTTP hosts directly; unarmed, it goes out -as before. The CLI itself runs on real time and its plugin (env_date.js) tells the model the env's date, which it reads -from a command as the model's own commands do. What every clocked image shares is checked in -tst/unit/agents/test_agent_clock_images.py.""" +as before. Where the image follows the clock, the CLI itself runs on real time and its model relay puts the env's date, +read from a command as the model's own commands read it, where the CLI put its own. What every clocked image shares is +checked in tst/unit/agents/test_agent_clock_images.py.""" from __future__ import annotations +import asyncio +import contextlib import json -import re -import shutil +import os import subprocess +import time import pytest @@ -42,69 +44,83 @@ def test_without_the_proxy_or_an_armed_clock_the_cli_goes_out_directly_as_before env = opencode_bridge.cli_env("ctx", environ, clock_armed=armed) assert not {"HTTPS_PROXY", "NO_PROXY"} & set(env) - assert set(env) == {*environ, "XDG_DATA_HOME", "XDG_STATE_HOME", "AGENTENV_REAL_TIME"} + assert set(env) == {*environ, "XDG_DATA_HOME", "XDG_STATE_HOME"} -@pytest.mark.parametrize("armed", [True, False]) -def test_the_cli_starts_on_real_time_so_its_sessions_keep_their_order_at_any_env_date(armed): - """libfaketime takes the marker out of the CLI's environment, so what the CLI starts reads the env's time.""" - env = opencode_bridge.cli_env("ctx", {agent_egress.EGRESS_PROXY_ENV: PROXY}, clock_armed=armed) +@pytest.mark.parametrize("follows", [True, False]) +def test_where_the_image_follows_the_clock_the_cli_starts_on_real_time_so_its_sessions_keep_their_order( + monkeypatch, follows): + """libfaketime takes the marker out of the CLI's environment, so what the CLI starts reads the env's time; where + nothing follows the clock, as on an install target, the CLI starts as before.""" + monkeypatch.setattr(opencode_bridge, "follows", lambda: follows) - assert env["AGENTENV_REAL_TIME"] == "1" + for armed in (True, False): + env = opencode_bridge.cli_env("ctx", {agent_egress.EGRESS_PROXY_ENV: PROXY}, clock_armed=armed) + assert env.get("AGENTENV_REAL_TIME") == ("1" if follows else None) -def test_every_turn_loads_the_date_plugin_which_the_image_and_an_install_carry_beside_the_bridge(): - config = opencode_bridge._build_config("m", None, {}, None) +def test_every_turns_relay_puts_the_env_date_in_its_model_calls(monkeypatch): + seen = {} - assert config["plugin"] == [(AGENT_DIR / "env_date.js").as_uri()] - assert opencode_bridge.ENV_DATE_PLUGIN == AGENT_DIR / "env_date.js" and opencode_bridge.ENV_DATE_PLUGIN.is_file() - assert re.search(r"^COPY .*\benv_date\.js\b.* \./$", (AGENT_DIR / "Dockerfile").read_text(), re.MULTILINE) - assert "env_date.js" in re.search(r'^AGENT_FILES="([^"]+)"$', (AGENT_DIR / "install.sh").read_text(), - re.MULTILINE).group(1).split() + @contextlib.asynccontextmanager + async def relay(upstream, calls, **options): + seen.update(options) + yield "http://relay" + + async def turn(prompt, context_id, **kwargs): + seen["base_url"] = kwargs["base_url"] + return opencode_bridge.OpencodeResult(response="", tool_call_count=0, session_id=None) + + monkeypatch.setattr(opencode_bridge, "model_relay", relay) + monkeypatch.setattr(opencode_bridge, "_run_opencode", turn) + asyncio.run(opencode_bridge.run_opencode("go", "ctx")) + + assert seen == {"rewrite": opencode_bridge.env_date_rewrite, "base_url": "http://relay"} + assert "plugin" not in opencode_bridge._build_config("m", None, {}, None) # OpenCode's system prompt as its SystemPrompt.environment writes it (opencode-ai 1.17.18, src/session/system.ts). -SYSTEM = ("You are OpenCode, the best coding agent on the planet.\n" - "You are powered by the model named m. The exact model ID is litellm/m\n" - "Here is some useful information about the environment you are running in:\n\n" - " Working directory: /app\n Workspace root folder: /app\n Is directory a git repo: no\n" - " Platform: linux\n Today's date: Sat Nov 21 2026\n\n" +ENV_BLOCK = ("Here is some useful information about the environment you are running in:\n\n" + " Working directory: /app\n Workspace root folder: /app\n Is directory a git repo: no\n" + " Platform: linux\n Today's date: Sat Nov 21 2026\n") +SYSTEM = (f"You are OpenCode, the best coding agent on the planet.\n{ENV_BLOCK}\n" "The task's notes say: Today's date: as written") -HARNESS = """ -const plugin = (await import(process.argv[1])).default -const hooks = await plugin.server({}) -const out = { system: JSON.parse(process.argv[2]) } -const search = { description: "Searches the web. The current year is 2026. You MUST use this year.", parameters: {} } -const other = { description: "The current year is 2026.", parameters: {} } -try { - await hooks["experimental.chat.system.transform"]({ model: {} }, out) - await hooks["tool.definition"]({ toolID: "websearch" }, search) - await hooks["tool.definition"]({ toolID: "bash" }, other) -} catch (error) { - console.log(JSON.stringify({ error: String(error.message) })) - process.exit(0) -} -console.log(JSON.stringify({ id: plugin.id, system: out.system, search: search.description, other: other.description })) -""" - - -def _plugin(tmp_path, date_out: str | None, system: list[str] = [SYSTEM]) -> tuple[dict, str]: - """The plugin run by node as the CLI's Bun runs it, with a ``date`` that prints ``date_out`` (fails when None) - and records the environment it got.""" - node = shutil.which("node") - assert node, "node runs the CLI plugin's test" +SEARCH = "Search the web.\n\nThe current year is 2026. You MUST use this year when searching for recent information." + + +def _call(system=SYSTEM, *, parts=False, tools=True, user=SYSTEM) -> dict: + content = [{"type": "text", "text": "header"}, {"type": "text", "text": system}] if parts else system + call = {"model": "m", "stream": True, "messages": [{"role": "system", "content": content}, + {"role": "user", "content": user}]} + if tools: + call["tools"] = [{"type": "function", "function": {"name": "websearch", "description": SEARCH}}, + {"type": "function", "function": {"name": "bash", "description": "The current year is 2026."}}] + return call + + +@pytest.fixture +def env_clock(tmp_path, monkeypatch): + """An armed clock, in UTC, whose time a stand-in ``date`` prints (``FAKE_DATE_OUT``; it fails without one), + recording the environment it got.""" bin_dir = tmp_path / "bin" bin_dir.mkdir() (bin_dir / "date").write_text('#!/bin/sh\nenv > "$FAKE_DATE_ENV"\n[ "$1" = "+%s %N" ] || exit 2\n' - '[ -n "$FAKE_DATE_OUT" ] || exit 1\necho "$FAKE_DATE_OUT"\n') + '[ -n "$FAKE_DATE_SLEEP" ] && sleep "$FAKE_DATE_SLEEP"\n' + '[ -n "$FAKE_DATE_OUT" ] || { echo no clock >&2; exit 1; }\necho "$FAKE_DATE_OUT"\n') (bin_dir / "date").chmod(0o755) - plugin = tmp_path / "env_date.mjs" - shutil.copy(AGENT_DIR / "env_date.js", plugin) - env = {"PATH": f"{bin_dir}:/usr/bin:/bin", "TZ": "UTC", "AGENTENV_REAL_TIME": "1", - "FAKE_DATE_ENV": str(tmp_path / "date.env"), **({"FAKE_DATE_OUT": date_out} if date_out else {})} - done = subprocess.run([node, "--input-type=module", "-e", HARNESS, plugin.as_uri(), json.dumps(system)], - capture_output=True, text=True, env=env, timeout=30, check=True) - return json.loads(done.stdout), (tmp_path / "date.env").read_text() + monkeypatch.setenv("PATH", f"{bin_dir}:{os.environ['PATH']}") + monkeypatch.setenv("FAKE_DATE_ENV", str(tmp_path / "date.env")) + monkeypatch.setenv("AGENTENV_REAL_TIME", "1") + monkeypatch.setenv("TZ", "UTC") + time.tzset() + monkeypatch.setattr(opencode_bridge, "clock_armed", lambda: True) + yield tmp_path / "date.env" + monkeypatch.undo() + time.tzset() + + +def _rewrite(call: dict) -> dict: + return json.loads(asyncio.run(opencode_bridge.env_date_rewrite(json.dumps(call).encode()))) @pytest.mark.parametrize("date_out, today, year", [ @@ -114,27 +130,57 @@ def _plugin(tmp_path, date_out: str | None, system: list[str] = [SYSTEM]) -> tup # Half a second before 1950: date prints the second below and a positive fraction. ("-631152001 500000000", "Sat Dec 31 1949", 1949), ]) -def test_the_plugin_tells_the_model_the_env_date_a_command_reads(tmp_path, date_out, today, year): - result, child_env = _plugin(tmp_path, date_out) +@pytest.mark.parametrize("parts", [False, True]) +def test_on_an_armed_clock_the_model_is_told_the_env_date_a_command_reads(env_clock, monkeypatch, date_out, today, + year, parts): + monkeypatch.setenv("FAKE_DATE_OUT", date_out) + call = _rewrite(_call(parts=parts)) + + system = call["messages"][0]["content"][1]["text"] if parts else call["messages"][0]["content"] + assert system == SYSTEM.replace("Today's date: Sat Nov 21 2026", f"Today's date: {today}") + assert call["messages"][1]["content"] == SYSTEM + assert call["tools"][0]["function"]["description"] == SEARCH.replace("2026", str(year)) + assert call["tools"][1]["function"]["description"] == "The current year is 2026." + assert "AGENTENV_REAL_TIME" not in env_clock.read_text() and "TZ=UTC" in env_clock.read_text() + + +def test_the_date_is_written_in_the_zone_the_cli_writes_its_own_in(env_clock, monkeypatch): + monkeypatch.setenv("FAKE_DATE_OUT", "1801785600 000000000") # 2027-02-05T00:00Z, still the 4th in New York + monkeypatch.setenv("TZ", "America/New_York") + time.tzset() + + assert "Today's date: Thu Feb 04 2027" in _rewrite(_call())["messages"][0]["content"] + + +@pytest.mark.parametrize("armed", [False, True]) +def test_a_call_with_nothing_to_rewrite_or_off_the_clock_goes_as_written_and_reads_no_date(env_clock, monkeypatch, + armed): + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + monkeypatch.setattr(opencode_bridge, "clock_armed", lambda: armed) + calls = [json.dumps(_call(), indent=1).encode()] if not armed else [] + calls += [json.dumps(_call("A title for this conversation", tools=False, user="hi")).encode(), b"not json"] - assert result["id"] == "agentenv-env-date" - assert result["system"] == [SYSTEM.replace("Today's date: Sat Nov 21 2026", f"Today's date: {today}")] - assert result["search"] == f"Searches the web. The current year is {year}. You MUST use this year." - assert result["other"] == "The current year is 2026." - assert "AGENTENV_REAL_TIME" not in child_env and "TZ=UTC" in child_env + for body in calls: + assert asyncio.run(opencode_bridge.env_date_rewrite(body)) == body + assert not env_clock.exists() -def test_the_plugin_leaves_a_prompt_without_the_env_block_alone(tmp_path): - system = ["You are a subagent.\nToday's date: whatever the task says"] +@pytest.mark.parametrize("environ", [{}, {"FAKE_DATE_OUT": "soon"}, {"FAKE_DATE_OUT": "1 0", "FAKE_DATE_SLEEP": "5"}]) +def test_a_date_that_cant_be_read_refuses_the_call_rather_than_tell_the_model_real_time(env_clock, monkeypatch, + environ): + monkeypatch.setattr(opencode_bridge, "_DATE_TIMEOUT_S", 0.5) + for name, value in environ.items(): + monkeypatch.setenv(name, value) - assert _plugin(tmp_path, "1801742400 000000000", system)[0]["system"] == system + with pytest.raises(opencode_bridge.Refusal, match="the env's date couldn't be read"): + _rewrite(_call()) -@pytest.mark.parametrize("date_out", [None, "not a time"]) -def test_a_date_the_plugin_cant_read_fails_the_turn_rather_than_show_real_time(tmp_path, date_out): - result, _ = _plugin(tmp_path, date_out) +def test_an_env_block_without_a_date_line_this_knows_refuses_the_call(env_clock, monkeypatch): + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") - assert result["error"] + with pytest.raises(opencode_bridge.Refusal, match="no date line"): + _rewrite(_call(SYSTEM.replace(" Today's date:", " Date:"))) @pytest.mark.parametrize("base_url, direct", [("http://10.0.0.5:4000", True), ("https://litellm.example.com", False)]) diff --git a/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py b/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py index 63ad2e5a9..75bee09fe 100644 --- a/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py +++ b/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py @@ -49,7 +49,7 @@ async def _exec(*cmd, **kwargs): def test_no_selection_leaves_the_config_and_argv_as_they_were(monkeypatch, spawned): """The whole config and argv of a turn without a selection, as origin/main builds them, except that the prompt - goes on stdin rather than as the positional message and the date plugin is loaded.""" + goes on stdin rather than as the positional message.""" monkeypatch.setenv("LITELLM_BASE_URL", "https://gateway.example") monkeypatch.delenv("LITELLM_EXTRA_HEADERS", raising=False) @@ -72,7 +72,6 @@ def test_no_selection_leaves_the_config_and_argv_as_they_were(monkeypatch, spawn "model": "litellm/m", "permission": {"*": "allow", "question": "deny"}, "autoupdate": False, - "plugin": [opencode_bridge.ENV_DATE_PLUGIN.as_uri()], "mcp": {"env": {"type": "remote", "url": "https://gw/mcp", "enabled": True}}, }) diff --git a/tst/unit/agents/test_model_relay.py b/tst/unit/agents/test_model_relay.py index e0e2bfb47..31a1993e3 100644 --- a/tst/unit/agents/test_model_relay.py +++ b/tst/unit/agents/test_model_relay.py @@ -240,6 +240,36 @@ async def exercise(client, root, endpoint): assert sent["content-type"] == "application/json" +def test_a_rewrite_changes_each_model_call_before_it_goes_and_leaves_other_routes_alone(): + async def rewrite(body): + return body.replace(b'"m"', b'"rewritten"') + + async def exercise(client, root, endpoint): + await _chat(client, root) + await client.post(f"{root}/v1/embeddings", json={"model": "m"}) + + _, calls, endpoint = _through_relay([(200, CLAUDE_STREAM, "text/event-stream"), (200, "{}", "application/json")], + exercise, rewrite=rewrite) + + assert json.loads(endpoint.requests[0]["body"])["model"] == "rewritten" + assert json.loads(endpoint.requests[1]["body"])["model"] == "m" + assert len(calls.answered) == 1 + + +def test_a_refused_call_is_answered_by_the_relay_with_its_reason_and_goes_no_further(): + async def rewrite(body): + raise model_relay.Refusal("no date for the model") + + async def exercise(client, root, endpoint): + answer = await _chat(client, root) + return answer.status_code, answer.json() + + (status, answer), calls, endpoint = _through_relay([], exercise, rewrite=rewrite) + + assert status == 400 and answer["error"]["message"] == "no date for the model" + assert endpoint.requests == [] and (calls.answered, calls.unreported, calls.refused) == ([], 0, 1) + + def test_an_unreachable_endpoint_is_a_502_and_counts_nothing(): calls = model_relay.Calls() From 3c32ae3ff6e0dcbd86ba9416b77d090eec88c02d Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 22 Nov 2026 09:53:25 -0800 Subject: [PATCH 3/8] fix(agents): OpenCode's relay refuses what it can't rewrite rather than hang or tell the real date - A rewrite error other than a Refusal (a lone surrogate an MCP tool sent, which json.dumps(ensure_ascii=False) couldn't encode) became an aiohttp 500, which OpenCode retries without limit until the turn's timeout. The relay now answers any rewrite error with a 400 naming it, and the rewrite writes escaped JSON. - Every block's date line takes the env's date, not only the first: a config's agent prompt with a block of its own came first and left OpenCode's with the real date. - An armed call that isn't JSON is refused rather than sent as written. - The date read checks date's exit code before its output, names the timeout, and kills what date started with it (a new session and _kill_cli), so a child holding its pipes no longer stretches the 5 s bound to the child's lifetime. - The CLI version test asks a bump to recheck where the CLI writes its date. Co-Authored-By: Claude Opus 5.5 --- .../agents/agents/opencode/opencode_bridge.py | 44 +++++---- .../utils/model_relay/model_relay.py | 9 +- tst/unit/agents/opencode/test_env_clock.py | 91 +++++++++++++++++-- .../test_opencode_bridge_builtin_tools.py | 3 +- tst/unit/agents/test_model_relay.py | 14 +++ 5 files changed, 129 insertions(+), 32 deletions(-) diff --git a/src/agent_env/agents/agents/opencode/opencode_bridge.py b/src/agent_env/agents/agents/opencode/opencode_bridge.py index 8655fca16..4ed11327b 100644 --- a/src/agent_env/agents/agents/opencode/opencode_bridge.py +++ b/src/agent_env/agents/agents/opencode/opencode_bridge.py @@ -122,17 +122,17 @@ def cli_env(context_id: str, environ: Mapping[str, str] = os.environ, *, mcp_ser **({"AGENTENV_REAL_TIME": "1"} if follows() else {})} -async def _communicate(*cmd: str, env: Mapping[str, str], timeout_s: int) -> tuple[int, bytes, bytes]: - """Run a short CLI command to its end; one that outlives ``timeout_s`` is killed.""" +async def _communicate(*cmd: str, env: Mapping[str, str], timeout_s: float) -> tuple[int, bytes, bytes]: + """Run a short CLI command to its end; one that outlives ``timeout_s`` is killed with what it started, which would + otherwise hold its output open.""" proc = await asyncio.create_subprocess_exec( - *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=dict(env), + *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=dict(env), start_new_session=True, ) try: out, err = await asyncio.wait_for(proc.communicate(), timeout=timeout_s) except BaseException: - with contextlib.suppress(ProcessLookupError): - proc.kill() - await proc.wait() + _kill_cli(proc) + await _reap(proc) raise return proc.returncode, out, err @@ -140,16 +140,23 @@ async def _communicate(*cmd: str, env: Mapping[str, str], timeout_s: int) -> tup async def _env_today() -> tuple[str, int]: """The env's date, as the CLI's ``Date.toDateString()`` writes one in this zone, and its year, read from ``date``, which libfaketime fakes for what this server starts, as for the model's commands.""" + def unread(reason: str) -> Refusal: + return Refusal(f"the env's date couldn't be read for the model: {reason}") + environ = {name: value for name, value in os.environ.items() if name != "AGENTENV_REAL_TIME"} try: code, out, err = await _communicate("date", "+%s %N", env=environ, timeout_s=_DATE_TIMEOUT_S) + except TimeoutError: + raise unread(f"date gave no answer within {_DATE_TIMEOUT_S} s") from None + except OSError as exc: + raise unread(f"{type(exc).__name__}: {exc}") from exc + if code != 0: + raise unread(f"date exited {code}: {err.decode(errors='replace').strip()[:200]}") + try: seconds, _ = out.decode().split() day = time.localtime(int(seconds)) - except (OSError, ValueError, OverflowError, TimeoutError) as exc: - raise Refusal(f"the env's date couldn't be read for the model: {type(exc).__name__}: {exc}") from exc - if code != 0: - raise Refusal(f"the env's date couldn't be read for the model: date exited {code}: " - f"{err.decode(errors='replace')[:200]}") + except (ValueError, OverflowError, OSError) as exc: + raise unread(f"date printed {out.decode(errors='replace')[:100]!r}") from exc return f"{_DAYS[day.tm_wday]} {_MONTHS[day.tm_mon - 1]} {day.tm_mday:02d} {day.tm_year:04d}", day.tm_year @@ -174,16 +181,18 @@ def _search_descriptions(request: dict): async def env_date_rewrite(body: bytes) -> bytes: - """A model call as the CLI, on real time, wrote it, with the env's date where the CLI put its own, while this agent - follows an armed clock; as written otherwise, when the two dates are one. A system prompt whose block has no + """A model call as the CLI, on real time, wrote it, with the env's date on each block's date line, the CLI's + among any a prompt or instructions add, and in websearch's year, while this agent follows an armed clock; as + written otherwise, when the two dates are one. A call that isn't JSON, a system prompt whose block has no date line this knows, or a date that can't be read, refuses the call, so the model is never told the real date on the env's clock.""" if not clock_armed(): return body try: request = json.loads(body) - except ValueError: - return body + except ValueError as exc: + raise Refusal("the model call isn't JSON this agent can read, so the model can't be told the env's date") \ + from exc if not isinstance(request, dict): return body system = [(holder, key) for holder, key in _texts(request, ("system", "developer")) if "\n" in holder[key]] @@ -195,10 +204,11 @@ async def env_date_rewrite(body: bytes) -> bytes: "date") today, year = await _env_today() for holder, key in system: - holder[key] = _ENV_DATE.sub(lambda match: match.group(1) + today, holder[key], count=1) + holder[key] = _ENV_DATE.sub(lambda match: match.group(1) + today, holder[key]) for holder, key in search: holder[key] = _SEARCH_YEAR.sub(f"The current year is {year}.", holder[key], count=1) - return json.dumps(request, ensure_ascii=False, separators=(",", ":")).encode() + # Escaped, so a lone surrogate an MCP server's tool sent, which UTF-8 can't encode, goes as it came. + return json.dumps(request, separators=(",", ":")).encode() async def export_session(context_id: str, session_id: str, timeout_s: int = _CLI_TIMEOUT_S) -> bytes: diff --git a/src/agent_env/utils/model_relay/model_relay.py b/src/agent_env/utils/model_relay/model_relay.py index 84cdb5139..f27aa8eaf 100644 --- a/src/agent_env/utils/model_relay/model_relay.py +++ b/src/agent_env/utils/model_relay/model_relay.py @@ -150,8 +150,8 @@ async def model_relay(upstream: str, calls: Calls, *, headers: Mapping[str, str] has ended, read to its end even when the CLI hung up. ``headers`` replace the CLI's own on every request, so the endpoint's credentials need never reach the CLI; without them, the CLI's are forwarded. ``models`` is the list a ``GET .../models`` is answered with, sparing a CLI that lists them the endpoint's whole catalog. ``rewrite`` takes - each model call's request body and gives the one to forward; a ``Refusal`` it raises is the call's answer, a 400, - which no CLI retries, and the call goes no further.""" + each model call's request body and gives the one to forward; what it raises is the call's answer, a 400 with a + ``Refusal``'s reason or the error's name, which no CLI retries as it would a 500, and the call goes no further.""" token = secrets.token_hex(16) async with ClientSession(timeout=ClientTimeout(total=None)) as client: async def forward(request: web.Request) -> web.StreamResponse: @@ -172,9 +172,10 @@ async def forward(request: web.Request) -> web.StreamResponse: if call and rewrite is not None: try: body = await rewrite(body) - except Refusal as exc: + except Exception as exc: status = 400 - return web.json_response({"error": {"message": str(exc), "type": "invalid_request_error"}}, + reason = str(exc) if isinstance(exc, Refusal) else f"model relay: {type(exc).__name__}: {exc}" + return web.json_response({"error": {"message": reason, "type": "invalid_request_error"}}, status=status) async with client.request(request.method, f"{upstream}/{path}", params=request.query, data=body, headers=outgoing) as answer: diff --git a/tst/unit/agents/opencode/test_env_clock.py b/tst/unit/agents/opencode/test_env_clock.py index 78be8617b..747ab3672 100644 --- a/tst/unit/agents/opencode/test_env_clock.py +++ b/tst/unit/agents/opencode/test_env_clock.py @@ -14,9 +14,11 @@ import subprocess import time +import httpx import pytest +from aiohttp import web -from tst.unit.agents.opencode.agent import AGENT_DIR, agent_egress, opencode_bridge +from tst.unit.agents.opencode.agent import AGENT_DIR, agent_egress, model_relay, opencode_bridge PROXY = "http://127.0.0.1:3128" @@ -100,13 +102,14 @@ def _call(system=SYSTEM, *, parts=False, tools=True, user=SYSTEM) -> dict: @pytest.fixture def env_clock(tmp_path, monkeypatch): - """An armed clock, in UTC, whose time a stand-in ``date`` prints (``FAKE_DATE_OUT``; it fails without one), - recording the environment it got.""" + """An armed clock, in UTC, whose time a stand-in ``date`` prints (``FAKE_DATE_OUT``; it fails without one) before + it exits (``FAKE_DATE_EXIT``), recording the environment it got.""" bin_dir = tmp_path / "bin" bin_dir.mkdir() (bin_dir / "date").write_text('#!/bin/sh\nenv > "$FAKE_DATE_ENV"\n[ "$1" = "+%s %N" ] || exit 2\n' '[ -n "$FAKE_DATE_SLEEP" ] && sleep "$FAKE_DATE_SLEEP"\n' - '[ -n "$FAKE_DATE_OUT" ] || { echo no clock >&2; exit 1; }\necho "$FAKE_DATE_OUT"\n') + '[ -n "$FAKE_DATE_OUT" ] || { echo no clock >&2; exit 1; }\necho "$FAKE_DATE_OUT"\n' + 'exit "${FAKE_DATE_EXIT:-0}"\n') (bin_dir / "date").chmod(0o755) monkeypatch.setenv("PATH", f"{bin_dir}:{os.environ['PATH']}") monkeypatch.setenv("FAKE_DATE_ENV", str(tmp_path / "date.env")) @@ -144,6 +147,58 @@ def test_on_an_armed_clock_the_model_is_told_the_env_date_a_command_reads(env_cl assert "AGENTENV_REAL_TIME" not in env_clock.read_text() and "TZ=UTC" in env_clock.read_text() +def test_every_env_blocks_date_line_takes_the_env_date_so_the_clis_does_wherever_it_comes(env_clock, monkeypatch): + """A config's agent prompt, which comes before the CLI's block, or its instructions, after it, may hold an + block of their own.""" + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + prompt = "You are careful.\n\n Platform: linux\n Today's date: Mon Jan 01 2001\n\n" + written = prompt + SYSTEM + "\n" + prompt + + system = _rewrite(_call(written))["messages"][0]["content"] + + assert system == written.replace("Mon Jan 01 2001", "Thu Feb 04 2027").replace("Sat Nov 21 2026", "Thu Feb 04 2027") + + +def test_a_lone_surrogate_in_a_tool_an_mcp_server_sent_goes_as_it_came(env_clock, monkeypatch): + """The CLI sends it escaped, as a server's tool list had it; UTF-8 can't encode it unescaped.""" + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + call = _call() + call["tools"].append({"type": "function", "function": {"name": "env_cut", "description": "cut \ud83d"}}) + + assert _rewrite(call)["tools"][2]["function"]["description"] == "cut \ud83d" + + +@pytest.mark.usefixtures("socket_enabled") +def test_the_relay_sends_the_endpoint_the_call_with_the_env_date(env_clock, monkeypatch): + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + received = [] + + async def endpoint(request): + received.append((request.headers["Content-Length"], await request.read())) + return web.json_response({"choices": [], "usage": {"prompt_tokens": 1, "completion_tokens": 1}}) + + async def run(): + app = web.Application() + app.router.add_post("/v1/chat/completions", endpoint) + runner = web.AppRunner(app) + await runner.setup() + site = web.TCPSite(runner, "127.0.0.1", 0) + await site.start() + upstream = f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}" + try: + async with model_relay.model_relay(upstream, model_relay.Calls(), + rewrite=opencode_bridge.env_date_rewrite) as root: + async with httpx.AsyncClient(timeout=10) as client: + return (await client.post(f"{root}/v1/chat/completions", content=json.dumps(_call()))).status_code + finally: + await runner.cleanup() + + assert asyncio.run(run()) == 200 + ((length, body),) = received + assert int(length) == len(body) and json.loads(body)["stream"] is True + assert json.loads(body)["messages"][0]["content"] == SYSTEM.replace("Sat Nov 21 2026", "Thu Feb 04 2027") + + def test_the_date_is_written_in_the_zone_the_cli_writes_its_own_in(env_clock, monkeypatch): monkeypatch.setenv("FAKE_DATE_OUT", "1801785600 000000000") # 2027-02-05T00:00Z, still the 4th in New York monkeypatch.setenv("TZ", "America/New_York") @@ -157,24 +212,40 @@ def test_a_call_with_nothing_to_rewrite_or_off_the_clock_goes_as_written_and_rea armed): monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") monkeypatch.setattr(opencode_bridge, "clock_armed", lambda: armed) - calls = [json.dumps(_call(), indent=1).encode()] if not armed else [] - calls += [json.dumps(_call("A title for this conversation", tools=False, user="hi")).encode(), b"not json"] + calls = [json.dumps(_call(), indent=1).encode(), b"not json"] if not armed else [] + calls += [json.dumps(_call("A title for this conversation", tools=False, user="hi")).encode()] for body in calls: assert asyncio.run(opencode_bridge.env_date_rewrite(body)) == body assert not env_clock.exists() -@pytest.mark.parametrize("environ", [{}, {"FAKE_DATE_OUT": "soon"}, {"FAKE_DATE_OUT": "1 0", "FAKE_DATE_SLEEP": "5"}]) +def test_on_an_armed_clock_a_call_that_isnt_json_is_refused_rather_than_sent_with_the_real_date(env_clock): + with pytest.raises(opencode_bridge.Refusal, match="isn't JSON"): + asyncio.run(opencode_bridge.env_date_rewrite(json.dumps(_call()).encode()[:-1])) + + +@pytest.mark.parametrize("environ, reason", [ + ({}, "date exited 1: no clock"), + ({"FAKE_DATE_OUT": "1801742400 000000000", "FAKE_DATE_EXIT": "3"}, "date exited 3"), + ({"FAKE_DATE_OUT": "soon"}, "date printed 'soon\\n'"), + ({"FAKE_DATE_OUT": "1 0", "FAKE_DATE_SLEEP": "10"}, "date gave no answer within 2 s"), +]) def test_a_date_that_cant_be_read_refuses_the_call_rather_than_tell_the_model_real_time(env_clock, monkeypatch, - environ): - monkeypatch.setattr(opencode_bridge, "_DATE_TIMEOUT_S", 0.5) + environ, reason): + """A date that hangs is killed with the sleep it started, which holds its output open, so the refusal comes in + its time.""" + monkeypatch.setattr(opencode_bridge, "_DATE_TIMEOUT_S", 2) for name, value in environ.items(): monkeypatch.setenv(name, value) + started = time.monotonic() - with pytest.raises(opencode_bridge.Refusal, match="the env's date couldn't be read"): + with pytest.raises(opencode_bridge.Refusal) as refused: _rewrite(_call()) + assert str(refused.value).startswith(f"the env's date couldn't be read for the model: {reason}") + assert time.monotonic() - started < 6 + def test_an_env_block_without_a_date_line_this_knows_refuses_the_call(env_clock, monkeypatch): monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") diff --git a/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py b/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py index 75bee09fe..0bab105b9 100644 --- a/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py +++ b/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py @@ -172,4 +172,5 @@ def test_the_tool_names_are_those_of_the_cli_version_package_json_pins(): pinned = json.loads((AGENT_DIR / "package.json").read_text())["dependencies"]["opencode-ai"] assert opencode_bridge.TOOLS_CLI_VERSION == pinned, ( - "the CLI version changed: record the tools the new CLI offers in OpenCodeTool, then TOOLS_CLI_VERSION") + "the CLI version changed: record the tools the new CLI offers in OpenCodeTool, check that _ENV_DATE and " + "_SEARCH_YEAR still find where it writes its date, then TOOLS_CLI_VERSION") diff --git a/tst/unit/agents/test_model_relay.py b/tst/unit/agents/test_model_relay.py index 31a1993e3..69f5e7966 100644 --- a/tst/unit/agents/test_model_relay.py +++ b/tst/unit/agents/test_model_relay.py @@ -270,6 +270,20 @@ async def exercise(client, root, endpoint): assert endpoint.requests == [] and (calls.answered, calls.unreported, calls.refused) == ([], 0, 1) +def test_a_rewrite_that_fails_is_answered_by_the_relay_with_the_error_rather_than_a_500_a_cli_retries(): + async def rewrite(body): + raise ValueError("bad body") + + async def exercise(client, root, endpoint): + answer = await _chat(client, root) + return answer.status_code, answer.json() + + (status, answer), calls, endpoint = _through_relay([], exercise, rewrite=rewrite) + + assert status == 400 and answer["error"]["message"] == "model relay: ValueError: bad body" + assert endpoint.requests == [] and (calls.answered, calls.unreported, calls.refused) == ([], 0, 1) + + def test_an_unreachable_endpoint_is_a_502_and_counts_nothing(): calls = model_relay.Calls() From f40c1b5e22fc2a81739e36ffc72b6808003b15cb Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 22 Nov 2026 10:06:21 -0800 Subject: [PATCH 4/8] fix(agents): on an armed clock OpenCode enables only the endpoint its relay dates A project's opencode.json can add a provider and name a model on it, as for the general subagent; that call skipped the turn's relay and, with the CLI on real time, told the model the real date (a second stand-in received "Sun Nov 22 2026" while the env was at 2031; main's faked CLI sent 2031). While the clock is armed at the turn's start the config sets enabled_providers to the endpoint alone, so such a model isn't found (the task tool answers "Model not found") instead. Unarmed, the config is as before. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/README.md | 5 +++-- .../agents/agents/opencode/opencode_bridge.py | 12 +++++++++--- .../agents/opencode/test_opencode_bridge_config.py | 11 +++++++++++ 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index d84731cc1..911f2f889 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -53,8 +53,9 @@ The A2A server starts with the real-time marker, so it and its records stay on r before 1970, so a clock set behind a session's messages broke it. Where the image follows the clock, its bridge starts the CLI with the real-time marker instead, so the commands it runs read the env's time, and the turn's model relay puts the env's date, read from `date` as those commands read it, in the prompt's "Today's date" line and the - websearch tool's year while the clock is armed. A call whose date can't be read, or whose `` block has no date - line the relay knows, is refused, failing the turn rather than telling the model the real date. + websearch tool's year while the clock is armed, and the CLI enables no provider but the endpoint, so none bypasses + the relay. A call whose date can't be read, or whose `` block has no date line the relay knows, is refused, + failing the turn rather than telling the model the real date. - **For the rest of the run.** An agent that follows goes on following: a later `sync_env_clock` without `agent_clock` re-arms the clock it follows, and only agents that never followed keep real time. - **Through the egress proxy.** While the agent follows an armed clock, the CLI goes out through the egress proxy, which diff --git a/src/agent_env/agents/agents/opencode/opencode_bridge.py b/src/agent_env/agents/agents/opencode/opencode_bridge.py index 4ed11327b..1f2c5d874 100644 --- a/src/agent_env/agents/agents/opencode/opencode_bridge.py +++ b/src/agent_env/agents/agents/opencode/opencode_bridge.py @@ -369,11 +369,14 @@ def _build_config( environ: Mapping[str, str] = os.environ, instructions: list[str] | None = None, builtin_tools: OpenCodeTools | None = None, + clock_armed: bool = False, ) -> dict: """Assemble the inline OpenCode config passed via OPENCODE_CONFIG_CONTENT. Everything dynamic (model, MCP servers, headers) is rebuilt per turn so there - is no on-disk config to race on.""" + is no on-disk config to race on. On an armed clock only the endpoint is enabled, whose calls the turn's relay + dates: a provider a project's config adds would tell the model the real date, and a model named on one isn't + found.""" options: dict = {"baseURL": _base_url(environ), "apiKey": "{env:LITELLM_API_KEY}"} if headers: options["headers"] = dict(headers) @@ -423,6 +426,8 @@ def _build_config( } if instructions: config["instructions"] = list(instructions) + if clock_armed: + config["enabled_providers"] = ["litellm"] if mcp_servers: mcp: dict[str, dict] = {} @@ -570,9 +575,10 @@ async def _run_opencode( + json.dumps(schema, separators=(",", ":")) ) + 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) + instructions=instructions, builtin_tools=builtin_tools, clock_armed=armed) # Resume a specific session by id (multi-turn continuity). `--continue` # does NOT replay history to the model; `-s ` does. First turn @@ -593,7 +599,7 @@ async def _run_opencode( cmd += ["--file", path] env = { - **cli_env(context_id, mcp_servers=mcp_servers, clock_armed=clock_armed()), + **cli_env(context_id, mcp_servers=mcp_servers, clock_armed=armed), "OPENCODE_CONFIG_CONTENT": json.dumps(config), } diff --git a/tst/unit/agents/opencode/test_opencode_bridge_config.py b/tst/unit/agents/opencode/test_opencode_bridge_config.py index 0b73dd5c5..83edd80bd 100644 --- a/tst/unit/agents/opencode/test_opencode_bridge_config.py +++ b/tst/unit/agents/opencode/test_opencode_bridge_config.py @@ -167,6 +167,17 @@ def test_the_system_prompt_reaches_the_model_as_instructions_and_the_output_form assert Path(instructions).read_text() == "be brief" +@pytest.mark.parametrize("armed", [False, True]) +def test_on_an_armed_clock_only_the_endpoint_the_relay_dates_is_enabled(monkeypatch, spawned, armed): + """A provider a project's opencode.json adds, as for a subagent's model, would reach a model with the real date.""" + monkeypatch.setattr(opencode_bridge, "clock_armed", lambda: armed) + + asyncio.run(opencode_bridge.run_opencode(prompt="go", context_id="ctx")) + + ((_argv, env),) = spawned + assert json.loads(env["OPENCODE_CONFIG_CONTENT"]).get("enabled_providers") == (["litellm"] if armed else None) + + def test_a_turn_with_no_system_prompt_names_no_instructions(spawned): asyncio.run(opencode_bridge.run_opencode(prompt="go", context_id="ctx")) From 718eb08ace92a94484697000313e1fbc07f99ff9 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 22 Nov 2026 13:13:25 -0800 Subject: [PATCH 5/8] fix(agents): OpenCode's date read kills what a date left holding its output A date that exits but leaves a process holding its stdout outlived the 5 s bound's kill, which skips the process group once its leader has exited, and the process and two pipes stayed open in the A2A server after each refused call. The read now kills the command's session group either way. Co-Authored-By: Claude Opus 5.5 --- .../agents/agents/opencode/opencode_bridge.py | 5 ++++- tst/unit/agents/opencode/test_env_clock.py | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/agent_env/agents/agents/opencode/opencode_bridge.py b/src/agent_env/agents/agents/opencode/opencode_bridge.py index 1f2c5d874..981abc1f5 100644 --- a/src/agent_env/agents/agents/opencode/opencode_bridge.py +++ b/src/agent_env/agents/agents/opencode/opencode_bridge.py @@ -124,13 +124,16 @@ def cli_env(context_id: str, environ: Mapping[str, str] = os.environ, *, mcp_ser async def _communicate(*cmd: str, env: Mapping[str, str], timeout_s: float) -> tuple[int, bytes, bytes]: """Run a short CLI command to its end; one that outlives ``timeout_s`` is killed with what it started, which would - otherwise hold its output open.""" + otherwise hold its output open. Its session's group is killed even when the command has exited itself and left + something holding its output, which the group's id keeps from being another process's.""" proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=dict(env), start_new_session=True, ) try: out, err = await asyncio.wait_for(proc.communicate(), timeout=timeout_s) except BaseException: + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(proc.pid, signal.SIGKILL) _kill_cli(proc) await _reap(proc) raise diff --git a/tst/unit/agents/opencode/test_env_clock.py b/tst/unit/agents/opencode/test_env_clock.py index 747ab3672..b52dcdc31 100644 --- a/tst/unit/agents/opencode/test_env_clock.py +++ b/tst/unit/agents/opencode/test_env_clock.py @@ -108,6 +108,7 @@ def env_clock(tmp_path, monkeypatch): bin_dir.mkdir() (bin_dir / "date").write_text('#!/bin/sh\nenv > "$FAKE_DATE_ENV"\n[ "$1" = "+%s %N" ] || exit 2\n' '[ -n "$FAKE_DATE_SLEEP" ] && sleep "$FAKE_DATE_SLEEP"\n' + '[ -n "$FAKE_DATE_KID" ] && { sleep 30 & echo $! > "$FAKE_DATE_KID"; }\n' '[ -n "$FAKE_DATE_OUT" ] || { echo no clock >&2; exit 1; }\necho "$FAKE_DATE_OUT"\n' 'exit "${FAKE_DATE_EXIT:-0}"\n') (bin_dir / "date").chmod(0o755) @@ -247,6 +248,23 @@ def test_a_date_that_cant_be_read_refuses_the_call_rather_than_tell_the_model_re assert time.monotonic() - started < 6 +def test_a_date_that_exits_leaving_a_process_on_its_output_is_refused_and_that_process_killed(env_clock, monkeypatch, + tmp_path): + """The date has exited, so only its session's group still reaches what it left holding the pipes.""" + monkeypatch.setattr(opencode_bridge, "_DATE_TIMEOUT_S", 1) + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + monkeypatch.setenv("FAKE_DATE_KID", str(tmp_path / "kid")) + + with pytest.raises(opencode_bridge.Refusal, match="date gave no answer within 1 s"): + _rewrite(_call()) + + kid, deadline = (tmp_path / "kid").read_text().strip(), time.monotonic() + 5 + while (state := subprocess.run(["ps", "-o", "stat=", "-p", kid], capture_output=True, text=True).stdout.strip()) \ + and not state.startswith("Z") and time.monotonic() < deadline: + time.sleep(0.1) + assert not state or state.startswith("Z"), state + + def test_an_env_block_without_a_date_line_this_knows_refuses_the_call(env_clock, monkeypatch): monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") From a9d47e4f0e1696a8bd6c69f5a4fab0a609a2d421 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 22 Nov 2026 21:19:43 -0800 Subject: [PATCH 6/8] test(agents): the pinned OpenCode CLI still writes its date where the relay rewrites it An integration test installs the CLI the agent's package-lock.json pins and runs a turn through the bridge's relay on an armed clock: the model is sent the env's date on the line and in websearch's year, with no copy of the machine's date in the system prompt or a tool; the CLI's bin is its native binary, which the real-time marker reaches; and the turn runs in that one process. Bumping the CLI runs it against the new version. Co-Authored-By: Claude Opus 5.5 --- .../agent/opencode_env_date_test.py | 133 ++++++++++++++++++ .../test_opencode_bridge_builtin_tools.py | 4 +- 2 files changed, 135 insertions(+), 2 deletions(-) create mode 100644 tst/integration/agent/opencode_env_date_test.py diff --git a/tst/integration/agent/opencode_env_date_test.py b/tst/integration/agent/opencode_env_date_test.py new file mode 100644 index 000000000..c01e303b2 --- /dev/null +++ b/tst/integration/agent/opencode_env_date_test.py @@ -0,0 +1,133 @@ +"""The OpenCode CLI the agent's package-lock.json pins, against what its bridge relies on to tell the model the env's +date while the CLI runs on real time: the CLI's own date line and websearch's year are where the turn's relay rewrites +them, so the model is sent the env's date and no copy of the machine's; its bin is the native binary, which the +real-time marker reaches; and a turn runs in that one process, with no second CLI that would follow the env's clock. +Bumping the CLI runs this against the new version, so a version that moves or rewrites any of these fails here.""" + +import asyncio +import json +import os +import shutil +import subprocess +import time +from pathlib import Path + +import pytest + +from tst.unit.agents.opencode.agent import AGENT_DIR, opencode_bridge +from tst.util import fake_openai + +pytestmark = [pytest.mark.integration] + +VERSION = json.loads((AGENT_DIR / "package.json").read_text())["dependencies"]["opencode-ai"] +ENV_TODAY, ENV_YEAR = "Sun Jan 01 1950", 1950 +_DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") +_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") + + +@pytest.fixture(scope="module") +def opencode_bin(tmp_path_factory) -> Path: + """The CLI installed as the image installs it: npm ci from the lockfile, then opencode-ai's own postinstall.""" + npm, node = shutil.which("npm"), shutil.which("node") + assert npm and node, "node and npm install the pinned OpenCode CLI" + folder = tmp_path_factory.mktemp("opencode") + for name in ("package.json", "package-lock.json"): + shutil.copy(AGENT_DIR / name, folder / name) + subprocess.run([npm, "ci", "--ignore-scripts", "--omit=dev", "--no-audit", "--no-fund", "--loglevel=error"], + cwd=folder, check=True, timeout=600) + subprocess.run([node, "node_modules/opencode-ai/postinstall.mjs"], cwd=folder, check=True, timeout=120) + return folder / "node_modules" / ".bin" / "opencode" + + +def test_the_cli_is_its_native_binary_so_the_real_time_marker_reaches_it(opencode_bin): + """A launcher script would be what the marker starts, and libfaketime takes the marker out of its environment, so + the CLI it starts would follow the env's clock.""" + with open(opencode_bin.resolve(), "rb") as binary: + assert binary.read(4) in (b"\x7fELF", b"\xcf\xfa\xed\xfe"), f"OpenCode {VERSION}: {opencode_bin.resolve()}" + + +def _system_texts(body: dict) -> list[str]: + texts = [] + for message in body.get("messages") or []: + if message.get("role") not in ("system", "developer"): + continue + content = message.get("content") + parts = content if isinstance(content, list) else [{"text": content}] + texts += [part["text"] for part in parts if isinstance(part, dict) and isinstance(part.get("text"), str)] + return texts + + +def _descriptions(body: dict) -> dict[str, str]: + return {tool["function"]["name"]: tool["function"].get("description") or "" for tool in body.get("tools") or []} + + +def _machine_dates() -> set[str]: + """This machine's date, as the CLI on real time writes one (``Date.toDateString()``) and as ISO, for yesterday, + today and tomorrow, so a turn across midnight is still caught.""" + dates = set() + for offset in (-86400, 0, 86400): + day = time.localtime(time.time() + offset) + dates |= {f"{_DAYS[day.tm_wday]} {_MONTHS[day.tm_mon - 1]} {day.tm_mday:02d} {day.tm_year:04d}", + time.strftime("%Y-%m-%d", day)} + return dates + + +def _opencode_processes_under(pid: int) -> list[str]: + rows = [line.split(None, 2) for line in subprocess.run(["ps", "-eo", "pid=,ppid=,comm="], capture_output=True, + text=True, check=True).stdout.splitlines()] + children: dict[str, list[tuple[str, str]]] = {} + for row in rows: + if len(row) == 3: + children.setdefault(row[1], []).append((row[0], row[2])) + found, pending = [], [str(pid)] + while pending: + for child, command in children.get(pending.pop(), ()): + pending.append(child) + if os.path.basename(command).startswith("opencode"): + found.append(f"{child} {command}") + return found + + +def test_a_turn_on_an_armed_clock_tells_the_model_the_env_date_and_no_other(opencode_bin, tmp_path, monkeypatch): + seen_clis: list[list[str]] = [] + + def respond(body: dict) -> fake_openai.Text: + seen_clis.append(_opencode_processes_under(os.getpid())) + return fake_openai.Text("done") + + async def env_today() -> tuple[str, int]: + return ENV_TODAY, ENV_YEAR + + for name in ("HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"): + monkeypatch.setenv(name, str(tmp_path / name.lower())) + monkeypatch.setenv("PATH", f"{opencode_bin.parent}{os.pathsep}{os.environ['PATH']}") + monkeypatch.setenv("LITELLM_API_KEY", "sk-fake") + monkeypatch.setenv("OPENCODE_ENABLE_EXA", "1") + monkeypatch.setattr(opencode_bridge, "SESSIONS_ROOT", str(tmp_path / "sessions")) + monkeypatch.setattr(opencode_bridge, "clock_armed", lambda: True) + monkeypatch.setattr(opencode_bridge, "_env_today", env_today) + (tmp_path / "work").mkdir() + + with fake_openai.FakeOpenAI(respond=respond) as endpoint: + monkeypatch.setenv("LITELLM_BASE_URL", endpoint.url) + result = asyncio.run(opencode_bridge.run_opencode("Say done.", "ctx", model="m", timeout_s=300, + workspace=str(tmp_path / "work"))) + + assert not result.error, result.error + sent = [seen.body for seen in endpoint.completions()] + turns = [body for body in sent if any("" in text for text in _system_texts(body))] + assert turns, (f"OpenCode {VERSION} sent its block in no system message, so the relay can't tell the model " + "the env's date: find where it puts its date now, and fix _ENV_DATE in opencode_bridge") + for body in turns: + assert f" Today's date: {ENV_TODAY}\n" in "\n".join(_system_texts(body)), ( + f"OpenCode {VERSION}'s block no longer writes its date where _ENV_DATE finds it") + assert f"The current year is {ENV_YEAR}." in _descriptions(body).get("websearch", ""), ( + f"OpenCode {VERSION}'s websearch tool no longer names its year where _SEARCH_YEAR finds it") + machine = _machine_dates() + for body in sent: + harness = "\n".join([*_system_texts(body), *_descriptions(body).values()]) + assert not [date for date in machine if date in harness], ( + f"OpenCode {VERSION} wrote this machine's date where the relay doesn't rewrite it") + assert seen_clis and all(len(clis) == 1 for clis in seen_clis), ( + f"OpenCode {VERSION} ran a turn in other than one process, and one it starts follows the env's clock: " + f"{seen_clis}") diff --git a/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py b/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py index 0bab105b9..20b5bea65 100644 --- a/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py +++ b/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py @@ -172,5 +172,5 @@ def test_the_tool_names_are_those_of_the_cli_version_package_json_pins(): pinned = json.loads((AGENT_DIR / "package.json").read_text())["dependencies"]["opencode-ai"] assert opencode_bridge.TOOLS_CLI_VERSION == pinned, ( - "the CLI version changed: record the tools the new CLI offers in OpenCodeTool, check that _ENV_DATE and " - "_SEARCH_YEAR still find where it writes its date, then TOOLS_CLI_VERSION") + "the CLI version changed: record the tools the new CLI offers in OpenCodeTool, then TOOLS_CLI_VERSION; " + "tst/integration/agent/opencode_env_date_test.py checks that the relay still finds where it writes its date") From 5f64a45295cc40a0f7817fcc983b56352c0633cb Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 22 Nov 2026 21:50:13 -0800 Subject: [PATCH 7/8] refactor(agents): OpenCode's env date lives in its own module, and the relay logs what it refuses Everything that depends on where the pinned OpenCode writes its date, the patterns, the date read and the rewrite, moves from the bridge into opencode_date.py with its own tests, so a CLI upgrade touches one file. The date read keeps its process-group kill to itself, leaving the bridge's _communicate as it was. The relay logs each call it refuses, the bridge's config parameter no longer shares the clock_armed function's name, and the docstrings and README say it plainly. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/README.md | 12 +- .../agents/agents/opencode/Dockerfile | 2 +- .../agents/agents/opencode/install.sh | 2 +- .../agents/agents/opencode/opencode_bridge.py | 120 ++-------- .../agents/agents/opencode/opencode_date.py | 114 ++++++++++ .../utils/model_relay/model_relay.py | 4 + .../agent/opencode_env_date_test.py | 12 +- tst/unit/agents/opencode/agent.py | 1 + tst/unit/agents/opencode/test_env_clock.py | 207 +----------------- .../test_opencode_bridge_builtin_tools.py | 2 +- .../agents/opencode/test_opencode_date.py | 207 ++++++++++++++++++ tst/unit/agents/test_model_relay.py | 3 +- 12 files changed, 365 insertions(+), 321 deletions(-) create mode 100644 src/agent_env/agents/agents/opencode/opencode_date.py create mode 100644 tst/unit/agents/opencode/test_opencode_date.py diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index 911f2f889..39e9ca233 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -50,12 +50,12 @@ The A2A server starts with the real-time marker, so it and its records stay on r armed. From then on the CLI, its own "Today's date is" line included, and every command the model runs read the env's time, and a clock write that waits for followers waits for the agent. - **OpenCode's CLI on real time.** OpenCode orders a session's messages by when they were written and takes no time - before 1970, so a clock set behind a session's messages broke it. Where the image follows the clock, its bridge - starts the CLI with the real-time marker instead, so the commands it runs read the env's time, and the turn's model - relay puts the env's date, read from `date` as those commands read it, in the prompt's "Today's date" line and the - websearch tool's year while the clock is armed, and the CLI enables no provider but the endpoint, so none bypasses - the relay. A call whose date can't be read, or whose `` block has no date line the relay knows, is refused, - failing the turn rather than telling the model the real date. + before 1970, so on the env's clock a clock set behind its messages broke the session. Where the image follows the + clock, the bridge starts the CLI on real time; the commands it runs still read the env's time. While the clock is + armed, the turn's model relay puts the env's date, read from `date`, in the prompt's "Today's date" line and the + websearch tool's year, and the CLI enables no provider but the endpoint, so no call bypasses the relay. A call whose + date the relay can't read or place is refused, so the turn fails rather than tell the model the machine's date + (`opencode_date.py`). - **For the rest of the run.** An agent that follows goes on following: a later `sync_env_clock` without `agent_clock` re-arms the clock it follows, and only agents that never followed keep real time. - **Through the egress proxy.** While the agent follows an armed clock, the CLI goes out through the egress proxy, which diff --git a/src/agent_env/agents/agents/opencode/Dockerfile b/src/agent_env/agents/agents/opencode/Dockerfile index 1b18c8479..a366eac39 100644 --- a/src/agent_env/agents/agents/opencode/Dockerfile +++ b/src/agent_env/agents/agents/opencode/Dockerfile @@ -39,7 +39,7 @@ RUN npm ci --ignore-scripts --omit=dev --no-audit --no-fund --loglevel=error && COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt # install.sh and run.sh are install/v1's: in the image, so they stay in its build context. -COPY a2a_server.py opencode_bridge.py opencode_kit.py entrypoint.sh install.sh run.sh ./ +COPY a2a_server.py opencode_bridge.py opencode_date.py opencode_kit.py entrypoint.sh install.sh run.sh ./ # Every clocked agent's egress rule, which the bridge imports, the clock page's format it reads, and the model relay # that counts the turn's model calls (shared_sources.toml). COPY agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py ./ diff --git a/src/agent_env/agents/agents/opencode/install.sh b/src/agent_env/agents/agents/opencode/install.sh index 2eb3d29a6..f4906aa40 100755 --- a/src/agent_env/agents/agents/opencode/install.sh +++ b/src/agent_env/agents/agents/opencode/install.sh @@ -24,7 +24,7 @@ START_TIMEOUT_S=120 STOP_TIMEOUT_S=10 dockerfile_arg() { sed -n "s/^ARG $1=//p" "$here/Dockerfile"; } NODE_VERSION=$(dockerfile_arg NODE_VERSION) -AGENT_FILES="a2a_server.py opencode_bridge.py opencode_kit.py requirements.txt run.sh agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py" +AGENT_FILES="a2a_server.py opencode_bridge.py opencode_date.py opencode_kit.py requirements.txt run.sh agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py" # put SRC DEST replaces DEST by a rename, so a binary an earlier install's agent still runs can be replaced; put_dir SRC # DEST copies a folder to DEST, which isn't there. diff --git a/src/agent_env/agents/agents/opencode/opencode_bridge.py b/src/agent_env/agents/agents/opencode/opencode_bridge.py index 981abc1f5..67c2b465c 100644 --- a/src/agent_env/agents/agents/opencode/opencode_bridge.py +++ b/src/agent_env/agents/agents/opencode/opencode_bridge.py @@ -23,7 +23,6 @@ import re import signal import threading -import time from collections.abc import Callable, Mapping from dataclasses import dataclass, field from datetime import datetime, timezone @@ -36,7 +35,8 @@ from agent_egress import clock_armed, egress_env from agentenv_protocol.a2a_agent import Usage from agentenv_protocol.a2a_agent.clock import follows -from model_relay import Calls, Refusal, model_relay +from model_relay import Calls, model_relay +from opencode_date import env_date_rewrite logger = logging.getLogger(__name__) @@ -47,13 +47,6 @@ 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" -# Where the CLI, on real time, puts its own date in a model call: the block's line in its system prompt and the -# websearch tool's year, as TOOLS_CLI_VERSION writes them (src/session/system.ts, src/tool/websearch.txt). -_ENV_DATE = re.compile(r"(\n(?: [^\n]*\n)*? Today's date: )[^\n]*") -_SEARCH_YEAR = re.compile(r"The current year is -?\d+\.") -_DATE_TIMEOUT_S = 5 -_DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") -_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") # 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. @@ -113,107 +106,29 @@ def cli_env(context_id: str, environ: Mapping[str, str] = os.environ, *, mcp_ser clock_armed: bool = False) -> dict[str, str]: """The CLI's environment for ``context_id``: this process's, with the context's own data and state dirs, and on an armed clock the egress proxy (``egress_env``) for the model endpoint and the env's MCP servers, which the CLI - connects to itself. Where the image follows the env's clock, the CLI starts on real time: it orders a session's - messages by when they were written and takes no time before 1970, so on the env's clock a set behind them broke - the session. What it starts, the model's commands, reads the env's time, and the relay puts the env's date in the - model calls (``env_date_rewrite``).""" + connects to itself. Where the image follows the env's clock, the CLI starts on real time, since it orders a + session's messages by when they were written and takes no time before 1970; what it starts still reads the env's + time, and the turn's relay tells the model the env's date (``opencode_date``).""" urls = [environ.get("LITELLM_BASE_URL", ""), *(info["url"] for info in (mcp_servers or {}).values())] return {**environ, **_context_xdg(context_id), **egress_env(environ, urls, armed=clock_armed), **({"AGENTENV_REAL_TIME": "1"} if follows() else {})} -async def _communicate(*cmd: str, env: Mapping[str, str], timeout_s: float) -> tuple[int, bytes, bytes]: - """Run a short CLI command to its end; one that outlives ``timeout_s`` is killed with what it started, which would - otherwise hold its output open. Its session's group is killed even when the command has exited itself and left - something holding its output, which the group's id keeps from being another process's.""" +async def _communicate(*cmd: str, env: Mapping[str, str], timeout_s: int) -> tuple[int, bytes, bytes]: + """Run a short CLI command to its end; one that outlives ``timeout_s`` is killed.""" proc = await asyncio.create_subprocess_exec( - *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=dict(env), start_new_session=True, + *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=dict(env), ) try: out, err = await asyncio.wait_for(proc.communicate(), timeout=timeout_s) except BaseException: - with contextlib.suppress(ProcessLookupError, PermissionError): - os.killpg(proc.pid, signal.SIGKILL) - _kill_cli(proc) - await _reap(proc) + with contextlib.suppress(ProcessLookupError): + proc.kill() + await proc.wait() raise return proc.returncode, out, err -async def _env_today() -> tuple[str, int]: - """The env's date, as the CLI's ``Date.toDateString()`` writes one in this zone, and its year, read from ``date``, - which libfaketime fakes for what this server starts, as for the model's commands.""" - def unread(reason: str) -> Refusal: - return Refusal(f"the env's date couldn't be read for the model: {reason}") - - environ = {name: value for name, value in os.environ.items() if name != "AGENTENV_REAL_TIME"} - try: - code, out, err = await _communicate("date", "+%s %N", env=environ, timeout_s=_DATE_TIMEOUT_S) - except TimeoutError: - raise unread(f"date gave no answer within {_DATE_TIMEOUT_S} s") from None - except OSError as exc: - raise unread(f"{type(exc).__name__}: {exc}") from exc - if code != 0: - raise unread(f"date exited {code}: {err.decode(errors='replace').strip()[:200]}") - try: - seconds, _ = out.decode().split() - day = time.localtime(int(seconds)) - except (ValueError, OverflowError, OSError) as exc: - raise unread(f"date printed {out.decode(errors='replace')[:100]!r}") from exc - return f"{_DAYS[day.tm_wday]} {_MONTHS[day.tm_mon - 1]} {day.tm_mday:02d} {day.tm_year:04d}", day.tm_year - - -def _texts(request: dict, roles: tuple[str, ...]): - """Each text of the request's messages in ``roles``, as (holder, key).""" - for message in request.get("messages") or []: - if not isinstance(message, dict) or message.get("role") not in roles: - continue - content = message.get("content") - if isinstance(content, str): - yield message, "content" - elif isinstance(content, list): - yield from ((part, "text") for part in content if isinstance(part, dict) and isinstance(part.get("text"), str)) - - -def _search_descriptions(request: dict): - for tool in request.get("tools") or []: - function = tool.get("function") if isinstance(tool, dict) else None - if isinstance(function, dict) and function.get("name") == "websearch" \ - and isinstance(function.get("description"), str): - yield function, "description" - - -async def env_date_rewrite(body: bytes) -> bytes: - """A model call as the CLI, on real time, wrote it, with the env's date on each block's date line, the CLI's - among any a prompt or instructions add, and in websearch's year, while this agent follows an armed clock; as - written otherwise, when the two dates are one. A call that isn't JSON, a system prompt whose block has no - date line this knows, or a date that can't be read, refuses the call, so the model is never told the real date on - the env's clock.""" - if not clock_armed(): - return body - try: - request = json.loads(body) - except ValueError as exc: - raise Refusal("the model call isn't JSON this agent can read, so the model can't be told the env's date") \ - from exc - if not isinstance(request, dict): - return body - system = [(holder, key) for holder, key in _texts(request, ("system", "developer")) if "\n" in holder[key]] - search = [(holder, key) for holder, key in _search_descriptions(request) if _SEARCH_YEAR.search(holder[key])] - if not system and not search: - return body - if any(not _ENV_DATE.search(holder[key]) for holder, key in system): - raise Refusal("OpenCode's block has no date line this agent knows, so the model can't be told the env's " - "date") - today, year = await _env_today() - for holder, key in system: - holder[key] = _ENV_DATE.sub(lambda match: match.group(1) + today, holder[key]) - for holder, key in search: - holder[key] = _SEARCH_YEAR.sub(f"The current year is {year}.", holder[key], count=1) - # Escaped, so a lone surrogate an MCP server's tool sent, which UTF-8 can't encode, goes as it came. - return json.dumps(request, separators=(",", ":")).encode() - - async def export_session(context_id: str, session_id: str, timeout_s: int = _CLI_TIMEOUT_S) -> bytes: """`opencode export ` for the given context: the transcript JSON bytes.""" env = cli_env(context_id, clock_armed=clock_armed()) @@ -372,14 +287,13 @@ def _build_config( environ: Mapping[str, str] = os.environ, instructions: list[str] | None = None, builtin_tools: OpenCodeTools | None = None, - clock_armed: bool = False, + armed: bool = False, ) -> dict: """Assemble the inline OpenCode config passed via OPENCODE_CONFIG_CONTENT. Everything dynamic (model, MCP servers, headers) is rebuilt per turn so there - is no on-disk config to race on. On an armed clock only the endpoint is enabled, whose calls the turn's relay - dates: a provider a project's config adds would tell the model the real date, and a model named on one isn't - found.""" + is no on-disk config to race on. On an armed clock only the endpoint is enabled, whose calls the relay dates, so a + provider a project's config adds can't send the model the machine's date.""" options: dict = {"baseURL": _base_url(environ), "apiKey": "{env:LITELLM_API_KEY}"} if headers: options["headers"] = dict(headers) @@ -429,7 +343,7 @@ def _build_config( } if instructions: config["instructions"] = list(instructions) - if clock_armed: + if armed: config["enabled_providers"] = ["litellm"] if mcp_servers: @@ -527,7 +441,7 @@ async def run_opencode(prompt: str, context_id: str, **kwargs) -> OpencodeResult """Run one turn, ``_run_opencode``'s, with OpenCode's provider pointed at a model relay of the turn's own, which counts every model call the CLI makes: its steps', its subagents' sessions', its compaction's, its title's and its answered retries'. The turn's usage is theirs, a call answered without usage counted as unreported. The relay - puts the env's date in each call (``env_date_rewrite``).""" + tells the model the env's date on an armed clock (``opencode_date``).""" calls = Calls() async with model_relay(_base_url(os.environ).removesuffix("/v1"), calls, rewrite=env_date_rewrite) as relay: result = await _run_opencode(prompt, context_id, base_url=relay, **kwargs) @@ -581,7 +495,7 @@ 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, clock_armed=armed) + instructions=instructions, builtin_tools=builtin_tools, armed=armed) # Resume a specific session by id (multi-turn continuity). `--continue` # does NOT replay history to the model; `-s ` does. First turn diff --git a/src/agent_env/agents/agents/opencode/opencode_date.py b/src/agent_env/agents/agents/opencode/opencode_date.py new file mode 100644 index 000000000..b127a6f32 --- /dev/null +++ b/src/agent_env/agents/agents/opencode/opencode_date.py @@ -0,0 +1,114 @@ +"""The env's date in OpenCode's model calls. Where the image follows the env's clock, the CLI runs on real time to keep +its sessions in order, and the turn's model relay puts the env's date where the CLI put its own. The patterns below +are where the pinned CLI, TOOLS_CLI_VERSION, writes its date; tst/integration/agent/opencode_env_date_test.py checks +them against it.""" + +from __future__ import annotations + +import asyncio +import contextlib +import json +import os +import re +import signal +import time + +from agent_egress import clock_armed +from model_relay import Refusal + +# The block's date line in the CLI's system prompt (src/session/system.ts) and the websearch tool's year +# (src/tool/websearch.txt). +_ENV_DATE = re.compile(r"(\n(?: [^\n]*\n)*? Today's date: )[^\n]*") +_SEARCH_YEAR = re.compile(r"The current year is -?\d+\.") +_DATE_TIMEOUT_S = 5 +_DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") +_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") + + +async def env_date_rewrite(body: bytes) -> bytes: + """The model call with the env's date in place of the CLI's, while this agent follows an armed clock; unchanged + otherwise. A call that isn't JSON, an block without a date line this knows, or a date that can't be read is + refused, so the model is never told the machine's date instead.""" + if not clock_armed(): + return body + try: + request = json.loads(body) + except ValueError as exc: + raise Refusal("the model call isn't JSON this agent can read, so the model can't be told the env's date") \ + from exc + if not isinstance(request, dict): + return body + system = [(holder, key) for holder, key in _texts(request, ("system", "developer")) if "\n" in holder[key]] + search = [(holder, key) for holder, key in _search_descriptions(request) if _SEARCH_YEAR.search(holder[key])] + if not system and not search: + return body + if any(not _ENV_DATE.search(holder[key]) for holder, key in system): + raise Refusal("OpenCode's block has no date line this agent knows, so the model can't be told the env's " + "date") + today, year = await _env_today() + # Every block, the CLI's and any a prompt or its instructions add. + for holder, key in system: + holder[key] = _ENV_DATE.sub(lambda match: match.group(1) + today, holder[key]) + for holder, key in search: + holder[key] = _SEARCH_YEAR.sub(f"The current year is {year}.", holder[key], count=1) + # Escaped, so a lone surrogate an MCP server's tool sent, which UTF-8 can't encode, goes as it came. + return json.dumps(request, separators=(",", ":")).encode() + + +def _texts(request: dict, roles: tuple[str, ...]): + """Each text of the request's messages in ``roles``, as (holder, key), so it can be replaced in place.""" + for message in request.get("messages") or []: + if not isinstance(message, dict) or message.get("role") not in roles: + continue + content = message.get("content") + if isinstance(content, str): + yield message, "content" + elif isinstance(content, list): + yield from ((part, "text") for part in content if isinstance(part, dict) and isinstance(part.get("text"), str)) + + +def _search_descriptions(request: dict): + for tool in request.get("tools") or []: + function = tool.get("function") if isinstance(tool, dict) else None + if isinstance(function, dict) and function.get("name") == "websearch" \ + and isinstance(function.get("description"), str): + yield function, "description" + + +async def _env_today() -> tuple[str, int]: + """The env's date as the CLI's ``Date.toDateString()`` writes one in this zone, and its year. It comes from + ``date``: this server runs on real time, but what it starts reads the env's clock, as the model's commands do.""" + def unread(reason: str) -> Refusal: + return Refusal(f"the env's date couldn't be read for the model: {reason}") + + try: + code, out, err = await _read_date() + except TimeoutError: + raise unread(f"date gave no answer within {_DATE_TIMEOUT_S} s") from None + except OSError as exc: + raise unread(f"{type(exc).__name__}: {exc}") from exc + if code != 0: + raise unread(f"date exited {code}: {err.decode(errors='replace').strip()[:200]}") + try: + seconds, _ = out.decode().split() + day = time.localtime(int(seconds)) + except (ValueError, OverflowError, OSError) as exc: + raise unread(f"date printed {out.decode(errors='replace')[:100]!r}") from exc + return f"{_DAYS[day.tm_wday]} {_MONTHS[day.tm_mon - 1]} {day.tm_mday:02d} {day.tm_year:04d}", day.tm_year + + +async def _read_date() -> tuple[int, bytes, bytes]: + """``date``'s exit code and output. Past the timeout its process group is killed, which reaches anything it left + holding its output, even after it exited itself.""" + environ = {name: value for name, value in os.environ.items() if name != "AGENTENV_REAL_TIME"} + proc = await asyncio.create_subprocess_exec("date", "+%s %N", stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, env=environ, start_new_session=True) + try: + out, err = await asyncio.wait_for(proc.communicate(), timeout=_DATE_TIMEOUT_S) + except BaseException: + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(proc.pid, signal.SIGKILL) + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(proc.wait(), _DATE_TIMEOUT_S) + raise + return proc.returncode, out, err diff --git a/src/agent_env/utils/model_relay/model_relay.py b/src/agent_env/utils/model_relay/model_relay.py index f27aa8eaf..489512930 100644 --- a/src/agent_env/utils/model_relay/model_relay.py +++ b/src/agent_env/utils/model_relay/model_relay.py @@ -6,6 +6,7 @@ import contextlib import json +import logging import secrets from collections.abc import AsyncIterator, Awaitable, Callable, Mapping from contextlib import asynccontextmanager @@ -15,6 +16,8 @@ from agentenv_protocol.a2a_agent import Usage from aiohttp import ClientError, ClientSession, ClientTimeout, web +logger = logging.getLogger(__name__) + # The routes whose POSTs are model calls: Chat Completions, Responses and Anthropic's Messages. _CALL_ROUTES = ("/chat/completions", "/responses", "/messages") _HOP_HEADERS = {"host", "content-length", "transfer-encoding", "connection", "keep-alive", "accept-encoding"} @@ -175,6 +178,7 @@ async def forward(request: web.Request) -> web.StreamResponse: except Exception as exc: status = 400 reason = str(exc) if isinstance(exc, Refusal) else f"model relay: {type(exc).__name__}: {exc}" + logger.warning("model relay refused a call: %s", reason) return web.json_response({"error": {"message": reason, "type": "invalid_request_error"}}, status=status) async with client.request(request.method, f"{upstream}/{path}", params=request.query, diff --git a/tst/integration/agent/opencode_env_date_test.py b/tst/integration/agent/opencode_env_date_test.py index c01e303b2..03577b06c 100644 --- a/tst/integration/agent/opencode_env_date_test.py +++ b/tst/integration/agent/opencode_env_date_test.py @@ -14,7 +14,7 @@ import pytest -from tst.unit.agents.opencode.agent import AGENT_DIR, opencode_bridge +from tst.unit.agents.opencode.agent import AGENT_DIR, opencode_bridge, opencode_date from tst.util import fake_openai pytestmark = [pytest.mark.integration] @@ -104,8 +104,8 @@ async def env_today() -> tuple[str, int]: monkeypatch.setenv("LITELLM_API_KEY", "sk-fake") monkeypatch.setenv("OPENCODE_ENABLE_EXA", "1") monkeypatch.setattr(opencode_bridge, "SESSIONS_ROOT", str(tmp_path / "sessions")) - monkeypatch.setattr(opencode_bridge, "clock_armed", lambda: True) - monkeypatch.setattr(opencode_bridge, "_env_today", env_today) + monkeypatch.setattr(opencode_date, "clock_armed", lambda: True) + monkeypatch.setattr(opencode_date, "_env_today", env_today) (tmp_path / "work").mkdir() with fake_openai.FakeOpenAI(respond=respond) as endpoint: @@ -117,12 +117,12 @@ async def env_today() -> tuple[str, int]: sent = [seen.body for seen in endpoint.completions()] turns = [body for body in sent if any("" in text for text in _system_texts(body))] assert turns, (f"OpenCode {VERSION} sent its block in no system message, so the relay can't tell the model " - "the env's date: find where it puts its date now, and fix _ENV_DATE in opencode_bridge") + "the env's date: find where it puts its date now, and fix _ENV_DATE in opencode_date.py") for body in turns: assert f" Today's date: {ENV_TODAY}\n" in "\n".join(_system_texts(body)), ( - f"OpenCode {VERSION}'s block no longer writes its date where _ENV_DATE finds it") + f"OpenCode {VERSION}'s block no longer writes its date where opencode_date's _ENV_DATE finds it") assert f"The current year is {ENV_YEAR}." in _descriptions(body).get("websearch", ""), ( - f"OpenCode {VERSION}'s websearch tool no longer names its year where _SEARCH_YEAR finds it") + f"OpenCode {VERSION}'s websearch tool no longer names its year where opencode_date's _SEARCH_YEAR finds it") machine = _machine_dates() for body in sent: harness = "\n".join([*_system_texts(body), *_descriptions(body).values()]) diff --git a/tst/unit/agents/opencode/agent.py b/tst/unit/agents/opencode/agent.py index 8836771e8..3253b3611 100644 --- a/tst/unit/agents/opencode/agent.py +++ b/tst/unit/agents/opencode/agent.py @@ -17,6 +17,7 @@ PYTHONPATH = os.pathsep.join(IMPORTED) sys.path[:0] = IMPORTED opencode_bridge = importlib.import_module("opencode_bridge") +opencode_date = importlib.import_module("opencode_date") opencode_kit = importlib.import_module("opencode_kit") agent_egress = importlib.import_module("agent_egress") model_relay = importlib.import_module("model_relay") diff --git a/tst/unit/agents/opencode/test_env_clock.py b/tst/unit/agents/opencode/test_env_clock.py index b52dcdc31..eabbb6ff0 100644 --- a/tst/unit/agents/opencode/test_env_clock.py +++ b/tst/unit/agents/opencode/test_env_clock.py @@ -1,24 +1,19 @@ """OpenCode on the env's clock: its bridge hands the shared egress rule (tst/unit/agents/test_agent_egress.py) the model endpoint's URL and every MCP server's, which the CLI connects to itself, so on an armed clock it goes out through the image's egress proxy, and to loopback, the hosts NO_PROXY names and plain-HTTP hosts directly; unarmed, it goes out -as before. Where the image follows the clock, the CLI itself runs on real time and its model relay puts the env's date, -read from a command as the model's own commands read it, where the CLI put its own. What every clocked image shares is -checked in tst/unit/agents/test_agent_clock_images.py.""" +as before. Where the image follows the clock, the CLI itself runs on real time and each turn's relay tells the model the +env's date (test_opencode_date.py). What every clocked image shares is checked in +tst/unit/agents/test_agent_clock_images.py.""" from __future__ import annotations import asyncio import contextlib -import json -import os import subprocess -import time -import httpx import pytest -from aiohttp import web -from tst.unit.agents.opencode.agent import AGENT_DIR, agent_egress, model_relay, opencode_bridge +from tst.unit.agents.opencode.agent import AGENT_DIR, agent_egress, opencode_bridge, opencode_date PROXY = "http://127.0.0.1:3128" @@ -77,199 +72,7 @@ async def turn(prompt, context_id, **kwargs): monkeypatch.setattr(opencode_bridge, "_run_opencode", turn) asyncio.run(opencode_bridge.run_opencode("go", "ctx")) - assert seen == {"rewrite": opencode_bridge.env_date_rewrite, "base_url": "http://relay"} - assert "plugin" not in opencode_bridge._build_config("m", None, {}, None) - - -# OpenCode's system prompt as its SystemPrompt.environment writes it (opencode-ai 1.17.18, src/session/system.ts). -ENV_BLOCK = ("Here is some useful information about the environment you are running in:\n\n" - " Working directory: /app\n Workspace root folder: /app\n Is directory a git repo: no\n" - " Platform: linux\n Today's date: Sat Nov 21 2026\n") -SYSTEM = (f"You are OpenCode, the best coding agent on the planet.\n{ENV_BLOCK}\n" - "The task's notes say: Today's date: as written") -SEARCH = "Search the web.\n\nThe current year is 2026. You MUST use this year when searching for recent information." - - -def _call(system=SYSTEM, *, parts=False, tools=True, user=SYSTEM) -> dict: - content = [{"type": "text", "text": "header"}, {"type": "text", "text": system}] if parts else system - call = {"model": "m", "stream": True, "messages": [{"role": "system", "content": content}, - {"role": "user", "content": user}]} - if tools: - call["tools"] = [{"type": "function", "function": {"name": "websearch", "description": SEARCH}}, - {"type": "function", "function": {"name": "bash", "description": "The current year is 2026."}}] - return call - - -@pytest.fixture -def env_clock(tmp_path, monkeypatch): - """An armed clock, in UTC, whose time a stand-in ``date`` prints (``FAKE_DATE_OUT``; it fails without one) before - it exits (``FAKE_DATE_EXIT``), recording the environment it got.""" - bin_dir = tmp_path / "bin" - bin_dir.mkdir() - (bin_dir / "date").write_text('#!/bin/sh\nenv > "$FAKE_DATE_ENV"\n[ "$1" = "+%s %N" ] || exit 2\n' - '[ -n "$FAKE_DATE_SLEEP" ] && sleep "$FAKE_DATE_SLEEP"\n' - '[ -n "$FAKE_DATE_KID" ] && { sleep 30 & echo $! > "$FAKE_DATE_KID"; }\n' - '[ -n "$FAKE_DATE_OUT" ] || { echo no clock >&2; exit 1; }\necho "$FAKE_DATE_OUT"\n' - 'exit "${FAKE_DATE_EXIT:-0}"\n') - (bin_dir / "date").chmod(0o755) - monkeypatch.setenv("PATH", f"{bin_dir}:{os.environ['PATH']}") - monkeypatch.setenv("FAKE_DATE_ENV", str(tmp_path / "date.env")) - monkeypatch.setenv("AGENTENV_REAL_TIME", "1") - monkeypatch.setenv("TZ", "UTC") - time.tzset() - monkeypatch.setattr(opencode_bridge, "clock_armed", lambda: True) - yield tmp_path / "date.env" - monkeypatch.undo() - time.tzset() - - -def _rewrite(call: dict) -> dict: - return json.loads(asyncio.run(opencode_bridge.env_date_rewrite(json.dumps(call).encode()))) - - -@pytest.mark.parametrize("date_out, today, year", [ - ("1801742400 000000000", "Thu Feb 04 2027", 2027), - ("7258161600 250000000", "Wed Jan 01 2200", 2200), - ("-631108800 000000000", "Sun Jan 01 1950", 1950), - # Half a second before 1950: date prints the second below and a positive fraction. - ("-631152001 500000000", "Sat Dec 31 1949", 1949), -]) -@pytest.mark.parametrize("parts", [False, True]) -def test_on_an_armed_clock_the_model_is_told_the_env_date_a_command_reads(env_clock, monkeypatch, date_out, today, - year, parts): - monkeypatch.setenv("FAKE_DATE_OUT", date_out) - call = _rewrite(_call(parts=parts)) - - system = call["messages"][0]["content"][1]["text"] if parts else call["messages"][0]["content"] - assert system == SYSTEM.replace("Today's date: Sat Nov 21 2026", f"Today's date: {today}") - assert call["messages"][1]["content"] == SYSTEM - assert call["tools"][0]["function"]["description"] == SEARCH.replace("2026", str(year)) - assert call["tools"][1]["function"]["description"] == "The current year is 2026." - assert "AGENTENV_REAL_TIME" not in env_clock.read_text() and "TZ=UTC" in env_clock.read_text() - - -def test_every_env_blocks_date_line_takes_the_env_date_so_the_clis_does_wherever_it_comes(env_clock, monkeypatch): - """A config's agent prompt, which comes before the CLI's block, or its instructions, after it, may hold an - block of their own.""" - monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") - prompt = "You are careful.\n\n Platform: linux\n Today's date: Mon Jan 01 2001\n\n" - written = prompt + SYSTEM + "\n" + prompt - - system = _rewrite(_call(written))["messages"][0]["content"] - - assert system == written.replace("Mon Jan 01 2001", "Thu Feb 04 2027").replace("Sat Nov 21 2026", "Thu Feb 04 2027") - - -def test_a_lone_surrogate_in_a_tool_an_mcp_server_sent_goes_as_it_came(env_clock, monkeypatch): - """The CLI sends it escaped, as a server's tool list had it; UTF-8 can't encode it unescaped.""" - monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") - call = _call() - call["tools"].append({"type": "function", "function": {"name": "env_cut", "description": "cut \ud83d"}}) - - assert _rewrite(call)["tools"][2]["function"]["description"] == "cut \ud83d" - - -@pytest.mark.usefixtures("socket_enabled") -def test_the_relay_sends_the_endpoint_the_call_with_the_env_date(env_clock, monkeypatch): - monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") - received = [] - - async def endpoint(request): - received.append((request.headers["Content-Length"], await request.read())) - return web.json_response({"choices": [], "usage": {"prompt_tokens": 1, "completion_tokens": 1}}) - - async def run(): - app = web.Application() - app.router.add_post("/v1/chat/completions", endpoint) - runner = web.AppRunner(app) - await runner.setup() - site = web.TCPSite(runner, "127.0.0.1", 0) - await site.start() - upstream = f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}" - try: - async with model_relay.model_relay(upstream, model_relay.Calls(), - rewrite=opencode_bridge.env_date_rewrite) as root: - async with httpx.AsyncClient(timeout=10) as client: - return (await client.post(f"{root}/v1/chat/completions", content=json.dumps(_call()))).status_code - finally: - await runner.cleanup() - - assert asyncio.run(run()) == 200 - ((length, body),) = received - assert int(length) == len(body) and json.loads(body)["stream"] is True - assert json.loads(body)["messages"][0]["content"] == SYSTEM.replace("Sat Nov 21 2026", "Thu Feb 04 2027") - - -def test_the_date_is_written_in_the_zone_the_cli_writes_its_own_in(env_clock, monkeypatch): - monkeypatch.setenv("FAKE_DATE_OUT", "1801785600 000000000") # 2027-02-05T00:00Z, still the 4th in New York - monkeypatch.setenv("TZ", "America/New_York") - time.tzset() - - assert "Today's date: Thu Feb 04 2027" in _rewrite(_call())["messages"][0]["content"] - - -@pytest.mark.parametrize("armed", [False, True]) -def test_a_call_with_nothing_to_rewrite_or_off_the_clock_goes_as_written_and_reads_no_date(env_clock, monkeypatch, - armed): - monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") - monkeypatch.setattr(opencode_bridge, "clock_armed", lambda: armed) - calls = [json.dumps(_call(), indent=1).encode(), b"not json"] if not armed else [] - calls += [json.dumps(_call("A title for this conversation", tools=False, user="hi")).encode()] - - for body in calls: - assert asyncio.run(opencode_bridge.env_date_rewrite(body)) == body - assert not env_clock.exists() - - -def test_on_an_armed_clock_a_call_that_isnt_json_is_refused_rather_than_sent_with_the_real_date(env_clock): - with pytest.raises(opencode_bridge.Refusal, match="isn't JSON"): - asyncio.run(opencode_bridge.env_date_rewrite(json.dumps(_call()).encode()[:-1])) - - -@pytest.mark.parametrize("environ, reason", [ - ({}, "date exited 1: no clock"), - ({"FAKE_DATE_OUT": "1801742400 000000000", "FAKE_DATE_EXIT": "3"}, "date exited 3"), - ({"FAKE_DATE_OUT": "soon"}, "date printed 'soon\\n'"), - ({"FAKE_DATE_OUT": "1 0", "FAKE_DATE_SLEEP": "10"}, "date gave no answer within 2 s"), -]) -def test_a_date_that_cant_be_read_refuses_the_call_rather_than_tell_the_model_real_time(env_clock, monkeypatch, - environ, reason): - """A date that hangs is killed with the sleep it started, which holds its output open, so the refusal comes in - its time.""" - monkeypatch.setattr(opencode_bridge, "_DATE_TIMEOUT_S", 2) - for name, value in environ.items(): - monkeypatch.setenv(name, value) - started = time.monotonic() - - with pytest.raises(opencode_bridge.Refusal) as refused: - _rewrite(_call()) - - assert str(refused.value).startswith(f"the env's date couldn't be read for the model: {reason}") - assert time.monotonic() - started < 6 - - -def test_a_date_that_exits_leaving_a_process_on_its_output_is_refused_and_that_process_killed(env_clock, monkeypatch, - tmp_path): - """The date has exited, so only its session's group still reaches what it left holding the pipes.""" - monkeypatch.setattr(opencode_bridge, "_DATE_TIMEOUT_S", 1) - monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") - monkeypatch.setenv("FAKE_DATE_KID", str(tmp_path / "kid")) - - with pytest.raises(opencode_bridge.Refusal, match="date gave no answer within 1 s"): - _rewrite(_call()) - - kid, deadline = (tmp_path / "kid").read_text().strip(), time.monotonic() + 5 - while (state := subprocess.run(["ps", "-o", "stat=", "-p", kid], capture_output=True, text=True).stdout.strip()) \ - and not state.startswith("Z") and time.monotonic() < deadline: - time.sleep(0.1) - assert not state or state.startswith("Z"), state - - -def test_an_env_block_without_a_date_line_this_knows_refuses_the_call(env_clock, monkeypatch): - monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") - - with pytest.raises(opencode_bridge.Refusal, match="no date line"): - _rewrite(_call(SYSTEM.replace(" Today's date:", " Date:"))) + assert seen == {"rewrite": opencode_date.env_date_rewrite, "base_url": "http://relay"} @pytest.mark.parametrize("base_url, direct", [("http://10.0.0.5:4000", True), ("https://litellm.example.com", False)]) diff --git a/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py b/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py index 20b5bea65..049463c41 100644 --- a/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py +++ b/tst/unit/agents/opencode/test_opencode_bridge_builtin_tools.py @@ -173,4 +173,4 @@ def test_the_tool_names_are_those_of_the_cli_version_package_json_pins(): assert opencode_bridge.TOOLS_CLI_VERSION == pinned, ( "the CLI version changed: record the tools the new CLI offers in OpenCodeTool, then TOOLS_CLI_VERSION; " - "tst/integration/agent/opencode_env_date_test.py checks that the relay still finds where it writes its date") + "tst/integration/agent/opencode_env_date_test.py checks that opencode_date still finds where it writes its date") diff --git a/tst/unit/agents/opencode/test_opencode_date.py b/tst/unit/agents/opencode/test_opencode_date.py new file mode 100644 index 000000000..64b3c5af2 --- /dev/null +++ b/tst/unit/agents/opencode/test_opencode_date.py @@ -0,0 +1,207 @@ +"""The env's date in OpenCode's model calls (opencode_date): on an armed clock the turn's relay puts the env's date, as +a ``date`` started by the A2A server reads it, where the CLI, on real time, put its own, and refuses a call whose date +it can't read or place; off the clock, or with nothing to rewrite, a call goes as the CLI wrote it.""" + +from __future__ import annotations + +import asyncio +import json +import os +import subprocess +import time + +import httpx +import pytest +from aiohttp import web + +from tst.unit.agents.opencode.agent import model_relay, opencode_date + +# OpenCode's system prompt as its SystemPrompt.environment writes it (opencode-ai 1.17.18, src/session/system.ts). +ENV_BLOCK = ("Here is some useful information about the environment you are running in:\n\n" + " Working directory: /app\n Workspace root folder: /app\n Is directory a git repo: no\n" + " Platform: linux\n Today's date: Sat Nov 21 2026\n") +SYSTEM = (f"You are OpenCode, the best coding agent on the planet.\n{ENV_BLOCK}\n" + "The task's notes say: Today's date: as written") +SEARCH = "Search the web.\n\nThe current year is 2026. You MUST use this year when searching for recent information." + + +def _call(system=SYSTEM, *, parts=False, tools=True, user=SYSTEM) -> dict: + content = [{"type": "text", "text": "header"}, {"type": "text", "text": system}] if parts else system + call = {"model": "m", "stream": True, "messages": [{"role": "system", "content": content}, + {"role": "user", "content": user}]} + if tools: + call["tools"] = [{"type": "function", "function": {"name": "websearch", "description": SEARCH}}, + {"type": "function", "function": {"name": "bash", "description": "The current year is 2026."}}] + return call + + +@pytest.fixture +def env_clock(tmp_path, monkeypatch): + """An armed clock, in UTC, whose time a stand-in ``date`` prints (``FAKE_DATE_OUT``; it fails without one) before + it exits (``FAKE_DATE_EXIT``), recording the environment it got.""" + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + (bin_dir / "date").write_text('#!/bin/sh\nenv > "$FAKE_DATE_ENV"\n[ "$1" = "+%s %N" ] || exit 2\n' + '[ -n "$FAKE_DATE_SLEEP" ] && sleep "$FAKE_DATE_SLEEP"\n' + '[ -n "$FAKE_DATE_KID" ] && { sleep 30 & echo $! > "$FAKE_DATE_KID"; }\n' + '[ -n "$FAKE_DATE_OUT" ] || { echo no clock >&2; exit 1; }\necho "$FAKE_DATE_OUT"\n' + 'exit "${FAKE_DATE_EXIT:-0}"\n') + (bin_dir / "date").chmod(0o755) + monkeypatch.setenv("PATH", f"{bin_dir}:{os.environ['PATH']}") + monkeypatch.setenv("FAKE_DATE_ENV", str(tmp_path / "date.env")) + monkeypatch.setenv("AGENTENV_REAL_TIME", "1") + monkeypatch.setenv("TZ", "UTC") + time.tzset() + monkeypatch.setattr(opencode_date, "clock_armed", lambda: True) + yield tmp_path / "date.env" + monkeypatch.undo() + time.tzset() + + +def _rewrite(call: dict) -> dict: + return json.loads(asyncio.run(opencode_date.env_date_rewrite(json.dumps(call).encode()))) + + +@pytest.mark.parametrize("date_out, today, year", [ + ("1801742400 000000000", "Thu Feb 04 2027", 2027), + ("7258161600 250000000", "Wed Jan 01 2200", 2200), + ("-631108800 000000000", "Sun Jan 01 1950", 1950), + # Half a second before 1950: date prints the second below and a positive fraction. + ("-631152001 500000000", "Sat Dec 31 1949", 1949), +]) +@pytest.mark.parametrize("parts", [False, True]) +def test_on_an_armed_clock_the_model_is_told_the_env_date_a_command_reads(env_clock, monkeypatch, date_out, today, + year, parts): + monkeypatch.setenv("FAKE_DATE_OUT", date_out) + call = _rewrite(_call(parts=parts)) + + system = call["messages"][0]["content"][1]["text"] if parts else call["messages"][0]["content"] + assert system == SYSTEM.replace("Today's date: Sat Nov 21 2026", f"Today's date: {today}") + assert call["messages"][1]["content"] == SYSTEM + assert call["tools"][0]["function"]["description"] == SEARCH.replace("2026", str(year)) + assert call["tools"][1]["function"]["description"] == "The current year is 2026." + assert "AGENTENV_REAL_TIME" not in env_clock.read_text() and "TZ=UTC" in env_clock.read_text() + + +def test_every_env_blocks_date_line_takes_the_env_date_so_the_clis_does_wherever_it_comes(env_clock, monkeypatch): + """A config's agent prompt, which comes before the CLI's block, or its instructions, after it, may hold an + block of their own.""" + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + prompt = "You are careful.\n\n Platform: linux\n Today's date: Mon Jan 01 2001\n\n" + written = prompt + SYSTEM + "\n" + prompt + + system = _rewrite(_call(written))["messages"][0]["content"] + + assert system == written.replace("Mon Jan 01 2001", "Thu Feb 04 2027").replace("Sat Nov 21 2026", "Thu Feb 04 2027") + + +def test_a_lone_surrogate_in_a_tool_an_mcp_server_sent_goes_as_it_came(env_clock, monkeypatch): + """The CLI sends it escaped, as a server's tool list had it; UTF-8 can't encode it unescaped.""" + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + call = _call() + call["tools"].append({"type": "function", "function": {"name": "env_cut", "description": "cut \ud83d"}}) + + assert _rewrite(call)["tools"][2]["function"]["description"] == "cut \ud83d" + + +@pytest.mark.usefixtures("socket_enabled") +def test_the_relay_sends_the_endpoint_the_call_with_the_env_date(env_clock, monkeypatch): + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + received = [] + + async def endpoint(request): + received.append((request.headers["Content-Length"], await request.read())) + return web.json_response({"choices": [], "usage": {"prompt_tokens": 1, "completion_tokens": 1}}) + + async def run(): + app = web.Application() + app.router.add_post("/v1/chat/completions", endpoint) + runner = web.AppRunner(app) + await runner.setup() + site = web.TCPSite(runner, "127.0.0.1", 0) + await site.start() + upstream = f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}" + try: + async with model_relay.model_relay(upstream, model_relay.Calls(), + rewrite=opencode_date.env_date_rewrite) as root: + async with httpx.AsyncClient(timeout=10) as client: + return (await client.post(f"{root}/v1/chat/completions", content=json.dumps(_call()))).status_code + finally: + await runner.cleanup() + + assert asyncio.run(run()) == 200 + ((length, body),) = received + assert int(length) == len(body) and json.loads(body)["stream"] is True + assert json.loads(body)["messages"][0]["content"] == SYSTEM.replace("Sat Nov 21 2026", "Thu Feb 04 2027") + + +def test_the_date_is_written_in_the_zone_the_cli_writes_its_own_in(env_clock, monkeypatch): + monkeypatch.setenv("FAKE_DATE_OUT", "1801785600 000000000") # 2027-02-05T00:00Z, still the 4th in New York + monkeypatch.setenv("TZ", "America/New_York") + time.tzset() + + assert "Today's date: Thu Feb 04 2027" in _rewrite(_call())["messages"][0]["content"] + + +@pytest.mark.parametrize("armed", [False, True]) +def test_a_call_with_nothing_to_rewrite_or_off_the_clock_goes_as_written_and_reads_no_date(env_clock, monkeypatch, + armed): + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + monkeypatch.setattr(opencode_date, "clock_armed", lambda: armed) + calls = [json.dumps(_call(), indent=1).encode(), b"not json"] if not armed else [] + calls += [json.dumps(_call("A title for this conversation", tools=False, user="hi")).encode()] + + for body in calls: + assert asyncio.run(opencode_date.env_date_rewrite(body)) == body + assert not env_clock.exists() + + +def test_on_an_armed_clock_a_call_that_isnt_json_is_refused_rather_than_sent_with_the_real_date(env_clock): + with pytest.raises(opencode_date.Refusal, match="isn't JSON"): + asyncio.run(opencode_date.env_date_rewrite(json.dumps(_call()).encode()[:-1])) + + +@pytest.mark.parametrize("environ, reason", [ + ({}, "date exited 1: no clock"), + ({"FAKE_DATE_OUT": "1801742400 000000000", "FAKE_DATE_EXIT": "3"}, "date exited 3"), + ({"FAKE_DATE_OUT": "soon"}, "date printed 'soon\\n'"), + ({"FAKE_DATE_OUT": "1 0", "FAKE_DATE_SLEEP": "10"}, "date gave no answer within 2 s"), +]) +def test_a_date_that_cant_be_read_refuses_the_call_rather_than_tell_the_model_real_time(env_clock, monkeypatch, + environ, reason): + """A date that hangs is killed with the sleep it started, which holds its output open, so the refusal comes in + its time.""" + monkeypatch.setattr(opencode_date, "_DATE_TIMEOUT_S", 2) + for name, value in environ.items(): + monkeypatch.setenv(name, value) + started = time.monotonic() + + with pytest.raises(opencode_date.Refusal) as refused: + _rewrite(_call()) + + assert str(refused.value).startswith(f"the env's date couldn't be read for the model: {reason}") + assert time.monotonic() - started < 6 + + +def test_a_date_that_exits_leaving_a_process_on_its_output_is_refused_and_that_process_killed(env_clock, monkeypatch, + tmp_path): + """The date has exited, so only its session's group still reaches what it left holding the pipes.""" + monkeypatch.setattr(opencode_date, "_DATE_TIMEOUT_S", 1) + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + monkeypatch.setenv("FAKE_DATE_KID", str(tmp_path / "kid")) + + with pytest.raises(opencode_date.Refusal, match="date gave no answer within 1 s"): + _rewrite(_call()) + + kid, deadline = (tmp_path / "kid").read_text().strip(), time.monotonic() + 5 + while (state := subprocess.run(["ps", "-o", "stat=", "-p", kid], capture_output=True, text=True).stdout.strip()) \ + and not state.startswith("Z") and time.monotonic() < deadline: + time.sleep(0.1) + assert not state or state.startswith("Z"), state + + +def test_an_env_block_without_a_date_line_this_knows_refuses_the_call(env_clock, monkeypatch): + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + + with pytest.raises(opencode_date.Refusal, match="no date line"): + _rewrite(_call(SYSTEM.replace(" Today's date:", " Date:"))) diff --git a/tst/unit/agents/test_model_relay.py b/tst/unit/agents/test_model_relay.py index 69f5e7966..353942b47 100644 --- a/tst/unit/agents/test_model_relay.py +++ b/tst/unit/agents/test_model_relay.py @@ -256,7 +256,7 @@ async def exercise(client, root, endpoint): assert len(calls.answered) == 1 -def test_a_refused_call_is_answered_by_the_relay_with_its_reason_and_goes_no_further(): +def test_a_refused_call_is_answered_by_the_relay_with_its_reason_and_goes_no_further(caplog): async def rewrite(body): raise model_relay.Refusal("no date for the model") @@ -268,6 +268,7 @@ async def exercise(client, root, endpoint): assert status == 400 and answer["error"]["message"] == "no date for the model" assert endpoint.requests == [] and (calls.answered, calls.unreported, calls.refused) == ([], 0, 1) + assert "model relay refused a call: no date for the model" in caplog.text def test_a_rewrite_that_fails_is_answered_by_the_relay_with_the_error_rather_than_a_500_a_cli_retries(): From 0cc73eaf12357a53c78c8422a8cb9689bbf2d3e9 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 08:04:01 -0800 Subject: [PATCH 8/8] refactor(agents): name the limit on what a failing date's refusal quotes Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/agents/opencode/opencode_date.py | 6 ++++-- tst/integration/agent/opencode_env_date_test.py | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/agent_env/agents/agents/opencode/opencode_date.py b/src/agent_env/agents/agents/opencode/opencode_date.py index b127a6f32..fc515e4a1 100644 --- a/src/agent_env/agents/agents/opencode/opencode_date.py +++ b/src/agent_env/agents/agents/opencode/opencode_date.py @@ -21,6 +21,8 @@ _ENV_DATE = re.compile(r"(\n(?: [^\n]*\n)*? Today's date: )[^\n]*") _SEARCH_YEAR = re.compile(r"The current year is -?\d+\.") _DATE_TIMEOUT_S = 5 +# How much of what a failing date printed its refusal quotes. +_SHOWN_CHARS = 200 _DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") _MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") @@ -88,12 +90,12 @@ def unread(reason: str) -> Refusal: except OSError as exc: raise unread(f"{type(exc).__name__}: {exc}") from exc if code != 0: - raise unread(f"date exited {code}: {err.decode(errors='replace').strip()[:200]}") + raise unread(f"date exited {code}: {err.decode(errors='replace').strip()[:_SHOWN_CHARS]}") try: seconds, _ = out.decode().split() day = time.localtime(int(seconds)) except (ValueError, OverflowError, OSError) as exc: - raise unread(f"date printed {out.decode(errors='replace')[:100]!r}") from exc + raise unread(f"date printed {out.decode(errors='replace')[:_SHOWN_CHARS]!r}") from exc return f"{_DAYS[day.tm_wday]} {_MONTHS[day.tm_mon - 1]} {day.tm_mday:02d} {day.tm_year:04d}", day.tm_year diff --git a/tst/integration/agent/opencode_env_date_test.py b/tst/integration/agent/opencode_env_date_test.py index 03577b06c..3704624dc 100644 --- a/tst/integration/agent/opencode_env_date_test.py +++ b/tst/integration/agent/opencode_env_date_test.py @@ -21,6 +21,7 @@ VERSION = json.loads((AGENT_DIR / "package.json").read_text())["dependencies"]["opencode-ai"] ENV_TODAY, ENV_YEAR = "Sun Jan 01 1950", 1950 +_DAY_S = 86400 _DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") _MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") @@ -65,7 +66,7 @@ def _machine_dates() -> set[str]: """This machine's date, as the CLI on real time writes one (``Date.toDateString()``) and as ISO, for yesterday, today and tomorrow, so a turn across midnight is still caught.""" dates = set() - for offset in (-86400, 0, 86400): + for offset in (-_DAY_S, 0, _DAY_S): day = time.localtime(time.time() + offset) dates |= {f"{_DAYS[day.tm_wday]} {_MONTHS[day.tm_mon - 1]} {day.tm_mday:02d} {day.tm_year:04d}", time.strftime("%Y-%m-%d", day)}