diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index e174e5c8e..39e9ca233 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -49,6 +49,13 @@ 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 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 4bbc97803..67c2b465c 100644 --- a/src/agent_env/agents/agents/opencode/opencode_bridge.py +++ b/src/agent_env/agents/agents/opencode/opencode_bridge.py @@ -34,7 +34,9 @@ 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, model_relay +from opencode_date import env_date_rewrite logger = logging.getLogger(__name__) @@ -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. 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)} + 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: int) -> tuple[int, bytes, bytes]: @@ -282,11 +287,13 @@ def _build_config( environ: Mapping[str, str] = os.environ, instructions: list[str] | None = None, builtin_tools: OpenCodeTools | None = None, + 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 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) @@ -336,6 +343,8 @@ def _build_config( } if instructions: config["instructions"] = list(instructions) + if armed: + config["enabled_providers"] = ["litellm"] if mcp_servers: mcp: dict[str, dict] = {} @@ -431,9 +440,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 + 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) 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 @@ -482,9 +492,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, armed=armed) # Resume a specific session by id (multi-turn continuity). `--continue` # does NOT replay history to the model; `-s ` does. First turn @@ -505,7 +516,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/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..fc515e4a1 --- /dev/null +++ b/src/agent_env/agents/agents/opencode/opencode_date.py @@ -0,0 +1,116 @@ +"""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 +# 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") + + +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()[:_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')[:_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 + + +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 a0c35c1d3..489512930 100644 --- a/src/agent_env/utils/model_relay/model_relay.py +++ b/src/agent_env/utils/model_relay/model_relay.py @@ -6,8 +6,9 @@ import contextlib import json +import logging 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 @@ -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"} @@ -27,6 +30,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 +145,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; 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: @@ -161,8 +171,18 @@ 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 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, - 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/integration/agent/opencode_env_date_test.py b/tst/integration/agent/opencode_env_date_test.py new file mode 100644 index 000000000..3704624dc --- /dev/null +++ b/tst/integration/agent/opencode_env_date_test.py @@ -0,0 +1,134 @@ +"""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, opencode_date +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 +_DAY_S = 86400 +_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 (-_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)} + 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_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: + 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_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 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 opencode_date's _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/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 67d69e5f9..eabbb6ff0 100644 --- a/tst/unit/agents/opencode/test_env_clock.py +++ b/tst/unit/agents/opencode/test_env_clock.py @@ -1,15 +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. 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 subprocess import pytest -from tst.unit.agents.opencode.agent import AGENT_DIR, agent_egress, opencode_bridge +from tst.unit.agents.opencode.agent import AGENT_DIR, agent_egress, opencode_bridge, opencode_date PROXY = "http://127.0.0.1:3128" @@ -40,6 +44,37 @@ def test_without_the_proxy_or_an_armed_clock_the_cli_goes_out_directly_as_before assert set(env) == {*environ, "XDG_DATA_HOME", "XDG_STATE_HOME"} +@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) + + 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_turns_relay_puts_the_env_date_in_its_model_calls(monkeypatch): + seen = {} + + @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_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)]) def test_a_model_endpoint_over_plain_http_is_reached_directly_on_an_armed_clock(base_url, direct): env = opencode_bridge.cli_env("ctx", {agent_egress.EGRESS_PROXY_ENV: PROXY, "LITELLM_BASE_URL": base_url}, 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..049463c41 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, then TOOLS_CLI_VERSION; " + "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_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")) 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 e0e2bfb47..353942b47 100644 --- a/tst/unit/agents/test_model_relay.py +++ b/tst/unit/agents/test_model_relay.py @@ -240,6 +240,51 @@ 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(caplog): + 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) + 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(): + 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()