Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/agent_env/agents/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/agent_env/agents/agents/opencode/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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 ./
Expand Down
2 changes: 1 addition & 1 deletion src/agent_env/agents/agents/opencode/install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
25 changes: 18 additions & 7 deletions src/agent_env/agents/agents/opencode/opencode_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

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

Expand Down
116 changes: 116 additions & 0 deletions src/agent_env/agents/agents/opencode/opencode_date.py
Original file line number Diff line number Diff line change
@@ -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 <env> 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"(<env>\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 <env> 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 "<env>\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 <env> 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
28 changes: 24 additions & 4 deletions src/agent_env/utils/model_relay/model_relay.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,18 @@

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

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"}
Expand All @@ -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,
Expand Down Expand Up @@ -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 (``<root>/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:
Expand All @@ -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={
Expand Down
Loading
Loading