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: 5 additions & 2 deletions src/agent_env/agents/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,11 @@ Reference: `enable(TRAJECTORY_V1, live=True, ...)`, `ClaudeCodeAgent.run` passin
`event_callback=request.trajectory.append`, and `get_context_trajectory` / `upload_context_trajectory`. Its adapter,
`claude_code_atif.py`, builds steps from stream-json with each message's time, usage and tools from the CLI's session
transcript, which `claude_bridge.SessionTail` feeds as aux records only while `request.trajectory.builds_atif`. Codex's,
`codex_atif.py`, builds them from the CLI's rollout alone, which `codex_bridge.RolloutTail` feeds; Gemini's,
`gemini_atif.py`, from its session transcript (`gemini_bridge.SessionTail`) and the proxy's call records. A runtime
`codex_atif.py`, builds them from the CLI's rollout alone, which `codex_rollout.RolloutTail` feeds; Gemini's,
`gemini_atif.py`, from its session transcript (`gemini_transcript.SessionTail`) and the proxy's call records. Each
bridge follows its tail with `tail_follow.following` (`utils/tail_follow`, which its image takes in `shared_sources.toml`
and copies beside the bridge): read while the CLI runs and once more after it exits, a read in flight when the run ends
fed rather than dropped. A runtime
that only has a record at the end returns it with `native_trajectory(...)`: `agents/pi/pi_agent.py` `_result`.

### `skill-config/v1`, `/ext/skill-config`
Expand Down
5 changes: 3 additions & 2 deletions src/agent_env/agents/agents/claude-code/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ COPY requirements.txt model-requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt -r model-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 claude_bridge.py claude_code_atif.py kit.py tar_changelog.py entrypoint.sh install.sh run.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 ./
# Every clocked agent's egress rule, which the bridge imports, the clock page's format it reads, and the follower that
# feeds the atif/1 adapter the transcript (shared_sources.toml).
COPY agent_clock/agent_egress.py clock/clockpage.py tail_follow/tail_follow.py ./
# The CLI's cwd, /app, and its state, fixed so neither follows the uid.
RUN useradd --create-home --uid 10001 agent && mkdir -p /app /home/agent/.claude \
&& chown agent:agent /app /home/agent/.claude && chmod 0755 entrypoint.sh
Expand Down
73 changes: 18 additions & 55 deletions src/agent_env/agents/agents/claude-code/claude_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from pydantic import BaseModel, ConfigDict, model_validator

from agent_egress import clock_armed, egress_env
from tail_follow import following
from kit import in_thread_to_its_end

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -513,10 +514,10 @@ class SessionTail:
"""One turn's new transcript records, its sub-agents' transcripts' too, as the CLI appends them, each as the ATIF
adapter's aux record (``session_aux``). It starts where each file ends, so an earlier turn isn't fed again, and
finds its place in a file the scrub replaced between attempts by its line count, which a redaction keeps; a file is
taken as replaced when its inode or the line before the place it was read to changed.
``read`` only reads; ``advance`` commits what it read, so a read abandoned midway is read again. For a new
document, ``new_document``, the first read also gives the latest request shape the transcript already held, which
the CLI writes once per session. Where it reads a whole file it reads it in pieces, since a long computer-use
taken as replaced when its inode or the line before the place it was read to changed. Each read moves past what
it gives, since the follower feeds every read it makes (``tail_follow``). For a new document, ``new_document``, the
first read also gives the latest request shape the transcript already held, which the CLI writes once per
session. Where it reads a whole file it reads it in pieces, since a long computer-use
session's transcript holds each screenshot twice."""

def __init__(self, session_id: str, on_stdout: Collection[str], shapes: set[tuple[str | None, str]], *,
Expand All @@ -539,34 +540,27 @@ def _paths(self) -> list[Path]:
subagents = sorted(self._subagents.glob(f"{_SUBAGENT_PREFIX}*.jsonl")) if self._subagents.is_dir() else []
return ([self._main] if self._main.exists() else []) + subagents

def read(self) -> tuple[list[tuple[str, dict]], dict[Path, _TailedFile], set[tuple[str | None, str]]]:
"""The aux records the files gained since the last ``advance``, where each file is read to, and the request
shapes fed then."""
def read(self, final: bool = False) -> list[tuple[str, dict]]:
"""The aux records the files gained since the last read. The transcript has no end of its own to read to, so a
final read is like any other."""
records: list[tuple[str, dict]] = []
files: dict[Path, _TailedFile] = {}
shapes = set(self._shapes)
if self._earlier_shape is not None and (fed := session_aux(self._earlier_shape, None, (), shapes)):
if self._earlier_shape is not None and (fed := session_aux(self._earlier_shape, None, (), self._shapes)):
records.append(fed)
self._earlier_shape = None
for path in self._paths():
try:
tailed, lines = self._new_lines(path, self._files.get(path))
self._files[path], lines = self._new_lines(path, self._files.get(path))
except OSError:
continue
files[path] = tailed
agent_id = path.stem.removeprefix(_SUBAGENT_PREFIX) if path.parent == self._subagents else None
for raw in lines:
try:
record = json.loads(raw)
except (json.JSONDecodeError, UnicodeDecodeError):
continue
if isinstance(record, dict) and (fed := session_aux(record, agent_id, self._on_stdout, shapes)):
if isinstance(record, dict) and (fed := session_aux(record, agent_id, self._on_stdout, self._shapes)):
records.append(fed)
return records, files, shapes

def advance(self, files: Mapping[Path, _TailedFile], shapes: set[tuple[str | None, str]]) -> None:
self._files.update(files)
self._shapes.update(shapes)
self._earlier_shape = None
return records

@staticmethod
def _new_lines(path: Path, tailed: _TailedFile | None) -> tuple[_TailedFile, list[bytes]]:
Expand Down Expand Up @@ -656,35 +650,6 @@ def _ends_in(file, tailed: _TailedFile) -> bool:
return file.read(len(tailed.last)) == tailed.last


async def _stop_following(following: asyncio.Task, tail: SessionTail, feed: Callable[[str, Any], None]) -> None:
"""Stop following once the CLI has exited, then feed what its transcripts gained since the last read. A follower
that failed is logged; the turn goes on without its records."""
following.cancel()
try:
await following
except asyncio.CancelledError:
if (current := asyncio.current_task()) is not None and current.cancelling():
raise
except Exception:
logger.warning("following the session transcript failed; the ATIF copy lacks its later records", exc_info=True)
return
await _feed_tail(tail, feed)


async def _follow(tail: SessionTail, feed: Callable[[str, Any], None]) -> None:
"""Feed ``tail``'s records while the CLI runs."""
while True:
await _feed_tail(tail, feed)
await asyncio.sleep(SESSION_POLL_S)


async def _feed_tail(tail: SessionTail, feed: Callable[[str, Any], None]) -> None:
records, files, shapes = await asyncio.to_thread(tail.read)
tail.advance(files, shapes)
for name, record in records:
feed(name, record)


def _one_line(text: str) -> str:
return _LINE_BREAK_PATTERN.sub(" ", text).strip()

Expand Down Expand Up @@ -782,15 +747,13 @@ async def run_claude(
else max(int(deadline - time.monotonic()) - _DEADLINE_HEADROOM_S, 1))
# Each scrub ends before the turn does, cancelled or not: a later turn on the context mustn't start while it
# can still replace the transcript that turn appends to.
following = asyncio.create_task(_follow(tail, aux_callback)) if tail is not None else None
follow = following(tail.read, aux_callback, SESSION_POLL_S, "session transcript") if tail is not None \
else contextlib.nullcontext()
try:
result = await spawn(prompt=attempt_prompt, session_id=attempt_session, resume=attempt_resume,
timeout_s=attempt_timeout_s)
if following is not None:
await _stop_following(following, tail, aux_callback)
async with follow:
result = await spawn(prompt=attempt_prompt, session_id=attempt_session, resume=attempt_resume,
timeout_s=attempt_timeout_s)
finally:
if following is not None:
following.cancel()
await in_thread_to_its_end(scrub_session_transcript, attempt_session)
if result.session_id != attempt_session:
await in_thread_to_its_end(scrub_session_transcript, result.session_id)
Expand Down
2 changes: 1 addition & 1 deletion src/agent_env/agents/agents/claude-code/install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ PYTHON_VERSION=3.12
START_TIMEOUT_S=120
STOP_TIMEOUT_S=10
CLAUDE_CODE_VERSION=$(sed -n 's/^ARG CLAUDE_CODE_VERSION=//p' "$here/Dockerfile")
AGENT_FILES="a2a_server.py claude_bridge.py claude_code_atif.py kit.py requirements.txt run.sh tar_changelog.py agent_clock/agent_egress.py clock/clockpage.py"
AGENT_FILES="a2a_server.py claude_bridge.py claude_code_atif.py kit.py requirements.txt run.sh tar_changelog.py agent_clock/agent_egress.py clock/clockpage.py tail_follow/tail_follow.py"

# put SRC DEST replaces DEST by a rename, so a binary an earlier install's agent still runs can be replaced.
case $mode in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
clock = "utils/faketime_clock"
egress = "utils/egress_proxy"
agent_clock = "utils/agent_clock"
tail_follow = "utils/tail_follow"
8 changes: 4 additions & 4 deletions src/agent_env/agents/agents/codex/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ RUN npm ci --ignore-scripts --omit=dev --no-audit --no-fund --loglevel=error &&
COPY requirements.txt model-requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt -r model-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 codex_atif.py codex_bridge.py codex_config.py codex_date.py codex_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
# each CLI run calls the endpoint through (shared_sources.toml).
COPY agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py ./
COPY a2a_server.py codex_atif.py codex_bridge.py codex_config.py codex_date.py codex_kit.py codex_rollout.py entrypoint.sh install.sh run.sh ./
# Every clocked agent's egress rule, which the bridge imports, the clock page's format it reads, the model relay each
# CLI run calls the endpoint through, and the follower that feeds the atif/1 adapter the rollouts (shared_sources.toml).
COPY agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py tail_follow/tail_follow.py ./
# The CLI's cwd, /app, and its state, fixed so neither follows the uid.
RUN useradd --create-home --uid 10001 agent && mkdir -p /app /home/agent/.codex \
&& chown agent:agent /app /home/agent/.codex && chmod 0755 entrypoint.sh
Expand Down
29 changes: 19 additions & 10 deletions src/agent_env/agents/agents/codex/codex_atif.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import json
import re
from dataclasses import dataclass, field
from enum import Enum
from typing import Any

from agentenv_protocol.atif import Adapter, Native, atif_adapter, aux, finish, is_token_count, native
Expand Down Expand Up @@ -51,16 +52,25 @@ def _string(value: Any) -> str | None:
return value if isinstance(value, str) and value else None


class _Placed(Enum):
"""Where a sub-agent's records go: held until it's declared under its spawn in this task, then into its embedded
trajectory; one an earlier task saw has its records left to the native log, and no spawn now takes it, even one
that reuses its path."""

HELD = "held"
EMBEDDED = "embedded"
EARLIER = "earlier"


@dataclass
class _Sub:
"""A sub-agent's thread: its path and name once its first record gives them, its records while it isn't declared
in this task, and whether an earlier task saw it, so a spawn now that reuses its path names another thread."""
"""A sub-agent's thread: its path and name once its first record gives them, where its records go (``placed``),
and its records while they're held."""

path: str | None = None
name: str | None = None
held: list[dict[str, Any]] = field(default_factory=list)
declared: bool = False
earlier: bool = False
placed: _Placed = _Placed.HELD


@atif_adapter(native_format=NATIVE_FORMAT, version="0.1.0", input_includes_cache=True, tested_with=TESTED_WITH)
Expand Down Expand Up @@ -93,7 +103,7 @@ def rollout(self, record: dict[str, Any], turn: Any) -> None:
if record.get("type") == "session_meta":
self._meta(thread, sub, record["payload"], turn)
return
if not sub.declared:
if sub.placed is not _Placed.EMBEDDED:
sub.held.append(record)
return
self._apply(record, thread, turn)
Expand All @@ -106,13 +116,13 @@ def end(self, turn: Any) -> None:
for record in sub.held:
turn.unmatched(record)
sub.held.clear()
sub.declared, sub.earlier = False, True
sub.placed = _Placed.EARLIER
self._new_task()

def _meta(self, thread: str, sub: _Sub, payload: dict[str, Any], turn: Any) -> None:
sub.path = _string(payload.get("agent_path"))
sub.name = _string(payload.get("agent_nickname")) or sub.path
if not sub.earlier and sub.path in self._held_results:
if sub.placed is _Placed.HELD and sub.path in self._held_results:
self._declare(thread, *self._held_results.pop(sub.path), turn)

def _apply(self, record: dict[str, Any], thread: str, turn: Any) -> None:
Expand Down Expand Up @@ -177,8 +187,7 @@ def _output(self, payload: dict[str, Any], record: dict[str, Any], turn: Any) ->
if path is None:
self._result(record, turn)
return
thread = next((t for t, sub in self._subs.items() if sub.path == path and not sub.declared and not sub.earlier),
None)
thread = next((t for t, sub in self._subs.items() if sub.path == path and sub.placed is _Placed.HELD), None)
if thread is None:
self._held_results[path] = (call_id, record)
else:
Expand Down Expand Up @@ -217,7 +226,7 @@ def _declare(self, thread: str, call_id: str, result: dict[str, Any], turn: Any)
the sub-agent's held records."""
sub = self._subs[thread]
turn.subagent(thread, spawned_by=call_id, name=sub.name)
sub.declared = True
sub.placed = _Placed.EMBEDDED
self._result(result, turn)
held, sub.held = sub.held, []
for record in held:
Expand Down
Loading
Loading