diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index 0b6798057..71669103b 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -61,7 +61,11 @@ The A2A server starts with the real-time marker, so it and its records stay on r - **One rule for every clocked agent.** That rule is `agent_egress.py` in `utils/agent_clock`, which only agent images take (`agent_clock = "utils/agent_clock"` in `shared_sources.toml`), so changing it rebuilds no computer base. The bridge imports it, and the image and `install.sh` copy it beside the bridge with the clock's `clockpage.py`, whose - layout and check it reads the page by, so every agent put on the clock, OpenCode's too, goes out the same way. + layout and check it reads the page by, so every agent put on the clock, OpenCode's and Hermes' too, goes out the same + way. +- **Hermes' harness stays on real time.** In the Hermes image, Hermes itself keeps real time while the commands it runs + follow the env's clock, and it shows the model the env's date: its own records, leases and cleanups are set against + real file times and elapsed time. `agents/hermes/README.md` says how. Started as a user other than root, the image runs the A2A server alone, on real time, as before. diff --git a/src/agent_env/agents/agents/hermes/Dockerfile b/src/agent_env/agents/agents/hermes/Dockerfile index 5b143517f..b4ef2669c 100644 --- a/src/agent_env/agents/agents/hermes/Dockerfile +++ b/src/agent_env/agents/agents/hermes/Dockerfile @@ -1,3 +1,17 @@ +# The env's clock: the egress proxy, one static Go binary, and agent-env's libfaketime and its TLS shim, taken from +# agent-env's sources as clock/ and egress/ (shared_sources.toml) and built for this image's libc (Debian bookworm) in +# stages of their own, so no toolchain is left in the image. +FROM public.ecr.aws/docker/library/golang:1.26.11-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS egress +COPY egress/ /egress/ +RUN cd /egress && go vet ./... && go test -count=1 ./... \ + && CGO_ENABLED=0 GOFLAGS=-mod=readonly go build -trimpath -ldflags=-s -o /out/egress . + +FROM public.ecr.aws/docker/library/python:3.11-slim@sha256:c20888b6acdd1e63e1c433a185bf3ad162c0288fe484616ce062e0d28add2900 AS clock +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + build-essential patch curl ca-certificates +COPY clock/ /clock/ +RUN sh /clock/build.sh /out + FROM public.ecr.aws/docker/library/python:3.11-slim@sha256:c20888b6acdd1e63e1c433a185bf3ad162c0288fe484616ce062e0d28add2900 # Hermes Agent at a pinned release, installed by its own installer, which the image checks against its checksum. The # installer brings Hermes' runtime (its Python, Node and ripgrep among them) under its home, /data/.hermes; git and xz @@ -23,12 +37,38 @@ WORKDIR /opt/agent COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY a2a_server.py hermes_bridge.py hermes_kit.py entrypoint.sh ./ +# Every clocked agent's egress rule, which the bridge imports, and the clock page's format it reads (shared_sources.toml). +COPY agent_clock/agent_egress.py clock/clockpage.py ./ COPY agentenv_plugin ./agentenv_plugin -RUN chmod 0755 entrypoint.sh -# Each context's Hermes profile is under /data/.hermes, Hermes' home, whatever the uid: Modal runs the image as root. +# A turn on an armed clock runs the command Hermes' launcher runs, without its shell (hermes_bridge.cli_command): the +# build fails, rather than such a turn, when the pinned release's launcher isn't one the bridge reads. +RUN chmod 0755 entrypoint.sh && python3 -c 'import hermes_bridge; hermes_bridge.launcher_command()' +# The env's clock: the follower and the egress proxy, each as its own user, under root's supervisord (root.conf), and +# agent-env's libfaketime and its TLS shim preloaded into every process, faking only the agent's (clock.conf). The +# follower's config is the agent's user's to write (agentenv_protocol.a2a_agent.clock) and the follower's to read. +RUN pip install --no-cache-dir supervisor==4.2.5 \ + && useradd --system --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin agentenv-clock \ + && useradd --system --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin agentenv-egress \ + && mkdir -p /usr/local/lib/agentenv-clock /usr/local/lib/agentenv-egress /etc/agentenv \ + && install -d -o agent -g agentenv-clock -m 2750 /etc/agentenv/clock \ + && touch /etc/agentenv/ca.pem \ + && cp /etc/ssl/certs/ca-certificates.crt /etc/agentenv/ca-bundle.pem \ + && cp /etc/ssl/certs/ca-certificates.crt /usr/local/lib/agentenv-egress/roots.pem +COPY --from=clock /out/libfaketimeMT.so.1 /out/libtls_realtime.so /usr/local/lib/agentenv-clock/ +COPY --from=egress /out/egress /usr/local/lib/agentenv-egress/egress +COPY clock/clockpage.py clock/clock-follower /usr/local/lib/agentenv-clock/ +COPY clock/clock.conf /etc/agentenv/clock.conf +COPY root.conf /etc/agentenv/root.conf +COPY start-agent /usr/local/bin/start-agent +RUN sed -i -e "s/^AGENTENV_SESSION_UID=.*/AGENTENV_SESSION_UID=$(id -u agent)/" \ + -e "s/^AGENTENV_CLOCK_PAGE_UID=.*/AGENTENV_CLOCK_PAGE_UID=$(id -u agentenv-clock)/" /etc/agentenv/clock.conf \ + && chmod 0755 /usr/local/lib/agentenv-clock/clock-follower /usr/local/bin/start-agent \ + && printf '%s\n' /usr/local/lib/agentenv-clock/libfaketimeMT.so.1 /usr/local/lib/agentenv-clock/libtls_realtime.so \ + > /etc/ld.so.preload +# Each context's Hermes profile is under /data/.hermes, Hermes' home, whatever the uid. ENV A2A_PORT=8000 PYTHONPATH=/opt/agent HOME=/data HERMES_ROOT=/data/.hermes -USER agent WORKDIR /app EXPOSE 8000 -# CMD rather than ENTRYPOINT: Modal passes a sandbox's env to the image's CMD only. -CMD ["/opt/agent/entrypoint.sh"] +# Starts as root, which start-agent needs for the clock; the A2A server and the CLI run as the agent's user. CMD rather +# than ENTRYPOINT: Modal passes a sandbox's env to the image's CMD only. +CMD ["/usr/local/bin/start-agent"] diff --git a/src/agent_env/agents/agents/hermes/README.md b/src/agent_env/agents/agents/hermes/README.md index 822785e0c..18e08e0d3 100644 --- a/src/agent_env/agents/agents/hermes/README.md +++ b/src/agent_env/agents/agents/hermes/README.md @@ -47,6 +47,49 @@ A turn's usage counts every model call the turn made: its main calls and its aux compression), as Hermes' usage file reports them, and a `delegate_task` child's, from their `post_api_request` events, which the file leaves out. A turn killed before it wrote the file keeps the calls its events counted, marked as a lower bound. Hermes' estimated cost is kept only where it priced the calls. The profile turns Hermes' background review off: -its fork outlives the turn's process, which kills it before it reports what the proxy billed. The image is `python:3.11-slim` with Hermes, `pdftoppm` and the agent, running -as the `agent` user. Hermes' runtime (its own Python, Node and ripgrep) and the profiles are under `/data/.hermes`, -whatever the uid. It has no `install/v1`. +its fork outlives the turn's process, which kills it before it reports what the proxy billed. The image is +`python:3.11-slim` with Hermes, `pdftoppm` and the agent. It starts as root, which runs the env clock's follower and +egress proxy under supervisord (`start-agent`, `root.conf`), and the A2A server and Hermes run as the `agent` user, on +Modal too; started as another user, it runs the A2A server alone as that user. A server that exits, for any reason, +stops supervisord and the container with it, as when the server was the container's process, so the run fails at +once; the follower and the proxy restart in place. Hermes' runtime (its own Python, Node and ripgrep) and the profiles +are under `/data/.hermes`, whatever the uid. It has no `install/v1`. + +## The env's clock + +The image follows a task env's clock as the agents README describes (`../../README.md`), with one difference: Hermes +itself stays on real time and the commands it runs follow the env's clock. + +- **Off by default.** Without `agent_clock` on `sync_env_clock`, a turn runs as it would without the clock: + `hermes agentenv turn` with the same flags, the server's environment and a profile config with nothing of the + clock's, on real time, with no proxy variables. The server's environment is supervisord's, which adds its + `SUPERVISOR_*` variables, `USER`, `LOGNAME` and `AGENTENV_EGRESS_PROXY`, and points TLS trust at agent-env's bundles + (`root.conf`). +- **Opted in.** While the agent follows an armed clock, the bridge starts each turn with the command Hermes' launcher + runs, Hermes' own Python, rather than the launcher, a shell script, so the real-time marker reaches Hermes and not the + shell, and passes `--env-clock` (`hermes_bridge.cli_command`). Every command Hermes starts, the model's `date`, + shell and `execute_code` scripts among them, reads the env's time, and goes out through the egress proxy with Hermes, + as the shared rule (`agent_egress.egress_env`) has it for the model endpoint and every MCP server. `execute_code` + hands its scripts only a few variables of its own choosing, so the turn's config names the proxy's, its CA's and the + task's zone (`TZ`) for it (`terminal.env_passthrough`). +- **Why Hermes stays on real time.** Hermes compares its clock with times it didn't make on that clock in many places: + its scratch folder (`TMPDIR`), pruned at each start of entries idle for 24 hours and the processes running in them; + its spill files and large tool results, deleted past 7 days and `sessions.retention_days`; its checkpoints, past + their retention; the turn's lease, which stops the turn when the clock jumps past the lease's deadline or runs a few + times fast; and the stream stall check, which drops a model stream the clock jumps past. Each runs in Hermes' own + process against real file times or real elapsed time, so on real time a conversation keeps its history and files at + any date, jump or rate the env's clock takes. +- **The date the model sees.** With `--env-clock`, the plugin has Hermes read the date it shows the model, its + `Conversation started` line (and `Today's date` after a rebuild) and the date its compaction summary carries, from a + `date` it runs, which follows the env's clock; the session ids it mints, a compaction's new one included, whose stamp + gives the start date, are stamped from it too. Hermes writes that line when a session starts and keeps it, as it does + on any clock, so a session started before the clock was armed keeps the real date it started on until Hermes rebuilds + its prompt. Other times Hermes reports itself, such as the dates `session_search` lists, are real, as files' + modification times are. +- **A clock armed mid-turn.** The command and environment are chosen as a turn starts. A turn already running when the + clock is armed was started as an unarmed turn is, through the launcher with no marker, so its Hermes follows the + env's clock from then on, without the proxy. Its own model and MCP calls then check certificates on the env's + clock: Hermes' Python carries its own OpenSSL, which agent-env's TLS shim doesn't reach, so at a date outside the + endpoint's certificate they fail (`APIConnectionError: Connection error.`), and its turn lease or stall check may + stop it too (`Session turn lease ...`). The turn ends with that error, the conversation keeps its history, and the + next turn is armed. diff --git a/src/agent_env/agents/agents/hermes/agentenv_plugin/__init__.py b/src/agent_env/agents/agents/hermes/agentenv_plugin/__init__.py index a8aabf368..2fa424b43 100644 --- a/src/agent_env/agents/agents/hermes/agentenv_plugin/__init__.py +++ b/src/agent_env/agents/agents/hermes/agentenv_plugin/__init__.py @@ -4,17 +4,32 @@ gateway: so the turn ends with this process, and a timeout or cancel that kills it stops the turn. Hermes' plugin hooks write the turn's events, each as one JSON line, to the pipe AGENTENV_EVENTS_FD names, as they happen; the bridge reads them as the turn's trajectory. Each event is a hook's name as ``type`` and the hook's fields the bridge keeps. + +On an armed env clock the bridge runs this process on real time and passes ``--env-clock``: everything the process +starts follows the env's clock, and the dates Hermes shows the model are read from one of those (``_EnvDatetime``). """ from __future__ import annotations import json import os +import subprocess +import sys import threading import time +import types +from datetime import datetime + +import hermes_state_ids +import hermes_time _EVENTS_FD = "AGENTENV_EVENTS_FD" _write_lock = threading.Lock() +# The Hermes release whose names --env-clock replaces (hermes_time.datetime, hermes_state_ids.new_session_id and the +# copies its modules bind by import); a test holds it to the Dockerfile's HERMES_COMMIT, so a bump checks them again. +ENV_CLOCK_HERMES_COMMIT = "bf0203a794a07aac3ff764972ab9087baa4e4f4e" +# The env's time, in whole seconds since the epoch, as a command the model runs reads it. +ENV_TIME_COMMAND = ("date", "+%s") # Each hook this plugin records, and the fields of its payload an event keeps. _HOOKS = { @@ -32,6 +47,34 @@ } +class _EnvDatetime(datetime): + """``datetime`` whose ``now`` is the env's time, read from a command this process starts: this process stays on + real time, and what it starts follows the env's clock.""" + + @classmethod + def now(cls, tz=None) -> datetime: + seconds = int(subprocess.run(ENV_TIME_COMMAND, capture_output=True, text=True, check=True).stdout) + return datetime.fromtimestamp(seconds, tz) + + +def _show_the_envs_date() -> None: + """Hermes' dates on the env's clock: the date it shows (``hermes_time.now``) and the session ids it mints, whose + stamp its start date is read from: ``new_session_id`` and every copy a loaded module bound by import, as + ``agent.agent_init`` and ``agent.conversation_compression`` (a compaction's new session) do. A module loaded later + binds the replacement, and none is imported here, so Hermes loads its modules in its own order.""" + hermes_time.datetime = _EnvDatetime + minted = hermes_state_ids.new_session_id + + def new_session_id(now: datetime | None = None, **kwargs) -> str: + return minted(_EnvDatetime.now(), **kwargs) + + for module in list(sys.modules.values()): + if isinstance(module, types.ModuleType): + for name, value in list(vars(module).items()): + if value is minted: + setattr(module, name, new_session_id) + + def _write(event: dict) -> None: descriptor = os.environ.get(_EVENTS_FD) if not descriptor: @@ -58,12 +101,16 @@ def _setup(parser) -> None: turn.add_argument("--resume", help="The session the turn continues") turn.add_argument("--reasoning", help="The reasoning effort") turn.add_argument("--usage-file", help="Where to write the turn's usage report") + turn.add_argument("--env-clock", action="store_true", + help="This process is on real time while the env's clock is armed: show the model the env's date") def _handle(args) -> None: # The one-shot runner: the turn in this process, then Hermes' own cleanup and a hard exit. from hermes_cli.main import _run_and_exit_oneshot + if args.env_clock: + _show_the_envs_date() with open(args.prompt_file, encoding="utf-8") as prompt: message = prompt.read() _run_and_exit_oneshot(message, model=args.model, provider=args.provider, resume=args.resume, diff --git a/src/agent_env/agents/agents/hermes/hermes_bridge.py b/src/agent_env/agents/agents/hermes/hermes_bridge.py index a52626bc9..a7773b372 100644 --- a/src/agent_env/agents/agents/hermes/hermes_bridge.py +++ b/src/agent_env/agents/agents/hermes/hermes_bridge.py @@ -7,6 +7,8 @@ enabled. The system prompt is the profile's SOUL.md, Hermes' identity slot. - The turn runs in the plugin's process, not in a Hermes gateway, so killing that process stops the turn. The plugin writes each hook event as a JSON line to a pipe this module reads as it goes: the turn's trajectory. + - On an armed env clock, Hermes itself stays on real time and everything it starts follows the env's clock + (``cli_command``, ``cli_env``). """ from __future__ import annotations @@ -16,6 +18,7 @@ import json import logging import os +import shlex import shutil import signal import tempfile @@ -27,6 +30,7 @@ from jsonschema import Draft202012Validator, SchemaError, ValidationError +from agent_egress import clock_armed, egress_env from hermes_kit import in_thread_to_its_end logger = logging.getLogger(__name__) @@ -47,6 +51,11 @@ # Marks a SOUL.md this agent wrote, so a later turn with no system prompt gives Hermes its own back. _SOUL_MARKER = ".agentenv-soul" _EVENTS_FD_ENV = "AGENTENV_EVENTS_FD" +# Keeps the process it's given to on real time under the image's libfaketime, which takes it out of that process's +# environment, so everything the process starts follows the env's clock. +REAL_TIME_ENV = "AGENTENV_REAL_TIME" +# Where root.conf points the server's TLS trust: agent-env's bundles, which hold the egress proxy's CA. +_CA_ENV = ("SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "NODE_EXTRA_CA_CERTS") # How long the event pipe may stay open after the turn's process exits, held by something it left behind. _EVENTS_DRAIN_S = 2 @@ -131,6 +140,42 @@ def get_last_attribution_snapshot() -> dict[str, str | None]: return dict(_last_attribution) +def cli_env(environ: Mapping[str, str], home: Path, *, events_fd: int | None = None, + mcp_servers: dict[str, dict] | None = None, clock_armed: bool = False) -> dict[str, str]: + """The turn's process's environment: this process's, with the context's profile as Hermes' home and the event + pipe's descriptor for the plugin. On an armed clock it adds the real-time marker for Hermes (``cli_command``) and + the egress proxy (``egress_env``) for the model endpoint, the turn's MCP servers and what Hermes' commands reach.""" + env = {**environ, "HERMES_HOME": str(home)} + if events_fd is not None: + env[_EVENTS_FD_ENV] = str(events_fd) + if clock_armed: + env[REAL_TIME_ENV] = "1" + urls = [environ.get("LITELLM_BASE_URL", ""), *(str(info.get("url") or "") for info in (mcp_servers or {}).values())] + env.update(egress_env(environ, urls, armed=clock_armed)) + return env + + +def cli_command(args: list[str], *, clock_armed: bool = False) -> list[str]: + """``hermes`` with ``args``; on an armed clock, the command its launcher runs, without the shell that would take the + marker, and ``--env-clock`` for the env's date. Hermes stays on real time: its session records, turn lease, stall + check and the age cutoffs of its temp files, spills and checkpoints are set against real file and elapsed times.""" + if not clock_armed: + return [HERMES_BIN, *args] + return [*launcher_command(), *args, "--env-clock"] + + +def launcher_command(launcher: str | None = None) -> list[str]: + """The command Hermes' launcher runs: the launcher is ``#!/bin/sh`` and ``exec -I -c + "$@"``, as Hermes' installer writes it (``shlex.join``). Any other ``exec``, such as Hermes' forwarder to another + launcher or ``env``, would take the marker in Hermes' place.""" + name = launcher or HERMES_BIN + path = Path(shutil.which(name) or name).resolve() + words = shlex.split(path.read_text(), comments=True) + if len(words) != 6 or words[0] != "exec" or words[2:4] != ["-I", "-c"] or words[5] != "$@": + raise ValueError(f"{path} doesn't exec Hermes' interpreter as Hermes' launcher does") + return words[1:5] + + def _attribution_headers(project_id: str | None, task_id: str | None) -> dict[str, str]: """LiteLLM cost-attribution headers, x-litellm-customer-id + x-litellm-tags; {} when nothing to attribute.""" headers: dict[str, str] = {} @@ -194,6 +239,8 @@ def build_config( role: str | None, skills_dir: Path, environ: Mapping[str, str] = os.environ, + *, + clock_armed: bool = False, ) -> dict: """The profile's config.yaml for one turn, as JSON (which YAML reads). Everything dynamic is rebuilt each turn, and a context's turns run one at a time, so no turn reads another's.""" @@ -209,6 +256,12 @@ def build_config( # its calls, which the proxy bills anyway, as Hermes turns it off for its own one-shot turns. "auxiliary": {"background_review": {"enabled": False}}, } + if clock_armed: + # Hermes' execute_code hands its scripts a fixed few variables and those this names: the egress proxy's, its + # CA's and the task's zone, which the terminal's commands get anyway, so scripts on the env's clock reach TLS + # hosts through it and read the time in the zone the terminal does. + names = {*egress_env(environ, armed=True), *(name for name in (*_CA_ENV, "TZ") if name in environ)} + config["terminal"] = {"env_passthrough": sorted(names)} if mcp_servers: servers: dict[str, dict] = {} for name, info in mcp_servers.items(): @@ -342,21 +395,24 @@ async def run_hermes( "\n\nReturn only a JSON object matching this schema, with no Markdown or surrounding text: " + json.dumps(schema, separators=(",", ":")) ) - config = build_config(model, mcp_servers, provider_headers(os.environ, attribution), role, skills_dir) + armed = clock_armed() + config = build_config(model, mcp_servers, provider_headers(os.environ, attribution), role, skills_dir, os.environ, + clock_armed=armed) # To its end even for a cancelled turn: a snapshot may archive the profile as soon as the turn lets go. home = await in_thread_to_its_end(prepare_profile, context_id, config, system_prompt) with tempfile.TemporaryDirectory(prefix="hermes-turn-") as scratch: prompt_file, usage_file = Path(scratch) / "prompt.txt", Path(scratch) / "usage.json" prompt_file.write_text(prompt) - cmd = [HERMES_BIN, "agentenv", "turn", "--prompt-file", str(prompt_file), "--provider", PROVIDER, - "--model", model, "--usage-file", str(usage_file)] + args = ["agentenv", "turn", "--prompt-file", str(prompt_file), "--provider", PROVIDER, + "--model", model, "--usage-file", str(usage_file)] if session_id: - cmd += ["--resume", session_id] + args += ["--resume", session_id] if effort: - cmd += ["--reasoning", effort] + args += ["--reasoning", effort] + cmd = cli_command(args, clock_armed=armed) logger.info(f"Running hermes (session={session_id}, model={model}, effort={effort}, ctx={context_id[:12]}, " - f"mcp={list((mcp_servers or {}).keys())})") + f"mcp={list((mcp_servers or {}).keys())}, env_clock={armed})") if attribution: logger.info(f"hermes attribution headers: {attribution}") @@ -368,7 +424,7 @@ async def run_hermes( stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=workspace, - env={**os.environ, "HERMES_HOME": str(home), _EVENTS_FD_ENV: str(write_end)}, + env=cli_env(os.environ, home, events_fd=write_end, mcp_servers=mcp_servers, clock_armed=armed), pass_fds=(write_end,), start_new_session=True, )) diff --git a/src/agent_env/agents/agents/hermes/root.conf b/src/agent_env/agents/agents/hermes/root.conf new file mode 100644 index 000000000..ea361280c --- /dev/null +++ b/src/agent_env/agents/agents/hermes/root.conf @@ -0,0 +1,88 @@ +; Root's supervisord (start-agent): the clock follower and the egress proxy, each as its own user, on real time, and +; the A2A server as the agent's user. The server starts with the real-time marker, which agent-env's libfaketime takes +; out of its environment, so the server's own records keep real timestamps and what it starts reads the env's time; on +; an armed clock it starts Hermes with the marker again, so only the commands Hermes runs do (hermes_bridge.cli_command). +; Its socket and logs are root's alone, so the agent's user can neither stop nor restart any of them. The follower +; follows nothing until the server writes its config, which sync_env_clock has it do, then picks it up within a quarter +; second. The follower and the proxy restart in place; the server doesn't, and its exit stops the container +; ([eventlistener:agent-exit]). +[supervisord] +nodaemon=true +user=root +logfile=/var/log/agentenv-root/supervisord.log +pidfile=/run/agentenv-root/supervisord.pid +childlogdir=/var/log/agentenv-root + +[unix_http_server] +file=/run/agentenv-root/supervisor.sock +chmod=0700 + +[rpcinterface:supervisor] +supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface + +[supervisorctl] +serverurl=unix:///run/agentenv-root/supervisor.sock + +[program:clock] +command=/usr/local/bin/python3 -I /usr/local/lib/agentenv-clock/clock-follower +user=agentenv-clock +directory=/ +priority=3 +autorestart=true +startsecs=1 +startretries=1000 +redirect_stderr=true +stdout_logfile=/var/log/agentenv-root/clock.log +environment=HOME="/nonexistent",USER="agentenv-clock",LOGNAME="agentenv-clock" + +[program:egress] +command=/usr/local/lib/agentenv-egress/egress serve +user=agentenv-egress +directory=/ +priority=3 +autorestart=true +startsecs=1 +startretries=1000 +redirect_stderr=true +stdout_logfile=/var/log/agentenv-root/egress.log +environment=HOME="/nonexistent",USER="agentenv-egress",LOGNAME="agentenv-egress",AGENTENV_EGRESS_PRIVATE="allow" + +; uvicorn itself, not entrypoint.sh: the marker holds for the process it's given to alone, and a shell that execs +; uvicorn would hand uvicorn an environment without it. HOME is Hermes' install's, /data, as the image sets it; its +; HERMES_ROOT and PYTHONPATH come from the image's environment. It isn't restarted, nor started again when it exits as +; it starts (startretries=0, FATAL at once): a server started in a dead one's place would have none of its turns or +; registrations, and the turns the dead one ran would go on beside it. +[program:agent] +command=/usr/local/bin/python3 -m uvicorn a2a_server:app --host 0.0.0.0 --port %(ENV_A2A_PORT)s --timeout-graceful-shutdown 5 +user=agent +directory=/app +priority=10 +autorestart=false +startretries=0 +stopasgroup=true +killasgroup=true +stopwaitsecs=30 +redirect_stderr=true +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +environment=HOME="/data",USER="agent",LOGNAME="agent",AGENTENV_REAL_TIME="1",AGENTENV_EGRESS_PROXY="http://127.0.0.1:3128",NODE_EXTRA_CA_CERTS="/etc/agentenv/ca.pem",SSL_CERT_FILE="/etc/agentenv/ca-bundle.pem",REQUESTS_CA_BUNDLE="/etc/agentenv/ca-bundle.pem" + +; When the A2A server exits for any reason (EXITED, or FATAL when it exits as it starts), this stops supervisord, its +; parent, which stops the follower and the proxy and exits, so the container does, as when the server was the +; container's process, and the run fails at once. The follower's and the proxy's exits are let pass, as supervisord +; restarts them, and a normal stop is no exit (the server is STOPPED). supervisord 4.2.5 exits 0 after any shutdown, so +; the container's status doesn't say the server crashed; supervisord's log line before its exit, "exited: agent (exit +; status N; not expected)", does. It runs as root, supervisord's user, to signal it, and speaks supervisord's +; eventlistener protocol: READY, then a header line and the payload of the length it gives, then RESULT 2 OK. +[eventlistener:agent-exit] +command=/usr/local/bin/python3 -I -c "import os,signal,sys + def say(text): sys.stdout.write(text);sys.stdout.flush() + def fields(raw): return dict(word.split(':',1) for word in raw.decode().split()) + def payload(header): return fields(sys.stdin.buffer.read(int(fields(header)['len']))) + def stop(event): event.get('processname')=='agent' and os.kill(os.getppid(),signal.SIGTERM) + say('READY\n') + for header in sys.stdin.buffer: stop(payload(header));say('RESULT 2\nOKREADY\n')" +events=PROCESS_STATE_EXITED,PROCESS_STATE_FATAL +directory=/ +priority=1 +autorestart=true diff --git a/src/agent_env/agents/agents/hermes/shared_sources.toml b/src/agent_env/agents/agents/hermes/shared_sources.toml new file mode 100644 index 000000000..6076f3540 --- /dev/null +++ b/src/agent_env/agents/agents/hermes/shared_sources.toml @@ -0,0 +1,5 @@ +# What this image's build context takes from agent-env's own sources, at the name its Dockerfile copies it from: one +# copy of each, shared with the other images that take it (utils/docker/context.py). Paths are under src/agent_env. +clock = "utils/faketime_clock" +egress = "utils/egress_proxy" +agent_clock = "utils/agent_clock" diff --git a/src/agent_env/agents/agents/hermes/start-agent b/src/agent_env/agents/agents/hermes/start-agent new file mode 100755 index 000000000..b70c27792 --- /dev/null +++ b/src/agent_env/agents/agents/hermes/start-agent @@ -0,0 +1,30 @@ +#!/bin/sh +# The image's start. As root, it makes what the agent's user must not touch, the clock page and file (the clock +# user's from their first byte) and the egress proxy's CA (its key the egress user's alone, trusted in the system +# store, agent-env's trust files and every certifi bundle), then starts root's supervisord (root.conf), which runs the +# clock follower and the egress proxy, each as its own user on real time, and the A2A server as the agent's user on +# real time, the commands Hermes runs reading the env's time from the page. Until sync_env_clock has the agent +# follow a clock, the page holds real time and the proxy relays TLS untouched. Started as another user, the image runs +# the A2A server alone, as before, on real time. +set -eu +if [ "$(id -u)" != 0 ]; then + exec /opt/agent/entrypoint.sh +fi +install -d -o root -g root -m 0700 /var/log/agentenv-root /run/agentenv-root +install -d -o agentenv-clock -g agentenv-clock -m 0755 /run/agentenv-clock +python3 -I /usr/local/lib/agentenv-clock/clockpage.py create agentenv-clock +AGENTENV_SESSION_USER=agent AGENTENV_EGRESS_NSS=off \ + /usr/local/lib/agentenv-egress/egress boot > /var/log/agentenv-root/egress-boot.log 2>&1 \ + || { cat /var/log/agentenv-root/egress-boot.log >&2; echo "the egress proxy's boot failed" >&2; exit 2; } +# A provider's own CA bundle stays trusted: Sail, for one, points SSL_CERT_FILE and the like at the bundle it signs +# model requests under, and root.conf points the server's trust at agent-env's bundles instead, so the provider's goes +# into them, and into the egress proxy's roots, which carry those requests once the clock is armed. +for bundle in "${SSL_CERT_FILE:-}" "${REQUESTS_CA_BUNDLE:-}" "${NODE_EXTRA_CA_CERTS:-}" "${CURL_CA_BUNDLE:-}"; do + case "$bundle" in ""|/etc/agentenv/*) continue ;; esac + [ -r "$bundle" ] || continue + for target in /etc/agentenv/ca-bundle.pem /etc/agentenv/ca.pem /usr/local/lib/agentenv-egress/roots.pem; do + grep -qxF "# agentenv: $bundle" "$target" 2>/dev/null && continue + { printf '\n# agentenv: %s\n' "$bundle"; cat "$bundle"; } >> "$target" + done +done +exec supervisord -c /etc/agentenv/root.conf diff --git a/tst/integration/task_step/test_agent_env_clock_local.py b/tst/integration/task_step/test_agent_env_clock_local.py index 87468d613..b4608d310 100644 --- a/tst/integration/task_step/test_agent_env_clock_local.py +++ b/tst/integration/task_step/test_agent_env_clock_local.py @@ -38,8 +38,10 @@ local_registry as local_registry, ) from tst.integration.task_step.test_register_env_triggers_local import _deploy_items +from tst.util import fake_openai from tst.util.capabilities import agent_clock_image, skip_without_agent_clock_image from tst.util.fake_anthropic import FakeAnthropic, tool_then_answer +from tst.util.fake_openai import FakeOpenAI pytestmark = [pytest.mark.integration, pytest.mark.int_test_slow] @@ -75,20 +77,46 @@ async def _claude_turn(context: TaskStepContext, endpoint: FakeAnthropic) -> Non assert any(VIRTUAL in result for result in endpoint.tool_results()), endpoint.tool_results() +# Each Hermes session the agent's profiles hold, with the time Hermes' own clock gave its start. +_HERMES_SESSIONS = ("import glob, json, sqlite3; print(json.dumps([row for db in glob.glob('/data/.hermes/profiles/*/" + "state.db') for row in sqlite3.connect(db).execute('select id, started_at from sessions')]))") + + +async def _hermes_turn(context: TaskStepContext, endpoint: FakeOpenAI) -> None: + """One turn of the real Hermes: the date its prompt gives the model, a terminal `date` the model runs and its + session id's stamp are the env's, while Hermes itself keeps real time, as the start its session store records.""" + endpoint.respond = fake_openai.tool_then_answer("terminal", {"command": "date -u +%FT%TZ"}, + prefix="the shell said: ") + await PromptAgentTaskStep(id="ask", version=None, prompt="What's the date? Run date.", agent_name="solver", + max_conversation_turns=1).execute(context) + bodies = [json.dumps(call.body) for call in endpoint.completions()] + started = {m for body in bodies for m in re.findall(r"Conversation started: (\w+, \w+ [0-9]{2}, [0-9]{4})", body)} + container = _container_of(context.deployed_agents[-1].sandbox_id) + sessions = json.loads(_in_agent(container, "python3", "-c", _HERMES_SESSIONS)) + print("Hermes' date line:", started, "terminal date:", endpoint.tool_results(), "sessions:", sessions) + assert started == {datetime.fromisoformat(VIRTUAL).strftime("%A, %B %d, %Y")}, started + assert any(VIRTUAL in result for result in endpoint.tool_results()), endpoint.tool_results() + [[session, started_at]] = sessions + assert session.startswith(VIRTUAL[:10].replace("-", "") + "_") and abs(started_at - time.time()) < 3600 + + @dataclass(frozen=True) class Agent: """What the test needs of an agent's image: its bridge module, a command its CLI answers without a model (which - must return under the preloaded library), and a turn against the stub endpoint, for a CLI that speaks its protocol.""" + must return under the preloaded library), and a turn against the stub endpoint of the protocol its CLI speaks.""" bridge: str version: tuple[str, ...] shows: str - turn: Callable[[TaskStepContext, FakeAnthropic], Awaitable[None]] | None = None + turn: Callable[[TaskStepContext, FakeAnthropic | FakeOpenAI], Awaitable[None]] | None = None + endpoint: type[FakeAnthropic] | type[FakeOpenAI] = FakeAnthropic AGENTS = { "claude-code": Agent(bridge="claude_bridge", version=("claude", "--version"), shows="(Claude Code)", turn=_claude_turn), + "hermes": Agent(bridge="hermes_bridge", version=("hermes", "--version"), shows="Hermes Agent v", + turn=_hermes_turn, endpoint=FakeOpenAI), "opencode": Agent(bridge="opencode_bridge", version=("opencode", "--version"), shows="1.17.18"), } @@ -120,11 +148,11 @@ async def _followers(deployed) -> dict: @pytest.mark.parametrize("name", [pytest.param(name, marks=skip_without_agent_clock_image(name)) for name in AGENTS]) @pytest.mark.asyncio async def test_an_agent_image_follows_the_envs_clock_until_it_is_torn_down(local_registry, name): - with FakeAnthropic(host=_host_ips()[-1]) as endpoint: # where this machine's containers reach it + with AGENTS[name].endpoint(host=_host_ips()[-1]) as endpoint: # where this machine's containers reach it await _follows_until_torn_down(name, AGENTS[name], agent_clock_image(name), endpoint) -async def _follows_until_torn_down(name: str, spec: Agent, tag: str, endpoint: FakeAnthropic) -> None: +async def _follows_until_torn_down(name: str, spec: Agent, tag: str, endpoint: FakeAnthropic | FakeOpenAI) -> None: _seed_bootstrap_envs() env, deployed, _ = await _deploy_items("agentclock") uid = uuid.uuid4().hex[:8] diff --git a/tst/unit/agents/hermes/agent.py b/tst/unit/agents/hermes/agent.py index 774e1061e..b0f11cb31 100644 --- a/tst/unit/agents/hermes/agent.py +++ b/tst/unit/agents/hermes/agent.py @@ -1,17 +1,23 @@ -"""The Hermes agent's modules, imported from its folder as its image runs them: by their own names, from the folder on -the path.""" +"""The Hermes agent's modules, imported as its image runs them: by their own names, from its folder and from the folders +its build context takes as agent_clock/ and clock/, whose modules the image copies beside the bridge.""" import importlib import importlib.util +import os import sys from pathlib import Path import agent_env +from tst.util.build_context import sent AGENT_DIR = Path(agent_env.__file__).parent / "agents" / "agents" / "hermes" -sys.path.insert(0, str(AGENT_DIR)) +IMPORTED = [str(AGENT_DIR), str(sent(AGENT_DIR, "agent_clock/agent_egress.py").parent), + str(sent(AGENT_DIR, "clock/clockpage.py").parent)] +PYTHONPATH = os.pathsep.join(IMPORTED) +sys.path[:0] = IMPORTED hermes_bridge = importlib.import_module("hermes_bridge") hermes_kit = importlib.import_module("hermes_kit") +agent_egress = importlib.import_module("agent_egress") # By its path: another agent's a2a_server, imported by the same name, may be loaded already. _spec = importlib.util.spec_from_file_location("hermes_a2a_server", AGENT_DIR / "a2a_server.py") a2a_server = importlib.util.module_from_spec(_spec) diff --git a/tst/unit/agents/hermes/conftest.py b/tst/unit/agents/hermes/conftest.py index 10bc586a9..51a254d11 100644 --- a/tst/unit/agents/hermes/conftest.py +++ b/tst/unit/agents/hermes/conftest.py @@ -4,6 +4,7 @@ from __future__ import annotations import os +import shlex import stat import sys import uuid @@ -15,6 +16,9 @@ from tst.unit.agents.hermes.agent import a2a_server, hermes_bridge FAKE_HERMES = os.path.join(os.path.dirname(__file__), "fake_hermes.py") +# What the fake launcher's Python runs with -I -c, as Hermes' runs its bootstrap: fake_hermes.py, with the launcher's +# arguments. +FAKE_HERMES_BOOTSTRAP = f"import runpy\nrunpy.run_path({FAKE_HERMES!r}, run_name='__main__')\n" class Harness: @@ -69,10 +73,11 @@ def folders(monkeypatch, tmp_path): @pytest.fixture def fake_hermes(monkeypatch, tmp_path): - """A `hermes` that runs fake_hermes.py; what it was run with is in the returned record file.""" + """A `hermes` that runs fake_hermes.py, a launcher as Hermes' installer writes one; what it was run with is in the + returned record file.""" launcher = tmp_path / "bin" / "hermes" launcher.parent.mkdir() - launcher.write_text(f"#!/bin/sh\nexec {sys.executable} {FAKE_HERMES} \"$@\"\n") + launcher.write_text(f"#!/bin/sh\nexec {shlex.join([sys.executable, '-I', '-c', FAKE_HERMES_BOOTSTRAP])} \"$@\"\n") launcher.chmod(launcher.stat().st_mode | stat.S_IXUSR) record = tmp_path / "record.json" monkeypatch.setattr(hermes_bridge, "HERMES_BIN", str(launcher)) diff --git a/tst/unit/agents/hermes/fake_hermes.py b/tst/unit/agents/hermes/fake_hermes.py index e289ae55e..61d4ba3e5 100644 --- a/tst/unit/agents/hermes/fake_hermes.py +++ b/tst/unit/agents/hermes/fake_hermes.py @@ -1,6 +1,7 @@ """A scripted `hermes agentenv turn` for the bridge tests, run as the real one is: a process of its own. It writes the events, usage report and stdout a turn would, as FAKE_HERMES_MODE says: ``ok`` answers, ``fail`` fails the model call, -``hang`` starts a tool and never finishes. Its arguments, environment and cwd go to FAKE_HERMES_RECORD.""" +``hang`` starts a tool and never finishes. Its arguments, Hermes home, cwd, prompt and the variables the env clock sets +go to FAKE_HERMES_RECORD.""" import json import os import subprocess @@ -14,7 +15,9 @@ session = option.get("--resume") or "20260101_000000_abcdef" with open(os.environ["FAKE_HERMES_RECORD"], "w") as record: json.dump({"args": args, "cwd": os.getcwd(), "home": os.environ.get("HERMES_HOME"), - "prompt": open(option["--prompt-file"]).read()}, record) + "prompt": open(option["--prompt-file"]).read(), + "env": {name: os.environ.get(name) for name in ("AGENTENV_REAL_TIME", "HTTPS_PROXY", "NO_PROXY")}}, + record) def emit(kind, **fields): diff --git a/tst/unit/agents/hermes/test_card_contract.py b/tst/unit/agents/hermes/test_card_contract.py index e89f706eb..126efe93b 100644 --- a/tst/unit/agents/hermes/test_card_contract.py +++ b/tst/unit/agents/hermes/test_card_contract.py @@ -10,7 +10,7 @@ import pytest -from tst.unit.agents.hermes.agent import AGENT_DIR, hermes_bridge +from tst.unit.agents.hermes.agent import AGENT_DIR, PYTHONPATH, hermes_bridge def _methods(card: dict) -> dict[str, list[str]]: @@ -57,7 +57,8 @@ async def test_the_attribution_probe_reads_back_what_the_last_turn_sent(monkeypa def test_the_card_is_read_by_importing_agent_card(): """agent-env imports AGENT_CARD from the image with no agent environment, and parses its stdout as the card.""" script = "import json; from a2a_server import AGENT_CARD; print(json.dumps(AGENT_CARD.model_dump(mode='json')))" - env = {key: value for key, value in os.environ.items() if not key.startswith("LITELLM_")} + env = {**{key: value for key, value in os.environ.items() if not key.startswith("LITELLM_")}, + "PYTHONPATH": PYTHONPATH} out = subprocess.run([sys.executable, "-c", script], cwd=AGENT_DIR, env=env, capture_output=True, text=True, check=True) diff --git a/tst/unit/agents/hermes/test_env_clock.py b/tst/unit/agents/hermes/test_env_clock.py new file mode 100644 index 000000000..fd5d1a82d --- /dev/null +++ b/tst/unit/agents/hermes/test_env_clock.py @@ -0,0 +1,318 @@ +"""Hermes on the env's clock. Unarmed, a turn runs exactly as before the clock: ``hermes agentenv turn`` with the same +flags and environment. On an armed clock Hermes stays on real time, run as the command its launcher runs with the +real-time marker, so its own records, leases and cleanups keep real times while every command it starts follows the +env's clock; the bridge hands the shared egress rule (tst/unit/agents/test_agent_egress.py) the model endpoint's URL and +every MCP server's, which Hermes connects to itself, and names its variables for execute_code's scripts too; and the +plugin shows the model the env's date. What every clocked image shares is checked in +tst/unit/agents/test_agent_clock_images.py.""" + +from __future__ import annotations + +import argparse +import asyncio +import importlib.util +import json +import re +import shlex +import subprocess +import sys +import types +from datetime import datetime, timezone +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from tst.unit.agents.hermes.agent import AGENT_DIR, agent_egress, hermes_bridge +from tst.unit.agents.hermes.conftest import FAKE_HERMES_BOOTSTRAP + +PROXY = "http://127.0.0.1:3128" +HOME = Path("/data/.hermes/profiles/ctx-0") +# The server's environment as root.conf gives it, and the endpoint agent-env gives the agent. +ENVIRON = {agent_egress.EGRESS_PROXY_ENV: PROXY, "SSL_CERT_FILE": "/etc/agentenv/ca-bundle.pem", + "REQUESTS_CA_BUNDLE": "/etc/agentenv/ca-bundle.pem", "NODE_EXTRA_CA_CERTS": "/etc/agentenv/ca.pem", + "LITELLM_BASE_URL": "https://litellm.example.com", "LITELLM_API_KEY": "k"} +MCP = {"env": {"url": "https://abc-123.w.modal.host/mcp"}, + "peer_agents": {"url": "http://127.0.0.1:8000/ext/peer-agents/mcp"}} + + +def test_on_an_armed_clock_the_turn_runs_on_real_time_and_goes_out_through_the_proxy(): + env = hermes_bridge.cli_env({agent_egress.EGRESS_PROXY_ENV: PROXY, "NO_PROXY": "registry.internal"}, HOME, + events_fd=7, clock_armed=True) + + assert env["AGENTENV_REAL_TIME"] == "1" + assert {env[name] for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "https_proxy")} == {PROXY} + assert {"localhost", "host.docker.internal", "registry.internal"} <= set(env["NO_PROXY"].split(",")) + assert (env["HERMES_HOME"], env["AGENTENV_EVENTS_FD"]) == (str(HOME), "7") + + +@pytest.mark.parametrize("environ", [{}, {agent_egress.EGRESS_PROXY_ENV: PROXY}]) +def test_unarmed_the_turns_environment_is_this_processs_with_its_hermes_home_and_event_pipe(environ): + env = hermes_bridge.cli_env(environ, HOME, events_fd=7, mcp_servers=MCP, clock_armed=False) + + assert env == {**environ, "HERMES_HOME": str(HOME), "AGENTENV_EVENTS_FD": "7"} + + +@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 = hermes_bridge.cli_env({agent_egress.EGRESS_PROXY_ENV: PROXY, "LITELLM_BASE_URL": base_url}, HOME, + clock_armed=True) + assert (base_url.split("//")[1].split(":")[0] in env["NO_PROXY"].split(",")) is direct + + +def test_the_turns_plain_http_mcp_servers_are_reached_directly_and_https_ones_through_the_proxy_on_an_armed_clock(): + """The proxy checks an HTTPS server's certificate on real time, and reaches a private address in this image; a host + reached over HTTPS too stays behind it, as NO_PROXY goes by host.""" + servers = {"env": {"url": "http://gateway.internal:8080/mcp"}, "docs": {"url": "https://10.1.2.3/mcp"}, + "remote": {"url": "https://abc-123.w.modal.host/mcp"}, "both": {"url": "http://abc-123.w.modal.host/sse"}} + env = hermes_bridge.cli_env({agent_egress.EGRESS_PROXY_ENV: PROXY}, HOME, mcp_servers=servers, clock_armed=True) + + direct = set(env["NO_PROXY"].split(",")) + assert "gateway.internal" in direct and not {"10.1.2.3", "abc-123.w.modal.host"} & direct + + +def _spawned(monkeypatch, tmp_path, armed: bool, environ: dict = ENVIRON) -> dict: + """What run_hermes starts the turn's process with, and the profile config it writes for it, for a resumed turn + with an effort and the env's MCP servers, from a server whose environment is ``environ``.""" + spawned = {} + + async def fake_exec(*cmd, env, pass_fds, **_): + spawned.update(cmd=list(cmd), env=env, fd=pass_fds[0]) + raise RuntimeError("not starting hermes") + + monkeypatch.setattr(hermes_bridge.asyncio, "create_subprocess_exec", fake_exec) + monkeypatch.setattr(hermes_bridge, "clock_armed", lambda: armed) + monkeypatch.setattr(hermes_bridge.os, "environ", dict(environ)) + with pytest.raises(RuntimeError, match="not starting hermes"): + asyncio.run(hermes_bridge.run_hermes("hi", "ctx-0", session_id="s-1", model="m", effort="high", + mcp_servers=MCP, skills_dir=tmp_path / "skills", + workspace=str(tmp_path))) + cmd = spawned["cmd"] + spawned["files"] = (cmd[cmd.index("--prompt-file") + 1], cmd[cmd.index("--usage-file") + 1]) + spawned["config"] = json.loads((hermes_bridge.profile_dir("ctx-0") / "config.yaml").read_text()) + return spawned + + +def test_unarmed_the_bridge_starts_hermes_with_the_command_and_environment_it_always_has(monkeypatch, fake_hermes, + tmp_path): + spawned = _spawned(monkeypatch, tmp_path, armed=False) + + prompt, usage = spawned["files"] + assert spawned["cmd"] == [hermes_bridge.HERMES_BIN, "agentenv", "turn", "--prompt-file", prompt, "--provider", + "litellm", "--model", "m", "--usage-file", usage, "--resume", "s-1", "--reasoning", "high"] + assert spawned["env"] == {**ENVIRON, "HERMES_HOME": str(hermes_bridge.profile_dir("ctx-0")), + "AGENTENV_EVENTS_FD": str(spawned["fd"])} + assert spawned["config"] == { + "model": {"provider": "litellm", "default": "m"}, + "providers": {"litellm": {"api": "https://litellm.example.com/v1", "key_env": "LITELLM_API_KEY", + "transport": "chat_completions"}}, + "skills": {"external_dirs": [str(tmp_path / "skills")]}, "plugins": {"enabled": ["agentenv"]}, + "auxiliary": {"background_review": {"enabled": False}}, + "mcp_servers": {name: {"url": info["url"]} for name, info in MCP.items()}} + + +def test_the_clock_adds_only_execute_codes_passthrough_to_the_profile_config(monkeypatch, fake_hermes, tmp_path): + unarmed = _spawned(monkeypatch, tmp_path, armed=False)["config"] + armed = _spawned(monkeypatch, tmp_path, armed=True)["config"] + + assert {key: value for key, value in armed.items() if key != "terminal"} == unarmed + assert list(armed["terminal"]) == ["env_passthrough"] + + +def test_on_an_armed_clock_the_bridge_starts_hermes_own_python_on_real_time_behind_the_proxy(monkeypatch, fake_hermes, + tmp_path): + """Not the launcher: its shell would take the marker, and the Python it starts would follow the env's clock.""" + spawned = _spawned(monkeypatch, tmp_path, armed=True) + + prompt, usage = spawned["files"] + assert spawned["cmd"] == [sys.executable, "-I", "-c", FAKE_HERMES_BOOTSTRAP, "agentenv", "turn", "--prompt-file", + prompt, "--provider", "litellm", "--model", "m", "--usage-file", usage, "--resume", "s-1", + "--reasoning", "high", "--env-clock"] + env = spawned["env"] + assert env["AGENTENV_REAL_TIME"] == "1" and env["HTTPS_PROXY"] == env["https_proxy"] == PROXY + assert "abc-123.w.modal.host" not in env["NO_PROXY"].split(",") and "127.0.0.1" in env["NO_PROXY"].split(",") + + +@pytest.mark.parametrize("zone", [None, "America/Chicago"]) +def test_on_an_armed_clock_execute_codes_scripts_get_the_proxy_its_ca_and_the_zone_as_the_terminals_commands_do( + monkeypatch, fake_hermes, tmp_path, zone): + """execute_code passes its scripts a fixed few variables and those terminal.env_passthrough names; it sets TZ only + from Hermes' own timezone setting, not from the TZ sync_env_clock's ``timezone`` sets in the server's + environment.""" + spawned = _spawned(monkeypatch, tmp_path, armed=True, environ={**ENVIRON, **({"TZ": zone} if zone else {})}) + + passed = set(spawned["config"]["terminal"]["env_passthrough"]) + egress = {name for name in spawned["env"] if name.upper() in {"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"}} + named = {"NODE_USE_ENV_PROXY", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "NODE_EXTRA_CA_CERTS", *(["TZ"] if zone else [])} + assert egress | named == passed + assert len(egress) == 8 and spawned["env"].get("TZ") == zone + + +@pytest.mark.asyncio +async def test_an_armed_turn_runs_to_its_end_as_the_launchers_command(monkeypatch, fake_hermes, folders): + monkeypatch.setattr(hermes_bridge, "clock_armed", lambda: True) + monkeypatch.setenv(agent_egress.EGRESS_PROXY_ENV, PROXY) + + result = await hermes_bridge.run_hermes(prompt="what is 6*7?", context_id="ctx-a", workspace=str(folders)) + + ran = json.loads(fake_hermes.read_text()) + assert (result.error, result.response) == (None, "42") + assert ran["args"][:2] == ["agentenv", "turn"] and ran["args"][-1] == "--env-clock" + assert (ran["env"]["AGENTENV_REAL_TIME"], ran["env"]["HTTPS_PROXY"]) == ("1", PROXY) + + +def test_the_launchers_command_is_read_as_hermes_installer_writes_it(tmp_path): + """``#!/bin/sh`` and ``exec`` with the Python, -I and a bootstrap of many lines, quoted by ``shlex.join``, then + ``"$@"``; /usr/local/bin/hermes links to it.""" + python = str(tmp_path / "tools" / "python 3.14" / "bin" / "python3") + script = "import os, sys\n# the repair's own stdlib: it's bound first\nsys.exit(main())\n" + launcher = tmp_path / "hermes" + launcher.write_text(f'#!/bin/sh\nexec {shlex.join([python, "-I", "-c", script])} "$@"\n') + launcher.chmod(0o755) + link = tmp_path / "bin" / "hermes" + link.parent.mkdir() + link.symlink_to(launcher) + + assert hermes_bridge.launcher_command(str(link)) == [python, "-I", "-c", script] + + +@pytest.mark.parametrize("body", [ + "#!/usr/bin/env python3\nfrom hermes_cli.main import main\nmain()\n", + "#!/bin/sh\nexec python3 -m hermes_cli.main\n", + # Hermes' forwarder to its own launcher, and an interpreter behind env: sh or env would take the marker. + '#!/bin/sh\nexec /opt/hermes/.hermes/bin/hermes "$@"\n', + '#!/bin/sh\nexec env FOO=1 /opt/hermes/python -I -c "import hermes" "$@"\n', + '#!/bin/sh\nexec /opt/hermes/python -E -c "import hermes" "$@"\n', + '#!/bin/sh\nexec /opt/hermes/python -I -c "import hermes" --flag "$@"\n', +]) +def test_a_launcher_that_isnt_hermes_installers_is_refused(tmp_path, body): + launcher = tmp_path / "hermes" + launcher.write_text(body) + launcher.chmod(0o755) + + with pytest.raises(ValueError, match="doesn't exec Hermes' interpreter"): + hermes_bridge.launcher_command(str(launcher)) + + +# The two Hermes functions --env-clock reaches, as the pinned release has them. +HERMES_TIME = """ +from datetime import datetime + +def get_timezone(): + return TZ + +def now(): + tz = get_timezone() + return datetime.now(tz) if tz is not None else datetime.now().astimezone() +""" +HERMES_STATE_IDS = """ +import uuid +from datetime import datetime + +def new_session_id(now=None, *, hex_len=6): + stamp = (now or datetime.now()).strftime("%Y%m%d_%H%M%S") + return f"{stamp}_{uuid.uuid4().hex[:hex_len]}" +""" + + +def _module(name: str, source: str = "", **values) -> types.ModuleType: + module = types.ModuleType(name) + module.__dict__.update(values) + exec(source, module.__dict__) + return module + + +@pytest.fixture +def plugin(monkeypatch): + """The plugin as Hermes loads it, over stand-ins for the Hermes modules it reads and the one-shot runner it ends + in, which records each turn's message.""" + ran: list[str] = [] + hermes_time = _module("hermes_time", HERMES_TIME, TZ=timezone.utc) + ids = _module("hermes_state_ids", HERMES_STATE_IDS) + for module in (hermes_time, ids, _module("hermes_cli"), + _module("hermes_cli.main", _run_and_exit_oneshot=lambda message, **_: ran.append(message))): + monkeypatch.setitem(sys.modules, module.__name__, module) + spec = importlib.util.spec_from_file_location("hermes_agentenv_plugin", AGENT_DIR / "agentenv_plugin" / "__init__.py") + loaded = importlib.util.module_from_spec(spec) + spec.loader.exec_module(loaded) + return SimpleNamespace(module=loaded, hermes_time=hermes_time, ids=ids, ran=ran) + + +def _turn(plugin, tmp_path, *flags: str) -> None: + """``hermes agentenv turn`` as the bridge runs it, through the command the plugin registers.""" + parser = argparse.ArgumentParser() + plugin.module._setup(parser) + prompt = tmp_path / "prompt.txt" + prompt.write_text("hi") + plugin.module._handle(parser.parse_args(["turn", "--prompt-file", str(prompt), *flags])) + + +@pytest.mark.parametrize("env_time", ["2031-03-04T05:06:07+00:00", "3026-11-20T12:00:00+00:00", + "1950-01-01T00:00:00+00:00"]) +@pytest.mark.parametrize("loaded", [{}, {"agent.agent_init": "new_session_id", + "agent.conversation_compression": "mint_session_id"}]) +def test_with_env_clock_hermes_dates_its_prompt_and_session_by_the_envs_clock(plugin, monkeypatch, tmp_path, env_time, + loaded): + """The date line's date and the session ids' stamp, which its start date is read from, as a command started from + Hermes reads the time: Hermes runs on real time, what it starts on the env's clock. Modules that bound + new_session_id by import before the turn, as the agent and compaction do, each under its own name for it, mint by + the env's clock too; the plugin imports neither.""" + epoch = int(datetime.fromisoformat(env_time).timestamp()) + monkeypatch.setattr(plugin.module, "ENV_TIME_COMMAND", (sys.executable, "-c", f"print({epoch})")) + for module, name in loaded.items(): + monkeypatch.setitem(sys.modules, module, _module(module, **{name: plugin.ids.new_session_id})) + + _turn(plugin, tmp_path, "--env-clock") + + stamp = datetime.fromtimestamp(epoch).strftime("%Y%m%d_%H%M%S_") + assert plugin.hermes_time.now() == datetime.fromisoformat(env_time) + assert plugin.ids.new_session_id(datetime(2026, 11, 20)).startswith(stamp) + for module, name in loaded.items(): + assert getattr(sys.modules[module], name)().startswith(stamp), module + assert {"agent.agent_init", "agent.conversation_compression"} & set(sys.modules) == set(loaded) + assert plugin.ran == ["hi"] + + +def test_without_env_clock_hermes_reads_its_own_clock(plugin, monkeypatch, tmp_path): + monkeypatch.setattr(plugin.module, "ENV_TIME_COMMAND", (sys.executable, "-c", "raise SystemExit(1)")) + minted = plugin.ids.new_session_id + + _turn(plugin, tmp_path) + + assert plugin.hermes_time.datetime is datetime and plugin.ids.new_session_id is minted + assert abs(plugin.hermes_time.now().timestamp() - datetime.now().timestamp()) < 60 + assert plugin.ran == ["hi"] + + +def test_the_env_time_command_prints_whole_seconds_since_the_epoch(plugin): + """Whole seconds: ``%N`` beside a negative ``%s`` reads a second off before 1970.""" + out = subprocess.run(plugin.module.ENV_TIME_COMMAND, capture_output=True, text=True, check=True).stdout + + assert abs(int(out) - datetime.now().timestamp()) < 60 + + +def test_the_names_env_clock_replaces_were_checked_against_the_hermes_the_image_installs(plugin): + pinned = re.search(r"^ARG HERMES_COMMIT=(\w+)$", (AGENT_DIR / "Dockerfile").read_text(), re.MULTILINE).group(1) + + assert plugin.module.ENV_CLOCK_HERMES_COMMIT == pinned + + +def test_start_agent_keeps_a_providers_ca_bundle_trusted_by_the_server_and_the_proxy(tmp_path): + """Sail points SSL_CERT_FILE and the like at the bundle it signs model requests under; root.conf points the server + at agent-env's bundles, so start-agent adds the provider's to them and to the proxy's roots, once each.""" + start = (AGENT_DIR / "start-agent").read_text() + merge = start[start.index('for bundle in "${SSL_CERT_FILE'):start.index("exec supervisord")] + targets = {"/etc/agentenv/ca-bundle.pem": tmp_path / "ca-bundle.pem", "/etc/agentenv/ca.pem": tmp_path / "ca.pem", + "/usr/local/lib/agentenv-egress/roots.pem": tmp_path / "roots.pem"} + for real, fake in targets.items(): + fake.write_text("SYSTEM ROOTS\n") + merge = merge.replace(real, str(fake)) + sail = tmp_path / "sailbox-ca-bundle.crt" + sail.write_text("-----BEGIN CERTIFICATE-----\nSAIL\n-----END CERTIFICATE-----\n") + + subprocess.run(["sh", "-c", merge], check=True, env={"PATH": "/usr/bin:/bin", "SSL_CERT_FILE": str(sail), + "NODE_EXTRA_CA_CERTS": str(sail), "REQUESTS_CA_BUNDLE": "/etc/agentenv/ca-bundle.pem"}) + + for fake in targets.values(): + text = fake.read_text() + assert text.startswith("SYSTEM ROOTS\n") and text.count("SAIL") == 1, (fake.name, text) diff --git a/tst/unit/agents/hermes/test_image_contract.py b/tst/unit/agents/hermes/test_image_contract.py new file mode 100644 index 000000000..4642af65a --- /dev/null +++ b/tst/unit/agents/hermes/test_image_contract.py @@ -0,0 +1,138 @@ +"""The agent's folder is its build context: the Dockerfile copies only files the context sends, the image carries every +module the server imports in the folder it runs the server from, its build fails, rather than a turn on an armed +clock, when the pinned Hermes' launcher isn't one the bridge reads, and the A2A server's exit stops the container, as +when the server was the container's process, while the follower and the proxy restart in place.""" + +from __future__ import annotations + +import ast +import configparser +import os +import re +import select +import shlex +import signal +import subprocess +import sys +import time + +import pytest + +from agent_env.utils.docker.context import BuildContext +from tst.unit.agents.hermes.agent import AGENT_DIR +from tst.unit.agents.test_agent_clock_images import _copied_to + +DOCKERFILE = (AGENT_DIR / "Dockerfile").read_text() +SENT = {entry.name: entry.path for entry in BuildContext.of(AGENT_DIR, AGENT_DIR / "Dockerfile").entries} +SERVER_DIR = "/opt/agent" + + +def _imported(source: str) -> set[str]: + names = set() + for node in ast.walk(ast.parse(source)): + if isinstance(node, ast.Import): + names |= {alias.name.split(".")[0] for alias in node.names} + elif isinstance(node, ast.ImportFrom) and node.module and not node.level: + names.add(node.module.split(".")[0]) + return names + + +def test_every_file_the_image_copies_is_in_its_build_context(): + copied = list(_copied_to(DOCKERFILE)) + + assert copied and all(name in SENT or any(sent.startswith(name.rstrip("/") + "/") for sent in SENT) + for name in copied), copied + + +def test_the_image_carries_every_module_the_server_imports_beside_it(): + """The folder's own modules and those the context takes from agent-env's sources, the egress rule and the clock + page's format among them, each copied into the folder uvicorn imports the server from.""" + modules = {name.rsplit("/", 1)[-1].removesuffix(".py"): name for name in SENT + if name.endswith(".py") and name.count("/") <= 1 and not name.startswith("agentenv_plugin/")} + needed, pending = set(), ["a2a_server"] + while pending: + if (name := modules[pending.pop()]) not in needed: + needed.add(name) + pending += _imported(SENT[name].read_text()) & set(modules) + folders = _copied_to(DOCKERFILE) + + assert {"hermes_bridge.py", "hermes_kit.py", "agent_clock/agent_egress.py", "clock/clockpage.py"} <= needed + assert all(SERVER_DIR in folders.get(name, set()) for name in needed), (needed, folders) + # Beside the bridge too, where its PLUGIN_DIR is: each profile's plugins/agentenv links to it. + assert SERVER_DIR in folders["agentenv_plugin"] + + +def test_the_build_reads_the_pinned_hermes_launcher_as_an_armed_turn_does(): + assert re.search(r"^RUN .*python3 -c 'import hermes_bridge; hermes_bridge\.launcher_command\(\)'$", DOCKERFILE, + re.MULTILINE) + + +def _root_conf() -> configparser.RawConfigParser: + """root.conf as supervisord reads it: ';' or '#' after whitespace starts a comment, and a continuation line is a + line of its value.""" + conf = configparser.RawConfigParser(inline_comment_prefixes=(";", "#"), strict=False) + conf.read_string((AGENT_DIR / "root.conf").read_text()) + return conf + + +ROOT_CONF = _root_conf() +LISTENER = ROOT_CONF["eventlistener:agent-exit"] + + +def test_the_server_isnt_started_again_and_a_listener_hears_it_exit_while_the_follower_and_the_proxy_restart(): + server = ROOT_CONF["program:agent"] + + assert (server["autorestart"], server["startretries"]) == ("false", "0") + assert [ROOT_CONF[f"program:{name}"]["autorestart"] for name in ("clock", "egress")] == ["true", "true"] + assert set(LISTENER["events"].split(",")) == {"PROCESS_STATE_EXITED", "PROCESS_STATE_FATAL"} + assert "user" not in LISTENER and ROOT_CONF["supervisord"]["user"] == "root" + + +def _read(stream, size: int, timeout_s: float = 10) -> bytes: + data, deadline = b"", time.monotonic() + timeout_s + while len(data) < size: + ready, _, _ = select.select([stream], [], [], max(0.0, deadline - time.monotonic())) + assert ready, f"the listener said {data!r}, short of {size} bytes" + chunk = os.read(stream.fileno(), size - len(data)) + assert chunk, f"the listener closed its stdout after {data!r}" + data += chunk + return data + + +def _event(name: str, process: str, from_state: str) -> bytes: + payload = f"processname:{process} groupname:{process} from_state:{from_state} expected:0 pid:4242".encode() + header = f"ver:3.0 server:supervisor serial:7 pool:agent-exit poolserial:7 eventname:{name} len:{len(payload)}\n" + return header.encode() + payload + + +@pytest.mark.parametrize(("name", "from_state"), + [("PROCESS_STATE_EXITED", "RUNNING"), ("PROCESS_STATE_FATAL", "BACKOFF")]) +def test_the_listener_stops_supervisord_when_the_server_exits_and_lets_the_followers_and_the_proxys_exits_pass( + name, from_state): + """The listener's command as supervisord runs it, under a stand-in for supervisord, its parent, that holds its + stdin and stdout as supervisord does.""" + argv = shlex.split(LISTENER["command"] % {}) + assert argv[0] == "/usr/local/bin/python3" + supervisord = subprocess.Popen( + [sys.executable, "-c", "import subprocess, sys, time; subprocess.Popen(sys.argv[1:]); time.sleep(60)", + sys.executable, *argv[1:]], stdin=subprocess.PIPE, stdout=subprocess.PIPE) + try: + assert _read(supervisord.stdout, 6) == b"READY\n" + for other in (_event("PROCESS_STATE_EXITED", "clock", "RUNNING"), + _event("PROCESS_STATE_EXITED", "egress", "RUNNING"), + _event("PROCESS_STATE_FATAL", "clock", "BACKOFF")): + supervisord.stdin.write(other) + supervisord.stdin.flush() + assert _read(supervisord.stdout, 17) == b"RESULT 2\nOKREADY\n" + with pytest.raises(subprocess.TimeoutExpired): + supervisord.wait(0.5) + + supervisord.stdin.write(_event(name, "agent", from_state)) + supervisord.stdin.flush() + + assert supervisord.wait(10) == -signal.SIGTERM + finally: + supervisord.kill() + supervisord.wait() + supervisord.stdin.close() + supervisord.stdout.close()