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
20 changes: 18 additions & 2 deletions AGENTS.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/agent_env/a2a_agent/a2a_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,14 +498,14 @@ def get(cls, id: str, version: Optional[int] = None) -> A2AAgent:
raise NotFoundError(f"{id!r} is an alias of {named.target_id}, which comes with "
f"{named.declared_by}, so it has no fixed version; drop the pin") from None
else:
note_read(EntityKind.AGENT, id, asked, agent.version)
note_read(EntityKind.AGENT, id, asked, agent)
return agent
try:
agent = store.get(named.target_id)
except NotFoundError:
raise NotFoundError(f"{id!r} is an alias of {named.target_id}, which comes with {named.declared_by} and "
"isn't in the store yet: an `agent-env run` of a bundle that uses it writes it") from None
note_read(EntityKind.AGENT, id, asked, agent.version, alias=True)
note_read(EntityKind.AGENT, id, asked, agent, alias=True)
return agent

@classmethod
Expand Down
2 changes: 1 addition & 1 deletion src/agent_env/artifact/artifact.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def get(cls, id: str, version: Optional[int] = None) -> Self:
artifact = get_artifact_store().get(id, pinned_version(EntityKind.ARTIFACT, id, version))
if not isinstance(artifact, cls):
raise TypeError(f"artifact {id!r} is a {artifact.type!r} artifact, not a {cls.__name__}")
note_read(EntityKind.ARTIFACT, id, version, artifact.version)
note_read(EntityKind.ARTIFACT, id, version, artifact)
return artifact

@classmethod
Expand Down
10 changes: 10 additions & 0 deletions src/agent_env/artifact/artifacts/docker_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,16 @@ def pinned_name(self) -> str:
"""What a sandbox pulls: ``image_name`` pinned to the ``image_digest`` when it records one."""
return f"{self.image_name}@{self.image_digest}" if self.image_digest else self.image_name

@property
def image_identity(self) -> str | None:
"""What the image is, whichever build of it ran: ``source:<digest>``, its build context's content hash, when it
has one, so a rebuild of the same context is the same image; else ``registry:<digest>``, the digest it is
pinned to; None for an image held only as a tarball, which this artifact's version names."""
if self.source_digest:
return f"source:{self.source_digest}"
digest = self.image_digest or self.image_name.partition("@")[2]
return f"registry:{digest}" if digest else None

@property
def context_only(self) -> bool:
"""Whether only the image's build context is stored: no tar.gz, and an image name that names no registry, the
Expand Down
16 changes: 13 additions & 3 deletions src/agent_env/config/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,23 +41,33 @@
SEAM_KEYS = ("impl", "config")


# How the config file in effect was found, as a run records it: never its path.
FOUND_BY_ENVIRONMENT, FOUND_BY_DISCOVERY, FOUND_BY_NONE = "environment", "discovered", "none"


def discover_config_path(start: Optional[Path] = None) -> Optional[Path]:
"""Locate the config.toml: ``AGENT_ENV_CONFIG`` wins, else the nearest
``.agentenv/config.toml`` walking up from ``start`` (CWD by default).
An explicit ``AGENT_ENV_CONFIG`` override must point to an existing file —
fail loud rather than silently drop the whole config (and derive local-store
paths from a non-existent directory) on a typo'd override path."""
return discover_config(start)[0]


def discover_config(start: Optional[Path] = None) -> tuple[Optional[Path], str]:
"""``discover_config_path``'s answer, and how it was found: ``environment`` (``AGENT_ENV_CONFIG``, which a plugin
may set), ``discovered`` (walking up) or ``none``."""
override = os.getenv(ENV_CONFIG_PATH)
if override:
path = Path(override)
if not path.is_file():
raise ConfigError(f"{ENV_CONFIG_PATH}={override!r} does not point to an existing file")
return path
return path, FOUND_BY_ENVIRONMENT
for candidate in _walk_up_candidates(start):
if candidate.is_file():
return candidate
return None
return candidate, FOUND_BY_DISCOVERY
return None, FOUND_BY_NONE


def _walk_up_candidates(start: Optional[Path] = None) -> list[Path]:
Expand Down
4 changes: 4 additions & 0 deletions src/agent_env/config/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,10 @@ def section(self, *names: str) -> Mapping[str, Any]:
"""The config table at ``names``: ``{}`` when absent, an error when mis-shaped."""
return self._document().section(*names)

def config_found_by(self) -> str:
"""How the config file this Config reads was found (``loader.discover_config``), never its path."""
return self._document().found_by

def config_path(self) -> Optional[Path]:
"""The config.toml this Config resolves against. The process resolves one document,
so every section and every local-store path agree about which file they came from."""
Expand Down
15 changes: 8 additions & 7 deletions src/agent_env/config/snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@

@dataclass(frozen=True)
class Snapshot:
"""Where the document came from, and what it said."""
"""Where the document came from, how it was found (``loader.discover_config``), and what it said."""

path: Optional[Path]
_document: Mapping[str, Any]
error: Optional[Exception] = None
found_by: str = loader.FOUND_BY_NONE

def section(self, *names: str) -> Mapping[str, Any]:
"""The table at ``names`` as a copy; ``{}`` when absent, an error when mis-shaped.
Expand Down Expand Up @@ -58,24 +59,24 @@ def _require_table(node: Any, walked: list) -> None:
)


def _parse(path: Optional[Path]) -> Snapshot:
def _parse(path: Optional[Path], found_by: str = loader.FOUND_BY_NONE) -> Snapshot:
"""A parse error rides on the snapshot so the path stays reportable — `config show` needs
to name the file most when the file is the broken thing."""
if path is None:
return Snapshot(path=None, _document={})
return Snapshot(path=None, _document={}, found_by=found_by)
try:
# A strict read, with no existence check in front of it: discovery returned this
# path a moment ago, so a missing file is a race and must be loud. Checking first
# and reading second would only narrow the window, which is not the same as closing
# it — the open is the check.
return Snapshot(path=path, _document=loader.read_config_file(path))
return Snapshot(path=path, _document=loader.read_config_file(path), found_by=found_by)
except FileNotFoundError:
return Snapshot(path=path, _document={}, error=ConfigError(
return Snapshot(path=path, _document={}, found_by=found_by, error=ConfigError(
f"config.toml at {path} vanished between discovery and read"))
except (ConfigError, OSError) as e:
return Snapshot(path=path, _document={}, error=e)
return Snapshot(path=path, _document={}, found_by=found_by, error=e)


def resolve() -> Snapshot:
"""Discover and parse, with no caching — the Config holds the result."""
return _parse(loader.discover_config_path())
return _parse(*loader.discover_config())
58 changes: 46 additions & 12 deletions src/agent_env/entity/pins.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
from collections.abc import Iterator, Mapping
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
import threading
from dataclasses import dataclass, field, replace
from typing import Any, Optional

from agent_env.entity.refs import EntityKind
Expand All @@ -34,13 +35,17 @@
class Read:
"""One read of an entity: ``asked`` is the version asked for, None for the latest, and ``version`` the one read.
``alias`` marks an id that named an installed bundle's entity rather than one of the store's, which takes no
pin: its version is the installed bundle's."""
pin: its version is the installed bundle's. ``type`` is the entity's type and ``cls`` its class, which says the
distribution that supplied it; ``image_identity`` is an image's (``DockerImageArtifact.image_identity``)."""

kind: EntityKind
id: str
asked: Optional[int]
version: int
alias: bool = False
type: Optional[str] = None
cls: Optional[type] = field(default=None, compare=False)
image_identity: Optional[str] = None


def checked_pins(value: Any) -> dict[str, dict[str, int]]:
Expand Down Expand Up @@ -85,18 +90,45 @@ def pinned_version(kind: EntityKind, entity_id: str, version: Optional[int]) ->
return _PINS.get().get(str(kind), {}).get(entity_id)


class Reads:
"""The distinct reads a ``recording`` block made, each entity version once, in the order first read: a read of one
already listed adds only what it says, that it was read at its latest or through an alias, so a long run that reads
one env over and over keeps one entry. Reads made on several threads at once are kept whole."""

def __init__(self) -> None:
self._by_version: dict[tuple[str, str, int], Read] = {}
self._lock = threading.Lock()

def add(self, read: Read) -> None:
key = (str(read.kind), read.id, read.version)
with self._lock:
held = self._by_version.get(key)
if held is None:
self._by_version[key] = read
elif (read.asked is None and held.asked is not None) or (read.alias and not held.alias):
self._by_version[key] = replace(held, asked=None if read.asked is None else held.asked,
alias=held.alias or read.alias)

def __iter__(self) -> Iterator[Read]:
with self._lock:
return iter(list(self._by_version.values()))

def __len__(self) -> int:
return len(self._by_version)


@dataclass
class _Recording:
reads: list[Read]
reads: Reads
pins: Optional[dict[str, dict[str, int]]]


@contextmanager
def recording(pins: Optional[dict[str, dict[str, int]]] = None) -> Iterator[list[Read]]:
"""The reads the getters make in the block, in order, each loaded child's before its parent's. With ``pins``, the
block reads through them, and each read at its latest, not through an alias, adds its version to them as it lands,
so every later read of that id, a sibling child's in the same load included, reads the same version."""
record = _Recording([], pins)
def recording(pins: Optional[dict[str, dict[str, int]]] = None) -> Iterator[Reads]:
"""The distinct reads the getters make in the block (``Reads``), each loaded child's before its parent's. With
``pins``, the block reads through them, and each read at its latest, not through an alias, adds its version to them
as it lands, so every later read of that id, a sibling child's in the same load included, reads the same version."""
record = _Recording(Reads(), pins)
token = _RECORDING.set(record)
try:
if pins is None:
Expand All @@ -108,10 +140,12 @@ def recording(pins: Optional[dict[str, dict[str, int]]] = None) -> Iterator[list
_RECORDING.reset(token)


def note_read(kind: EntityKind, entity_id: str, asked: Optional[int], version: int, *, alias: bool = False) -> None:
"""Add a read to the block ``recording`` is listing, if any, pinning it there when it was read at its latest."""
def note_read(kind: EntityKind, entity_id: str, asked: Optional[int], entity: Any, *, alias: bool = False) -> None:
"""Add the read of ``entity`` to the block ``recording`` is listing, if any, pinning it there when it was read at
its latest."""
if (record := _RECORDING.get()) is None:
return
record.reads.append(Read(kind, entity_id, asked, version, alias))
record.reads.add(Read(kind, entity_id, asked, entity.version, alias, getattr(entity, "type", None),
type(entity), getattr(entity, "image_identity", None)))
if record.pins is not None and asked is None and not alias:
record.pins.setdefault(str(kind), {}).setdefault(entity_id, version)
record.pins.setdefault(str(kind), {}).setdefault(entity_id, entity.version)
4 changes: 2 additions & 2 deletions src/agent_env/env/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ def get(cls, id: str, version: Optional[int] = None) -> "Env":
if named is None:
raise NotFoundError(refusal) from None
else:
note_read(EntityKind.ENV, id, asked, env.version)
note_read(EntityKind.ENV, id, asked, env)
return env
if not namespace_routing_enabled():
raise NotFoundError(f"{id!r} is an alias of {named.target_id}, which comes with {named.declared_by}, and "
Expand All @@ -374,7 +374,7 @@ def get(cls, id: str, version: Optional[int] = None) -> "Env":
"isn't in the store yet: an `agent-env run` of a bundle that uses it writes it") from None
env = copy.copy(env)
env._stored_id, env.id = env.id, id
note_read(EntityKind.ENV, id, asked, env.version, alias=True)
note_read(EntityKind.ENV, id, asked, env, alias=True)
return env

@property
Expand Down
59 changes: 59 additions & 0 deletions src/agent_env/eval/intent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""What a run of a task is asked to do, computed the same way by an eval's plan (``agent_env.eval.resolve``) and by
each run on the process that runs it (``agent_env.task.run_lock``), so the two compare: the task's content hash, the
overrides a run reads, each role's model and the host its calls go to, and those overrides as a record keeps them.
"""

from __future__ import annotations

import hashlib
from typing import TYPE_CHECKING, Any, Mapping, Optional

from agent_env.config import get_config
from agent_env.config.errors import ConfigError
from agent_env.config.model import ModelRole, endpoint_host, run_endpoint, run_model, without_credentials
from agent_env.entity.pins import PINS_KEY
from agent_env.eval.lock import RoleModel
from agent_env.task_step.context import strip_redacted_keys
from agent_env.utils.canonical import canonical_json

if TYPE_CHECKING:
from agent_env.task import Task


def content_hash(task: "Task") -> str:
"""A hash of what the task runs, without its id and version, which a lock records beside it: a version that
republishes the same content hashes the same."""
content = {key: value for key, value in task.to_dict().items() if key not in ("id", "version")}
return "sha256:" + hashlib.sha256(canonical_json(content)).hexdigest()


def run_overrides(user_overrides: Mapping[str, Any], *, agent_model: Optional[str] = None,
agent_artifact_id: Optional[str] = None) -> dict[str, Any]:
"""The overrides a run reads, without its pins, which a lock records apart: ``user_overrides`` with the run's
``agent_model`` and ``agent_artifact_id``, which ``Task.run`` takes beside them."""
overrides = {key: value for key, value in user_overrides.items() if key != PINS_KEY}
overrides.update({key: value for key, value in (("agent_model", agent_model),
("agent_artifact_id", agent_artifact_id)) if value})
return overrides


def role_models(overrides: Mapping[str, Any]) -> dict[str, RoleModel]:
"""Each role's model where no step or agent names one, as this process's config resolves it with ``overrides``,
and the host its calls go to, by the role's name."""
config = get_config()
try:
configured = config.get_litellm_base_url()
except ConfigError:
configured = None
roles = {}
for role in ModelRole:
resolved = config.resolve_model(role, run=run_model(role, overrides))
roles[role.value] = RoleModel(resolved.model, None if resolved.source is None else str(resolved.source),
endpoint_host(run_endpoint(role, overrides) or configured))
return roles


def recorded_overrides(overrides: Mapping[str, Any]) -> dict[str, Any]:
"""``overrides`` without secrets, at any depth (a step's ``step_params`` included): each endpoint override as its
host, and no URL with a user or password in it."""
return without_credentials(strip_redacted_keys(dict(overrides)))
Loading
Loading