From 064343bebcdebff3c1b22b6894e5317de30b9260 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Wed, 25 Nov 2026 10:20:36 -0800 Subject: [PATCH 1/3] feat(agents): Antigravity agent on the env's clock Google's Antigravity SDK (google-antigravity 0.1.24) behind the protocol's A2A agent framework, shipped in the agents bundle as @local/agentenv-framework/agents/antigravity with the alias antigravity, a smoke task and a published image. Each turn is one Agent.chat() in the server's process, resumed in the context's SDK conversation; the env's MCP servers are its streamable-HTTP servers; its streamed steps, with each tool result from the SDK's hooks, are the trajectory (antigravity-sdk/1). The SDK's harness sends no key, so a model relay of the turn's own adds the endpoint's key, [model.headers] and the run's attribution, and counts usage from every call, which the SDK doesn't report. builtin_tools selects the SDK's own tools, so a task can turn its web tools off. The SDK retries a model call the endpoint answers with a transient error. The image follows the env's clock as the other clocked agents do. The harness is a static binary libfaketime can't reach, so it stays on real time with its conversation store; on an armed clock the relay puts the env's time in the local-time line of each turn's message and shifts the stamps on each command's result, and records what each was given, so a resumed conversation's history keeps its times. install/v1 installs it into a container or onto a host. Co-Authored-By: Claude Opus 5.5 --- .github/dependabot.yml | 1 + .github/scripts/infra_build.py | 5 +- CONTRIBUTING.md | 2 +- src/agent_env/agents/README.md | 20 +- .../agents/agents/antigravity/Dockerfile | 59 ++ .../agents/agents/antigravity/README.md | 65 ++ .../agents/agents/antigravity/a2a_server.py | 684 ++++++++++++++++++ .../agents/antigravity/antigravity_bridge.py | 441 +++++++++++ .../agents/antigravity/antigravity_date.py | 201 +++++ .../agents/antigravity/antigravity_kit.py | 86 +++ .../agents/agents/antigravity/entrypoint.sh | 4 + .../agents/agents/antigravity/install.sh | 149 ++++ .../agents/antigravity/requirements.txt | 11 + .../agents/agents/antigravity/root.conf | 74 ++ .../agents/agents/antigravity/run.sh | 12 + .../agents/antigravity/shared_sources.toml | 6 + .../agents/agents/antigravity/start-agent | 30 + src/agent_env/agents/aliases.toml | 1 + .../agents/tasks/antigravity-smoke.json | 7 + .../agent/antigravity_env_date_test.py | 212 ++++++ tst/unit/agents/antigravity/__init__.py | 0 tst/unit/agents/antigravity/agent.py | 31 + tst/unit/agents/antigravity/conftest.py | 90 +++ tst/unit/agents/antigravity/fake_sdk.py | 177 +++++ .../antigravity/test_antigravity_bridge.py | 375 ++++++++++ .../antigravity/test_antigravity_date.py | 242 +++++++ .../agents/antigravity/test_card_contract.py | 128 ++++ .../agents/antigravity/test_image_contract.py | 101 +++ tst/unit/agents/antigravity/test_install.py | 123 ++++ .../antigravity/test_message_contract.py | 273 +++++++ tst/unit/agents/antigravity/test_snapshot.py | 126 ++++ tst/unit/agents/test_host_workdir.py | 4 +- .../agents/test_installed_control_token.py | 2 +- tst/unit/agents/test_trajectory_formats.py | 1 + tst/unit/bundle/shipped_bundles_test.py | 3 +- tst/unit/test_infra_build_script.py | 2 +- tst/unit/test_infra_images_script.py | 4 +- 37 files changed, 3741 insertions(+), 11 deletions(-) create mode 100644 src/agent_env/agents/agents/antigravity/Dockerfile create mode 100644 src/agent_env/agents/agents/antigravity/README.md create mode 100644 src/agent_env/agents/agents/antigravity/a2a_server.py create mode 100644 src/agent_env/agents/agents/antigravity/antigravity_bridge.py create mode 100644 src/agent_env/agents/agents/antigravity/antigravity_date.py create mode 100644 src/agent_env/agents/agents/antigravity/antigravity_kit.py create mode 100755 src/agent_env/agents/agents/antigravity/entrypoint.sh create mode 100755 src/agent_env/agents/agents/antigravity/install.sh create mode 100644 src/agent_env/agents/agents/antigravity/requirements.txt create mode 100644 src/agent_env/agents/agents/antigravity/root.conf create mode 100755 src/agent_env/agents/agents/antigravity/run.sh create mode 100644 src/agent_env/agents/agents/antigravity/shared_sources.toml create mode 100755 src/agent_env/agents/agents/antigravity/start-agent create mode 100644 src/agent_env/agents/tasks/antigravity-smoke.json create mode 100644 tst/integration/agent/antigravity_env_date_test.py create mode 100644 tst/unit/agents/antigravity/__init__.py create mode 100644 tst/unit/agents/antigravity/agent.py create mode 100644 tst/unit/agents/antigravity/conftest.py create mode 100644 tst/unit/agents/antigravity/fake_sdk.py create mode 100644 tst/unit/agents/antigravity/test_antigravity_bridge.py create mode 100644 tst/unit/agents/antigravity/test_antigravity_date.py create mode 100644 tst/unit/agents/antigravity/test_card_contract.py create mode 100644 tst/unit/agents/antigravity/test_image_contract.py create mode 100644 tst/unit/agents/antigravity/test_install.py create mode 100644 tst/unit/agents/antigravity/test_message_contract.py create mode 100644 tst/unit/agents/antigravity/test_snapshot.py diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 5c0de2b4f..04d969ac3 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -44,6 +44,7 @@ updates: - "/src/agent_env/env/gateway" - "/src/agent_env/env/envs/service_db" - "/src/agent_env/env/envs/playwright_mcp" + - "/src/agent_env/agents/agents/antigravity" - "/src/agent_env/agents/agents/browser-use" - "/src/agent_env/agents/agents/claude-code" - "/src/agent_env/agents/agents/codex" diff --git a/.github/scripts/infra_build.py b/.github/scripts/infra_build.py index 78a7dde8d..4f6f562b8 100644 --- a/.github/scripts/infra_build.py +++ b/.github/scripts/infra_build.py @@ -53,6 +53,7 @@ "agentenv-db-web": "src/agent_env/env/envs/service_db/Dockerfile.db-web", "agentenv-db-mcp": "src/agent_env/env/envs/service_db/Dockerfile.db-mcp", "agentenv-playwright-mcp": "src/agent_env/env/envs/playwright_mcp/Dockerfile", + "agentenv-antigravity": "src/agent_env/agents/agents/antigravity/Dockerfile", "agentenv-browser-use": "src/agent_env/agents/agents/browser-use/Dockerfile", "agentenv-claude-code": "src/agent_env/agents/agents/claude-code/Dockerfile", "agentenv-codex": "src/agent_env/agents/agents/codex/Dockerfile", @@ -108,7 +109,7 @@ # Each image's check, beyond its build: the gateway imports its server, Postgres turns healthy, the sidecars and the # browser answer their own commands, Claude Code's, Codex's, Gemini's, Hermes', OpenCode's and pi's agents run their -# CLIs and import their servers, OpenHands' imports its server, which loads the OpenHands SDK, Pydantic AI's imports its +# CLIs and import their servers, Antigravity's runs its SDK's harness and imports its server, OpenHands' imports its server, which loads the OpenHands SDK, Pydantic AI's imports its # server, which loads Pydantic AI, Browser Use's loads browser-use in its own environment and imports its server, the proxy imports its # server, the mail example's env imports its server, and the base computer's desktop comes up, every program running. _SMOKES = { @@ -120,6 +121,8 @@ " && ls -d /root/.cache/ms-playwright/chromium-*"], "agentenv-claude-code": ["docker", "run", "--rm", "--entrypoint", "sh", "{image}", "-c", 'claude --version && python -c "import a2a_server"'], + "agentenv-antigravity": ["docker", "run", "--rm", "--entrypoint", "sh", "{image}", "-c", + 'python -c "import a2a_server"'], "agentenv-browser-use": ["docker", "run", "--rm", "--entrypoint", "sh", "{image}", "-c", '/opt/browser-use/bin/python -c "import agent" && python -c "import a2a_server"'], "agentenv-codex": ["docker", "run", "--rm", "--entrypoint", "sh", "{image}", "-c", diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2c6e81d47..8a376d3c2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -91,7 +91,7 @@ the previous release, so a clear pull request title is also the release note. A A release also publishes the infra images agent-env ships, once the `PUBLISH_INFRA_IMAGES` repository variable is `true`: one per Dockerfile under `src/agent_env/env`, and one per shipped agent (`agentenv-claude-code`, its CLI -included, `agentenv-codex`, `agentenv-gemini`, `agentenv-hermes`, `agentenv-opencode`, `agentenv-pi`, `agentenv-openhands` and `agentenv-pydantic-ai`), at `ghcr.io/scaleapi/agentenv-:src-` for linux/amd64 +included, `agentenv-codex`, `agentenv-gemini`, `agentenv-hermes`, `agentenv-opencode`, `agentenv-antigravity`, `agentenv-pi`, `agentenv-openhands` and `agentenv-pydantic-ai`), at `ghcr.io/scaleapi/agentenv-:src-` for linux/amd64 and linux/arm64, where the tag is the build context's source digest, so an unchanged Dockerfile is not built again. The agents' images install the newest `agentenv-framework-protocol` at or above the floor in their `requirements.txt`, which a release doesn't pin, so each is built again only when its folder changes: once the protocol diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index 5abe0f237..0367f9ea6 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -61,6 +61,11 @@ The A2A server starts with the real-time marker, so it and its records stay on r websearch tool's year, and the CLI enables no provider but the endpoint, so no call bypasses the relay. A call whose date the relay can't read or place is refused, so the turn fails rather than tell the model the machine's date (`opencode_date.py`). +- **Antigravity's harness on real time.** The Antigravity SDK's harness is a static Go binary, which libfaketime can't + reach, so it keeps real time while the commands it runs read the env's. While the clock is armed, the turn's model + relay puts the env's time, read from `date`, in the "The current local time is" line the harness opens each user + message with, and keeps the time each turn was given, so a resumed conversation's history doesn't change + (`antigravity_date.py`). A call whose time it can't read is refused. - **For the rest of the run.** An agent that follows goes on following: a later `sync_env_clock` without `agent_clock` re-arms the clock it follows, and only agents that never followed keep real time. - **Through the egress proxy.** While the agent follows an armed clock, the CLI goes out through the egress proxy, which @@ -118,6 +123,15 @@ OpenAI-compatible one, `/v1/chat/completions`, and takes its model from th `anthropic/claude-sonnet-5-5`. It declares `install/v1` too, into a container or onto a `vm` sandbox's Linux host, with glibc. Its folder's `README.md` covers the extensions it implements. +`agents/antigravity/` runs Google's [Antigravity SDK](https://pypi.org/project/google-antigravity/) behind the +protocol's A2A agent framework, in process rather than a CLI: each turn is one `Agent.chat()` of the SDK, resumed in the +context's SDK conversation, the task env's MCP servers are its streamable-HTTP servers, and its streamed steps, with each +tool call's result from the SDK's hooks, are the turn's trajectory. Name it as `antigravity`, its alias, or by its id, +`@local/agentenv-framework/agents/antigravity`. Its harness calls the `[model]` endpoint as an OpenAI-compatible one, +`/v1/chat/completions`, through a relay that adds the key and the run's attribution and counts usage, and takes +its model from the prompt, else `anthropic/claude-sonnet-5-5`. It declares `install/v1` too, into a container or onto a +`vm` sandbox's Linux host, with glibc. Its folder's `README.md` covers the extensions it implements. + `agents/letta-code/` runs [Letta Code](https://github.com/letta-ai/letta-code) behind the protocol's A2A agent framework: each turn is one `letta --backend local -p --output-format stream-json` run, resumed in the context's conversation, with a separate local agent and memory per context. Name it as `letta-code`, its alias, or by its id, @@ -160,8 +174,8 @@ it as `hermes`, its alias, or by its id, `@local/agentenv-framework/agents/herme an OpenAI-compatible one, `/v1/chat/completions`, and takes its model from the prompt, else `anthropic/claude-sonnet-4-6`. Its folder's `README.md` covers the extensions it implements. -A release publishes Codex's, Gemini's, Hermes', OpenCode's, pi's, OpenHands' and Pydantic AI's images too, at -`ghcr.io/scaleapi/agentenv-codex:src-`, `ghcr.io/scaleapi/agentenv-gemini:src-`, +A release publishes Antigravity's, Codex's, Gemini's, Hermes', OpenCode's, pi's, OpenHands' and Pydantic AI's images +too, at `ghcr.io/scaleapi/agentenv-antigravity:src-`, `ghcr.io/scaleapi/agentenv-codex:src-`, `ghcr.io/scaleapi/agentenv-gemini:src-`, `ghcr.io/scaleapi/agentenv-hermes:src-`, `ghcr.io/scaleapi/agentenv-opencode:src-`, `ghcr.io/scaleapi/agentenv-pi:src-`, `ghcr.io/scaleapi/agentenv-openhands:src-` and `ghcr.io/scaleapi/agentenv-pydantic-ai:src-`, each built again only when its folder changes, and a run deploys them as it does Claude Code's: it pulls the image @@ -179,4 +193,4 @@ others'. It has no alias and no smoke task: with nobody driving it, a prompt onl `agent-env run agents` runs every agent's smoke task, pulling or building each image; `--task claude-code-smoke` runs Claude Code's alone, `--task codex-smoke` Codex's, `--task gemini-smoke` Gemini's, `--task hermes-smoke` Hermes', `--task opencode-smoke` OpenCode's, -`--task pi-smoke` pi's, `--task openhands-smoke` OpenHands', `--task pydantic-ai-smoke` Pydantic AI's. +`--task antigravity-smoke` Antigravity's, `--task pi-smoke` pi's, `--task openhands-smoke` OpenHands', `--task pydantic-ai-smoke` Pydantic AI's. diff --git a/src/agent_env/agents/agents/antigravity/Dockerfile b/src/agent_env/agents/agents/antigravity/Dockerfile new file mode 100644 index 000000000..cd390704b --- /dev/null +++ b/src/agent_env/agents/agents/antigravity/Dockerfile @@ -0,0 +1,59 @@ +# 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 +# poppler-utils renders a PDF attachment to the page images the model sees; git and curl are for the model's commands. +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl git poppler-utils \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /opt/agent +# The Antigravity SDK, whose wheel for this CPU holds its harness, a static Go binary, with the agent's other +# requirements. +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt +# install.sh and run.sh are install/v1's: in the image, so they stay in its build context. +COPY a2a_server.py antigravity_bridge.py antigravity_date.py antigravity_kit.py entrypoint.sh install.sh run.sh ./ +# Every clocked agent's egress rule, which the bridge imports, the clock page's format it reads, and the model relay +# that counts the turn's model calls (shared_sources.toml). +COPY agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py ./ +# The agent's workspace, /app, and its home under /data, fixed so neither follows the uid. +RUN useradd --create-home --uid 10001 agent && mkdir -p /app /data \ + && chown agent:agent /app /data && chmod 0755 entrypoint.sh +# 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 +ENV A2A_PORT=8000 PYTHONPATH=/opt/agent HOME=/data +WORKDIR /app +EXPOSE 8000 +# Starts as root, which start-agent needs for the clock; the A2A server and the harness 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/antigravity/README.md b/src/agent_env/agents/agents/antigravity/README.md new file mode 100644 index 000000000..9614fe806 --- /dev/null +++ b/src/agent_env/agents/agents/antigravity/README.md @@ -0,0 +1,65 @@ +# Antigravity A2A agent + +Google's [Antigravity SDK](https://pypi.org/project/google-antigravity/) (`google-antigravity`) wrapped with the +`agentenv_protocol.a2a_agent` framework, shipped in the `agents` bundle as +`@local/agentenv-framework/agents/antigravity`. This directory is the whole build context: the protocol package and the +SDK, whose wheel holds its harness, come from PyPI (`requirements.txt`). + +Each task is one `Agent.chat()` of the SDK in the A2A server's process, in `/app`. The SDK runs its own harness, +`localharness`, a static Go binary that runs the tools and calls the model. A context's first task starts an SDK +conversation, and each later task resumes it by its id; the SDK keeps each conversation in a SQLite store under +`$ANTIGRAVITY_HOME/conversations/`. Text parts are the prompt, and file parts are written under `/app/inputs//` +and named in it; an image goes to the model inline too, and a PDF as its pages' PNGs, rendered with `pdftoppm`. Turns of +different contexts run at once, a context's turns one at a time. + +The SDK's `LocalOpenAIAgentConfig` takes a chat-completions `base_url` and nothing else for the endpoint, and its +harness sends no key, so each task's harness calls a model relay of the task's own on loopback (`model_relay.py`, +shared with other agents), which forwards each call to `$LITELLM_BASE_URL/v1/chat/completions` with: + +- the endpoint's key from `LITELLM_API_KEY`, `[model.headers]` (`LITELLM_EXTRA_HEADERS`) and the run's `project_id` and + `task_id` as `x-litellm-customer-id` and `x-litellm-tags`. The run's tags join an `x-litellm-tags` that + `[model.headers]` names; +- the task's `effort` as `reasoning_effort` (`xhigh` and `max` as `high`) and its images, which the SDK has no setting + for; +- the env's time in the harness's "The current local time is" line while the agent follows an armed clock (below). + +The relay counts each call from the answer's usage, every subagent's included, so the task's `Usage` is their sum; the +SDK reports none. A call answered without usage is counted in `unreported_calls`. + +The rest of each task's config: + +- the task's `system_prompt`, as the SDK's `system_instructions`, a section after the harness's own; +- the model: the task's, else `ANTIGRAVITY_MODEL`, else `anthropic/claude-sonnet-5-5`; +- every registered MCP server, the task's `peer_agents` tools included, as a streamable-HTTP server. Its + `AgentEnv-Role` header is the role its registration names, unless the task has a role of its own; +- every tool call allowed (`policy.allow_all()`), autonomous behaviour, `ask_question` and `generate_image` off, and the + SDK's own retries of a model call the endpoint answers with a transient error: six, from 5 s, doubling. + +| Extension | Implementation | +|---|---| +| `agent-config/v1` | `AntigravityConfig`: `model`, `effort`, `system_prompt`, `project_id`, `task_id`, `timeout_seconds` (1800 by default; past it the task fails with `timeout`), `max_turns` (the model calls a task may make, the SDK's `max_model_calls`; a task stopped at it fails with `max_turns_exceeded`), `builtin_tools` (below) | +| `mcp-config/v1` | SDK default; each server passed to the task's harness. One that fails to start fails the task with `mcp_load_failed`, an infra error | +| `skill-config/v1` | inline and bundle skills installed as `$ANTIGRAVITY_HOME/skills//`, the harness's skills path; an inline `SKILL.md` without frontmatter gets one from the skill's name and description, since the SDK lists a skill by its frontmatter alone | +| `trajectory/v1` | the SDK's streamed steps, a step's text and thought each as one record, and each tool call's result from the SDK's hooks after it, live while the task runs (format `antigravity-sdk/1`) | +| `snapshot/v1` | `save` archives the context's conversation store with the env times its turns were given, and `/app`, once no task runs; `load` restores the store under its own id, bound to the target context, and replaces `/app`'s contents. Where `tar` is GNU tar, the changelog too: an incremental archive of its roots after each task, uploaded through the namespace grant, and applied in order; an increment is a whole task's changes, since the harness has no hook this agent can hold a task at | +| `peer-agents/v1` | SDK default: the harness reaches the task's other agents through the SDK's `peer_agents` MCP tools | +| `triggers/v1` | SDK default | +| `attribution-probe/v1` | the `project_id` and `task_id` the last task sent | +| `install/v1` | `install.sh`, into a task container (as root, working in `/app`) or onto a `vm` sandbox's Linux host: uv checked against its checksum and the agent's requirements in a Python of its own, which the target's own Python is never replaced by. The SDK's wheels need glibc on x86_64 or aarch64 | + +The image is `python:3.11-slim` with `pdftoppm`, git, the SDK and the agent, running as the `agent` user, its `HOME` +`/data`. + +**The env's clock.** The image follows the env's clock as the other clocked agents do (the agents' README). The harness +is a static binary, which agent-env's libfaketime can't reach, so it keeps real time and its conversation store stays in +order at any env date, while the commands it runs read the env's time and go out through the egress proxy. The model +sees the time only in the line the harness opens each user message with, "The current local time is: .": +while the clock is armed, the relay puts the env's time there, read from `date`, and records it beside the +conversations, so a resumed conversation's earlier turns keep the time each was given (`antigravity_date.py`). A call +whose time the relay can't read is refused, so the task fails rather than tell the model the machine's time. + +A `deploy_agent` `builtin_tools` selection picks the SDK's own tools: `{"disable": "*"}` and `{"only": [...]}` turn off +every tool but those named, a list to turn off turns off those alone; the tools of the MCP servers agent-env gives the +agent stay in every case, `finish`, which ends a task, stays on, and `ask_question` and `generate_image` stay off. The +names are `AntigravityTool`'s in `antigravity_bridge.py`, the SDK's own: `search_web` and `read_url_content` are its +web tools. A test fails when `requirements.txt`'s SDK pin moves, until `SDK_VERSION` moves with it. diff --git a/src/agent_env/agents/agents/antigravity/a2a_server.py b/src/agent_env/agents/agents/antigravity/a2a_server.py new file mode 100644 index 000000000..9d8a4df99 --- /dev/null +++ b/src/agent_env/agents/agents/antigravity/a2a_server.py @@ -0,0 +1,684 @@ +"""A2A agent running Google's Antigravity SDK. + +Built on agentenv-protocol's `AgentEnvAgent`: the framework serves the Agent Card, the A2A task lifecycle and the +SDK-owned extensions (agent-config, mcp-config, skill listing, task trajectories, peer agents, triggers). Each turn is +one `Agent.chat()` of the Antigravity SDK in this process (`antigravity_bridge`), whose streamed chunks are appended to +the framework's trajectory log as they come. A context's first turn starts an SDK conversation, which later turns +resume by its id. +""" +from __future__ import annotations + +import asyncio +import base64 +import binascii +import json +import logging +import os +import re +import shutil +import subprocess +import tarfile +import tempfile +import uuid +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Any +from urllib.parse import urlparse +from weakref import WeakValueDictionary + +import httpx +from a2a.types import AgentSkill +from agentenv_protocol.a2a_agent import ( + ATTRIBUTION_PROBE_V1, + INSTALL_V1, + MCP_CONFIG_V1, + PEER_AGENTS_V1, + SKILL_CONFIG_V1, + SNAPSHOT_V1, + TRAJECTORY_V1, + TRIGGERS_V1, + AgentConfig, + AgentEnvAgent, + AgentIdentity, + AttributionProbeResponse, + BuiltinTools, + BundleSkillRequest, + DataPart, + FilePart, + InlineSkillRequest, + NamespaceChangelogEnableRequest, + NamespaceUploader, + ObjectChangelogApplyRequest, + ObjectSnapshotLoadRequest, + ObjectSnapshotSaveRequest, + SkillAddResponse, + TaskRequest, + TaskResult, + TextPart, + Usage, + a2a_agent, + download, + enable, + extension, + upload, +) +from pydantic import Field +from starlette.applications import Starlette +from starlette.exceptions import HTTPException + +from antigravity_bridge import ( + ENV_TIMES, + ERROR_MESSAGE_LIMIT, + SAVE_DIR, + SKILLS_DIR, + AntigravityTool, + get_last_attribution_snapshot, + run_antigravity, +) +from antigravity_kit import DurableSessionRefs, install_skill, json_error_bodies + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +WORKSPACE_DIR = Path(os.environ.get("ANTIGRAVITY_WORKSPACE_DIR", "/app")) +INPUTS_DIR = WORKSPACE_DIR / "inputs" +# One per port, since agents installed on one host listen on their own. +_CHANGELOG_DIR = Path(tempfile.gettempdir()) / f"antigravity-changelog-{os.environ.get('A2A_PORT') or 'default'}" +_CHANGELOG_SNAR = _CHANGELOG_DIR / "state.snar" +# Each increment's record of the roots it saw removed, in a directory of its own beside the changelog, which captures +# exclude, and outside its roots: tar dumps a directory it hasn't seen whole, so the record goes in however soon after +# the last capture it is written. +_META_DIR_SUFFIX = ".changelog-meta" +_META_NAME = "antigravity-changelog-meta.json" +_CHANGELOG_META_DIR = _CHANGELOG_DIR.parent / f"{_CHANGELOG_DIR.name}{_META_DIR_SUFFIX}" +_META_MEMBER = re.compile(rf"(?:^|/)[^/]+{re.escape(_META_DIR_SUFFIX)}/\d+/{re.escape(_META_NAME)}\Z") +# Never removed on replay, whatever an increment's record says. +_SYSTEM_DIRS = frozenset({"/", "/bin", "/boot", "/dev", "/etc", "/home", "/lib", "/lib32", "/lib64", "/libx32", + "/media", "/mnt", "/opt", "/proc", "/root", "/run", "/sbin", "/srv", "/sys", "/tmp", "/usr", + "/var"}) +_TAR_VERSION_TIMEOUT_S = 10 +_FILE_DOWNLOAD_TIMEOUT_S = 60 +_PDF_RENDER_TIMEOUT_S = 60 +_PDF_RENDER_DPI = 150 +_SAFE_NAME_RE = re.compile(r"[^A-Za-z0-9._-]") +# The versioned format of the SDK chunks and hook results this agent appends to its trajectory. +TRAJECTORY_FORMAT = "antigravity-sdk/1" +_MANIFEST = "manifest.json" +_ENV_TIMES_MEMBER = "env-times.json" + + +class AntigravityConfig(AgentConfig): + model: str | None = None + effort: str | None = None + system_prompt: str | None = None + project_id: str | None = None + task_id: str | None = None + timeout_seconds: int = Field(default=1800, gt=0) + # The model calls one turn may make; the SDK stops the turn at the cap. + max_turns: int | None = Field(default=None, gt=0) + # Which of the SDK's own tools it may use. With any selection, the tools of the MCP servers agent-env gives it stay. + builtin_tools: BuiltinTools[AntigravityTool] | None = None + + +class FilePartMaterializeError(Exception): + """A supplied file cannot be passed to the agent.""" + + +def _safe_name(candidate: str | None, fallback_ext: str = "") -> str: + if candidate: + candidate = _SAFE_NAME_RE.sub("_", Path(candidate).name) + return candidate or f"{uuid.uuid4().hex}{fallback_ext}" + + +def _download_uri_to(uri: str, target: Path) -> None: + parsed = urlparse(uri) + if parsed.scheme not in ("http", "https"): + raise FilePartMaterializeError(f"unsupported file URI scheme {parsed.scheme!r}") + try: + with httpx.Client(timeout=_FILE_DOWNLOAD_TIMEOUT_S, follow_redirects=True) as client: + response = client.get(uri) + response.raise_for_status() + target.write_bytes(response.content) + except httpx.HTTPError as exc: + raise FilePartMaterializeError("HTTP file download failed") from exc + + +def _materialize_and_render(part: FilePart, task_id: str) -> list[str]: + """The files a part gives the turn, under the workspace's inputs: the file, or a PDF's pages as images, which the + model sees inline where it can't read the PDF itself.""" + directory = INPUTS_DIR / task_id + directory.mkdir(parents=True, exist_ok=True) + name = _safe_name(part.name) + target = directory / name + if target.exists(): + target = directory / f"{uuid.uuid4().hex[:8]}-{name}" + if part.bytes is not None: + try: + target.write_bytes(base64.b64decode(part.bytes, validate=True)) + except (binascii.Error, ValueError, OSError) as exc: + raise FilePartMaterializeError(f"invalid file attachment {name!r}") from exc + else: + _download_uri_to(part.uri, target) + if (part.mime_type or "").lower() != "application/pdf" and target.suffix.lower() != ".pdf": + return [str(target)] + prefix = str(target.with_suffix("")) + "_page" + try: + subprocess.run(["pdftoppm", "-png", "-r", str(_PDF_RENDER_DPI), str(target), prefix], + check=True, capture_output=True, timeout=_PDF_RENDER_TIMEOUT_S) + except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired): + logger.warning("PDF rendering failed for %s; passing the PDF directly", target) + return [str(target)] + pages = sorted(directory.glob(f"{Path(prefix).name}*.png")) + return [str(target), *(str(page) for page in pages)] + + +class _WorkspaceBarrier: + """Turns share the workspace and snapshots take it alone, so a snapshot's conversation and files come from a point + no turn is writing at, while turns of different contexts run at once. A waiting snapshot holds new turns back, so + it is never starved.""" + + def __init__(self) -> None: + self._condition = asyncio.Condition() + self._readers = 0 + self._writer = False + self._waiting_writers = 0 + + @asynccontextmanager + async def shared(self): + async with self._condition: + await self._condition.wait_for(lambda: not self._writer and self._waiting_writers == 0) + self._readers += 1 + try: + yield + finally: + async with self._condition: + self._readers -= 1 + if self._readers == 0: + self._condition.notify_all() + + @asynccontextmanager + async def exclusive(self): + async with self._condition: + self._waiting_writers += 1 + try: + await self._condition.wait_for(lambda: not self._writer and self._readers == 0) + self._writer = True + finally: + self._waiting_writers -= 1 + if not self._writer: + self._condition.notify_all() + try: + yield + finally: + async with self._condition: + self._writer = False + self._condition.notify_all() + + +# The turns running now, cancelled as the server stops: each one's SDK agent then ends its harness, which would +# otherwise go on in the workspace after it. +_RUNNING: set[asyncio.Task] = set() + + +@asynccontextmanager +async def lifespan(app: Starlette): + try: + yield + finally: + running = [task for task in _RUNNING if not task.done()] + for task in running: + task.cancel() + if running: + await asyncio.gather(*running, return_exceptions=True) + logger.info(f"Cancelled {len(running)} Antigravity turn(s) still running as the agent shut down") + + +# install.sh, from the build context install_agent unpacks, brings uv and a Python of the agent's own with the SDK; +# the endpoint reaches it as environment, never as arguments. +_UNPACK = "mkdir -p {work_dir}/agent && tar -xzf {agent_ctx_tar} -C {work_dir}/agent" +_ENDPOINT = ("LITELLM_API_KEY={litellm_api_key} LITELLM_BASE_URL={litellm_base_url} " + "LITELLM_EXTRA_HEADERS={litellm_extra_headers} AGENT_TRUST_ENV={trust_env} ") +_ENDPOINT_PARAMS = ["litellm_api_key", "litellm_base_url", "litellm_extra_headers", "trust_env"] +_INSTALL_COMMANDS = [_UNPACK, _ENDPOINT + "bash {work_dir}/agent/install.sh container {container} {a2a_port}"] +_HOST_WORKDIR = "/app" +_INSTALL_COMMANDS_HOST = [_UNPACK, _ENDPOINT + f"bash {{work_dir}}/agent/install.sh host {{agent_name}} {{a2a_port}} {_HOST_WORKDIR}"] + + +@a2a_agent( + identity=AgentIdentity( + name="Antigravity", + description="A2A-compliant agent running Google's Antigravity SDK.", + version="1.0.0", + input_modes=("text", "image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf"), + output_modes=("text",), + skills=(AgentSkill( + id="antigravity", name="antigravity", + description="Runs Google's Antigravity agent with its own tools (shell, files, subagents).", + tags=["coding", "agent"], + ),), + ), + config=AntigravityConfig, + extensions=( + MCP_CONFIG_V1, + enable(TRAJECTORY_V1, live=True, native=TRAJECTORY_FORMAT), + enable(ATTRIBUTION_PROBE_V1), + enable( + INSTALL_V1, + install_commands=_INSTALL_COMMANDS, + # Port the agent's A2A server listens on inside the container. + a2a_port=8000, + # Every placeholder referenced in install_commands must be in this list. + optional_params=["control_token"], + required_params=["container", "work_dir", "agent_ctx_tar", "a2a_port", *_ENDPOINT_PARAMS], + install_commands_host=_INSTALL_COMMANDS_HOST, + optional_params_host=["control_token"], + required_params_host=["work_dir", "agent_ctx_tar", "a2a_port", "agent_name", *_ENDPOINT_PARAMS], + workdir_host=_HOST_WORKDIR, + user_host="root", + ), + # SDK default: the agent reaches the task's other agents through the SDK's peer_agents MCP tools. + PEER_AGENTS_V1, + enable(TRIGGERS_V1, description=( + "Register a typed trigger script and decide the stakeholder reply per turn " + "(step / env_trigger / conversational / all / any conditions -> say / end actions).")), + ), + lifespan=lifespan, + workspace=str(WORKSPACE_DIR), +) +class AntigravityAgent(DurableSessionRefs, AgentEnvAgent): + """Bridges A2A tasks onto the Antigravity SDK.""" + + def __init__(self) -> None: + self._turn_locks: WeakValueDictionary[str, asyncio.Lock] = WeakValueDictionary() + self._changelog: dict[str, Any] | None = None + self._changelog_lock = asyncio.Lock() + self._workspace = _WorkspaceBarrier() + + def _turn_lock(self, context_id: str) -> asyncio.Lock: + return self._turn_locks.setdefault(context_id, asyncio.Lock()) + + async def run(self, request: TaskRequest[AntigravityConfig]) -> TaskResult: + request.trajectory.set_format(TRAJECTORY_FORMAT) + prompt = "\n".join(part.text for part in request.parts if isinstance(part, TextPart) and part.text) + context_id = request.context_id + task = asyncio.current_task() + if task is not None: + _RUNNING.add(task) + try: + async with self._workspace.shared(), self._turn_lock(context_id): + # Read under the lock rather than from the request: a snapshot load that held it may have just bound + # this context to a restored conversation. + session_id = self.session_ref_for_context(context_id) + try: + attachments = [] + for part in request.parts: + if isinstance(part, FilePart): + attachments.extend(await asyncio.to_thread(_materialize_and_render, part, request.task_id)) + except FilePartMaterializeError as exc: + return TaskResult.failure("filepart_error", str(exc), error_type="infra_error") + try: + result = await run_antigravity( + prompt, + model=request.config.model, + project_id=request.config.project_id, + task_id=request.config.task_id, + effort=request.config.effort, + attachment_paths=attachments, + session_id=session_id, + mcp_servers=dict(request.mcp_servers), + system_prompt=request.config.system_prompt, + timeout_s=request.config.timeout_seconds, + role=request.config.role, + builtin_tools=request.config.builtin_tools, + max_turns=request.config.max_turns, + workspace=str(WORKSPACE_DIR), + event_callback=request.trajectory.append, + ) + except Exception: + logger.exception("Antigravity invocation failed") + return TaskResult.failure("antigravity_invocation_error", "Antigravity invocation failed", + error_type="infra_error") + if result.session_id: + self.set_session_ref_for_context(context_id, result.session_id) + await self._capture_changelog() + finally: + if task is not None: + _RUNNING.discard(task) + + usage = result.usage or Usage(tool_call_count=result.tool_call_count) + parts = [TextPart(text=result.response or result.error or "")] + if result.error: + message = result.error[:ERROR_MESSAGE_LIMIT] + parts.append(DataPart(data={"error_type": "antigravity_error", "error_code": result.error_code, + "error_message": message})) + return ( + TaskResult.builder() + .failed(result.error_code or "antigravity_error", message, + error_type="infra_error" if result.infra else "agent_error") + .parts(parts) + .session_ref(result.session_id) + .usage(usage) + .build() + ) + return TaskResult.builder().succeeded().parts(parts).session_ref(result.session_id).usage(usage).build() + + @extension(SKILL_CONFIG_V1.add.inline) + async def add_inline_skill(self, request: InlineSkillRequest) -> SkillAddResponse: + return await install_skill(request, SKILLS_DIR) + + @extension(SKILL_CONFIG_V1.add.bundle) + async def add_bundle_skill(self, request: BundleSkillRequest) -> SkillAddResponse: + return await install_skill(request, SKILLS_DIR) + + @extension(ATTRIBUTION_PROBE_V1.probe) + async def probe_attribution(self) -> AttributionProbeResponse: + """The LiteLLM attribution the last turn's model calls carried.""" + snapshot = get_last_attribution_snapshot() + return AttributionProbeResponse( + last_seen_attribution={ + key: value for key, value in snapshot.items() if key != "last_seen_at_utc" and isinstance(value, str) + }, + last_seen_at_utc=snapshot.get("last_seen_at_utc"), + ) + + @extension(SNAPSHOT_V1.save) + async def save_snapshot(self, request: ObjectSnapshotSaveRequest) -> dict[str, Any]: + """The context's conversation, its SDK store whole with the env times its turns were given, and the + workspace.""" + with tempfile.TemporaryDirectory(prefix="antigravity-snapshot-") as directory: + conversation = Path(directory) / "conversation.tgz" + workspace = Path(directory) / "workspace.tgz" + async with self._workspace.exclusive(), self._turn_lock(request.context_id): + conversation_id = self.session_ref_for_context(request.context_id) + if not conversation_id or not (SAVE_DIR / f"{conversation_id}.db").is_file(): + raise HTTPException(status_code=404, detail="No active conversation for context_id") + await asyncio.to_thread(_archive_conversation, conversation_id, conversation) + if request.objects.workspace is not None: + await asyncio.to_thread( + subprocess.run, + ["tar", *_backup_exclusions(), "-czf", str(workspace), "-C", str(WORKSPACE_DIR), "."], + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + ) + objects = {"trajectory": (await upload(request.objects.trajectory, conversation)).model_dump(mode="json")} + if request.objects.workspace is not None: + objects["workspace"] = (await upload(request.objects.workspace, workspace)).model_dump(mode="json") + return {"context_id": request.context_id, "objects": objects} + + @extension(SNAPSHOT_V1.load) + async def load_snapshot(self, request: ObjectSnapshotLoadRequest) -> dict[str, Any]: + """The conversation under its own id, which the SDK keys its store by, bound to the target context.""" + target_context_id = request.target_context_id or uuid.uuid4().hex + with tempfile.TemporaryDirectory(prefix="antigravity-restore-") as directory: + archive = Path(directory) / "conversation.tgz" + await download(request.objects.trajectory, archive) + staged_conversation = Path(directory) / "conversation" + staged_conversation.mkdir() + conversation_id = await asyncio.to_thread(_unpack_conversation, archive, staged_conversation) + staged = None + if request.objects.workspace is not None: + workspace_archive = Path(directory) / "workspace.tgz" + staged = Path(directory) / "workspace" + staged.mkdir() + await download(request.objects.workspace, workspace_archive) + await asyncio.to_thread( + subprocess.run, ["tar", "-xzf", str(workspace_archive), "-C", str(staged)], + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + ) + async with self._workspace.exclusive(), self._turn_lock(target_context_id): + await asyncio.to_thread(_restore_conversation, staged_conversation, conversation_id) + if staged is not None: + await asyncio.to_thread(_replace_workspace, staged) + self.set_session_ref_for_context(target_context_id, conversation_id) + return {"context_id": target_context_id} + + async def _capture_changelog(self) -> None: + """One incremental tar of the changelog's roots, uploaded after each turn, with the roots removed since the + last; the baseline advances only once the upload succeeds, so a failed capture's changes, and its removals, go + with the next.""" + async with self._changelog_lock: + config = self._changelog + if config is None: + return + roots = [root for root in config["roots"] if Path(root).exists()] + removed = [root for root in config["present"] if root not in roots] + if not roots and not removed: + return + sequence = config["sequence"] + _CHANGELOG_DIR.mkdir(parents=True, exist_ok=True) + archive = _CHANGELOG_DIR / f"{sequence:06d}.tgz" + pending_snar = _CHANGELOG_DIR / "pending.snar" + record = _CHANGELOG_META_DIR / f"{sequence:06d}" + try: + await asyncio.to_thread(shutil.rmtree, record, True) + record.mkdir(parents=True) + (record / _META_NAME).write_text(json.dumps({"sequence": sequence, "removed": removed})) + await asyncio.to_thread(shutil.copyfile, _CHANGELOG_SNAR, pending_snar) + await asyncio.to_thread( + subprocess.run, + ["tar", "--ignore-failed-read", f"--listed-incremental={pending_snar}", + *_changelog_backup_exclusions(), f"--exclude={_CHANGELOG_DIR}", "-czf", str(archive), *roots, + str(record)], + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=_real_time_env(), + ) + await config["uploader"].upload(f"{sequence:06d}.tgz", archive) + pending_snar.replace(_CHANGELOG_SNAR) + config["present"] = roots + config["sequence"] += 1 + except Exception: + logger.exception("Antigravity changelog capture failed") + finally: + archive.unlink(missing_ok=True) + pending_snar.unlink(missing_ok=True) + await asyncio.to_thread(shutil.rmtree, record, True) + + +class AntigravityChangelogAgent(AntigravityAgent): + """With snapshot/v1's changelog, which needs GNU tar's incremental archives. The SDK runs its tools inside its + harness with no hook between them this agent can hold a turn at, so an increment is a completed turn's changes; + conversation state lives outside the captured roots, so apply restores files only.""" + + @extension(SNAPSHOT_V1.changelog.enable) + async def enable_changelog(self, request: NamespaceChangelogEnableRequest) -> dict[str, Any]: + roots = request.roots or [str(WORKSPACE_DIR)] + async with self._workspace.exclusive(), self._changelog_lock: + await asyncio.to_thread(_baseline_changelog, roots) + present = [root for root in roots if Path(root).exists()] + self._changelog = {"roots": roots, "sequence": 0, "present": present, + "uploader": NamespaceUploader(request.write_namespace)} + return {"roots": roots} + + @extension(SNAPSHOT_V1.changelog.apply) + async def apply_changelog(self, request: ObjectChangelogApplyRequest) -> dict[str, Any]: + async with self._workspace.exclusive(): + with tempfile.TemporaryDirectory(prefix="antigravity-changelog-apply-") as directory: + for increment in request.increments: + archive = Path(directory) / f"{increment.sequence:06d}.tgz" + await download(increment.object, archive) + await asyncio.to_thread(_apply_increment, archive, increment.sequence) + return {"count": len(request.increments), "context_id": request.target_context_id} + + +def _conversation_files(conversation_id: str) -> list[Path]: + """The SDK's store for a conversation: its SQLite database and the journal files beside it.""" + return sorted(path for path in SAVE_DIR.glob(f"{conversation_id}.db*") if path.is_file()) + + +def _archive_conversation(conversation_id: str, archive: Path) -> None: + times = ENV_TIMES.all() + with tempfile.TemporaryDirectory(prefix="antigravity-conversation-") as directory: + (Path(directory) / _MANIFEST).write_text(json.dumps({"conversation_id": conversation_id})) + (Path(directory) / _ENV_TIMES_MEMBER).write_text(json.dumps(times)) + with tarfile.open(archive, "w:gz") as tar: + tar.add(Path(directory) / _MANIFEST, arcname=_MANIFEST) + tar.add(Path(directory) / _ENV_TIMES_MEMBER, arcname=_ENV_TIMES_MEMBER) + for path in _conversation_files(conversation_id): + tar.add(path, arcname=f"store/{path.name}") + + +def _unpack_conversation(archive: Path, staged: Path) -> str: + """Extract a snapshot's conversation into ``staged``, regular files only and none outside it; its conversation + id.""" + try: + with tarfile.open(archive, "r:gz") as tar: + tar.extractall(staged, filter="data") + except (tarfile.TarError, OSError) as exc: + raise HTTPException(status_code=400, detail="snapshot's conversation isn't an archive this agent reads") \ + from exc + try: + conversation_id = json.loads((staged / _MANIFEST).read_text())["conversation_id"] + except (OSError, ValueError, KeyError, TypeError) as exc: + raise HTTPException(status_code=400, detail="snapshot has no conversation manifest") from exc + if not isinstance(conversation_id, str) or Path(conversation_id).name != conversation_id or not conversation_id: + raise HTTPException(status_code=400, detail="snapshot names no valid conversation id") + if not (staged / "store" / f"{conversation_id}.db").is_file(): + raise HTTPException(status_code=400, detail="snapshot has no store for its conversation") + return conversation_id + + +def _restore_conversation(staged: Path, conversation_id: str) -> None: + SAVE_DIR.mkdir(parents=True, exist_ok=True) + for path in _conversation_files(conversation_id): + path.unlink() + for path in sorted((staged / "store").iterdir()): + if path.is_file() and path.name.startswith(f"{conversation_id}.db"): + shutil.copyfile(path, SAVE_DIR / path.name) + try: + times = json.loads((staged / _ENV_TIMES_MEMBER).read_text()) + except (OSError, ValueError): + times = {} + if isinstance(times, dict): + ENV_TIMES.merge({str(real): str(env) for real, env in times.items()}) + + +def _backup_exclusions() -> list[str]: + if not WORKSPACE_DIR.exists(): + return [] + return [f"--exclude=./{path.name}" for path in WORKSPACE_DIR.iterdir() + if path.is_dir() and path.name.startswith(".antigravity-backup-") and (path / "saved").is_dir()] + + +def _changelog_backup_exclusions() -> list[str]: + root = WORKSPACE_DIR.relative_to("/") + exclusions = _backup_exclusions() + return exclusions + [f"--exclude={root / option.removeprefix('--exclude=./')}" for option in exclusions] + + +def _replace_workspace(staged: Path) -> None: + WORKSPACE_DIR.mkdir(parents=True, exist_ok=True) + backup = Path(tempfile.mkdtemp(prefix=".antigravity-backup-", dir=WORKSPACE_DIR)) + saved = backup / "saved" + saved.mkdir() + committed = False + try: + try: + for child in WORKSPACE_DIR.iterdir(): + if child != backup: + child.rename(saved / child.name) + except Exception: + for child in saved.iterdir(): + child.rename(WORKSPACE_DIR / child.name) + raise + try: + for child in staged.iterdir(): + shutil.move(str(child), str(WORKSPACE_DIR / child.name)) + committed = True + except Exception: + for child in WORKSPACE_DIR.iterdir(): + if child == backup: + continue + if child.is_dir() and not child.is_symlink(): + shutil.rmtree(child) + else: + child.unlink() + for child in saved.iterdir(): + child.rename(WORKSPACE_DIR / child.name) + raise + finally: + if committed: + try: + shutil.rmtree(backup) + except OSError: + logger.warning("Could not remove snapshot backup %s", backup, exc_info=True) + elif not any(saved.iterdir()): + saved.rmdir() + backup.rmdir() + + +def _apply_increment(archive: Path, sequence: int) -> None: + """Extract an increment over /, all but its record, then remove the roots its record names.""" + listing = subprocess.run(["tar", "--incremental", "-tzf", str(archive)], check=True, stdout=subprocess.PIPE, + stderr=subprocess.PIPE).stdout.decode(errors="replace").splitlines() + records = [member for member in listing if _META_MEMBER.search(member)] + excluded = {member.rsplit("/", 1)[0] for member in records} + subprocess.run( + ["tar", "--incremental", "--no-wildcards", *(f"--exclude={member}" for member in sorted(excluded)), + "-xzf", str(archive), "-C", "/"], + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + ) + for member in records: + record = subprocess.run(["tar", "-xzOf", str(archive), member], check=True, stdout=subprocess.PIPE, + stderr=subprocess.PIPE).stdout + try: + removed = json.loads(record).get("removed") + except (ValueError, AttributeError): + logger.warning(f"changelog increment {sequence:06d}: unreadable record {member}") + continue + for path in removed if isinstance(removed, list) else []: + if not _removable(path): + logger.warning(f"changelog increment {sequence:06d}: not removing {path!r}") + continue + if os.path.isdir(path) and not os.path.islink(path): + shutil.rmtree(path) + else: + os.unlink(path) + logger.info(f"changelog increment {sequence:06d}: removed root {path}") + + +def _removable(path: object) -> bool: + """Whether a removed root a record names may be removed on replay: an absolute, normalized path that exists and + isn't / or a top-level system directory.""" + return (isinstance(path, str) and os.path.isabs(path) and os.path.normpath(path) == path + and path not in _SYSTEM_DIRS and os.path.lexists(path)) + + +def _baseline_changelog(roots: list[str]) -> None: + _CHANGELOG_DIR.mkdir(parents=True, exist_ok=True) + _CHANGELOG_SNAR.unlink(missing_ok=True) + present = [root for root in roots if Path(root).exists()] + subprocess.run( + ["tar", "--ignore-failed-read", f"--listed-incremental={_CHANGELOG_SNAR}", *_changelog_backup_exclusions(), + "-cf", "/dev/null", *present], + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=_real_time_env(), + ) + + +def _real_time_env() -> dict[str, str]: + """This server's environment for the changelog's tar, which keeps the time it starts at as the next capture's + baseline and archives only the files changed since, by their real mtimes, so it runs on real time: the server + does, but libfaketime took the marker out of the server's environment, so what it starts doesn't.""" + return {**os.environ, "AGENTENV_REAL_TIME": "1"} + + +def gnu_tar() -> bool: + """Whether this host's tar is GNU tar, which the changelog's incremental archives need.""" + try: + version = subprocess.run(["tar", "--version"], capture_output=True, text=True, + timeout=_TAR_VERSION_TIMEOUT_S).stdout + except (OSError, subprocess.SubprocessError): + return False + return "GNU tar" in version + + +def agent_for_this_host() -> AntigravityAgent: + """The agent, with the changelog where this host's tar can make its archives.""" + return AntigravityChangelogAgent() if gnu_tar() else AntigravityAgent() + + +def build_app(agent: AntigravityAgent) -> Starlette: + """The agent's Starlette app, answering errors with FastAPI's `{"detail": ...}` bodies.""" + return json_error_bodies(agent.create_app()) + + +app = build_app(agent_for_this_host()) +# agent-env's install/v1 deploys find the install parameters by importing this name from the image. +AGENT_CARD = app.state.agentenv_a2a.card diff --git a/src/agent_env/agents/agents/antigravity/antigravity_bridge.py b/src/agent_env/agents/agents/antigravity/antigravity_bridge.py new file mode 100644 index 000000000..f059400e0 --- /dev/null +++ b/src/agent_env/agents/agents/antigravity/antigravity_bridge.py @@ -0,0 +1,441 @@ +"""One Antigravity turn: an ``Agent`` of the Antigravity SDK (``google-antigravity``), run in this process, its harness +pointed at a model relay of the turn's own. + +The SDK's ``LocalOpenAIAgentConfig`` takes a chat-completions ``base_url`` and no key or headers, and its harness, +the Go ``localharness``, sends none, so the relay adds the endpoint's key, ``[model.headers]`` and the run's +attribution to every call. It also counts each call's usage, which the SDK never reports, and, while the agent +follows an armed clock, puts the env's time in the line the harness gives the model (``antigravity_date``). The +``agy`` CLI can't be used instead: it authenticates only by interactive OAuth and has no endpoint override. + +The harness is a static binary, which agent-env's libfaketime can't reach, so it keeps real time and its conversation +store stays in order at any env date, while the commands it starts read the env's time. They go out through the +egress proxy while the clock is armed, as every clocked agent's do (``agent_egress``). +""" +from __future__ import annotations + +import asyncio +import base64 +import json +import logging +import mimetypes +import os +import threading +from collections.abc import Awaitable, Callable, Mapping +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Literal +from urllib.parse import urlsplit, urlunsplit + +import google.antigravity as ag +from google.antigravity import types as agt +from google.antigravity.hooks import hooks as ag_hooks +from google.antigravity.hooks import policy as ag_policy + +from agent_egress import clock_armed, egress_env +from agentenv_protocol.a2a_agent import BuiltinTools, Usage +from antigravity_date import EnvTimes, env_time_rewrite +from model_relay import Calls, model_relay + +logger = logging.getLogger(__name__) + +# The model a run uses when neither the task nor the agent-config names one, sent to the endpoint as named. +DEFAULT_MODEL = os.environ.get("ANTIGRAVITY_MODEL", "anthropic/claude-sonnet-5-5") +ERROR_MESSAGE_LIMIT = 4000 +ROLE_HEADER = "AgentEnv-Role" +# What agent-env gives an agent for [model.headers]: a JSON object of header names to values. +MODEL_HEADERS_ENV = "LITELLM_EXTRA_HEADERS" +_TAGS_HEADER = "x-litellm-tags" +# The SDK version AntigravityTool names the tools of; a test holds it to requirements.txt's pin. +SDK_VERSION = "0.1.24" + +HOME_DIR = Path(os.environ.get("ANTIGRAVITY_HOME") or Path.home() / ".antigravity") +# The SDK's conversations, one SQLite store per conversation id, and the env times their turns were given. +SAVE_DIR = HOME_DIR / "conversations" +SKILLS_DIR = HOME_DIR / "skills" +ENV_TIMES = EnvTimes(SAVE_DIR / "env-times.json") + +# MCP calls into a large env can be slow; the SDK's own read timeout is shorter than a first tools/list there takes. +_MCP_TIMEOUT_S = 60.0 +_MCP_SSE_READ_TIMEOUT_S = 300.0 +# A model call the endpoint answers with a transient error is retried by the SDK itself: six times, from 5 s, doubling. +_API_RETRY = agt.ModelAPIRetryConfig(max_retries=6, initial_sleep_duration_ms=5000, exponential_multiplier=2.0) +# The reasoning efforts chat completions takes, and how agent-env's higher ones map onto them. +_EFFORTS = {"none": "none", "minimal": "minimal", "low": "low", "medium": "medium", "high": "high", + "xhigh": "high", "max": "high"} + +# The SDK's own tools, by the names a task selects them with. `ask_question` is off on every turn, so a headless run +# never waits for a human, and so is `generate_image`, which calls Google with an OAuth credential no run has. +# `finish` ends a turn, so it can't be turned off. +AntigravityTool = Literal["list_directory", "search_directory", "find_file", "view_file", "create_file", "edit_file", + "run_command", "invoke_subagent", "run_workflow", "search_web", "read_url_content", + "schedule"] +_ALWAYS_OFF = (agt.BuiltinTools.ASK_QUESTION, agt.BuiltinTools.GENERATE_IMAGE) +_ALWAYS_ON = (agt.BuiltinTools.FINISH,) + + +@dataclass +class AntigravityResult: + response: str = "" + session_id: str | None = None + tool_call_count: int = 0 + error: str | None = None + error_code: str | None = None + infra: bool = False + usage: Usage | None = None + + +def _api_root(url: str) -> str: + """``LITELLM_BASE_URL`` without a trailing ``/`` and one trailing ``/v1``, which the relay serves the SDK's + ``/v1/chat/completions`` from. Core's ``api_root``, copied since this image can't import core; a unit test + keeps the copies equal.""" + parts = urlsplit(url.strip()) + return urlunsplit(parts._replace(path=parts.path.rstrip("/").removesuffix("/v1").rstrip("/"))) + + +# The attribution the last turn sent, which /ext/attribution-probe reads back. +_last_attribution: dict[str, str | None] = {"project_id": None, "task_id": None, "last_seen_at_utc": None} +_attribution_lock = threading.Lock() + + +def _record_attribution(project_id: str | None, task_id: str | None) -> None: + if not project_id and not task_id: + return + with _attribution_lock: + _last_attribution.update(project_id=project_id or None, task_id=task_id or None, + last_seen_at_utc=datetime.now(timezone.utc).isoformat()) + + +def get_last_attribution_snapshot() -> dict[str, str | None]: + with _attribution_lock: + return dict(_last_attribution) + + +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] = {} + if project_id: + headers["x-litellm-customer-id"] = project_id + headers[_TAGS_HEADER] = ",".join([f"projectId:{project_id}", *([f"taskId:{task_id}"] if task_id else [])]) + elif task_id: + headers[_TAGS_HEADER] = f"taskId:{task_id}" + return headers + + +def model_headers(raw: str | None) -> dict[str, str]: + if not raw: + return {} + try: + headers = json.loads(raw) + except json.JSONDecodeError: + logger.warning(f"ignoring {MODEL_HEADERS_ENV}, which isn't JSON") + return {} + if not isinstance(headers, dict): + logger.warning(f"ignoring {MODEL_HEADERS_ENV}, which isn't a JSON object") + return {} + return {str(name): str(value) for name, value in headers.items()} + + +def endpoint_headers(environ: Mapping[str, str], attribution: Mapping[str, str]) -> dict[str, str]: + """What every model call the relay forwards carries, the harness sending none: the endpoint's key, then its + [model.headers], then the run's attribution, each replacing a header of the same name in any case, except that + the run's x-litellm-tags join the ones [model.headers] name.""" + configured = {name.lower(): value for name, value in model_headers(environ.get(MODEL_HEADERS_ENV)).items()} + if configured.get(_TAGS_HEADER) and _TAGS_HEADER in attribution: + tags = [tag for tag in configured[_TAGS_HEADER].split(",") if tag] + attribution = {**attribution, _TAGS_HEADER: ",".join(dict.fromkeys( + [*tags, *attribution[_TAGS_HEADER].split(",")]))} + key = environ.get("LITELLM_API_KEY") or "" + return {**({"authorization": f"Bearer {key}"} if key else {}), + **{name.lower(): value for layer in (configured, attribution) for name, value in layer.items()}} + + +def mcp_headers(headers: Mapping[str, str] | None, role: str | None) -> dict[str, str] | None: + """A server's registered headers; the run's role, when it has one, replaces a role header they name.""" + merged = dict(headers or {}) + if role: + merged = {name: value for name, value in merged.items() if name.lower() != ROLE_HEADER.lower()} + merged[ROLE_HEADER] = role + return merged or None + + +def capabilities(builtin_tools: BuiltinTools[AntigravityTool] | None) -> Any: + """The SDK's capabilities for a turn: autonomous, with `ask_question` and `generate_image` off on every turn, and + the task's selection of the rest; `finish` stays on whatever the selection.""" + always_off = list(_ALWAYS_OFF) + if builtin_tools is None: + return ag.CapabilitiesConfig(agent_behavior=agt.AgentBehavior.AUTONOMOUS, disabled_tools=always_off) + named = {tool.value: tool for tool in agt.BuiltinTools} + selectable = [named[name] for name in AntigravityTool.__args__] + if builtin_tools.only is not None: + enabled = [named[name] for name in builtin_tools.only] + list(_ALWAYS_ON) + return ag.CapabilitiesConfig(agent_behavior=agt.AgentBehavior.AUTONOMOUS, enabled_tools=enabled) + disabled = selectable if builtin_tools.disable == "*" else [named[name] for name in builtin_tools.disable] + return ag.CapabilitiesConfig(agent_behavior=agt.AgentBehavior.AUTONOMOUS, disabled_tools=always_off + disabled) + + +def conversation_store_exists(conversation_id: str | None) -> bool: + """Whether the SDK's store for ``conversation_id`` is on disk: resuming one that isn't fails the harness's start + rather than starting afresh.""" + return bool(conversation_id) and (SAVE_DIR / f"{conversation_id}.db").is_file() + + +def media_part(path: str) -> dict | None: + """An image the model sees inline, as a chat-completions image part with a data URL; None for any other file, + which the prompt names for the model's own tools to read. The SDK's chat-completions backend drops the media + ``chat()`` takes, so the relay adds them to the turn's request (``_with_media``).""" + mime = mimetypes.guess_type(path)[0] or "" + if not mime.startswith("image/"): + return None + data = base64.b64encode(Path(path).read_bytes()).decode() + return {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{data}"}} + + +def _with_media(request: dict, media: list[dict]) -> bool: + """Add ``media`` to the request's last user message, the turn's own, unless they're there already: the harness + sends the turn's history again on each call, from a store that never saw them. Whether it changed the request.""" + users = [message for message in request.get("messages") or [] if isinstance(message, dict) + and message.get("role") == "user"] + if not users or not media: + return False + message = users[-1] + content = message.get("content") + parts = [{"type": "text", "text": content}] if isinstance(content, str) else list(content or []) + present = {json.dumps(part, sort_keys=True) for part in parts if isinstance(part, dict)} + added = [part for part in media if json.dumps(part, sort_keys=True) not in present] + if not added: + return False + message["content"] = [*parts, *added] + return True + + +def turn_rewrite(effort: str | None, media: list[dict]) -> Callable[[bytes], Awaitable[bytes]]: + """The relay's rewrite for a turn's model calls: the env's time (``antigravity_date``), then the turn's reasoning + effort and its images, which the SDK takes no setting for.""" + date_rewrite = env_time_rewrite(ENV_TIMES) + reasoning = _EFFORTS.get(effort or "") + if effort and reasoning is None: + logger.warning(f"effort {effort!r} isn't one chat completions takes; the turn runs without one") + + async def rewrite(body: bytes) -> bytes: + body = await date_rewrite(body) + if reasoning is None and not media: + return body + try: + request = json.loads(body) + except ValueError: + return body + if not isinstance(request, dict): + return body + changed = _with_media(request, media) + if reasoning is not None and request.get("reasoning_effort") != reasoning: + request["reasoning_effort"] = reasoning + changed = True + return json.dumps(request, separators=(",", ":")).encode() if changed else body + + return rewrite + + +class TrajectoryRecorder: + """A turn's native trajectory, ``antigravity-sdk/1``, appended to ``emit`` as the SDK streams it: each step's + text and thought as one record, each tool call as the SDK streams it, and its result, which the SDK gives only to + its hooks, after it as ``{"kind": "tool_result", ..., "call_ref": }``. The hooks know a call + by the model's id and the stream by a step's, so a call the SDK lets its hooks decide binds to the next streamed + call of its name, which the SDK streams once the hook allows it; a result waits for its call to stream. The + harness's own tools, such as its skill lookup, stream and give their result to the hooks undecided: such a result + is tied to the earliest of those calls not yet tied to one.""" + + def __init__(self, emit: Callable[[dict], None]) -> None: + self._emit = emit + self._buffer: dict | None = None + self._deciding: list[tuple[str, str | None]] = [] + self._bound: dict[str, str | None] = {} + self._undecided: list[str | None] = [] + self._waiting: dict[str, dict] = {} + self.segments: list[list[tuple[Any, str]]] = [[]] + self.tool_calls = 0 + + def chunk(self, chunk: Any) -> None: + kind = type(chunk).__name__ + record = {"type": kind, **_plain(chunk)} + if kind in ("Text", "Thought"): + if kind == "Text": + self.segments[-1].append((record.get("step_index"), record.get("text") or "")) + buffered = self._buffer + same_step = buffered is not None and buffered.get("step_index") == record.get("step_index") + if same_step and buffered["type"] == kind: + buffered["text"] = (buffered.get("text") or "") + (record.get("text") or "") + return + self.flush() + self._buffer = record + return + self.flush() + self._emit(record) + if kind == "ToolCall": + self.tool_calls += 1 + self.segments.append([]) + streamed = record.get("id") + decided = next((index for index, (_, name) in enumerate(self._deciding) if name == record.get("name")), + None) + if decided is None: + self._undecided.append(streamed) + return + call_id, _ = self._deciding.pop(decided) + self._bound[call_id] = streamed + if (waiting := self._waiting.pop(call_id, None)) is not None: + self._emit({**waiting, "call_ref": streamed}) + + def hooked_call(self, call: Any) -> None: + if (call_id := getattr(call, "id", None)) is not None: + name = getattr(call, "name", None) + self._deciding.append((str(call_id), None if name is None else str(name))) + + def result(self, record: dict) -> None: + call_id = str(record.get("id")) + if call_id in self._bound: + call_ref = self._bound.pop(call_id) + elif any(deciding == call_id for deciding, _ in self._deciding): + self._waiting[call_id] = record + return + else: + call_ref = self._undecided.pop(0) if self._undecided else None + self.flush() + self._emit({**record, "call_ref": call_ref}) + + def flush(self) -> None: + if self._buffer is not None: + self._emit(self._buffer) + self._buffer = None + + def close(self) -> None: + self.flush() + for call_id in list(self._waiting): + self._emit({**self._waiting.pop(call_id), "call_ref": None}) + + def response(self) -> str: + """The turn's answer: its last text after a tool call, else the last text it has, a paragraph per step. The + model narrates between calls, and a verifier would read that as the outcome.""" + for segment in reversed(self.segments): + steps: dict[Any, str] = {} + for step, text in segment: + steps[step] = steps.get(step, "") + text + if answer := "\n\n".join(text.strip() for text in steps.values() if text.strip()): + return answer + return "" + + +def _plain(value: Any) -> dict: + """A chunk or hook payload as JSON: pydantic's dump, with what it can't serialize as text.""" + dump = getattr(value, "model_dump", None) + if callable(dump): + try: + return json.loads(json.dumps(dump(mode="json", exclude={"exception"}), default=str)) + except Exception: # noqa: BLE001 - a result's value may be anything + return {key: str(item) for key, item in dump(warnings=False).items() if key != "exception"} + return {"repr": str(value)[:2000]} + + +def _hooks(recorder: TrajectoryRecorder) -> list: + """The turn's hooks, which the SDK runs only when its config names them: every call allowed and recorded, and its + result, or its error, appended after it.""" + + @ag_hooks.pre_tool_call_decide + async def record_call(call: Any) -> Any: + recorder.hooked_call(call) + return agt.HookResult(allow=True) + + @ag_hooks.post_tool_call + async def record_result(result: Any) -> None: + recorder.result({"kind": "tool_result", **_plain(result)}) + + @ag_hooks.on_tool_error + async def record_error(error: Any) -> None: + recorder.result({"kind": "tool_result", "id": getattr(error, "call_id", None), + "name": str(getattr(error, "tool_name", None)), + "server_name": getattr(error, "server_name", None), "result": None, + "error": str(error)[:ERROR_MESSAGE_LIMIT]}) + + return [record_call, record_result, record_error] + + +async def run_antigravity(prompt: str, *, model: str | None, project_id: str | None = None, + task_id: str | None = None, effort: str | None = None, + attachment_paths: list[str] | None = None, **kwargs: Any) -> AntigravityResult: + """Run one turn, its model calls through a relay of the turn's own that adds the endpoint's key and the run's + attribution, counts every call the harness makes, its subagents' included, and tells the model the env's time on + an armed clock. The turn's usage is theirs, a call answered without usage counted as unreported.""" + _record_attribution(project_id, task_id) + media = [part for part in (media_part(path) for path in attachment_paths or []) if part is not None] + if attachment_paths: + prompt = f"{prompt}\n\nAttached files, also on disk for your tools:\n" + "\n".join( + f"- {path}" for path in attachment_paths) + calls = Calls() + headers = endpoint_headers(os.environ, attribution_headers(project_id, task_id)) + async with model_relay(_api_root(os.environ.get("LITELLM_BASE_URL") or ""), calls, headers=headers, + rewrite=turn_rewrite(effort, media)) as relay: + result = await _turn(prompt, base_url=f"{relay}/v1", model=model or DEFAULT_MODEL, **kwargs) + result.usage = calls.usage(result.tool_call_count, model or DEFAULT_MODEL) + return result + + +async def _turn(prompt: str, *, base_url: str, model: str, session_id: str | None, + mcp_servers: dict[str, dict] | None, system_prompt: str | None, timeout_s: int, role: str | None, + builtin_tools: BuiltinTools[AntigravityTool] | None, max_turns: int | None, workspace: str, + event_callback: Callable[[dict], None]) -> AntigravityResult: + recorder = TrajectoryRecorder(event_callback) + servers = mcp_servers or {} + urls = [os.environ.get("LITELLM_BASE_URL", ""), *(info["url"] for info in servers.values())] + SAVE_DIR.mkdir(parents=True, exist_ok=True) + config = dict( + base_url=base_url, model=model, save_dir=str(SAVE_DIR), workspaces=[workspace], + capabilities=capabilities(builtin_tools), policies=[ag_policy.allow_all()], hooks=_hooks(recorder), + retry_config=agt.RetryConfig(api_retry=_API_RETRY), + # Merged into the harness's environment, which the model's commands inherit: on an armed clock, the egress + # proxy, which keeps their TLS working at the env's date. + env=egress_env(os.environ, urls, armed=clock_armed()) or None, + mcp_servers=[agt.McpStreamableHttpServer(name=name, url=info["url"], + headers=mcp_headers(info.get("headers"), role), + timeout=_MCP_TIMEOUT_S, sse_read_timeout=_MCP_SSE_READ_TIMEOUT_S) + for name, info in servers.items()], + skills_paths=[str(SKILLS_DIR)] if SKILLS_DIR.is_dir() else [], + ) + if system_prompt: + # Appended to the harness's own instructions as a section, never in their place. + config["system_instructions"] = system_prompt + if max_turns: + config["budget_config"] = agt.BudgetConfig(max_model_calls=max_turns, scope=agt.BudgetScope.FORWARD_LOOKING) + if session_id: + if conversation_store_exists(session_id): + config["conversation_id"] = session_id + else: + logger.warning(f"conversation {session_id} has no store in {SAVE_DIR}: the turn starts a new one") + session_id = None + + async def converse() -> tuple[str | None, Any]: + async with ag.Agent(ag.LocalOpenAIAgentConfig(**config)) as agent: + response = await agent.chat(prompt) + async for chunk in response.chunks: + recorder.chunk(chunk) + return agent.conversation_id, response.stop_reason + + try: + conversation_id, stop = await asyncio.wait_for(converse(), timeout=timeout_s) + except TimeoutError: + recorder.close() + return AntigravityResult(session_id=session_id, tool_call_count=recorder.tool_calls, error_code="timeout", + error=f"the turn ran past its {timeout_s} s") + except agt.AntigravityExecutionError as exc: + recorder.close() + text = str(exc)[:ERROR_MESSAGE_LIMIT] + # A task env's MCP server that fails its initialize fails the harness's start: the run's tools aren't there. + mcp = "mcp load failed" in text.lower() + return AntigravityResult(session_id=session_id, tool_call_count=recorder.tool_calls, error=text, + error_code="mcp_load_failed" if mcp else "antigravity_error", infra=mcp) + recorder.close() + result = AntigravityResult(response=recorder.response(), session_id=conversation_id or session_id, + tool_call_count=recorder.tool_calls) + if stop == agt.StopReason.MAX_MODEL_CALLS_EXCEEDED: + result.error_code, result.error = "max_turns_exceeded", f"the turn stopped at its max_turns, {max_turns}" + elif stop not in (None, agt.StopReason.UNSPECIFIED): + result.error_code, result.error = "stopped", f"the SDK stopped the turn: {getattr(stop, 'name', stop)}" + return result diff --git a/src/agent_env/agents/agents/antigravity/antigravity_date.py b/src/agent_env/agents/agents/antigravity/antigravity_date.py new file mode 100644 index 000000000..3d9335824 --- /dev/null +++ b/src/agent_env/agents/agents/antigravity/antigravity_date.py @@ -0,0 +1,201 @@ +"""The env's time in Antigravity's model calls. The SDK's harness, `localharness`, is a static Go binary, which +agent-env's libfaketime can't reach, so it runs on real time wherever the image follows the env's clock, while the +commands it starts read the env's time. The model sees the harness's clock in two places: the line ``The current local +time is: .`` in each turn's user message, and the ``Created At:`` and ``Completed At:`` stamps that head a +command's result. While this agent follows an armed clock the turn's model relay puts the env's time in the line and +shifts the stamps by the env's offset from real time when it first sees them, so a command keeps its duration. Each +keeps what it was first given, recorded in ``EnvTimes`` beside the conversations by the time and the message it is in, +which the harness sends again as it stored it, so the earlier turns a resumed conversation sends again keep theirs. +tst/integration/agent/antigravity_env_date_test.py checks the SDK's model calls hold the machine's date nowhere else.""" + +from __future__ import annotations + +import asyncio +import contextlib +import hashlib +import json +import os +import re +import signal +import threading +from datetime import datetime, timezone +from pathlib import Path + +from agent_egress import clock_armed +from model_relay import Refusal + +_STAMP = r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:.]+(?:Z|[+-][0-9]{2}:[0-9]{2})" +LOCAL_TIME = re.compile(rf"(The current local time is: )({_STAMP})(\.)") +# The harness's head of a command's result: when the command started and, once it has, when it ended. +RUN_TIMES = re.compile(rf"^((?:Created|Completed) At: )({_STAMP})$", re.MULTILINE) +_DATE_TIMEOUT_S = 5 +_SHOWN_CHARS = 200 + + +class EnvTimes: + """Each turn's local-time line and the env time it was given, and each command result's env and real time when + the relay first saw it, in ``path``, keyed by ``line_key``.""" + + def __init__(self, path: Path) -> None: + self.path = path + self._lock = threading.Lock() + + def get(self, line: str) -> str | None: + return self._read().get(line) + + def all(self) -> dict[str, str]: + return self._read() + + def put(self, line: str, env: str) -> None: + with self._lock: + times = self._read() + times[line] = env + self.path.parent.mkdir(parents=True, exist_ok=True) + staged = self.path.with_suffix(".tmp") + staged.write_text(json.dumps(times)) + staged.replace(self.path) + + def merge(self, other: dict[str, str]) -> None: + """Add a snapshot's times, its own winning over none.""" + with self._lock: + times = {**other, **self._read()} + self.path.parent.mkdir(parents=True, exist_ok=True) + self.path.write_text(json.dumps(times)) + + def _read(self) -> dict[str, str]: + try: + times = json.loads(self.path.read_text()) + except (OSError, ValueError): + return {} + return times if isinstance(times, dict) else {} + + +def env_time_rewrite(times: EnvTimes): + """The relay's rewrite for a turn: while the agent follows an armed clock, every local-time line of a user message + gets the env time recorded for it, and the last one, the turn's own, the env's time now when none is recorded; + every command result's stamps are shifted by the offset recorded for it, a result of the turn's own recording the + env's offset now. A line or result of an earlier turn with none recorded is left as written: the agent followed no + clock then. Unchanged otherwise; a call that isn't JSON, or whose env time can't be read, is refused, so the model + is never told the machine's time instead.""" + + async def rewrite(body: bytes) -> bytes: + if not clock_armed(): + return body + try: + request = json.loads(body) + except ValueError as exc: + raise Refusal("the model call isn't JSON this agent can read, so the model can't be told the env's time") \ + from exc + if not isinstance(request, dict): + return body + messages = [message for message in request.get("messages") or [] if isinstance(message, dict)] + turn = max((index for index, message in enumerate(messages) if message.get("role") == "user"), default=-1) + lines = [(holder, key) for message in messages if message.get("role") == "user" + for holder, key in _texts(message) if LOCAL_TIME.search(holder[key])] + runs = [(holder, key, index > turn) for index, message in enumerate(messages) if message.get("role") == "tool" + for holder, key in _texts(message) if RUN_TIMES.search(holder[key])] + if not lines and not runs: + return body + now = _Now() + if lines: + latest = lines[-1][0][lines[-1][1]] + current = line_key(latest, LOCAL_TIME.findall(latest)[-1][1]) + if times.get(current) is None: + times.put(current, (await now())[0]) + for holder, key in lines: + text = holder[key] + holder[key] = LOCAL_TIME.sub(lambda match: _placed(match, line_key(text, match.group(2)), times), text) + for holder, key, own in runs: + text = holder[key] + run = line_key(text, "run") + if times.get(run) is None and own: + times.put(run, " ".join(await now())) + if (recorded := times.get(run)) is not None: + holder[key] = RUN_TIMES.sub(lambda match: match.group(1) + _shifted(match.group(2), recorded), text) + # Escaped, so a lone surrogate an MCP server's tool sent, which UTF-8 can't encode, goes as it came. + return json.dumps(request, separators=(",", ":")).encode() + + return rewrite + + +def line_key(text: str, real: str) -> str: + """A local-time line's or a command result's key: its time and the message text it is in, so two turns that start + in one second keep their own env times.""" + return f"{real}#{hashlib.sha256(text.encode('utf-8', 'surrogatepass')).hexdigest()[:16]}" + + +def _placed(match: re.Match, line: str, times: EnvTimes) -> str: + env = times.get(line) + return match.group(0) if env is None else f"{match.group(1)}{env}{match.group(3)}" + + +def _shifted(stamp: str, recorded: str) -> str: + """``stamp``, a real time, at the env's offset from real time that ``recorded`` holds, in the env's zone.""" + env, real = recorded.split(" ") + shifted = datetime.fromisoformat(env) + (datetime.fromisoformat(stamp) - datetime.fromisoformat(real)) + text = shifted.isoformat(timespec="seconds") + return text[:-6] + "Z" if text.endswith("+00:00") else text + + +class _Now: + """The env's time and the real time, read once a call needs them and kept for the rest of it.""" + + def __init__(self) -> None: + self._read: tuple[str, str] | None = None + + async def __call__(self) -> tuple[str, str]: + if self._read is None: + env = await _env_now() + self._read = (env, _real_now()) + return self._read + + +def _real_now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="seconds") + + +def _texts(message: dict): + """Each text of a message, as (holder, key), so it can be replaced in place.""" + content = message.get("content") + if isinstance(content, str): + yield message, "content" + elif isinstance(content, list): + yield from ((part, "text") for part in content if isinstance(part, dict) and isinstance(part.get("text"), str)) + + +async def _env_now() -> str: + """The env's time now in its zone, as the harness writes its own: RFC 3339 to the second, UTC as ``Z``. It comes + from ``date``: this server runs on real time, but what it starts reads the env's clock, as the model's commands + do.""" + def unread(reason: str) -> Refusal: + return Refusal(f"the env's time couldn't be read for the model: {reason}") + + try: + code, out, err = await _read_date() + except TimeoutError: + raise unread(f"date gave no answer within {_DATE_TIMEOUT_S} s") from None + except OSError as exc: + raise unread(f"{type(exc).__name__}: {exc}") from exc + if code != 0: + raise unread(f"date exited {code}: {err.decode(errors='replace').strip()[:_SHOWN_CHARS]}") + stamp = out.decode(errors="replace").strip() + if not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}[+-][0-9]{2}:[0-9]{2}", stamp): + raise unread(f"date printed {stamp[:_SHOWN_CHARS]!r}") + return stamp[:-6] + "Z" if stamp.endswith(("+00:00", "-00:00")) else stamp + + +async def _read_date() -> tuple[int, bytes, bytes]: + """``date``'s exit code and output. Past the timeout its process group is killed, which reaches anything it left + holding its output, even after it exited itself.""" + environ = {name: value for name, value in os.environ.items() if name != "AGENTENV_REAL_TIME"} + proc = await asyncio.create_subprocess_exec("date", "+%Y-%m-%dT%H:%M:%S%:z", stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, env=environ, start_new_session=True) + try: + out, err = await asyncio.wait_for(proc.communicate(), timeout=_DATE_TIMEOUT_S) + except BaseException: + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(proc.pid, signal.SIGKILL) + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(proc.wait(), _DATE_TIMEOUT_S) + raise + return proc.returncode, out, err diff --git a/src/agent_env/agents/agents/antigravity/antigravity_kit.py b/src/agent_env/agents/agents/antigravity/antigravity_kit.py new file mode 100644 index 000000000..dff504841 --- /dev/null +++ b/src/agent_env/agents/agents/antigravity/antigravity_kit.py @@ -0,0 +1,86 @@ +"""The pieces of agent plumbing this agent shares in shape with other agents, copied from the Claude Code agent's +``kit.py``: durable session references, skill installs and FastAPI-style error bodies. The Antigravity SDK lists a +skill by its SKILL.md's frontmatter alone, so an inline skill without any gets one from its name.""" + +from __future__ import annotations + +import json +import logging +import shutil +from pathlib import Path + +from agentenv_protocol.a2a_agent import BundleSkillRequest, InlineSkillRequest, SkillAddResponse +from agentenv_protocol.transfers import download +from starlette.applications import Starlette +from starlette.exceptions import HTTPException +from starlette.requests import Request +from starlette.responses import JSONResponse, Response + +logger = logging.getLogger(__name__) + +_REFS_ATTR = "_durable_session_refs" + + +class DurableSessionRefs: + """Mixin, listed before ``AgentEnvAgent``, that keeps every context's session reference for the life of the + process: the framework's own record is a bounded LRU, so an idle context would otherwise start a fresh CLI + session.""" + + def session_ref_for_context(self, context_id: str) -> str | None: + return self.__dict__.get(_REFS_ATTR, {}).get(context_id) or super().session_ref_for_context(context_id) + + def set_session_ref_for_context(self, context_id: str, session_ref: str) -> None: + super().set_session_ref_for_context(context_id, session_ref) + self.__dict__.setdefault(_REFS_ATTR, {})[context_id] = session_ref + + +_NO_BODY_STATUSES = frozenset({204, 205, 304}) + + +async def _detail_body(_request: Request, exc: HTTPException) -> Response: + if exc.status_code < 200 or exc.status_code in _NO_BODY_STATUSES: + return Response(status_code=exc.status_code, headers=exc.headers) + return JSONResponse({"detail": exc.detail}, status_code=exc.status_code, headers=exc.headers) + + +def json_error_bodies(app: Starlette) -> Starlette: + """Answer every ``HTTPException`` with a ``{"detail": ...}`` body, as agent-env reads errors.""" + app.add_exception_handler(HTTPException, _detail_body) + return app + + +def _validate_skill_name(name: str) -> None: + if name != Path(name).name or ".." in name or "/" in name or "\\" in name: + raise HTTPException(status_code=400, detail=f"Invalid skill name '{name}': must not contain path separators or '..'") + + +async def install_skill(request: InlineSkillRequest | BundleSkillRequest, skills_dir: Path) -> SkillAddResponse: + """Write ``skills_dir//``: the inline ``SKILL.md``, or every bundle file through its read grant. A failed + install leaves no directory behind.""" + _validate_skill_name(request.name) + skill_dir = skills_dir / request.name + if skill_dir.exists(): + raise HTTPException(status_code=409, detail=f"Skill '{request.name}' is already registered") + skill_dir.mkdir(parents=True) + try: + if isinstance(request, BundleSkillRequest): + for item in request.skill_bundle.files: + await download(item.object, skill_dir / item.path) + else: + if not request.skill_md or not request.skill_md.strip(): + raise HTTPException(status_code=400, detail="Skill content must not be empty") + (skill_dir / "SKILL.md").write_text(with_frontmatter(request.skill_md, request.name, request.description)) + except BaseException: + shutil.rmtree(skill_dir, ignore_errors=True) + raise + logger.info(f"Registered skill '{request.name}' at {skill_dir}") + return SkillAddResponse(name=request.name) + + +def with_frontmatter(skill_md: str, name: str, description: str | None) -> str: + """``skill_md`` as written when it opens with YAML frontmatter, else with a ``name`` and ``description`` one before + it: the SDK lists a skill to the model only by its frontmatter, so one without it would never be found.""" + if skill_md.lstrip().startswith("---"): + return skill_md + summary = " ".join((description or name).split()) + return f"---\nname: {json.dumps(name)}\ndescription: {json.dumps(summary)}\n---\n\n{skill_md}" diff --git a/src/agent_env/agents/agents/antigravity/entrypoint.sh b/src/agent_env/agents/agents/antigravity/entrypoint.sh new file mode 100755 index 000000000..d05a633b0 --- /dev/null +++ b/src/agent_env/agents/agents/antigravity/entrypoint.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -e +# A stop waits this long for open requests, then the server shuts down and ends the harnesses of turns still running. +exec uvicorn a2a_server:app --host 0.0.0.0 --port "${A2A_PORT:-8000}" --timeout-graceful-shutdown 5 diff --git a/src/agent_env/agents/agents/antigravity/install.sh b/src/agent_env/agents/agents/antigravity/install.sh new file mode 100755 index 000000000..c23b47b77 --- /dev/null +++ b/src/agent_env/agents/agents/antigravity/install.sh @@ -0,0 +1,149 @@ +#!/bin/bash +# Install this agent from the folder this script is in, and start it on PORT, without an image of its own: +# +# install.sh container NAME PORT into the running container NAME, as root, with /app as the agent's workspace +# install.sh host NAME PORT WORKDIR onto this Linux host, as agent NAME, with WORKDIR as the agent's workspace +# +# It brings uv, checked against its published checksum, and the agent's requirements, the Antigravity SDK with its +# harness among them, in a private Python, so the target's own Python and packages are never touched. A target with no +# bash, which the model's commands run in, gets it from its own package manager. The model endpoint's LITELLM_API_KEY, +# LITELLM_BASE_URL and LITELLM_EXTRA_HEADERS, and AGENT_TRUST_ENV, the KEY='VALUE' lines of the CA variables the agent +# needs, come in the environment and are kept in a 0600 file the agent reads. +set -euo pipefail +umask 077 + +mode=$1 target=$2 port=$3 +here=$(cd "$(dirname "$0")" && pwd) + +UV_VERSION=0.13.1 +UV_SHA256_X86_64=6c86040a8f045ab9adc9e3ec4cdafa03fd00e9a988ed2bf28971c7fc2d0debd0 +UV_SHA256_AARCH64=345a8308e4d1835cdfaadf692836fd3137a6d45864773f05ad7bf59442b1ba16 +PYTHON_VERSION=3.12 +START_TIMEOUT_S=120 +STOP_TIMEOUT_S=10 +AGENT_FILES="a2a_server.py antigravity_bridge.py antigravity_date.py antigravity_kit.py requirements.txt run.sh agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py" + +# put SRC DEST replaces DEST by a rename, so a binary an earlier install's agent still runs can be replaced. +case $mode in + container) + root=/opt/agentenv-agent-$port # one per agent: two in a container listen on two ports + workspace=/app + on() { docker exec -u 0 "$target" sh -c "$1"; } + put() { docker cp "$1" "$target:$2.new" > /dev/null && on "mv -f $(quoted "$2.new") $(quoted "$2")"; } + ;; + host) + [ "$(uname -s)" = Linux ] || { echo "a host install needs a Linux host, not $(uname -s)" >&2; exit 1; } + # Outside the work dir install_agent empties before each attempt, as a container's is, so a retry stops the agent an + # earlier attempt started. It ends in the sandbox's id, which names what a local sandbox's teardown removes from + # /tmp; a VM's host goes with the VM. + root=/tmp/agentenv-agent-$target-$port${AGENTENV_SANDBOX:+-$AGENTENV_SANDBOX} + workspace=$4 + on() { sh -c "$1"; } + put() { cp "$1" "$2.new" && mv -f "$2.new" "$2"; } + ;; + *) echo "usage: install.sh container NAME PORT | install.sh host NAME PORT WORKDIR" >&2; exit 2 ;; +esac + +if [ "$mode" = host ]; then + # /tmp is shared, and the folder will hold the model key: it is this user's alone, and one another made is refused. + if ! mkdir -m 0700 "$root" 2> /dev/null; then + [ -d "$root" ] && [ ! -L "$root" ] && [ -O "$root" ] \ + || { echo "$root is already there and isn't a folder of this user's own" >&2; exit 1; } + chmod 0700 "$root" + fi +fi + +case $(on 'uname -m') in + x86_64|amd64) uv_cpu=x86_64 uv_sha256=$UV_SHA256_X86_64 ;; + aarch64|arm64) uv_cpu=aarch64 uv_sha256=$UV_SHA256_AARCH64 ;; + *) echo "the Antigravity SDK has no build for $(on 'uname -m')" >&2; exit 1 ;; +esac + +if ! on 'command -v bash >/dev/null'; then + on 'if command -v apt-get >/dev/null; then apt-get update -qq && apt-get install -y -qq --no-install-recommends bash + elif command -v apk >/dev/null; then apk add -q bash + elif command -v dnf >/dev/null; then dnf install -y -q bash + elif command -v microdnf >/dev/null; then microdnf install -y bash + else exit 1; fi' > /dev/null \ + || { echo "the model's commands run in bash: the target has none, and bash can't be added" >&2; exit 1; } +fi + +sha256() { if command -v sha256sum >/dev/null; then sha256sum "$1"; else shasum -a 256 "$1"; fi | cut -d' ' -f1; } +# One more go when curl fails: --retry passes over some transient failures, such as a reset HTTP/2 stream (exit 92). +fetch() { curl -fsSL --retry 3 "$1" -o "$2" || { sleep 2; curl -fsSL --retry 3 "$1" -o "$2"; }; } +checked() { # checked FILE SHA256: FILE is what was published, or the install stops + [ "$(sha256 "$1")" = "$2" ] || { echo "$(basename "$1") doesn't match its published checksum" >&2; exit 1; } +} +quoted() { printf "'%s'" "$(printf %s "$1" | sed "s/'/'\\\\''/g")"; } +r=$(quoted "$root") # $root, as the commands run in the target read it + +# Beside this script, in the work dir the sandbox's teardown removes, so a killed install leaves nothing elsewhere. +stage=$(mktemp -d "$here/../stage.XXXXXX") +trap 'rm -rf "$stage"' EXIT + +uv_archive=uv-$uv_cpu-unknown-linux-musl.tar.gz +fetch "https://github.com/astral-sh/uv/releases/download/$UV_VERSION/$uv_archive" "$stage/$uv_archive" +checked "$stage/$uv_archive" "$uv_sha256" +tar -xzf "$stage/$uv_archive" -C "$stage" +chmod 0755 "$stage/uv-$uv_cpu-unknown-linux-musl/uv" + +# The model relay, in the agent's Python, reads the system's CA certificates, and a bare image has none: such a +# target's agent trusts certifi's, from that Python, unless the trust lines name a bundle. The SDK's harness, a Go +# binary, reads SSL_CERT_FILE too. +certifi=$root/venv/lib/python$PYTHON_VERSION/site-packages/certifi/cacert.pem +needs_cas= +on 'for f in /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt /etc/ssl/ca-bundle.pem /etc/ssl/cert.pem + do [ -s "$f" ] && exit 0; done; exit 1' || needs_cas=1 +case ${AGENT_TRUST_ENV:-} in *SSL_CERT_FILE=*) needs_cas= ;; esac + +# The model endpoint and CA, as the agent's environment, readable by its user only. +{ + for name in LITELLM_API_KEY LITELLM_BASE_URL LITELLM_EXTRA_HEADERS; do + printf '%s=%s\n' "$name" "$(quoted "${!name:-}")" + done + [ -z "${AGENT_TRUST_ENV:-}" ] || printf '%s\n' "$AGENT_TRUST_ENV" + [ -z "${AGENTENV_CONTROL_TOKEN:-}" ] || printf 'AGENTENV_CONTROL_TOKEN=%s\n' "$(quoted "$AGENTENV_CONTROL_TOKEN")" + [ -z "$needs_cas" ] || printf 'SSL_CERT_FILE=%s\n' "$(quoted "$certifi")" + # The SDK's conversations and skills, as the image keeps them under its home. + printf 'A2A_PORT=%s\nANTIGRAVITY_WORKSPACE_DIR=%s\nANTIGRAVITY_HOME=%s\nHOME=%s\n' \ + "$(quoted "$port")" "$(quoted "$workspace")" "$(quoted "$root/data/.antigravity")" "$(quoted "$root/data")" +} > "$stage/agent.env" + +# An earlier install's agent, a retried step's say, stops first: its files are replaced and its port is freed. +on "if [ -f $r/agent.pid ]; then pid=\$(cat $r/agent.pid); kill \$pid 2> /dev/null; i=0; \ + while [ \$i -lt $STOP_TIMEOUT_S ] && kill -0 \$pid 2> /dev/null; do sleep 1; i=\$((i + 1)); done; \ + kill -9 \$pid 2> /dev/null; rm -f $r/agent.pid; fi; true" + +# The agent starts afresh, with no conversations or skills of one it replaces. +on "rm -rf $r/data && mkdir -p $r/bin $r/app $r/data $(quoted "$workspace")" +put "$stage/uv-$uv_cpu-unknown-linux-musl/uv" "$root/bin/uv" +put "$stage/agent.env" "$root/agent.env" +for file in $AGENT_FILES; do + put "$here/$file" "$root/app/${file##*/}" +done +on "chmod 0600 $r/agent.env && chmod 0755 $r/bin/uv $r/app/run.sh" + +# A private Python, uv's own build of it and never the target's, with the agent's requirements; no cache is left +# behind. +on "cd $r && export UV_PYTHON_PREFERENCE=only-managed UV_PYTHON_INSTALL_DIR=$r/python \ + UV_CACHE_DIR=$r/cache/uv && bin/uv venv --quiet --clear --python $PYTHON_VERSION venv \ + && bin/uv pip install --quiet --python venv/bin/python -r app/requirements.txt \ + && rm -rf $r/cache && [ -s $(quoted "$certifi") ]" + +if [ "$mode" = container ]; then + docker exec -d -u 0 "$target" sh -c "exec $r/app/run.sh $r > $r/agent.log 2>&1" +else + cd "$workspace" + nohup "$root/app/run.sh" "$root" > "$root/agent.log" 2>&1 < /dev/null & +fi + +# Done once the agent answers on its port; an agent that exits first fails the install with the end of its log. +health="import urllib.request; urllib.request.urlopen('http://127.0.0.1:$port/health', timeout=2)" +for _ in $(seq "$START_TIMEOUT_S"); do + on "$r/venv/bin/python -c \"$health\"" 2> /dev/null && exit 0 + on "[ ! -f $r/agent.pid ] || kill -0 \$(cat $r/agent.pid)" 2> /dev/null || break + sleep 1 +done +echo "the agent didn't start; the end of its log:" >&2 +on "tail -n 40 $r/agent.log" >&2 || true +exit 1 diff --git a/src/agent_env/agents/agents/antigravity/requirements.txt b/src/agent_env/agents/agents/antigravity/requirements.txt new file mode 100644 index 000000000..720b89967 --- /dev/null +++ b/src/agent_env/agents/agents/antigravity/requirements.txt @@ -0,0 +1,11 @@ +# The image installs the newest agentenv-framework-protocol at or above this floor; a release doesn't pin it, so the +# image is built again only when this folder changes. The floor is the first with ModelUsage.of, which gives a model's +# share of a turn from its calls; raise it when the agent needs a newer protocol. +agentenv-framework-protocol[agent]>=0.1.643 +# The Antigravity SDK, whose wheel for this platform holds its harness, a static Go binary; AntigravityTool in +# antigravity_bridge.py names the tools of this version. +google-antigravity==0.1.24 +# The model relay's server and client (model_relay.py). +aiohttp>=3.9,<4 +# The CA bundle the relay trusts on an install target that has none of its own (install.sh). +certifi diff --git a/src/agent_env/agents/agents/antigravity/root.conf b/src/agent_env/agents/agents/antigravity/root.conf new file mode 100644 index 000000000..0687ad417 --- /dev/null +++ b/src/agent_env/agents/agents/antigravity/root.conf @@ -0,0 +1,74 @@ +; 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 the model's commands, +; which the SDK's harness starts, read the env's time; the harness, a static binary libfaketime can't reach, keeps real +; time. 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. +[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. Never restarted: see [eventlistener:agent-exit]. +[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" + +; The server's exit, for any reason, stops supervisord and with it the container, as when the server was the +; container's main process: one restarted in place would have lost the env's MCP servers, its config, its peers and its +; running tasks, while the harness the dead one started went on writing. The follower and the proxy restart in place. +; supervisord exits 0 however it stops, so the container's exit status doesn't tell a crash from a stop; its log does. +[eventlistener:agent-exit] +command=/bin/sh -c 'while echo READY && read -r header; do body=$(head -c "${header##*len:}"); case " $body " in *" processname:agent "*) echo "the A2A server exited ($body): stopping the container" >&2; kill -TERM "$PPID";; esac; printf "RESULT 2\nOK"; done' +events=PROCESS_STATE_EXITED,PROCESS_STATE_FATAL +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 diff --git a/src/agent_env/agents/agents/antigravity/run.sh b/src/agent_env/agents/agents/antigravity/run.sh new file mode 100755 index 000000000..4e6844257 --- /dev/null +++ b/src/agent_env/agents/agents/antigravity/run.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Start an installed agent from ROOT, in this shell's working directory: its environment from ROOT/agent.env and its +# own Python, whose packages hold the Antigravity SDK and its harness. +set -e +root=$1 +set -a +. "$root/agent.env" +set +a +echo $$ > "$root/agent.pid" +export PATH="$root/bin:$PATH:$root/venv/bin" PYTHONPATH="$root/app" +# Within install.sh's stop timeout, so a reinstall's stop reaches the shutdown that ends running turns' harnesses. +exec "$root/venv/bin/uvicorn" a2a_server:app --host 0.0.0.0 --port "$A2A_PORT" --timeout-graceful-shutdown 5 diff --git a/src/agent_env/agents/agents/antigravity/shared_sources.toml b/src/agent_env/agents/agents/antigravity/shared_sources.toml new file mode 100644 index 000000000..ba8b8a852 --- /dev/null +++ b/src/agent_env/agents/agents/antigravity/shared_sources.toml @@ -0,0 +1,6 @@ +# 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" +model_relay = "utils/model_relay" diff --git a/src/agent_env/agents/agents/antigravity/start-agent b/src/agent_env/agents/agents/antigravity/start-agent new file mode 100755 index 000000000..7b84a1e0c --- /dev/null +++ b/src/agent_env/agents/agents/antigravity/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, everything it starts 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/src/agent_env/agents/aliases.toml b/src/agent_env/agents/aliases.toml index 20d6b0604..451677a36 100644 --- a/src/agent_env/agents/aliases.toml +++ b/src/agent_env/agents/aliases.toml @@ -10,3 +10,4 @@ openhands = ["openhands"] letta-code = ["letta-code"] pydantic-ai = ["pydantic-ai"] browser-use = ["browser-use"] +antigravity = ["antigravity"] diff --git a/src/agent_env/agents/tasks/antigravity-smoke.json b/src/agent_env/agents/tasks/antigravity-smoke.json new file mode 100644 index 000000000..47dfb1fd8 --- /dev/null +++ b/src/agent_env/agents/tasks/antigravity-smoke.json @@ -0,0 +1,7 @@ +[ + {"id": "deploy", "type": "deploy_agent", "a2a_agent_id": "antigravity", "env_ids": [], "sandbox_type": "local"}, + {"id": "ask", "type": "prompt_agent", "prompt_id": "ask", "depends_on": ["deploy"], + "prompt": "Run the shell command `echo $((6 * 7))` and reply with only the number it prints."}, + {"id": "check", "type": "agent_prompt_response_verifier", "prompt_id": "ask", "verifier_id": "answer", + "criteria": [{"type": "response_contains", "needles": ["42"]}], "depends_on": ["ask"]} +] diff --git a/tst/integration/agent/antigravity_env_date_test.py b/tst/integration/agent/antigravity_env_date_test.py new file mode 100644 index 000000000..6788f559a --- /dev/null +++ b/tst/integration/agent/antigravity_env_date_test.py @@ -0,0 +1,212 @@ +"""The Antigravity SDK the agent's requirements.txt pins, against what its bridge relies on: the harness opens each turn's +user message with the local-time line the turn's relay rewrites on an armed clock, and writes the machine's date +nowhere else, so the model is sent the env's time alone, and a resumed conversation's earlier turn keeps the time it +was given; the harness is a static binary, which libfaketime can't reach; the n-th tool call the SDK's hooks see is the +n-th it streams, so a result is tied to its call; and the SDK's tools are those AntigravityTool and the two always off +name. Bumping the SDK runs this against the new version, so a version that moves any of these fails here.""" + +import json +import os +import shutil +import struct +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +from tst.unit.agents.antigravity.agent import AGENT_DIR, PYTHONPATH, antigravity_bridge +from tst.util import fake_openai + +pytestmark = [pytest.mark.integration] + +ENV_TIMES = ("1950-01-01T09:30:00Z", "1950-01-02T08:15:00Z") +# The tools the first turn calls, in order, by a word of the name the model is offered each by: a command, the +# harness's own skill listing, which its hooks never decide, and the workspace's file. +TOOLS = ("command", "list_skills", "view_file") +_DAY_S = 86400 +_PT_INTERP = 3 + +# Two turns of one conversation through the bridge, on an armed clock whose time is the next of argv's, with the real +# SDK; their results, trajectories and what the SDK holds, as JSON. +DRIVER = ''' +import asyncio, json, sys +from pathlib import Path +import google.antigravity as ag +from google.antigravity import types as agt +import antigravity_bridge, antigravity_date + +times = iter(sys.argv[2:]) +antigravity_date.clock_armed = lambda: True +async def env_now(): + return current +antigravity_date._env_now = env_now + +async def turn(prompt, session_id): + events = [] + result = await antigravity_bridge.run_antigravity( + prompt, model="m", session_id=session_id, mcp_servers=None, system_prompt=None, timeout_s=300, role=None, + builtin_tools=None, max_turns=None, workspace=sys.argv[1], event_callback=events.append) + return {"response": result.response, "error": result.error, "session_id": result.session_id, + "tool_calls": result.tool_call_count, "usage": result.usage.to_dict(), "events": events} + +current = next(times) +first = asyncio.run(turn("Run the shell command `echo 42` and reply with what it prints.", None)) +current = next(times) +second = asyncio.run(turn("Thanks. Reply with the word done.", first["session_id"])) +print(json.dumps({"turns": [first, second], "tools": sorted(tool.value for tool in agt.BuiltinTools), + "harness": str(Path(ag.__file__).parent / "bin" / "localharness")})) +''' + + +@pytest.fixture(scope="module") +def sdk_python(tmp_path_factory) -> Path: + """A Python with the agent's requirements, the pinned SDK among them, as the image installs them.""" + uv = shutil.which("uv") + assert uv, "uv installs the pinned Antigravity SDK, as install.sh does" + venv = tmp_path_factory.mktemp("antigravity") / "venv" + subprocess.run([uv, "venv", "--quiet", "--python", sys.executable, str(venv)], check=True, timeout=120) + python = venv / "bin" / "python" + subprocess.run([uv, "pip", "install", "--quiet", "--python", str(python), "-r", str(AGENT_DIR / "requirements.txt")], + check=True, timeout=900) + return python + + +def _arguments(schema: dict, workspace: Path, tool: str) -> dict: + """Arguments for ``tool``, whatever the SDK names them: a command that runs ``echo 42`` in the workspace, the + workspace listed, or its file viewed.""" + arguments = {} + for name in schema.get("required") or []: + kind = (schema.get("properties") or {}).get(name, {}).get("type") + lowered = name.lower() + if "command" in lowered: + arguments[name] = "echo 42" + elif "cwd" in lowered or "dir" in lowered or "path" in lowered or "file" in lowered: + arguments[name] = str(workspace / "notes.txt" if tool == "view_file" else workspace) + elif (schema.get("properties") or {}).get(name, {}).get("enum"): + arguments[name] = schema["properties"][name]["enum"][0] + elif kind == "boolean": + arguments[name] = False + elif kind in ("integer", "number"): + arguments[name] = 10000 + else: + arguments[name] = "" + return arguments + + +def _user_texts(body: dict) -> list[str]: + texts = [] + for message in body.get("messages") or []: + if message.get("role") != "user": + continue + content = message.get("content") + parts = content if isinstance(content, list) else [{"text": content}] + texts += [part["text"] for part in parts if isinstance(part, dict) and isinstance(part.get("text"), str)] + return texts + + +def _machine_dates() -> set[str]: + return {time.strftime("%Y-%m-%d", time.localtime(time.time() + offset)) for offset in (-_DAY_S, 0, _DAY_S)} | { + time.strftime("%Y-%m-%d", time.gmtime(time.time() + offset)) for offset in (-_DAY_S, 0, _DAY_S)} + + +def _is_static(binary: Path) -> bool: + """Whether an ELF binary has no program interpreter, the dynamic loader that would preload libfaketime.""" + data = binary.read_bytes() + assert data[:4] == b"\x7fELF" and data[4] == 2, f"{binary} isn't a 64-bit ELF binary" + endian = "<" if data[5] == 1 else ">" + phoff, = struct.unpack_from(f"{endian}Q", data, 0x20) + phentsize, phnum = struct.unpack_from(f"{endian}HH", data, 0x36) + types = [struct.unpack_from(f"{endian}I", data, phoff + index * phentsize)[0] for index in range(phnum)] + return _PT_INTERP not in types + + +@pytest.fixture(scope="module") +def run(sdk_python, tmp_path_factory) -> tuple[dict, fake_openai.FakeOpenAI]: + folder = tmp_path_factory.mktemp("turns") + workspace = folder / "work" + workspace.mkdir() + (workspace / "notes.txt").write_text("forty-two\n") + + def respond(body: dict) -> fake_openai.Text | fake_openai.ToolCall: + if any("done" in text for text in _user_texts(body)[-1:]): + return fake_openai.Text("done") + ran = sum(message.get("role") == "tool" for message in body.get("messages") or []) + if ran == len(TOOLS): + return fake_openai.Text("It printed 42.") + offered = [tool["function"] for tool in body.get("tools") or [] if TOOLS[ran] in tool["function"]["name"]] + if len(offered) != 1: + names = [tool["function"]["name"] for tool in body.get("tools") or []] + return fake_openai.Text(f"no single tool named for {TOOLS[ran]!r} among {names}") + return fake_openai.ToolCall(offered[0]["name"], _arguments(offered[0].get("parameters") or {}, workspace, + TOOLS[ran])) + + driver = folder / "driver.py" + driver.write_text(DRIVER) + with fake_openai.FakeOpenAI(respond=respond) as endpoint: + env = {**{key: value for key, value in os.environ.items() if not key.startswith(("LITELLM_", "AGENTENV_"))}, + "LITELLM_BASE_URL": f"{endpoint.url}/v1", "LITELLM_API_KEY": "sk-fake", "HOME": str(folder), + "ANTIGRAVITY_HOME": str(folder / ".antigravity"), "PYTHONPATH": PYTHONPATH} + out = subprocess.run([str(sdk_python), "-u", str(driver), str(workspace), *ENV_TIMES], + cwd=folder, env=env, capture_output=True, text=True, timeout=900) + assert out.returncode == 0, out.stderr[-4000:] + return json.loads(out.stdout.strip().splitlines()[-1]), endpoint + + +def test_the_harness_is_a_static_binary_so_it_keeps_real_time(run): + harness = Path(run[0]["harness"]) + + assert harness.is_file() and _is_static(harness), ( + f"the SDK's harness {harness} loads through the dynamic loader, so the image's libfaketime would put it on " + "the env's clock, and its conversation store, which orders turns by time, with it") + + +def test_the_sdks_tools_are_the_ones_a_task_selects_and_the_three_it_cant(run): + assert set(run[0]["tools"]) == {*antigravity_bridge.AntigravityTool.__args__, "ask_question", "generate_image", + "finish"}, "the SDK's tools changed: record them in AntigravityTool" + + +def test_on_an_armed_clock_the_model_is_told_the_env_time_and_no_other(run): + result, endpoint = run + bodies = [seen.body for seen in endpoint.completions()] + first = [body for body in bodies if len(_user_texts(body)) == 1] + second = [body for body in bodies if len(_user_texts(body)) >= 2] + + assert first and second, [len(_user_texts(body)) for body in bodies] + assert all(f"The current local time is: {ENV_TIMES[0]}." in _user_texts(body)[0] for body in first), ( + "the harness no longer opens a turn's user message with the line antigravity_date.LOCAL_TIME finds") + for body in second: + earlier, latest = _user_texts(body)[0], _user_texts(body)[-1] + assert f"The current local time is: {ENV_TIMES[0]}." in earlier + assert f"The current local time is: {ENV_TIMES[1]}." in latest + machine = _machine_dates() + for body in bodies: + written = json.dumps(body) + found = [written[max(0, at - 160):at + 60] for date in machine if (at := written.find(date)) >= 0] + assert not found, f"the harness wrote this machine's date where the relay doesn't rewrite it: {found}" + + +def test_each_tool_result_is_tied_to_the_call_the_sdk_streamed(run): + first, _second = run[0]["turns"] + + assert not first["error"], first["error"] + calls = [event for event in first["events"] if event.get("type") == "ToolCall"] + results = [event for event in first["events"] if event.get("kind") == "tool_result"] + assert len(calls) == len(results) == first["tool_calls"] == len(TOOLS), first["events"] + assert [result["call_ref"] for result in results] == [call["id"] for call in calls], json.dumps(first["events"]) + assert [result["name"] for result in results] == ["run_command", "list_skills", "view_file"], results + assert "42" in json.dumps(results[0]) + assert first["response"] == "It printed 42." + + +def test_the_turns_usage_is_every_model_call_the_harness_made_with_the_endpoints_key(run): + result, endpoint = run + completions = endpoint.completions() + usage = [turn["usage"] for turn in result["turns"]] + + assert sum(turn["provider_details"]["model_calls"] for turn in usage) == len(completions) + assert sum(turn["input_tokens"] for turn in usage) == fake_openai.USAGE["prompt_tokens"] * len(completions) + assert {seen.headers.get("authorization") for seen in completions} == {"Bearer sk-fake"} + assert result["turns"][1]["session_id"] == result["turns"][0]["session_id"] + assert result["turns"][1]["response"] == "done" diff --git a/tst/unit/agents/antigravity/__init__.py b/tst/unit/agents/antigravity/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tst/unit/agents/antigravity/agent.py b/tst/unit/agents/antigravity/agent.py new file mode 100644 index 000000000..f579abe6a --- /dev/null +++ b/tst/unit/agents/antigravity/agent.py @@ -0,0 +1,31 @@ +"""The Antigravity 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/, clock/ and model_relay/, whose modules the image copies beside the +bridge; with the SDK's stand-in (``fake_sdk``) as ``google.antigravity``, so they import without its wheel.""" + +import importlib +import importlib.util +import os +import sys +from pathlib import Path + +import agent_env +from tst.unit.agents.antigravity import fake_sdk +from tst.util.build_context import sent + +AGENT_DIR = Path(agent_env.__file__).parent / "agents" / "agents" / "antigravity" +IMPORTED = [str(AGENT_DIR), str(sent(AGENT_DIR, "agent_clock/agent_egress.py").parent), + str(sent(AGENT_DIR, "clock/clockpage.py").parent), str(sent(AGENT_DIR, "model_relay/model_relay.py").parent)] +PYTHONPATH = os.pathsep.join(IMPORTED) +sys.path[:0] = IMPORTED +fake_sdk.install() +antigravity_bridge = importlib.import_module("antigravity_bridge") +antigravity_date = importlib.import_module("antigravity_date") +antigravity_kit = importlib.import_module("antigravity_kit") +agent_egress = importlib.import_module("agent_egress") +model_relay = importlib.import_module("model_relay") +# By its path: another agent's a2a_server, imported by the same name, may be loaded already. +_spec = importlib.util.spec_from_file_location("antigravity_a2a_server", AGENT_DIR / "a2a_server.py") +a2a_server = importlib.util.module_from_spec(_spec) +# Registered first: pydantic resolves its config's annotations through the module's entry. +sys.modules[_spec.name] = a2a_server +_spec.loader.exec_module(a2a_server) diff --git a/tst/unit/agents/antigravity/conftest.py b/tst/unit/agents/antigravity/conftest.py new file mode 100644 index 000000000..bb534a6ad --- /dev/null +++ b/tst/unit/agents/antigravity/conftest.py @@ -0,0 +1,90 @@ +"""A fresh agent per test, driven over ASGI the way agent-env reaches it: its workspace, conversations, skills and +changelog under the test's own folder, the SDK's stand-in reset with no scripted turns, and a stand-in for the turn's +model relay, since unit tests open no loopback servers.""" + +from __future__ import annotations + +import uuid +from contextlib import asynccontextmanager + +import httpx +import pytest + +from tst.unit.agents.antigravity import fake_sdk +from tst.unit.agents.antigravity.agent import a2a_server, antigravity_bridge, antigravity_date + + +class Harness: + """One fresh agent and its app, reached the way agent-env reaches it: over HTTP.""" + + def __init__(self, agent: a2a_server.AntigravityAgent) -> None: + self.agent = agent + self.app = a2a_server.build_app(agent) + + @property + def card(self) -> dict: + return self.app.state.agentenv_a2a.card.model_dump(mode="json", exclude_none=True, by_alias=True) + + def client(self) -> httpx.AsyncClient: + return httpx.AsyncClient(transport=httpx.ASGITransport(app=self.app), base_url="http://antigravity") + + @staticmethod + async def send(client: httpx.AsyncClient, parts: str | list[dict], context_id: str = "ctx-1") -> dict: + """message/send, blocking; the terminal task.""" + if isinstance(parts, str): + parts = [{"kind": "text", "text": parts}] + message = {"kind": "message", "role": "user", "messageId": uuid.uuid4().hex, "contextId": context_id, + "parts": parts} + response = await client.post("/a2a", json={ + "jsonrpc": "2.0", "id": 1, "method": "message/send", + "params": {"message": message, "configuration": {"blocking": True}}, + }) + response.raise_for_status() + return response.json()["result"] + + +@pytest.fixture(autouse=True) +def sdk(): + """The SDK's stand-in, with no turns scripted and nothing recorded.""" + fake_sdk.Agent.turns, fake_sdk.Agent.configs, fake_sdk.Agent.prompts = [], [], [] + return fake_sdk + + +@pytest.fixture(autouse=True) +def relay(monkeypatch): + """A turn's model relay as the bridge opens it, without its loopback server: it hands the harness a stand-in root + and records what it was opened with, and its counted calls stay as the test leaves them.""" + opened: list[dict] = [] + + @asynccontextmanager + async def stand_in(upstream, calls, **kwargs): + opened.append({"upstream": upstream, "calls": calls, **kwargs}) + yield "http://relay.test/token" + + monkeypatch.setattr(antigravity_bridge, "model_relay", stand_in) + return opened + + +@pytest.fixture(autouse=True) +def folders(monkeypatch, tmp_path): + """The agent's workspace, conversations, skills and changelog in the test's folder.""" + workspace = tmp_path / "workspace" + workspace.mkdir() + conversations = tmp_path / "home" / "conversations" + times = antigravity_date.EnvTimes(conversations / "env-times.json") + for module in (a2a_server, antigravity_bridge): + monkeypatch.setattr(module, "SAVE_DIR", conversations) + monkeypatch.setattr(module, "SKILLS_DIR", tmp_path / "home" / "skills") + monkeypatch.setattr(module, "ENV_TIMES", times) + monkeypatch.setattr(a2a_server, "WORKSPACE_DIR", workspace) + monkeypatch.setattr(a2a_server, "INPUTS_DIR", workspace / "inputs") + monkeypatch.setattr(a2a_server, "_CHANGELOG_DIR", tmp_path / "changelog") + monkeypatch.setattr(a2a_server, "_CHANGELOG_SNAR", tmp_path / "changelog" / "state.snar") + monkeypatch.setattr(a2a_server, "_CHANGELOG_META_DIR", tmp_path / f"changelog{a2a_server._META_DIR_SUFFIX}") + return workspace + + +@pytest.fixture +def ag() -> Harness: + """The agent as the image serves it, changelog included.""" + return Harness(a2a_server.AntigravityChangelogAgent()) diff --git a/tst/unit/agents/antigravity/fake_sdk.py b/tst/unit/agents/antigravity/fake_sdk.py new file mode 100644 index 000000000..bd1217cad --- /dev/null +++ b/tst/unit/agents/antigravity/fake_sdk.py @@ -0,0 +1,177 @@ +"""A stand-in for the Antigravity SDK, ``google.antigravity``, as much of it as the agent uses, so its tests run offline +without the SDK's wheel: an ``Agent`` whose turns play a script of streamed chunks, tool calls through the hooks the +config names, results and errors, recording the config each turn started with. The names, values and shapes are the +pinned SDK's; tst/integration/agent/antigravity_env_date_test.py runs the real one.""" + +from __future__ import annotations + +import asyncio +import enum +import sys +import types +from dataclasses import dataclass, field +from typing import Any + + +class _Model: + """A pydantic-like record: its keyword arguments, and their dump.""" + + def __init__(self, **fields: Any) -> None: + self.__dict__.update(fields) + + def model_dump(self, mode: str | None = None, exclude: set[str] | None = None, warnings: bool = True) -> dict: + return {key: value for key, value in self.__dict__.items() if key not in (exclude or set())} + + def __eq__(self, other: object) -> bool: + return type(other) is type(self) and other.__dict__ == self.__dict__ + + def __repr__(self) -> str: + return f"{type(self).__name__}({self.__dict__})" + + +class BuiltinTools(str, enum.Enum): + LIST_DIR = "list_directory" + SEARCH_DIR = "search_directory" + FIND_FILE = "find_file" + VIEW_FILE = "view_file" + CREATE_FILE = "create_file" + EDIT_FILE = "edit_file" + RUN_COMMAND = "run_command" + ASK_QUESTION = "ask_question" + INVOKE_SUBAGENT = "invoke_subagent" + RUN_WORKFLOW = "run_workflow" + GENERATE_IMAGE = "generate_image" + SEARCH_WEB = "search_web" + READ_URL_CONTENT = "read_url_content" + SCHEDULE = "schedule" + FINISH = "finish" + + +class AgentBehavior(enum.Enum): + AUTONOMOUS = "autonomous" + INTERACTIVE = "interactive" + MINIMAL = "minimal" + + +class StopReason(enum.Enum): + UNSPECIFIED = 0 + MAX_MODEL_CALLS_EXCEEDED = 1 + MAX_TOOL_CALLS_EXCEEDED = 2 + QUOTA_EXHAUSTED = 6 + + +class BudgetScope(enum.Enum): + LIFETIME = 0 + FORWARD_LOOKING = 1 + + +class AntigravityExecutionError(Exception): + pass + + +class CapabilitiesConfig(_Model): ... +class McpStreamableHttpServer(_Model): ... +class RetryConfig(_Model): ... +class ModelAPIRetryConfig(_Model): ... +class BudgetConfig(_Model): ... +class LocalOpenAIAgentConfig(_Model): ... +class HookResult(_Model): ... +class Text(_Model): ... +class Thought(_Model): ... +class ToolCall(_Model): ... +class ToolResult(_Model): ... + + +@dataclass +class Turn: + """One scripted turn: its steps, each ``("chunk", obj)``, ``("call", hooked ToolCall)``, ``("result", ToolResult)``, + ``("error", tool error)``, ``("sleep", seconds)`` or ``("raise", exception)``; then the conversation id and stop + reason the turn ends with.""" + + steps: list[tuple[str, Any]] = field(default_factory=list) + conversation_id: str = "conv-1" + stop_reason: StopReason = StopReason.UNSPECIFIED + + +class Agent: + turns: list[Turn] = [] + configs: list[LocalOpenAIAgentConfig] = [] + prompts: list[Any] = [] + + def __init__(self, config: LocalOpenAIAgentConfig) -> None: + self.config = config + self.conversation_id: str | None = None + + async def __aenter__(self) -> Agent: + Agent.configs.append(self.config) + return self + + async def __aexit__(self, *exc: Any) -> bool: + return False + + async def chat(self, prompt: Any) -> ChatResponse: + Agent.prompts.append(prompt) + return ChatResponse(self, Agent.turns.pop(0)) + + +class ChatResponse: + def __init__(self, agent: Agent, turn: Turn) -> None: + self._agent, self._turn = agent, turn + self.stop_reason = StopReason.UNSPECIFIED + + @property + def chunks(self): + return self._play() + + async def _play(self): + hooks = getattr(self._agent.config, "hooks", None) or [] + for kind, value in self._turn.steps: + if kind == "chunk": + yield value + elif kind == "call": + for hook in hooks: + if hook.kind == "pre": + await hook(value) + elif kind == "result": + for hook in hooks: + if hook.kind == "post": + await hook(value) + elif kind == "error": + for hook in hooks: + if hook.kind == "error": + await hook(value) + elif kind == "sleep": + await asyncio.sleep(value) + elif kind == "raise": + raise value + self._agent.conversation_id = self._turn.conversation_id + self.stop_reason = self._turn.stop_reason + + +def _hook(kind: str): + def decorate(function): + function.kind = kind + return function + return decorate + + +def install() -> None: + """Register the stand-in as ``google.antigravity`` and its submodules, beside whatever else lives under ``google``.""" + package = types.ModuleType("google.antigravity") + sdk_types = types.ModuleType("google.antigravity.types") + hooks_package = types.ModuleType("google.antigravity.hooks") + hooks = types.ModuleType("google.antigravity.hooks.hooks") + policy = types.ModuleType("google.antigravity.hooks.policy") + for name in ("BuiltinTools", "AgentBehavior", "StopReason", "BudgetScope", "AntigravityExecutionError", + "CapabilitiesConfig", "McpStreamableHttpServer", "RetryConfig", "ModelAPIRetryConfig", "BudgetConfig", + "HookResult", "Text", "Thought", "ToolCall", "ToolResult"): + setattr(sdk_types, name, globals()[name]) + package.Agent, package.LocalOpenAIAgentConfig, package.CapabilitiesConfig = ( + Agent, LocalOpenAIAgentConfig, CapabilitiesConfig) + package.types, package.hooks = sdk_types, hooks_package + hooks.pre_tool_call_decide, hooks.post_tool_call, hooks.on_tool_error = _hook("pre"), _hook("post"), _hook("error") + policy.allow_all = lambda: "allow_all" + hooks_package.hooks, hooks_package.policy = hooks, policy + sys.modules.update({"google.antigravity": package, "google.antigravity.types": sdk_types, + "google.antigravity.hooks": hooks_package, "google.antigravity.hooks.hooks": hooks, + "google.antigravity.hooks.policy": policy}) diff --git a/tst/unit/agents/antigravity/test_antigravity_bridge.py b/tst/unit/agents/antigravity/test_antigravity_bridge.py new file mode 100644 index 000000000..00b28d89a --- /dev/null +++ b/tst/unit/agents/antigravity/test_antigravity_bridge.py @@ -0,0 +1,375 @@ +"""One turn of the Antigravity SDK (antigravity_bridge): the config the SDK's ``Agent`` is started with, its model calls +through the turn's own relay with the endpoint's key and the run's attribution, a task's selection of the SDK's tools, +the trajectory the SDK's streamed steps and hooks make, a tool result tied to its streamed call, and how a turn ends.""" + +from __future__ import annotations + +import asyncio +import json +from typing import Any + +import pytest + +from agent_env.a2a_agent import A2AAgent +from agent_env.task_step.task_steps.deploy_agent import _check_builtin_tools +from tst.unit.agents.antigravity import fake_sdk +from tst.unit.agents.antigravity.agent import AGENT_DIR, a2a_server, antigravity_bridge +from tst.unit.agents.antigravity.fake_sdk import StopReason, Text, Thought, ToolCall, ToolResult, Turn + +TOOLS = fake_sdk.BuiltinTools +ALWAYS_OFF = [TOOLS.ASK_QUESTION, TOOLS.GENERATE_IMAGE] + + +class ToolError(Exception): + """What the SDK gives its ``on_tool_error`` hook.""" + + def __init__(self, message: str, call_id: str, tool_name: str, server_name: str | None = None) -> None: + super().__init__(message) + self.call_id, self.tool_name, self.server_name = call_id, tool_name, server_name + + +def _run(turn: Turn | None = None, **kwargs: Any) -> tuple[antigravity_bridge.AntigravityResult, list[dict]]: + """One turn through the bridge, its trajectory as appended.""" + if turn is not None: + fake_sdk.Agent.turns.append(turn) + events: list[dict] = [] + arguments = dict(model="m", session_id=None, mcp_servers=None, system_prompt=None, timeout_s=30, role=None, + builtin_tools=None, max_turns=None, workspace="/w", event_callback=events.append) + result = asyncio.run(antigravity_bridge.run_antigravity("go", **{**arguments, **kwargs})) + return result, events + + +def _config() -> dict: + (config,) = fake_sdk.Agent.configs + return dict(config.__dict__) + + +def test_the_sdk_is_started_with_the_relay_the_workspace_and_every_call_allowed(monkeypatch): + monkeypatch.delenv("AGENTENV_EGRESS_PROXY", raising=False) + _run(Turn()) + + config = _config() + hooks = config.pop("hooks") + assert config == { + "base_url": "http://relay.test/token/v1", "model": "m", "save_dir": str(antigravity_bridge.SAVE_DIR), + "workspaces": ["/w"], + "capabilities": fake_sdk.CapabilitiesConfig(agent_behavior=fake_sdk.AgentBehavior.AUTONOMOUS, + disabled_tools=ALWAYS_OFF), + "policies": ["allow_all"], + "retry_config": fake_sdk.RetryConfig(api_retry=fake_sdk.ModelAPIRetryConfig( + max_retries=6, initial_sleep_duration_ms=5000, exponential_multiplier=2.0)), + "env": None, "mcp_servers": [], "skills_paths": [], + } + assert [hook.kind for hook in hooks] == ["pre", "post", "error"] + assert fake_sdk.Agent.prompts == ["go"] + + +def test_the_task_settings_reach_the_sdk(): + antigravity_bridge.SKILLS_DIR.mkdir(parents=True) + servers = {"env4821": {"url": "https://gw/mcp", "headers": {"agentenv-role": "seller", "x-k": "v"}}, + "peer_agents": {"url": "http://127.0.0.1:8000/ext/peer-agents/mcp"}} + + _run(Turn(), mcp_servers=servers, role="buyer", system_prompt="be brief", max_turns=5) + + config = _config() + assert config["mcp_servers"] == [ + fake_sdk.McpStreamableHttpServer(name="env4821", url="https://gw/mcp", + headers={"x-k": "v", "AgentEnv-Role": "buyer"}, timeout=60.0, + sse_read_timeout=300.0), + fake_sdk.McpStreamableHttpServer(name="peer_agents", url="http://127.0.0.1:8000/ext/peer-agents/mcp", + headers={"AgentEnv-Role": "buyer"}, timeout=60.0, sse_read_timeout=300.0)] + assert config["skills_paths"] == [str(antigravity_bridge.SKILLS_DIR)] + assert config["system_instructions"] == "be brief" + assert config["budget_config"] == fake_sdk.BudgetConfig(max_model_calls=5, + scope=fake_sdk.BudgetScope.FORWARD_LOOKING) + + +def test_a_server_keeps_its_own_role_when_the_task_has_none(): + _run(Turn(), mcp_servers={"env": {"url": "https://gw/mcp", "headers": {"AgentEnv-Role": "seller"}}}) + + (server,) = _config()["mcp_servers"] + assert server.headers == {"AgentEnv-Role": "seller"} + + +def test_a_conversation_is_resumed_by_its_id_when_its_store_is_there(): + antigravity_bridge.SAVE_DIR.mkdir(parents=True) + (antigravity_bridge.SAVE_DIR / "conv-1.db").write_bytes(b"") + + result, _ = _run(Turn(conversation_id="conv-1"), session_id="conv-1") + + assert _config()["conversation_id"] == "conv-1" + assert result.session_id == "conv-1" + + +def test_a_conversation_whose_store_is_gone_starts_afresh(): + result, _ = _run(Turn(conversation_id="conv-new"), session_id="conv-gone") + + assert "conversation_id" not in _config() + assert result.session_id == "conv-new" + + +def test_on_an_armed_clock_the_harness_goes_out_through_the_egress_proxy(monkeypatch): + monkeypatch.setenv("AGENTENV_EGRESS_PROXY", "http://127.0.0.1:3128") + monkeypatch.setenv("LITELLM_BASE_URL", "https://gw.example/v1") + monkeypatch.setattr(antigravity_bridge, "clock_armed", lambda: True) + + _run(Turn(), mcp_servers={"env": {"url": "http://env.internal:9000/mcp"}}) + + env = _config()["env"] + assert env["HTTPS_PROXY"] == "http://127.0.0.1:3128" + assert env["NO_PROXY"].split(",")[-1] == "env.internal" + + +def test_model_calls_carry_the_endpoints_key_its_headers_and_the_runs_attribution(monkeypatch, relay): + monkeypatch.setenv("LITELLM_BASE_URL", "https://gw.example/v1/") + monkeypatch.setenv("LITELLM_API_KEY", "sk-test") + monkeypatch.setenv("LITELLM_EXTRA_HEADERS", json.dumps({"X-LiteLLM-Tags": "team:envs", "X-Extra": "1"})) + + _run(Turn(), project_id="p-1", task_id="t-1") + + (opened,) = relay + assert opened["upstream"] == "https://gw.example" + assert opened["headers"] == {"authorization": "Bearer sk-test", "x-extra": "1", "x-litellm-customer-id": "p-1", + "x-litellm-tags": "team:envs,projectId:p-1,taskId:t-1"} + assert antigravity_bridge.get_last_attribution_snapshot()["project_id"] == "p-1" + + +def test_the_turns_usage_is_the_relays_count_of_its_calls(monkeypatch, relay): + async def answered(_prompt, **_kwargs): + relay[0]["calls"].add(200, antigravity_bridge.Usage(input_tokens=10, output_tokens=2), "m") + relay[0]["calls"].add(200, None, "m") + relay[0]["calls"].add(502, None, "m") + return antigravity_bridge.AntigravityResult(response="ok", tool_call_count=3) + + monkeypatch.setattr(antigravity_bridge, "_turn", answered) + result, _ = _run() + + assert (result.usage.input_tokens, result.usage.output_tokens, result.usage.tool_call_count) == (10, 2, 3) + assert result.usage.provider_details == {"model_calls": 2, "unreported_calls": 1} + + +@pytest.mark.parametrize("selection, expected", [ + (None, {"disabled_tools": ALWAYS_OFF}), + ({"only": ["view_file", "run_command"]}, {"enabled_tools": [TOOLS.VIEW_FILE, TOOLS.RUN_COMMAND, TOOLS.FINISH]}), + ({"only": []}, {"enabled_tools": [TOOLS.FINISH]}), + ({"disable": ["search_web", "read_url_content"]}, + {"disabled_tools": [*ALWAYS_OFF, TOOLS.SEARCH_WEB, TOOLS.READ_URL_CONTENT]}), + ({"disable": "*"}, {"disabled_tools": [*ALWAYS_OFF, TOOLS.LIST_DIR, TOOLS.SEARCH_DIR, TOOLS.FIND_FILE, + TOOLS.VIEW_FILE, TOOLS.CREATE_FILE, TOOLS.EDIT_FILE, TOOLS.RUN_COMMAND, + TOOLS.INVOKE_SUBAGENT, TOOLS.RUN_WORKFLOW, TOOLS.SEARCH_WEB, + TOOLS.READ_URL_CONTENT, TOOLS.SCHEDULE]}), +]) +def test_a_selection_of_the_sdks_tools_is_its_capabilities(selection, expected): + tools = a2a_server.AntigravityConfig(builtin_tools=selection).builtin_tools + + _run(Turn(), builtin_tools=tools) + + assert _config()["capabilities"] == fake_sdk.CapabilitiesConfig( + agent_behavior=fake_sdk.AgentBehavior.AUTONOMOUS, **expected) + + +@pytest.mark.parametrize("selection, match", [ + ({"only": ["ask_question"]}, "ask_question"), + ({"disable": ["finish"]}, "finish"), + ({"only": ["generate_image"]}, "generate_image"), + ({"disable": "*", "only": ["view_file"]}, "exactly one"), +]) +def test_a_selection_of_a_tool_the_task_cant_choose_is_refused(selection, match): + with pytest.raises(ValueError, match=match): + a2a_server.AntigravityConfig(builtin_tools=selection) + + +def test_the_card_takes_builtin_tools_so_deploy_agent_accepts_a_selection(ag): + extension = A2AAgent.find_extension(ag.card, A2AAgent.EXT_AGENT_CONFIG) + + assert "builtin_tools" in extension["params"]["methods"]["set"]["request"]["supported"] + _check_builtin_tools(extension, "antigravity", {"disable": ["search_web", "read_url_content"]}) + _check_builtin_tools(extension, "antigravity", {"only": ["view_file", "run_command"]}) + with pytest.raises(RuntimeError, match="can't take builtin_tools"): + _check_builtin_tools(extension, "antigravity", {"disable": ["bash"]}) + + +def test_the_selectable_tools_are_the_sdks_but_the_ones_a_headless_run_cant_use(): + assert set(antigravity_bridge.AntigravityTool.__args__) == ( + {tool.value for tool in TOOLS} - {"ask_question", "generate_image", "finish"}) + + +def test_the_tool_names_are_those_of_the_sdk_version_requirements_pin(): + pinned = [line for line in (AGENT_DIR / "requirements.txt").read_text().splitlines() + if line.startswith("google-antigravity==")] + + assert pinned == [f"google-antigravity=={antigravity_bridge.SDK_VERSION}"], ( + "the SDK version changed: record the tools the new SDK offers in AntigravityTool, then SDK_VERSION; " + "tst/integration/agent/antigravity_env_date_test.py checks the new SDK's tool names and local-time line") + + +def test_the_answer_is_the_last_text_after_a_tool_call_and_the_steps_are_the_trajectory(): + result, events = _run(Turn(steps=[ + ("chunk", Thought(step_index=0, text="thinking")), + ("chunk", Text(step_index=0, text="Let me ")), + ("chunk", Text(step_index=0, text="check.")), + ("call", ToolCall(id="h1", name="run_command")), + ("chunk", ToolCall(id="s1", name="run_command", step_index=0)), + ("result", ToolResult(id="h1", name="run_command", result="42")), + ("chunk", Text(step_index=1, text="42")), + ], conversation_id="conv-7")) + + assert (result.response, result.session_id, result.tool_call_count, result.error) == ("42", "conv-7", 1, None) + assert events == [ + {"type": "Thought", "step_index": 0, "text": "thinking"}, + {"type": "Text", "step_index": 0, "text": "Let me check."}, + {"type": "ToolCall", "id": "s1", "name": "run_command", "step_index": 0}, + {"kind": "tool_result", "id": "h1", "name": "run_command", "result": "42", "call_ref": "s1"}, + {"type": "Text", "step_index": 1, "text": "42"}, + ] + + +def test_a_turn_that_ends_on_a_tool_call_answers_with_its_last_text(): + result, _ = _run(Turn(steps=[ + ("chunk", Text(step_index=0, text="Done: 42")), + ("call", ToolCall(id="h1", name="finish")), + ("chunk", ToolCall(id="s1", name="finish", step_index=0)), + ])) + + assert result.response == "Done: 42" + + +def test_the_answer_is_a_paragraph_per_step_after_the_last_tool_call(): + result, _ = _run(Turn(steps=[ + ("call", ToolCall(id="h1", name="run_command")), + ("chunk", ToolCall(id="s1", name="run_command", step_index=0)), + ("chunk", Text(step_index=1, text="It runs in the ")), + ("chunk", Text(step_index=1, text="background.")), + ("chunk", Text(step_index=3, text="2031-04-01")), + ])) + + assert result.response == "It runs in the background.\n\n2031-04-01" + + +def test_a_result_that_comes_before_its_streamed_call_follows_it(): + _, events = _run(Turn(steps=[ + ("call", ToolCall(id="h1", name="view_file")), + ("call", ToolCall(id="h2", name="view_file")), + ("result", ToolResult(id="h2", name="view_file", result="b")), + ("chunk", ToolCall(id="s1", name="view_file", step_index=0)), + ("chunk", ToolCall(id="s2", name="view_file", step_index=0)), + ("result", ToolResult(id="h1", name="view_file", result="a")), + ])) + + assert [(event.get("type") or event["kind"], event.get("call_ref")) for event in events] == [ + ("ToolCall", None), ("ToolCall", None), ("tool_result", "s2"), ("tool_result", "s1")] + + +def test_a_result_of_the_harnesss_own_tool_is_tied_to_its_undecided_call(): + """The SDK's skill lookup streams and gives its result to the hooks, but never asks them to decide it.""" + _, events = _run(Turn(steps=[ + ("call", ToolCall(id="m1", name="run_command")), + ("chunk", ToolCall(id="c:1", name="run_command", step_index=0)), + ("result", ToolResult(id="m1", name="run_command", result="42")), + ("chunk", ToolCall(id="c:2", name="skill_lookup", step_index=1)), + ("result", ToolResult(id="m2", name="list_skills", result="[]")), + ("call", ToolCall(id="m3", name="view_file")), + ("chunk", ToolCall(id="c:3", name="view_file", step_index=2)), + ("result", ToolResult(id="m3", name="view_file", result="text")), + ])) + + assert [(event["id"], event["call_ref"]) for event in events if event.get("kind") == "tool_result"] == [ + ("m1", "c:1"), ("m2", "c:2"), ("m3", "c:3")] + + +def test_a_call_binds_to_the_next_streamed_call_of_its_name(): + _, events = _run(Turn(steps=[ + ("call", ToolCall(id="m1", name="view_file")), + ("chunk", ToolCall(id="c:1", name="skill_lookup", step_index=0)), + ("chunk", ToolCall(id="c:2", name="view_file", step_index=0)), + ("result", ToolResult(id="m1", name="view_file", result="text")), + ("result", ToolResult(id="m2", name="list_skills", result="[]")), + ])) + + assert [(event["id"], event["call_ref"]) for event in events if event.get("kind") == "tool_result"] == [ + ("m1", "c:2"), ("m2", "c:1")] + + +def test_a_failed_tool_call_is_its_result_with_the_error(): + _, events = _run(Turn(steps=[ + ("call", ToolCall(id="h1", name="run_command")), + ("chunk", ToolCall(id="s1", name="run_command", step_index=0)), + ("error", ToolError("exit status 1", call_id="h1", tool_name="run_command")), + ])) + + assert events[-1] == {"kind": "tool_result", "id": "h1", "name": "run_command", "server_name": None, + "result": None, "error": "exit status 1", "call_ref": "s1"} + + +def test_a_result_whose_call_never_streamed_is_kept_unlinked(): + _, events = _run(Turn(steps=[ + ("call", ToolCall(id="h1", name="run_command")), + ("result", ToolResult(id="h1", name="run_command", result="x")), + ("result", ToolResult(id="h9", name="peer_agents_send", result="y")), + ])) + + assert [(event["id"], event["call_ref"]) for event in events] == [("h9", None), ("h1", None)] + + +def test_a_turn_past_its_time_fails_with_what_it_streamed_kept(): + result, events = _run(Turn(steps=[("chunk", Text(step_index=0, text="working")), ("sleep", 5)]), timeout_s=0.2) + + assert (result.error_code, result.error) == ("timeout", "the turn ran past its 0.2 s") + assert events == [{"type": "Text", "step_index": 0, "text": "working"}] + + +@pytest.mark.parametrize("message, code, infra", [ + ("MCP load failed: env4821: 502 Bad Gateway", "mcp_load_failed", True), + ("localharness exited with status 2", "antigravity_error", False), +]) +def test_a_harness_that_fails_fails_the_turn(message, code, infra): + result, _ = _run(Turn(steps=[("raise", fake_sdk.AntigravityExecutionError(message))])) + + assert (result.error_code, result.error, result.infra) == (code, message, infra) + + +@pytest.mark.parametrize("stop, code, error", [ + (StopReason.MAX_MODEL_CALLS_EXCEEDED, "max_turns_exceeded", "the turn stopped at its max_turns, 3"), + (StopReason.QUOTA_EXHAUSTED, "stopped", "the SDK stopped the turn: QUOTA_EXHAUSTED"), +]) +def test_a_turn_the_sdk_stops_fails_with_its_answer_so_far(stop, code, error): + result, _ = _run(Turn(steps=[("chunk", Text(step_index=0, text="partial"))], stop_reason=stop), max_turns=3) + + assert (result.response, result.error_code, result.error) == ("partial", code, error) + + +@pytest.mark.parametrize("effort, sent", [("low", "low"), ("high", "high"), ("xhigh", "high"), ("max", "high"), + (None, None)]) +def test_the_effort_goes_as_reasoning_effort(effort, sent): + body = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}]}).encode() + + rewritten = json.loads(asyncio.run(antigravity_bridge.turn_rewrite(effort, [])(body))) + + assert rewritten.get("reasoning_effort") == sent + + +def test_an_image_goes_with_the_turns_own_message_once(tmp_path): + image = tmp_path / "chart.png" + image.write_bytes(b"\x89PNG") + part = antigravity_bridge.media_part(str(image)) + rewrite = antigravity_bridge.turn_rewrite(None, [part]) + body = {"model": "m", "messages": [{"role": "user", "content": "earlier"}, {"role": "assistant", "content": "ok"}, + {"role": "user", "content": "look"}]} + + once = json.loads(asyncio.run(rewrite(json.dumps(body).encode()))) + twice = json.loads(asyncio.run(rewrite(json.dumps(once).encode()))) + + assert part == {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw=="}} + assert once["messages"][0]["content"] == "earlier" + assert once["messages"][2]["content"] == [{"type": "text", "text": "look"}, part] + assert twice == once + assert antigravity_bridge.media_part(str(tmp_path / "notes.txt")) is None + + +def test_an_attachment_is_named_in_the_prompt(tmp_path): + notes = tmp_path / "notes.txt" + notes.write_text("n") + + _run(Turn(), attachment_paths=[str(notes)]) + + assert fake_sdk.Agent.prompts == [f"go\n\nAttached files, also on disk for your tools:\n- {notes}"] diff --git a/tst/unit/agents/antigravity/test_antigravity_date.py b/tst/unit/agents/antigravity/test_antigravity_date.py new file mode 100644 index 000000000..e9781b2a6 --- /dev/null +++ b/tst/unit/agents/antigravity/test_antigravity_date.py @@ -0,0 +1,242 @@ +"""The env's time in Antigravity's model calls (antigravity_date): on an armed clock the turn's relay puts the env's +time, as a ``date`` started by the A2A server reads it, in the local-time line the harness, on real time, opens each +user message with, keeps the time each turn's line was given for the turns a resumed conversation sends again, and +refuses a call whose time it can't read; off the clock, or with no line to rewrite, a call goes as the harness wrote +it.""" + +from __future__ import annotations + +import asyncio +import json +import os + +import pytest + +from tst.unit.agents.antigravity.agent import antigravity_date, model_relay + +REAL = "2026-11-25T10:00:00-08:00" +EARLIER = "2026-11-25T09:00:00-08:00" + + +def _line(stamp: str) -> str: + return f"\nThe current local time is: {stamp}. This is the latest source of truth.\n" + + +def _call(*users, parts: bool = False) -> dict: + messages = [{"role": "system", "content": "You are Antigravity."}] + for text in users: + messages += [{"role": "user", "content": [{"type": "text", "text": text}] if parts else text}, + {"role": "assistant", "content": "ok"}] + return {"model": "m", "stream": True, "messages": messages[:-1]} + + +@pytest.fixture +def times(tmp_path) -> antigravity_date.EnvTimes: + return antigravity_date.EnvTimes(tmp_path / "conversations" / "env-times.json") + + +@pytest.fixture +def env_clock(tmp_path, monkeypatch): + """An armed clock whose time a stand-in ``date`` prints (``FAKE_DATE_OUT``; it fails without one), recording the + environment it got and each time it ran.""" + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + (bin_dir / "date").write_text('#!/bin/sh\nenv > "$FAKE_DATE_ENV"\necho run >> "$FAKE_DATE_RUNS"\n' + '[ "$1" = "+%Y-%m-%dT%H:%M:%S%:z" ] || exit 2\n' + '[ -n "$FAKE_DATE_SLEEP" ] && sleep "$FAKE_DATE_SLEEP"\n' + '[ -n "$FAKE_DATE_OUT" ] || { echo no clock >&2; exit 1; }\necho "$FAKE_DATE_OUT"\n') + (bin_dir / "date").chmod(0o755) + monkeypatch.setenv("PATH", f"{bin_dir}:{os.environ['PATH']}") + monkeypatch.setenv("FAKE_DATE_ENV", str(tmp_path / "date.env")) + monkeypatch.setenv("FAKE_DATE_RUNS", str(tmp_path / "date.runs")) + monkeypatch.setenv("AGENTENV_REAL_TIME", "1") + monkeypatch.setattr(antigravity_date, "clock_armed", lambda: True) + return tmp_path + + +def _rewrite(times, call: dict) -> dict: + return json.loads(asyncio.run(antigravity_date.env_time_rewrite(times)(json.dumps(call).encode()))) + + +def _runs(env_clock) -> int: + runs = env_clock / "date.runs" + return len(runs.read_text().splitlines()) if runs.exists() else 0 + + +@pytest.mark.parametrize("parts", [False, True]) +@pytest.mark.parametrize("date_out, shown", [ + ("2031-03-03T23:06:07-06:00", "2031-03-03T23:06:07-06:00"), + ("2031-03-04T05:06:07+00:00", "2031-03-04T05:06:07Z"), + ("1950-01-01T00:00:00+05:30", "1950-01-01T00:00:00+05:30"), +]) +def test_on_an_armed_clock_the_model_is_told_the_env_time_a_command_reads(env_clock, monkeypatch, times, parts, + date_out, shown): + monkeypatch.setenv("FAKE_DATE_OUT", date_out) + + call = _rewrite(times, _call(_line(REAL) + "go", parts=parts)) + + user = call["messages"][1]["content"] + assert (user[0]["text"] if parts else user) == _line(shown) + "go" + assert call["messages"][0]["content"] == "You are Antigravity." + assert list(times.all().values()) == [shown] + + +def test_date_runs_on_the_envs_clock_not_the_servers(env_clock, monkeypatch, times): + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-03T23:06:07-06:00") + + _rewrite(times, _call(_line(REAL) + "go")) + + assert "AGENTENV_REAL_TIME=" not in (env_clock / "date.env").read_text() + + +def test_a_turns_line_keeps_the_env_time_it_was_first_given(env_clock, monkeypatch, times): + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-03T23:06:07-06:00") + first = _rewrite(times, _call(_line(REAL) + "go")) + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-03T23:09:00-06:00") + + again = _rewrite(times, _call(_line(REAL) + "go")) + + assert again == first + assert _runs(env_clock) == 1 + + +def test_a_resumed_conversations_earlier_turns_keep_their_times_and_the_new_one_gets_now(env_clock, monkeypatch, + times): + times.put(antigravity_date.line_key(_line(EARLIER) + "one", EARLIER), "2031-03-02T08:00:00-06:00") + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-03T23:06:07-06:00") + + call = _rewrite(times, _call(_line(EARLIER) + "one", _line(REAL) + "two")) + + assert [call["messages"][i]["content"] for i in (1, 3)] == [_line("2031-03-02T08:00:00-06:00") + "one", + _line("2031-03-03T23:06:07-06:00") + "two"] + + +def test_two_turns_that_start_in_one_second_keep_their_own_env_times(env_clock, monkeypatch, times): + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-03T23:06:07-06:00") + _rewrite(times, _call(_line(REAL) + "one")) + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-08T09:00:00-06:00") + + call = _rewrite(times, _call(_line(REAL) + "one", _line(REAL) + "two")) + + assert [call["messages"][i]["content"] for i in (1, 3)] == [_line("2031-03-03T23:06:07-06:00") + "one", + _line("2031-03-08T09:00:00-06:00") + "two"] + + +def _ran(created: str, completed: str, output: str = "42") -> str: + return f"Created At: {created}\nCompleted At: {completed}\n\nOutput:\n{output}" + + +def _with_run(call: dict, result: str, after: int) -> dict: + """``call`` with a command's call and ``result`` after its message ``after``.""" + messages = call["messages"] + messages[after + 1:after + 1] = [ + {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": { + "name": "run_command", "arguments": "{}"}}]}, + {"role": "tool", "tool_call_id": "c1", "content": result}] + return call + + +def test_a_commands_result_is_stamped_at_the_envs_offset_keeping_its_duration(env_clock, monkeypatch, times): + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-03T23:06:07-06:00") + monkeypatch.setattr(antigravity_date, "_real_now", lambda: "2026-11-25T18:08:35+00:00") + result = _ran("2026-11-25T18:08:29Z", "2026-11-25T18:08:34Z") + + call = _rewrite(times, _with_run(_call(_line(REAL) + "go"), result, after=1)) + + assert call["messages"][-1]["content"] == _ran("2031-03-03T23:06:01-06:00", "2031-03-03T23:06:06-06:00") + assert call["messages"][1]["content"] == _line("2031-03-03T23:06:07-06:00") + "go" + assert _runs(env_clock) == 1 + + +def test_a_commands_result_keeps_its_stamps_in_later_turns(env_clock, monkeypatch, times): + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-03T23:06:07-06:00") + monkeypatch.setattr(antigravity_date, "_real_now", lambda: "2026-11-25T18:08:35+00:00") + result = _ran("2026-11-25T18:08:29Z", "2026-11-25T18:08:34Z") + first = _rewrite(times, _with_run(_call(_line(REAL) + "go"), result, after=1)) + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-09T00:00:00+00:00") + monkeypatch.setattr(antigravity_date, "_real_now", lambda: "2026-11-25T18:20:00+00:00") + later = _with_run(_call(_line(REAL) + "go", _line("2026-11-25T10:12:00-08:00") + "again"), result, after=1) + + again = _rewrite(times, later) + + assert again["messages"][3]["content"] == first["messages"][-1]["content"] + assert again["messages"][-1]["content"] == _line("2031-03-09T00:00:00Z") + "again" + + +def test_a_commands_result_from_a_turn_off_the_clock_is_left_as_written(env_clock, monkeypatch, times): + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-03T23:06:07-06:00") + result = _ran("2026-11-25T18:08:29Z", "2026-11-25T18:08:34Z") + + call = _rewrite(times, _with_run(_call(_line(EARLIER) + "one", _line(REAL) + "two"), result, after=1)) + + assert call["messages"][3]["content"] == result + + +def test_an_earlier_turn_the_agent_followed_no_clock_for_is_left_as_written(env_clock, monkeypatch, times): + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-03T23:06:07-06:00") + + call = _rewrite(times, _call(_line(EARLIER) + "one", _line(REAL) + "two")) + + assert call["messages"][1]["content"] == _line(EARLIER) + "one" + + +@pytest.mark.parametrize("environ, reason", [ + ({}, "date exited 1: no clock"), + ({"FAKE_DATE_OUT": "Wed Mar 3 23:06:07 CST 2031"}, "date printed 'Wed Mar 3 23:06:07 CST 2031'"), +]) +def test_a_call_whose_env_time_cant_be_read_is_refused(env_clock, monkeypatch, times, environ, reason): + for name, value in environ.items(): + monkeypatch.setenv(name, value) + + with pytest.raises(model_relay.Refusal, match=reason): + _rewrite(times, _call(_line(REAL) + "go")) + assert times.all() == {} + + +def test_a_date_that_hangs_is_killed_and_the_call_refused(env_clock, monkeypatch, times): + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-03T23:06:07-06:00") + monkeypatch.setenv("FAKE_DATE_SLEEP", "30") + monkeypatch.setattr(antigravity_date, "_DATE_TIMEOUT_S", 0.3) + + with pytest.raises(model_relay.Refusal, match="no answer within"): + _rewrite(times, _call(_line(REAL) + "go")) + + +def test_a_call_that_isnt_json_is_refused_on_an_armed_clock(env_clock, times): + with pytest.raises(model_relay.Refusal, match="isn't JSON"): + asyncio.run(antigravity_date.env_time_rewrite(times)(b"not json")) + + +@pytest.mark.parametrize("call", [ + _call("no local time here"), + {"model": "m", "messages": [{"role": "system", "content": _line(REAL)}]}, + [1, 2], +]) +def test_a_call_with_no_users_local_time_line_goes_as_written(env_clock, times, call): + body = json.dumps(call, indent=1).encode() + + assert asyncio.run(antigravity_date.env_time_rewrite(times)(body)) == body + assert _runs(env_clock) == 0 + + +def test_off_the_clock_a_call_goes_as_the_harness_wrote_it(monkeypatch, times): + monkeypatch.setattr(antigravity_date, "clock_armed", lambda: False) + body = b"not even json " + _line(REAL).encode() + + assert asyncio.run(antigravity_date.env_time_rewrite(times)(body)) == body + + +def test_a_snapshots_times_join_the_agents_own_which_win(times): + times.put(REAL, "own") + + times.merge({REAL: "snapshot's", EARLIER: "restored"}) + + assert times.all() == {REAL: "own", EARLIER: "restored"} + + +def test_unreadable_times_read_as_none(times): + times.path.parent.mkdir(parents=True) + times.path.write_text("[1, 2]") + assert times.all() == {} + times.path.write_text("{torn") + assert times.get(REAL) is None diff --git a/tst/unit/agents/antigravity/test_card_contract.py b/tst/unit/agents/antigravity/test_card_contract.py new file mode 100644 index 000000000..0bc2418e4 --- /dev/null +++ b/tst/unit/agents/antigravity/test_card_contract.py @@ -0,0 +1,128 @@ +"""The Agent Card agent-env negotiates against: the agent's identity and extensions, the changelog offered only where +tar can make its archives, install/v1's commands, which reach install.sh with the endpoint as environment, and the card +as an install reads it, by importing the server.""" + +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +from pathlib import Path + +import pytest + +from tst.unit.agents.antigravity.agent import AGENT_DIR, PYTHONPATH, a2a_server, antigravity_bridge +from tst.unit.agents.antigravity.conftest import Harness + +_ENDPOINT = ["litellm_api_key", "litellm_base_url", "litellm_extra_headers", "trust_env"] +REPO = Path(__file__).parents[4] + + +def _methods(card: dict) -> dict[str, list[str]]: + return {ext["uri"]: sorted((ext.get("params") or {}).get("methods") or {}) + for ext in card["capabilities"]["extensions"]} + + +def test_identity(ag): + card = ag.card + assert {key: card[key] for key in ("name", "description", "version", "defaultInputModes", "defaultOutputModes", + "skills")} == { + "name": "Antigravity", + "description": "A2A-compliant agent running Google's Antigravity SDK.", + "version": "1.0.0", + "defaultInputModes": ["text", "image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf"], + "defaultOutputModes": ["text"], + "skills": [{"id": "antigravity", "name": "antigravity", "tags": ["coding", "agent"], + "description": "Runs Google's Antigravity agent with its own tools (shell, files, subagents)."}], + } + + +def test_the_extensions_are_the_agents_and_the_attribution_probe(ag): + assert _methods(ag.card) == { + "urn:agentenv:agent-config/v1": ["get", "set"], + "urn:agentenv:mcp-config/v1": ["add", "list"], + "urn:agentenv:trajectory/v1": ["get"], + "urn:agentenv:attribution-probe/v1": ["probe"], + "urn:agentenv:install/v1": [], + "urn:agentenv:peer-agents/v1": ["list", "set"], + "urn:agentenv:triggers/v1": ["decide", "register", "state"], + "urn:agentenv:skill-config/v1": ["add", "list"], + "urn:agentenv:snapshot/v1": ["apply-changelog", "enable-changelog", "load", "save"], + "urn:agentenv:staging/v1": [], + } + + +def test_the_trajectory_is_the_sdks_native_steps_served_live(ag): + (trajectory,) = [ext for ext in ag.card["capabilities"]["extensions"] + if ext["uri"] == "urn:agentenv:trajectory/v1"] + + assert trajectory["params"]["native"] == a2a_server.TRAJECTORY_FORMAT == "antigravity-sdk/1" + + +@pytest.mark.parametrize("gnu, changelog", [(True, True), (False, False)]) +def test_the_changelog_is_offered_where_tar_is_gnu_tar(monkeypatch, gnu, changelog): + monkeypatch.setattr(a2a_server, "gnu_tar", lambda: gnu) + + methods = _methods(Harness(a2a_server.agent_for_this_host()).card)["urn:agentenv:snapshot/v1"] + + assert ("enable-changelog" in methods and "apply-changelog" in methods) is changelog + assert {"save", "load"} <= set(methods) + + +@pytest.mark.parametrize(("commands", "params"), [ + (a2a_server._INSTALL_COMMANDS, ["container", "work_dir", "agent_ctx_tar", "a2a_port", *_ENDPOINT]), + (a2a_server._INSTALL_COMMANDS_HOST, ["work_dir", "agent_ctx_tar", "a2a_port", "agent_name", *_ENDPOINT]), +]) +def test_every_install_placeholder_is_a_declared_parameter(ag, commands, params): + (install,) = [ext for ext in ag.card["capabilities"]["extensions"] if ext["uri"] == "urn:agentenv:install/v1"] + used = {name for command in commands for name in re.findall(r"\{(\w+)\}", command)} + + assert used == set(params) + assert set(install["params"]["required_params"]) | set(install["params"]["required_params_host"]) >= used + for name in ("litellm_api_key", "litellm_base_url", "litellm_extra_headers"): + assert f"{name.upper()}={{{name}}}" in commands[-1] + assert "AGENT_TRUST_ENV={trust_env}" in commands[-1] + + +@pytest.mark.asyncio +async def test_the_attribution_probe_reads_back_what_the_last_run_sent(monkeypatch, ag): + monkeypatch.setattr(antigravity_bridge, "_last_attribution", {"project_id": None, "task_id": None, + "last_seen_at_utc": None}) + antigravity_bridge._record_attribution("p-1", "t-1") + + async with ag.client() as client: + probed = (await client.post("/ext/attribution-probe")).json() + + assert probed["last_seen_attribution"] == {"project_id": "p-1", "task_id": "t-1"} + assert probed["last_seen_at_utc"] + + +def test_install_mode_reads_the_card_by_importing_agent_card(): + """agent-env's install step imports AGENT_CARD from the image with no agent environment, and parses its stdout as + the card; the SDK's stand-in takes the wheel's place.""" + script = ("from tst.unit.agents.antigravity import fake_sdk; fake_sdk.install(); 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_")}, + "PYTHONPATH": os.pathsep.join([PYTHONPATH, str(REPO)])} + out = subprocess.run([sys.executable, "-c", script], cwd=AGENT_DIR, env=env, capture_output=True, text=True, + check=True) + extensions = {ext["uri"]: ext for ext in json.loads(out.stdout.splitlines()[-1])["capabilities"]["extensions"]} + + install = extensions["urn:agentenv:install/v1"]["params"] + assert install["install_commands"] == a2a_server._INSTALL_COMMANDS + assert install["install_commands_host"] == a2a_server._INSTALL_COMMANDS_HOST + assert (install["workdir_host"], install["user_host"]) == ("/app", "root") + assert extensions["urn:agentenv:staging/v1"]["params"]["endpoint"] == "/ext/staging" + + +@pytest.mark.asyncio +async def test_errors_are_answered_with_a_detail_body(ag): + async with ag.client() as client: + response = await client.post("/ext/snapshot", json={"context_id": "never-ran", "objects": { + "trajectory": {"media_type": "application/octet-stream", "max_bytes": 1024, + "write": {"kind": "http-put", "url": "https://objects.example/o", + "expires_at": "2099-01-01T00:00:00Z"}}}}) + + assert (response.status_code, response.json()) == (404, {"detail": "No active conversation for context_id"}) diff --git a/tst/unit/agents/antigravity/test_image_contract.py b/tst/unit/agents/antigravity/test_image_contract.py new file mode 100644 index 000000000..31cf544e1 --- /dev/null +++ b/tst/unit/agents/antigravity/test_image_contract.py @@ -0,0 +1,101 @@ +"""The agent's folder is its build context: the Dockerfile copies only its own files and those shared_sources.toml takes +from agent-env's sources, installs the SDK at the version its tool names are recorded for and the protocol at or above +its floor, which a release doesn't pin, and keeps the agent's state under /data whatever the uid; install.sh carries +the same modules.""" + +from __future__ import annotations + +import ast +import re +import tomllib + +from tst.unit.agents.antigravity.agent import AGENT_DIR, antigravity_bridge + +DOCKERFILE = (AGENT_DIR / "Dockerfile").read_text() +SOURCES = AGENT_DIR.parents[2] +SHARED = tomllib.loads((AGENT_DIR / "shared_sources.toml").read_text()) +INSTALL_SH = (AGENT_DIR / "install.sh").read_text() + + +def _copied() -> list[str]: + return [name for line in re.findall(r"^COPY (?!--from=)(.+) \S+$", DOCKERFILE, re.MULTILINE) + for name in line.split()] + + +def _source(name: str): + """Where the build context's ``name`` comes from: the folder, or a folder shared_sources.toml takes from agent-env's + own sources at that name.""" + first, _, rest = name.partition("/") + return SOURCES / SHARED[first] / rest if first in SHARED else AGENT_DIR / name + + +def _in_context(name: str) -> bool: + path = _source(name) + return path.is_dir() if name.endswith("/") else path.is_file() + + +def test_every_file_the_image_copies_is_in_the_folder(): + copied = _copied() + + assert copied and all(_in_context(name) for name in copied), copied + # install.sh and run.sh are install/v1's: a build context pruned to what the Dockerfile reads keeps them so. + assert {"a2a_server.py", "antigravity_bridge.py", "antigravity_date.py", "antigravity_kit.py", "entrypoint.sh", + "install.sh", "run.sh", "requirements.txt"} <= set(copied) + + +def _imported(path) -> set[str]: + names = set() + for node in ast.walk(ast.parse(path.read_text())): + if isinstance(node, ast.Import): + names |= {alias.name.split(".")[0] for alias in node.names} + elif isinstance(node, ast.ImportFrom) and node.module: + names.add(node.module.split(".")[0]) + return names + + +def test_the_image_and_an_install_carry_every_module_the_server_imports(): + """The folder's own modules and those the build context takes from agent-env's sources, the egress rule, the clock + page's format and the model relay among them, each by its name in the context.""" + shared = {path.stem: f"{name}/{path.name}" for name, source in SHARED.items() + for path in (SOURCES / source).glob("*.py")} + modules = {**shared, **{path.stem: path.name for path in AGENT_DIR.glob("*.py")}} + needed, pending = set(), ["a2a_server"] + while pending: + if (name := modules[pending.pop()]) not in needed: + needed.add(name) + pending += _imported(_source(name)) & set(modules) + installed = set(re.search(r'^AGENT_FILES="([^"]+)"$', INSTALL_SH, re.MULTILINE).group(1).split()) + + assert {"agent_clock/agent_egress.py", "clock/clockpage.py", "model_relay/model_relay.py", + "antigravity_date.py"} <= needed + assert needed <= set(_copied()) and needed <= installed, (needed, installed) + + +def test_the_requirements_are_the_protocol_floor_the_pinned_sdk_the_relays_http_and_the_ca_bundle(): + requirements = [line for line in (AGENT_DIR / "requirements.txt").read_text().splitlines() + if line and not line.startswith("#")] + + assert requirements == ["agentenv-framework-protocol[agent]>=0.1.643", + f"google-antigravity=={antigravity_bridge.SDK_VERSION}", "aiohttp>=3.9,<4", "certifi"] + assert "pip install --no-cache-dir -r requirements.txt" in DOCKERFILE + assert "-r app/requirements.txt" in INSTALL_SH + + +def test_the_image_starts_through_cmd_which_modal_passes_its_env_to(): + assert 'CMD ["/usr/local/bin/start-agent"]' in DOCKERFILE + assert not re.search(r"^ENTRYPOINT", DOCKERFILE, re.MULTILINE) + + +def test_the_agents_home_is_fixed_under_data_whatever_the_uid(): + env = dict(re.findall(r"(\w+)=(\S+)", re.search(r"^ENV (.+)$", DOCKERFILE, re.MULTILINE).group(1))) + + assert (env["HOME"], env["A2A_PORT"], env["PYTHONPATH"]) == ("/data", "8000", "/opt/agent") + assert "poppler-utils" in DOCKERFILE + assert "ANTIGRAVITY_HOME=%s" in INSTALL_SH and "HOME=%s" in INSTALL_SH + + +def test_the_harness_follows_the_clock_only_through_what_it_starts(): + """The harness is a static binary libfaketime can't reach: the image preloads the library for what it starts, and + the server runs on real time, as every clocked agent's does.""" + assert "/etc/ld.so.preload" in DOCKERFILE + assert 'AGENTENV_REAL_TIME="1"' in (AGENT_DIR / "root.conf").read_text() diff --git a/tst/unit/agents/antigravity/test_install.py b/tst/unit/agents/antigravity/test_install.py new file mode 100644 index 000000000..59626315d --- /dev/null +++ b/tst/unit/agents/antigravity/test_install.py @@ -0,0 +1,123 @@ +"""install.sh: a host install's folder in the shared /tmp, which holds the model key, is this user's alone; the agent it +starts keeps the SDK's conversations and skills in that folder, runs from its own Python, and trusts certifi's CAs only +on a target with none of its own.""" + +from __future__ import annotations + +import os +import platform +import shutil +import stat +import subprocess +import uuid +from pathlib import Path + +import pytest + +from tst.unit.agents.antigravity.agent import AGENT_DIR + +INSTALL_SH = (AGENT_DIR / "install.sh").read_text() + + +def _install(tmp_path: Path, root_named) -> subprocess.CompletedProcess: + """``install.sh host`` from a copy of the agent's folder, with a curl that fails so it stops at its first download. + ``root_named`` is given the folder it will use, before it runs.""" + folder = tmp_path / "agent" + folder.mkdir() + shutil.copy(AGENT_DIR / "install.sh", folder / "install.sh") + (tmp_path / "bin").mkdir() + (tmp_path / "bin" / "curl").write_text("#!/bin/sh\nexit 22\n") + (tmp_path / "bin" / "curl").chmod(0o755) + agent, port, sandbox = f"t-{uuid.uuid4().hex[:8]}", "18999", f"sb-{uuid.uuid4().hex[:8]}" + root_named(Path(f"/tmp/agentenv-agent-{agent}-{port}-{sandbox}")) + return subprocess.run(["bash", str(folder / "install.sh"), "host", agent, port, str(tmp_path / "app")], + env={"PATH": f"{tmp_path / 'bin'}:/usr/bin:/bin", "HOME": str(tmp_path), + "AGENTENV_SANDBOX": sandbox}, + capture_output=True, text=True, timeout=60) + + +_LINUX_ONLY = pytest.mark.skipif(platform.system() != "Linux", reason="install.sh installs onto a Linux host only") + + +@_LINUX_ONLY +def test_a_host_install_makes_its_folder_this_users_alone(tmp_path): + roots: list[Path] = [] + try: + result = _install(tmp_path, roots.append) + (root,) = roots + assert root.is_dir() and stat.S_IMODE(root.stat().st_mode) == 0o700, result.stderr + assert root.stat().st_uid == os.getuid() + finally: + for root in roots: + shutil.rmtree(root, ignore_errors=True) + + +@_LINUX_ONLY +def test_a_host_install_refuses_a_folder_it_did_not_make_in_its_place(tmp_path): + planted = tmp_path / "elsewhere" + planted.mkdir() + roots: list[Path] = [] + + def plant(root: Path) -> None: + root.symlink_to(planted) # as another user could, pointing where they read + roots.append(root) + + try: + result = _install(tmp_path, plant) + finally: + for root in roots: + root.unlink() + + assert result.returncode == 1 and "isn't a folder of this user's own" in result.stderr, result.stderr + assert not any(planted.iterdir()) + + +def test_an_installed_agent_runs_from_its_own_python_with_its_state_in_its_folder(): + run_sh = (AGENT_DIR / "run.sh").read_text() + + assert 'export PATH="$root/bin:$PATH:$root/venv/bin" PYTHONPATH="$root/app"' in run_sh + assert 'exec "$root/venv/bin/uvicorn" a2a_server:app' in run_sh + assert "ANTIGRAVITY_WORKSPACE_DIR=%s\\nANTIGRAVITY_HOME=%s\\nHOME=%s" in INSTALL_SH + assert '"$(quoted "$root/data/.antigravity")" "$(quoted "$root/data")"' in INSTALL_SH + assert 'on "rm -rf $r/data && mkdir -p $r/bin $r/app $r/data' in INSTALL_SH + + +CERTIFI = "SSL_CERT_FILE='/opt/agent/venv/lib/python3.12/site-packages/certifi/cacert.pem'\n" + + +@pytest.mark.parametrize("bundle, content, trust, written", [ + (None, "", "", CERTIFI), + ("etc/ssl/certs/ca-certificates.crt", "PEM", "", ""), + ("etc/pki/tls/certs/ca-bundle.crt", "PEM", "", ""), + ("etc/ssl/cert.pem", "PEM", "", ""), + ("etc/ssl/certs/ca-certificates.crt", "", "", CERTIFI), + (None, "", "SSL_CERT_FILE='/trust/ca-bundle.pem'", ""), +], ids=["no-bundle", "debian-bundle", "rhel-bundle", "alpine-bundle", "an-empty-bundle", "trust-lines-name-one"]) +def test_an_installed_agent_trusts_certifis_cas_only_on_a_target_with_none_and_no_bundle_named( + tmp_path, bundle, content, trust, written): + """The relay and the harness read the system's CA certificates: the agent's environment names certifi's only where + the target has no bundle and the trust lines name none.""" + if bundle: + (tmp_path / bundle).parent.mkdir(parents=True) + (tmp_path / bundle).write_text(content) + + assert _ca_line(tmp_path, trust) == written + + +def _ca_line(target: Path, trust: str) -> str: + """What install.sh writes to the agent's environment for its CA bundle, its decision run against a target whose + ``/etc`` is ``target``'s.""" + lines = INSTALL_SH.splitlines() + quoted = next(line for line in lines if line.startswith("quoted() {")) + decision = INSTALL_SH[INSTALL_SH.index("certifi=$root/venv"):] + decision = decision[:decision.index("needs_cas= ;; esac") + len("needs_cas= ;; esac")] + written = next(line.strip() for line in lines if '"$needs_cas" ] || printf' in line) + on = f'on() {{ sh -c "$(printf %s "$1" | sed "s#/etc/#{target}/etc/#g")"; }}' + script = "\n".join([quoted, on, "root=/opt/agent PYTHON_VERSION=3.12", decision, written]) + return subprocess.run(["bash", "-c", script], env={"PATH": "/usr/bin:/bin", "AGENT_TRUST_ENV": trust}, + capture_output=True, text=True, check=True).stdout + + +def test_uv_is_pinned_by_version_and_checksum(): + assert "UV_VERSION=0.13.1" in INSTALL_SH + assert 'checked "$stage/$uv_archive" "$uv_sha256"' in INSTALL_SH diff --git a/tst/unit/agents/antigravity/test_message_contract.py b/tst/unit/agents/antigravity/test_message_contract.py new file mode 100644 index 000000000..a9a903701 --- /dev/null +++ b/tst/unit/agents/antigravity/test_message_contract.py @@ -0,0 +1,273 @@ +"""What a turn hands the SDK and when it runs: turns of different contexts at once and a context's own one at a time, +each resuming the conversation the last one left; a snapshot alone; the task's config, attachments and MCP servers; +and how a turn's answer, usage and failure reach the A2A task.""" + +from __future__ import annotations + +import asyncio + +import pytest +from agentenv_protocol.a2a_agent import Uploaded + +from tst.unit.agents.antigravity import fake_sdk +from tst.unit.agents.antigravity.agent import a2a_server, antigravity_bridge, antigravity_kit +from tst.unit.agents.antigravity.fake_sdk import Text, ToolCall, Turn + + +def result(**fields) -> antigravity_bridge.AntigravityResult: + """What run_antigravity returns, a finished turn's by default.""" + return antigravity_bridge.AntigravityResult(**{"response": "done", "session_id": "conv-1", **fields}) + + +class Turns: + """Stand in for run_antigravity: each call's arguments, held until ``release`` when it is set.""" + + def __init__(self) -> None: + self.calls: list[dict] = [] + self.release: asyncio.Event | None = None + self.answer = lambda kwargs: result(session_id=kwargs["session_id"] or f"conv-{len(self.calls)}") + + async def __call__(self, prompt: str, **kwargs): + self.calls.append({"prompt": prompt, **kwargs}) + if self.release is not None: + await self.release.wait() + return self.answer(kwargs) + + +@pytest.fixture +def turns(monkeypatch) -> Turns: + stand_in = Turns() + monkeypatch.setattr(a2a_server, "run_antigravity", stand_in) + return stand_in + + +async def _until(condition, seconds: float = 5) -> None: + async with asyncio.timeout(seconds): + while not condition(): + await asyncio.sleep(0.01) + + +def _status(task: dict) -> tuple[str, list[dict]]: + return task["status"]["state"], task["status"]["message"]["parts"] + + +@pytest.mark.asyncio +async def test_a_turns_answer_and_usage_are_the_tasks(ag): + fake_sdk.Agent.turns.append(Turn(steps=[ + ("chunk", Text(step_index=0, text="checking")), + ("call", ToolCall(id="h1", name="run_command")), + ("chunk", ToolCall(id="s1", name="run_command", step_index=0)), + ("chunk", Text(step_index=1, text="42")), + ])) + async with ag.client() as client: + task = await ag.send(client, "what is 6 * 7?") + + state, parts = _status(task) + assert (state, parts[0]["text"]) == ("completed", "42") + assert parts[1]["data"]["usage"]["tool_call_count"] == 1 + assert fake_sdk.Agent.prompts == ["what is 6 * 7?"] + + +@pytest.mark.asyncio +async def test_a_contexts_next_turn_resumes_its_conversation_and_another_contexts_starts_its_own(ag, folders): + fake_sdk.Agent.turns.extend([Turn(conversation_id="conv-a"), Turn(conversation_id="conv-a"), + Turn(conversation_id="conv-b")]) + async with ag.client() as client: + await ag.send(client, "one", "ctx-a") + (antigravity_bridge.SAVE_DIR / "conv-a.db").write_bytes(b"") + await ag.send(client, "two", "ctx-a") + await ag.send(client, "three", "ctx-b") + + assert [config.__dict__.get("conversation_id") for config in fake_sdk.Agent.configs] == [None, "conv-a", None] + assert ag.agent.session_ref_for_context("ctx-b") == "conv-b" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("raised, code, error_type", [ + (fake_sdk.AntigravityExecutionError("MCP load failed: env: 502"), "mcp_load_failed", "infra_error"), + (fake_sdk.AntigravityExecutionError("localharness exited 2"), "antigravity_error", "agent_error"), +]) +async def test_a_failed_turn_fails_the_task_with_its_code(ag, raised, code, error_type): + fake_sdk.Agent.turns.append(Turn(steps=[("raise", raised)])) + async with ag.client() as client: + task = await ag.send(client, "go") + + state, parts = _status(task) + assert (state, parts[0]["text"]) == ("failed", str(raised)) + errors = [part["data"] for part in parts if part.get("kind") == "data" and "error_code" in part["data"]] + assert {"error_type": "antigravity_error", "error_code": code, "error_message": str(raised)} in errors + assert any(part["data"].get("error_type") == error_type for part in parts if part.get("kind") == "data") + + +@pytest.mark.asyncio +async def test_a_turn_the_bridge_cant_run_is_an_infra_failure(monkeypatch, ag): + async def broken(_prompt, **_kwargs): + raise RuntimeError("relay port in use") + + monkeypatch.setattr(a2a_server, "run_antigravity", broken) + async with ag.client() as client: + task = await ag.send(client, "go") + + state, parts = _status(task) + assert (state, parts[0]["text"]) == ("failed", "Antigravity invocation failed") + assert any(part["data"].get("error_type") == "infra_error" for part in parts if part.get("kind") == "data") + + +@pytest.mark.asyncio +async def test_turns_of_different_contexts_run_at_once(ag, turns): + turns.release = asyncio.Event() + async with ag.client() as client: + sent = [asyncio.create_task(ag.send(client, "go", context_id)) for context_id in ("ctx-a", "ctx-b")] + await _until(lambda: len(turns.calls) == 2) + turns.release.set() + tasks = await asyncio.gather(*sent) + + assert [task["status"]["state"] for task in tasks] == ["completed", "completed"] + + +@pytest.mark.asyncio +async def test_a_contexts_turns_run_one_at_a_time_each_resuming_the_last(ag, turns): + turns.release = asyncio.Event() + async with ag.client() as client: + first = asyncio.create_task(ag.send(client, "one")) + await _until(lambda: len(turns.calls) == 1) + second = asyncio.create_task(ag.send(client, "two")) + await asyncio.sleep(0.1) + running_together = len(turns.calls) + turns.release.set() + await asyncio.gather(first, second) + + assert running_together == 1 + assert [call["session_id"] for call in turns.calls] == [None, "conv-1"] + + +@pytest.mark.asyncio +async def test_a_snapshot_waits_for_running_turns_and_holds_new_ones_back(monkeypatch, ag, turns): + antigravity_bridge.SAVE_DIR.mkdir(parents=True, exist_ok=True) + (antigravity_bridge.SAVE_DIR / "conv-a.db").write_bytes(b"db") + ag.agent.set_session_ref_for_context("ctx-a", "conv-a") + archived = asyncio.Event() + archive = a2a_server._archive_conversation + + def archiving(conversation_id, path): + archived.set() + archive(conversation_id, path) + + async def upload(_target, source): + return Uploaded(size_bytes=1) + + monkeypatch.setattr(a2a_server, "_archive_conversation", archiving) + monkeypatch.setattr(a2a_server, "upload", upload) + turns.release = asyncio.Event() + async with ag.client() as client: + running = asyncio.create_task(ag.send(client, "go", "ctx-b")) + await _until(lambda: len(turns.calls) == 1) + save = asyncio.create_task(client.post("/ext/snapshot", json={"context_id": "ctx-a", "objects": { + "trajectory": _WRITE}})) + await asyncio.sleep(0.1) + held = asyncio.create_task(ag.send(client, "go", "ctx-c")) + await asyncio.sleep(0.1) + while_running = (archived.is_set(), len(turns.calls)) + turns.release.set() + saved = await save + await asyncio.gather(running, held) + + assert while_running == (False, 1) + assert saved.status_code == 200, saved.text + assert len(turns.calls) == 2 + + +@pytest.mark.asyncio +async def test_the_turns_config_and_workspace_reach_the_sdk(ag, turns, folders): + config = {"model": "provider/model", "effort": "high", "system_prompt": "be brief", "project_id": "p-1", + "task_id": "t-1", "role": "solver", "timeout_seconds": 42, "max_turns": 45, + "builtin_tools": {"disable": ["search_web", "read_url_content"]}} + async with ag.client() as client: + assert (await client.post("/ext/agent-config", json=config)).status_code == 200 + await ag.send(client, "go") + + (call,) = turns.calls + assert {key: call[key] for key in ("prompt", "model", "effort", "system_prompt", "project_id", "task_id", "role", + "timeout_s", "workspace", "max_turns")} == { + "prompt": "go", "model": "provider/model", "effort": "high", "system_prompt": "be brief", + "project_id": "p-1", "task_id": "t-1", "role": "solver", "timeout_s": 42, "workspace": str(folders), + "max_turns": 45} + assert call["builtin_tools"].disable == ["search_web", "read_url_content"] + + +@pytest.mark.asyncio +async def test_a_turn_gets_the_sdks_peer_tools_with_its_registered_servers(monkeypatch, ag, turns): + monkeypatch.setenv("A2A_PORT", "8000") + async with ag.client() as client: + added = await client.post("/ext/mcp-config", json={"name": "env", "url": "https://mcp.example/mcp", + "headers": {"X-Key": "k"}}) + await ag.send(client, "go") + + assert added.status_code == 200, added.text + (call,) = turns.calls + assert call["mcp_servers"]["env"] == {"url": "https://mcp.example/mcp", "headers": {"X-Key": "k"}} + assert call["mcp_servers"]["peer_agents"] == {"url": "http://127.0.0.1:8000/ext/peer-agents/mcp", "headers": None} + + +@pytest.mark.asyncio +async def test_a_timed_out_turn_keeps_the_conversation_it_started_for_the_next(ag, turns): + turns.answer = lambda kwargs: ( + result(response="", error="the turn ran past its 1 s", error_code="timeout", session_id="conv-started") + if not kwargs["session_id"] else result(session_id=kwargs["session_id"])) + async with ag.client() as client: + timed_out = await ag.send(client, "one") + await ag.send(client, "two") + + assert timed_out["status"]["state"] == "failed" + assert [call["session_id"] for call in turns.calls] == [None, "conv-started"] + + +@pytest.mark.asyncio +async def test_a_file_part_is_written_under_the_task_and_attached(ag, turns, folders): + parts = [{"kind": "text", "text": "describe"}, + {"kind": "file", "file": {"name": "../a b.png", "mimeType": "image/png", "bytes": "cG5n"}}] + async with ag.client() as client: + task = await ag.send(client, parts) + + (call,) = turns.calls + (attached,) = call["attachment_paths"] + assert attached == str(folders / "inputs" / task["id"] / "a_b.png") + assert open(attached, "rb").read() == b"png" + + +@pytest.mark.asyncio +async def test_an_unreadable_file_part_fails_the_turn_before_the_sdk_runs(ag, turns): + parts = [{"kind": "file", "file": {"name": "a.png", "mimeType": "image/png", "bytes": "not base64!"}}] + async with ag.client() as client: + task = await ag.send(client, parts) + + assert task["status"]["state"] == "failed" and turns.calls == [] + + +@pytest.mark.asyncio +async def test_an_inline_skill_without_frontmatter_gets_one_from_its_name(ag): + async with ag.client() as client: + added = await client.post("/ext/skill-config", json={"name": "report", "description": "Write the\nreport.", + "skill_md": "# Report\nSteps."}) + listed = await client.get("/ext/skill-config") + + assert added.status_code == 200, added.text + assert (antigravity_bridge.SKILLS_DIR / "report" / "SKILL.md").read_text() == ( + '---\nname: "report"\ndescription: "Write the report."\n---\n\n# Report\nSteps.') + assert "report" in listed.json()["skills"] + + +def test_a_skill_with_its_own_frontmatter_is_written_as_given(): + written = "---\nname: mine\ndescription: d\n---\nbody" + + assert antigravity_kit.with_frontmatter(written, "other", "x") == written + assert antigravity_kit.with_frontmatter("body", 'a "quoted" name', None).startswith( + '---\nname: "a \\"quoted\\" name"\ndescription: "a \\"quoted\\" name"\n---') + + +def test_conversation_references_outlive_the_frameworks_bounded_record(): + assert issubclass(a2a_server.AntigravityAgent, antigravity_kit.DurableSessionRefs) + + +_GRANT = {"expires_at": "2099-01-01T00:00:00Z", "url": "https://objects.example/o"} +_WRITE = {"media_type": "application/octet-stream", "max_bytes": 1024, "write": {"kind": "http-put", **_GRANT}} diff --git a/tst/unit/agents/antigravity/test_snapshot.py b/tst/unit/agents/antigravity/test_snapshot.py new file mode 100644 index 000000000..ab15d16e9 --- /dev/null +++ b/tst/unit/agents/antigravity/test_snapshot.py @@ -0,0 +1,126 @@ +"""snapshot/v1: a context's conversation, its SDK store whole with the env times its turns were given, and the +workspace, saved and loaded into another context under the conversation's own id; an archive that doesn't hold one is +refused.""" + +from __future__ import annotations + +import io +import json +import tarfile +from pathlib import Path + +import pytest +from agentenv_protocol.a2a_agent import Uploaded + +from tst.unit.agents.antigravity.agent import a2a_server, antigravity_bridge + +_GRANT = {"expires_at": "2099-01-01T00:00:00Z", "url": "https://objects.example/o"} +_WRITE = {"media_type": "application/octet-stream", "max_bytes": 1 << 20, "write": {"kind": "http-put", **_GRANT}} +_READ = {"media_type": "application/octet-stream", "max_bytes": 1 << 20, "size_bytes": 2, + "read": {"kind": "http-get", **_GRANT}} + + +@pytest.fixture +def objects(monkeypatch) -> dict[str, bytes]: + """The objects a snapshot uploads, by the name of the file it uploaded, and loads back by the name it downloads + to.""" + stored: dict[str, bytes] = {} + + async def upload(_target, source: Path): + stored[source.name] = source.read_bytes() + return Uploaded(size_bytes=len(stored[source.name])) + + async def download(_source, destination: Path): + destination.write_bytes(stored[destination.name]) + + monkeypatch.setattr(a2a_server, "upload", upload) + monkeypatch.setattr(a2a_server, "download", download) + return stored + + +def _members(archive: bytes) -> list[str]: + with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as tar: + return sorted(tar.getnames()) + + +@pytest.mark.asyncio +async def test_a_conversation_and_its_workspace_load_into_another_context(ag, objects, folders): + store = antigravity_bridge.SAVE_DIR + store.mkdir(parents=True) + (store / "conv-1.db").write_bytes(b"sqlite") + (store / "conv-1.db-wal").write_bytes(b"wal") + (store / "conv-2.db").write_bytes(b"another") + antigravity_bridge.ENV_TIMES.put("2026-11-25T10:00:00-08:00", "2031-03-03T23:06:07-06:00") + (folders / "report.md").write_text("draft") + ag.agent.set_session_ref_for_context("ctx-source", "conv-1") + + async with ag.client() as client: + saved = await client.post("/ext/snapshot", json={"context_id": "ctx-source", "objects": { + "trajectory": _WRITE, "workspace": _WRITE}}) + assert saved.status_code == 200, saved.text + assert _members(objects["conversation.tgz"]) == ["env-times.json", "manifest.json", "store/conv-1.db", + "store/conv-1.db-wal"] + for path in store.iterdir(): + path.unlink() + (folders / "report.md").write_text("changed since") + (folders / "stray.txt").write_text("stray") + + loaded = await client.put("/ext/snapshot", json={"target_context_id": "ctx-target", "objects": { + "trajectory": _READ, "workspace": _READ}}) + + assert loaded.status_code == 200, loaded.text + assert loaded.json() == {"context_id": "ctx-target"} + assert ag.agent.session_ref_for_context("ctx-target") == "conv-1" + assert {path.name: path.read_bytes() for path in store.glob("conv-*")} == {"conv-1.db": b"sqlite", + "conv-1.db-wal": b"wal"} + assert antigravity_bridge.ENV_TIMES.all() == {"2026-11-25T10:00:00-08:00": "2031-03-03T23:06:07-06:00"} + assert sorted(path.name for path in folders.iterdir()) == ["report.md"] + assert (folders / "report.md").read_text() == "draft" + + +@pytest.mark.asyncio +async def test_a_loaded_conversation_replaces_a_stale_store_of_its_own(ag, objects): + store = antigravity_bridge.SAVE_DIR + store.mkdir(parents=True) + (store / "conv-1.db").write_bytes(b"saved") + ag.agent.set_session_ref_for_context("ctx", "conv-1") + async with ag.client() as client: + await client.post("/ext/snapshot", json={"context_id": "ctx", "objects": {"trajectory": _WRITE}}) + (store / "conv-1.db").write_bytes(b"later") + (store / "conv-1.db-shm").write_bytes(b"stale") + loaded = await client.put("/ext/snapshot", json={"objects": {"trajectory": _READ}}) + + assert loaded.status_code == 200, loaded.text + assert {path.name: path.read_bytes() for path in store.glob("conv-1.db*")} == {"conv-1.db": b"saved"} + assert ag.agent.session_ref_for_context(loaded.json()["context_id"]) == "conv-1" + + +def _archive(members: dict[str, bytes]) -> bytes: + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:gz") as tar: + for name, data in members.items(): + info = tarfile.TarInfo(name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + return buffer.getvalue() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("archive, detail", [ + (_archive({"store/conv-1.db": b"db"}), "snapshot has no conversation manifest"), + (_archive({"manifest.json": json.dumps({"conversation_id": "../conv-1"}).encode()}), + "snapshot names no valid conversation id"), + (_archive({"manifest.json": json.dumps({"conversation_id": "conv-1"}).encode()}), + "snapshot has no store for its conversation"), + (_archive({"manifest.json": json.dumps({"conversation_id": "conv-1"}).encode(), "../escape.db": b"x"}), + "snapshot's conversation isn't an archive this agent reads"), + (b"not a tarball", "snapshot's conversation isn't an archive this agent reads"), +], ids=["no-manifest", "id-outside-the-store", "no-store", "member-outside", "not-an-archive"]) +async def test_an_archive_without_a_conversation_is_refused(ag, objects, archive, detail): + objects["conversation.tgz"] = archive + async with ag.client() as client: + loaded = await client.put("/ext/snapshot", json={"target_context_id": "ctx", "objects": { + "trajectory": _READ}}) + + assert (loaded.status_code, loaded.json()) == (400, {"detail": detail}) + assert ag.agent.session_ref_for_context("ctx") is None diff --git a/tst/unit/agents/test_host_workdir.py b/tst/unit/agents/test_host_workdir.py index c1a84908b..2ede2ff8a 100644 --- a/tst/unit/agents/test_host_workdir.py +++ b/tst/unit/agents/test_host_workdir.py @@ -3,6 +3,7 @@ import pytest +from tst.unit.agents.antigravity.agent import a2a_server as antigravity from tst.unit.agents.claude_code.agent import a2a_server as claude_code from tst.unit.agents.codex.agent import a2a_server as codex from tst.unit.agents.gemini.agent import a2a_server as gemini @@ -11,7 +12,8 @@ INSTALL_V1 = "urn:agentenv:install/v1" -@pytest.mark.parametrize("server", [claude_code, codex, gemini, opencode], ids=["claude-code", "codex", "gemini", "opencode"]) +@pytest.mark.parametrize("server", [antigravity, claude_code, codex, gemini, opencode], + ids=["antigravity", "claude-code", "codex", "gemini", "opencode"]) def test_an_agent_declares_the_host_folder_its_own_host_install_works_in(server): card = server.AGENT_CARD.model_dump(mode="json", by_alias=True, exclude_none=True) (params,) = [ext["params"] for ext in card["capabilities"]["extensions"] if ext["uri"] == INSTALL_V1] diff --git a/tst/unit/agents/test_installed_control_token.py b/tst/unit/agents/test_installed_control_token.py index 90f03abf4..34fea6e14 100644 --- a/tst/unit/agents/test_installed_control_token.py +++ b/tst/unit/agents/test_installed_control_token.py @@ -23,7 +23,7 @@ def _sources(agent: str) -> dict[str, str]: def test_the_bundled_agents_that_install_are_the_ones_this_test_knows(): - assert INSTALLABLE == ["claude-code", "codex", "gemini", "letta-code", "opencode", "openhands", "pi", "proxy", + assert INSTALLABLE == ["antigravity", "claude-code", "codex", "gemini", "letta-code", "opencode", "openhands", "pi", "proxy", "pydantic-ai"] diff --git a/tst/unit/agents/test_trajectory_formats.py b/tst/unit/agents/test_trajectory_formats.py index d7b6d37a0..69fe7c4c9 100644 --- a/tst/unit/agents/test_trajectory_formats.py +++ b/tst/unit/agents/test_trajectory_formats.py @@ -17,6 +17,7 @@ #: The agents with an ATIF adapter, whose cards offer atif/1 beside native. SERVES_ATIF = {"claude-code"} AGENTS = { + "antigravity": ("antigravity-sdk/1", "tst.unit.agents.antigravity.agent", "a2a_server"), "claude-code": ("claude-code-stream-json/1", "tst.unit.agents.claude_code.agent", "a2a_server"), "codex": ("codex-exec-json/1", "tst.unit.agents.codex.agent", "a2a_server"), "gemini": ("gemini-stream-json/1", "tst.unit.agents.gemini.agent", "a2a_server"), diff --git a/tst/unit/bundle/shipped_bundles_test.py b/tst/unit/bundle/shipped_bundles_test.py index e8ad09b89..6410c26ad 100644 --- a/tst/unit/bundle/shipped_bundles_test.py +++ b/tst/unit/bundle/shipped_bundles_test.py @@ -49,7 +49,8 @@ def test_the_shipped_aliases_are_agent_envs_alone_and_claude_code_names_the_defa "gemini": "@local/agentenv-framework/agents/gemini", "opencode": "@local/agentenv-framework/agents/opencode", "letta-code": "@local/agentenv-framework/agents/letta-code", "pydantic-ai": "@local/agentenv-framework/agents/pydantic-ai", "hermes": "@local/agentenv-framework/agents/hermes", - "browser-use": "@local/agentenv-framework/agents/browser-use"} + "browser-use": "@local/agentenv-framework/agents/browser-use", + "antigravity": "@local/agentenv-framework/agents/antigravity"} assert table.target("claude-code").target_id == get_config().get_default_a2a_agent_id() diff --git a/tst/unit/test_infra_build_script.py b/tst/unit/test_infra_build_script.py index 8832fff50..f14048494 100644 --- a/tst/unit/test_infra_build_script.py +++ b/tst/unit/test_infra_build_script.py @@ -289,7 +289,7 @@ def test_verify_record_refuses_a_digest_the_registry_doesnt_serve_under_its_tag( @pytest.mark.parametrize("record, problem", [ - ({"images": []}, "records no agentenv-browser-use, agentenv-claude-code, agentenv-codex"), + ({"images": []}, "records no agentenv-antigravity, agentenv-browser-use, agentenv-claude-code"), ({"images": [], "extra": 1}, "it holds ['extra', 'images']"), ({"images": [{"repository": "ghcr.io/someone/thing", "tag": _TAG, "digest": _DIGEST}]}, "'ghcr.io/someone/thing' isn't an image agent-env ships"), diff --git a/tst/unit/test_infra_images_script.py b/tst/unit/test_infra_images_script.py index 2e70d6927..3ccf7300d 100644 --- a/tst/unit/test_infra_images_script.py +++ b/tst/unit/test_infra_images_script.py @@ -74,8 +74,8 @@ def test_plan_only_lists_the_infra_images_the_agents_images_or_the_disk_forms(sc "forms"]["disk"]["min_disk_gb"])} assert "args" not in planned["infra"][0] assert "agentenv-gateway" in names["infra"] and bundles == [ - "agentenv-browser-use", "agentenv-claude-code", "agentenv-codex", "agentenv-gemini", "agentenv-hermes", - "agentenv-letta-code", "agentenv-opencode", "agentenv-openhands", "agentenv-pi", "agentenv-proxy", + "agentenv-antigravity", "agentenv-browser-use", "agentenv-claude-code", "agentenv-codex", "agentenv-gemini", + "agentenv-hermes", "agentenv-letta-code", "agentenv-opencode", "agentenv-openhands", "agentenv-pi", "agentenv-proxy", "agentenv-pydantic-ai", "agentenv-mail-mcp", "agentenv-ubuntu-24.04", "agentenv-ubuntu-24.04-browser"] From 8328bfcaa2c1adc86d826e97970e3148f6e78fb1 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Wed, 25 Nov 2026 11:11:10 -0800 Subject: [PATCH 2/3] fix(agents): Antigravity keeps a failed turn's conversation and its turns' images A turn that times out or fails after the SDK started its conversation leaves it for the next: the SDK names it with the turn's first streamed step, which the bridge now reads then, not only once the stream drains. A turn's images are recorded by the message they came with, so later turns, which the harness sends from a store that never saw them, carry them too. A snapshot whose conversation another context of the agent holds is refused rather than shared, since the SDK keys its store by an id inside it. A turn's own local-time line is read afresh once per turn, so a message identical to an earlier one in the same second never reuses its time. A SKILL.md that opens with a horizontal rule gets frontmatter. The release smoke starts the harness. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/infra_build.py | 7 +- .../agents/agents/antigravity/README.md | 7 +- .../agents/agents/antigravity/a2a_server.py | 34 ++++-- .../agents/antigravity/antigravity_bridge.py | 115 ++++++++++++------ .../agents/antigravity/antigravity_date.py | 43 ++++--- .../agents/antigravity/antigravity_kit.py | 15 ++- .../agent/antigravity_env_date_test.py | 40 ++++-- tst/unit/agents/antigravity/conftest.py | 4 +- tst/unit/agents/antigravity/fake_sdk.py | 2 + .../antigravity/test_antigravity_bridge.py | 55 +++++++-- .../antigravity/test_antigravity_date.py | 22 +++- .../antigravity/test_message_contract.py | 6 + tst/unit/agents/antigravity/test_snapshot.py | 35 +++++- 13 files changed, 279 insertions(+), 106 deletions(-) diff --git a/.github/scripts/infra_build.py b/.github/scripts/infra_build.py index 4f6f562b8..af3cf8157 100644 --- a/.github/scripts/infra_build.py +++ b/.github/scripts/infra_build.py @@ -109,7 +109,8 @@ # Each image's check, beyond its build: the gateway imports its server, Postgres turns healthy, the sidecars and the # browser answer their own commands, Claude Code's, Codex's, Gemini's, Hermes', OpenCode's and pi's agents run their -# CLIs and import their servers, Antigravity's runs its SDK's harness and imports its server, OpenHands' imports its server, which loads the OpenHands SDK, Pydantic AI's imports its +# CLIs and import their servers, Antigravity's imports its server and starts its SDK's harness, which refuses the +# config it isn't given, OpenHands' imports its server, which loads the OpenHands SDK, Pydantic AI's imports its # server, which loads Pydantic AI, Browser Use's loads browser-use in its own environment and imports its server, the proxy imports its # server, the mail example's env imports its server, and the base computer's desktop comes up, every program running. _SMOKES = { @@ -122,7 +123,9 @@ "agentenv-claude-code": ["docker", "run", "--rm", "--entrypoint", "sh", "{image}", "-c", 'claude --version && python -c "import a2a_server"'], "agentenv-antigravity": ["docker", "run", "--rm", "--entrypoint", "sh", "{image}", "-c", - 'python -c "import a2a_server"'], + 'python -c "import a2a_server" && "$(python -c "import google.antigravity as ag, pathlib; ' + 'print(pathlib.Path(ag.__file__).parent / \'bin\' / \'localharness\')")" < /dev/null 2>&1 ' + '| grep -q "Failed to read InputConfig"'], "agentenv-browser-use": ["docker", "run", "--rm", "--entrypoint", "sh", "{image}", "-c", '/opt/browser-use/bin/python -c "import agent" && python -c "import a2a_server"'], "agentenv-codex": ["docker", "run", "--rm", "--entrypoint", "sh", "{image}", "-c", diff --git a/src/agent_env/agents/agents/antigravity/README.md b/src/agent_env/agents/agents/antigravity/README.md index 9614fe806..6ccce2081 100644 --- a/src/agent_env/agents/agents/antigravity/README.md +++ b/src/agent_env/agents/agents/antigravity/README.md @@ -9,7 +9,8 @@ Each task is one `Agent.chat()` of the SDK in the A2A server's process, in `/app `localharness`, a static Go binary that runs the tools and calls the model. A context's first task starts an SDK conversation, and each later task resumes it by its id; the SDK keeps each conversation in a SQLite store under `$ANTIGRAVITY_HOME/conversations/`. Text parts are the prompt, and file parts are written under `/app/inputs//` -and named in it; an image goes to the model inline too, and a PDF as its pages' PNGs, rendered with `pdftoppm`. Turns of +and named in it; an image goes to the model inline too, with its message in every later turn, and a PDF as its +pages' PNGs, rendered with `pdftoppm`. Turns of different contexts run at once, a context's turns one at a time. The SDK's `LocalOpenAIAgentConfig` takes a chat-completions `base_url` and nothing else for the endpoint, and its @@ -20,7 +21,7 @@ shared with other agents), which forwards each call to `$LITELLM_BASE_URL/v1/cha `task_id` as `x-litellm-customer-id` and `x-litellm-tags`. The run's tags join an `x-litellm-tags` that `[model.headers]` names; - the task's `effort` as `reasoning_effort` (`xhigh` and `max` as `high`) and its images, which the SDK has no setting - for; + for, recorded by the message they came with so the turns after carry them too; - the env's time in the harness's "The current local time is" line while the agent follows an armed clock (below). The relay counts each call from the answer's usage, every subagent's included, so the task's `Usage` is their sum; the @@ -41,7 +42,7 @@ The rest of each task's config: | `mcp-config/v1` | SDK default; each server passed to the task's harness. One that fails to start fails the task with `mcp_load_failed`, an infra error | | `skill-config/v1` | inline and bundle skills installed as `$ANTIGRAVITY_HOME/skills//`, the harness's skills path; an inline `SKILL.md` without frontmatter gets one from the skill's name and description, since the SDK lists a skill by its frontmatter alone | | `trajectory/v1` | the SDK's streamed steps, a step's text and thought each as one record, and each tool call's result from the SDK's hooks after it, live while the task runs (format `antigravity-sdk/1`) | -| `snapshot/v1` | `save` archives the context's conversation store with the env times its turns were given, and `/app`, once no task runs; `load` restores the store under its own id, bound to the target context, and replaces `/app`'s contents. Where `tar` is GNU tar, the changelog too: an incremental archive of its roots after each task, uploaded through the namespace grant, and applied in order; an increment is a whole task's changes, since the harness has no hook this agent can hold a task at | +| `snapshot/v1` | `save` archives the context's conversation store with the env times its turns were given, and `/app`, once no task runs; `load` restores the store under its own id, which the SDK holds inside it, bound to the target context, and replaces `/app`'s contents; a conversation another context of the same agent holds is refused (409), since the two would share one history. Where `tar` is GNU tar, the changelog too: an incremental archive of its roots after each task, uploaded through the namespace grant, and applied in order; an increment is a whole task's changes, since the harness has no hook this agent can hold a task at | | `peer-agents/v1` | SDK default: the harness reaches the task's other agents through the SDK's `peer_agents` MCP tools | | `triggers/v1` | SDK default | | `attribution-probe/v1` | the `project_id` and `task_id` the last task sent | diff --git a/src/agent_env/agents/agents/antigravity/a2a_server.py b/src/agent_env/agents/agents/antigravity/a2a_server.py index 9d8a4df99..d4c1d1662 100644 --- a/src/agent_env/agents/agents/antigravity/a2a_server.py +++ b/src/agent_env/agents/agents/antigravity/a2a_server.py @@ -71,6 +71,7 @@ ERROR_MESSAGE_LIMIT, SAVE_DIR, SKILLS_DIR, + TURN_IMAGES, AntigravityTool, get_last_attribution_snapshot, run_antigravity, @@ -105,6 +106,7 @@ TRAJECTORY_FORMAT = "antigravity-sdk/1" _MANIFEST = "manifest.json" _ENV_TIMES_MEMBER = "env-times.json" +_TURN_IMAGES_MEMBER = "turn-images.json" class AntigravityConfig(AgentConfig): @@ -383,8 +385,8 @@ async def probe_attribution(self) -> AttributionProbeResponse: @extension(SNAPSHOT_V1.save) async def save_snapshot(self, request: ObjectSnapshotSaveRequest) -> dict[str, Any]: - """The context's conversation, its SDK store whole with the env times its turns were given, and the - workspace.""" + """The context's conversation, its SDK store whole with the env times its turns were given and the images their + messages carry, and the workspace.""" with tempfile.TemporaryDirectory(prefix="antigravity-snapshot-") as directory: conversation = Path(directory) / "conversation.tgz" workspace = Path(directory) / "workspace.tgz" @@ -406,7 +408,9 @@ async def save_snapshot(self, request: ObjectSnapshotSaveRequest) -> dict[str, A @extension(SNAPSHOT_V1.load) async def load_snapshot(self, request: ObjectSnapshotLoadRequest) -> dict[str, Any]: - """The conversation under its own id, which the SDK keys its store by, bound to the target context.""" + """The conversation under its own id, which the SDK keys its store by and holds inside it, bound to the target + context. A conversation another context of this agent is bound to is refused: the two would share one history, + and the load would roll the other's back.""" target_context_id = request.target_context_id or uuid.uuid4().hex with tempfile.TemporaryDirectory(prefix="antigravity-restore-") as directory: archive = Path(directory) / "conversation.tgz" @@ -425,6 +429,9 @@ async def load_snapshot(self, request: ObjectSnapshotLoadRequest) -> dict[str, A check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, ) async with self._workspace.exclusive(), self._turn_lock(target_context_id): + if [context for context in self.contexts_bound_to(conversation_id) if context != target_context_id]: + raise HTTPException(status_code=409, detail="the snapshot's conversation is another context's on " + "this agent: load it into another agent") await asyncio.to_thread(_restore_conversation, staged_conversation, conversation_id) if staged is not None: await asyncio.to_thread(_replace_workspace, staged) @@ -504,13 +511,13 @@ def _conversation_files(conversation_id: str) -> list[Path]: def _archive_conversation(conversation_id: str, archive: Path) -> None: - times = ENV_TIMES.all() with tempfile.TemporaryDirectory(prefix="antigravity-conversation-") as directory: (Path(directory) / _MANIFEST).write_text(json.dumps({"conversation_id": conversation_id})) - (Path(directory) / _ENV_TIMES_MEMBER).write_text(json.dumps(times)) + (Path(directory) / _ENV_TIMES_MEMBER).write_text(json.dumps(ENV_TIMES.all())) + (Path(directory) / _TURN_IMAGES_MEMBER).write_text(json.dumps(TURN_IMAGES.all())) with tarfile.open(archive, "w:gz") as tar: - tar.add(Path(directory) / _MANIFEST, arcname=_MANIFEST) - tar.add(Path(directory) / _ENV_TIMES_MEMBER, arcname=_ENV_TIMES_MEMBER) + for member in (_MANIFEST, _ENV_TIMES_MEMBER, _TURN_IMAGES_MEMBER): + tar.add(Path(directory) / member, arcname=member) for path in _conversation_files(conversation_id): tar.add(path, arcname=f"store/{path.name}") @@ -542,12 +549,13 @@ def _restore_conversation(staged: Path, conversation_id: str) -> None: for path in sorted((staged / "store").iterdir()): if path.is_file() and path.name.startswith(f"{conversation_id}.db"): shutil.copyfile(path, SAVE_DIR / path.name) - try: - times = json.loads((staged / _ENV_TIMES_MEMBER).read_text()) - except (OSError, ValueError): - times = {} - if isinstance(times, dict): - ENV_TIMES.merge({str(real): str(env) for real, env in times.items()}) + for member, records in ((_ENV_TIMES_MEMBER, ENV_TIMES), (_TURN_IMAGES_MEMBER, TURN_IMAGES)): + try: + restored = json.loads((staged / member).read_text()) + except (OSError, ValueError): + restored = {} + if isinstance(restored, dict): + records.merge({str(key): value for key, value in restored.items()}) def _backup_exclusions() -> list[str]: diff --git a/src/agent_env/agents/agents/antigravity/antigravity_bridge.py b/src/agent_env/agents/agents/antigravity/antigravity_bridge.py index f059400e0..5a15c3112 100644 --- a/src/agent_env/agents/agents/antigravity/antigravity_bridge.py +++ b/src/agent_env/agents/agents/antigravity/antigravity_bridge.py @@ -34,7 +34,7 @@ from agent_egress import clock_armed, egress_env from agentenv_protocol.a2a_agent import BuiltinTools, Usage -from antigravity_date import EnvTimes, env_time_rewrite +from antigravity_date import Records, env_time_rewrite, message_digest from model_relay import Calls, model_relay logger = logging.getLogger(__name__) @@ -50,10 +50,14 @@ SDK_VERSION = "0.1.24" HOME_DIR = Path(os.environ.get("ANTIGRAVITY_HOME") or Path.home() / ".antigravity") -# The SDK's conversations, one SQLite store per conversation id, and the env times their turns were given. +# The SDK's conversations, one SQLite store per conversation id, the env times their turns were given and the +# images their messages carry. SAVE_DIR = HOME_DIR / "conversations" SKILLS_DIR = HOME_DIR / "skills" -ENV_TIMES = EnvTimes(SAVE_DIR / "env-times.json") +ENV_TIMES = Records(SAVE_DIR / "env-times.json") +TURN_IMAGES = Records(SAVE_DIR / "turn-images.json") +# The characters of a value the SDK can't serialize that the trajectory keeps. +_REPR_CHARS = 2000 # MCP calls into a large env can be slow; the SDK's own read timeout is shorter than a first tools/list there takes. _MCP_TIMEOUT_S = 60.0 @@ -180,58 +184,86 @@ def conversation_store_exists(conversation_id: str | None) -> bool: return bool(conversation_id) and (SAVE_DIR / f"{conversation_id}.db").is_file() +def is_image(path: str) -> bool: + return (mimetypes.guess_type(path)[0] or "").startswith("image/") + + def media_part(path: str) -> dict | None: - """An image the model sees inline, as a chat-completions image part with a data URL; None for any other file, - which the prompt names for the model's own tools to read. The SDK's chat-completions backend drops the media - ``chat()`` takes, so the relay adds them to the turn's request (``_with_media``).""" - mime = mimetypes.guess_type(path)[0] or "" - if not mime.startswith("image/"): + """An image the model sees inline, as a chat-completions image part with a data URL; None for any other file, which + the prompt names for the model's own tools to read, or one that is gone.""" + if not is_image(path): + return None + try: + data = base64.b64encode(Path(path).read_bytes()).decode() + except OSError: + logger.warning(f"image {path} is gone: the model's message goes without it") return None - data = base64.b64encode(Path(path).read_bytes()).decode() - return {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{data}"}} + return {"type": "image_url", "image_url": {"url": f"data:{mimetypes.guess_type(path)[0]};base64,{data}"}} -def _with_media(request: dict, media: list[dict]) -> bool: - """Add ``media`` to the request's last user message, the turn's own, unless they're there already: the harness - sends the turn's history again on each call, from a store that never saw them. Whether it changed the request.""" +def _with_images(request: dict, images: list[str], recorded: Records) -> bool: + """Every user message's images, which the SDK's chat-completions backend drops: the turn's own go with its message, + the last user message, and are recorded by that message's text, so the turns after it, which send it again from a + store that never saw them, carry them too. Whether it changed the request.""" users = [message for message in request.get("messages") or [] if isinstance(message, dict) and message.get("role") == "user"] - if not users or not media: + if not users: return False - message = users[-1] + if images: + key = message_digest(_text_of(users[-1])) + if recorded.get(key) is None: + recorded.put(key, images) + changed = False + for message in users: + paths = recorded.get(message_digest(_text_of(message))) + if not paths: + continue + content = message.get("content") + parts = [{"type": "text", "text": content}] if isinstance(content, str) else list(content or []) + present = {json.dumps(part, sort_keys=True) for part in parts if isinstance(part, dict)} + added = [part for part in (media_part(path) for path in paths) + if part is not None and json.dumps(part, sort_keys=True) not in present] + if added: + message["content"] = [*parts, *added] + changed = True + return changed + + +def _text_of(message: dict) -> str: + """A message's text as the harness wrote it, by which its images are recorded.""" content = message.get("content") - parts = [{"type": "text", "text": content}] if isinstance(content, str) else list(content or []) - present = {json.dumps(part, sort_keys=True) for part in parts if isinstance(part, dict)} - added = [part for part in media if json.dumps(part, sort_keys=True) not in present] - if not added: - return False - message["content"] = [*parts, *added] - return True + if isinstance(content, str): + return content + return "".join(part.get("text") or "" for part in content or [] if isinstance(part, dict) + and part.get("type") == "text") -def turn_rewrite(effort: str | None, media: list[dict]) -> Callable[[bytes], Awaitable[bytes]]: - """The relay's rewrite for a turn's model calls: the env's time (``antigravity_date``), then the turn's reasoning - effort and its images, which the SDK takes no setting for.""" +def turn_rewrite(effort: str | None, images: list[str]) -> Callable[[bytes], Awaitable[bytes]]: + """The relay's rewrite for a turn's model calls: its messages' images, the env's time (``antigravity_date``), then + the turn's reasoning effort, which the SDK takes no setting for.""" date_rewrite = env_time_rewrite(ENV_TIMES) reasoning = _EFFORTS.get(effort or "") if effort and reasoning is None: logger.warning(f"effort {effort!r} isn't one chat completions takes; the turn runs without one") async def rewrite(body: bytes) -> bytes: + try: + request = json.loads(body) + except ValueError: + request = None + if isinstance(request, dict) and _with_images(request, images, TURN_IMAGES): + body = json.dumps(request, separators=(",", ":")).encode() body = await date_rewrite(body) - if reasoning is None and not media: + if reasoning is None: return body try: request = json.loads(body) except ValueError: return body - if not isinstance(request, dict): + if not isinstance(request, dict) or request.get("reasoning_effort") == reasoning: return body - changed = _with_media(request, media) - if reasoning is not None and request.get("reasoning_effort") != reasoning: - request["reasoning_effort"] = reasoning - changed = True - return json.dumps(request, separators=(",", ":")).encode() if changed else body + request["reasoning_effort"] = reasoning + return json.dumps(request, separators=(",", ":")).encode() return rewrite @@ -332,7 +364,7 @@ def _plain(value: Any) -> dict: return json.loads(json.dumps(dump(mode="json", exclude={"exception"}), default=str)) except Exception: # noqa: BLE001 - a result's value may be anything return {key: str(item) for key, item in dump(warnings=False).items() if key != "exception"} - return {"repr": str(value)[:2000]} + return {"repr": str(value)[:_REPR_CHARS]} def _hooks(recorder: TrajectoryRecorder) -> list: @@ -365,14 +397,14 @@ async def run_antigravity(prompt: str, *, model: str | None, project_id: str | N attribution, counts every call the harness makes, its subagents' included, and tells the model the env's time on an armed clock. The turn's usage is theirs, a call answered without usage counted as unreported.""" _record_attribution(project_id, task_id) - media = [part for part in (media_part(path) for path in attachment_paths or []) if part is not None] + images = [path for path in attachment_paths or [] if is_image(path)] if attachment_paths: prompt = f"{prompt}\n\nAttached files, also on disk for your tools:\n" + "\n".join( f"- {path}" for path in attachment_paths) calls = Calls() headers = endpoint_headers(os.environ, attribution_headers(project_id, task_id)) async with model_relay(_api_root(os.environ.get("LITELLM_BASE_URL") or ""), calls, headers=headers, - rewrite=turn_rewrite(effort, media)) as relay: + rewrite=turn_rewrite(effort, images)) as relay: result = await _turn(prompt, base_url=f"{relay}/v1", model=model or DEFAULT_MODEL, **kwargs) result.usage = calls.usage(result.tool_call_count, model or DEFAULT_MODEL) return result @@ -411,25 +443,34 @@ async def _turn(prompt: str, *, base_url: str, model: str, session_id: str | Non logger.warning(f"conversation {session_id} has no store in {SAVE_DIR}: the turn starts a new one") session_id = None + started: list[Any] = [] + async def converse() -> tuple[str | None, Any]: async with ag.Agent(ag.LocalOpenAIAgentConfig(**config)) as agent: + started.append(agent) response = await agent.chat(prompt) async for chunk in response.chunks: recorder.chunk(chunk) return agent.conversation_id, response.stop_reason + def kept() -> str | None: + """The conversation a failed turn leaves for the next: the one the SDK started, which it names with the turn's + first streamed step, once its store is on disk, else the one the turn resumed.""" + current = getattr(started[0], "conversation_id", None) if started else None + return current if conversation_store_exists(current) else session_id + try: conversation_id, stop = await asyncio.wait_for(converse(), timeout=timeout_s) except TimeoutError: recorder.close() - return AntigravityResult(session_id=session_id, tool_call_count=recorder.tool_calls, error_code="timeout", + return AntigravityResult(session_id=kept(), tool_call_count=recorder.tool_calls, error_code="timeout", error=f"the turn ran past its {timeout_s} s") except agt.AntigravityExecutionError as exc: recorder.close() text = str(exc)[:ERROR_MESSAGE_LIMIT] # A task env's MCP server that fails its initialize fails the harness's start: the run's tools aren't there. mcp = "mcp load failed" in text.lower() - return AntigravityResult(session_id=session_id, tool_call_count=recorder.tool_calls, error=text, + return AntigravityResult(session_id=kept(), tool_call_count=recorder.tool_calls, error=text, error_code="mcp_load_failed" if mcp else "antigravity_error", infra=mcp) recorder.close() result = AntigravityResult(response=recorder.response(), session_id=conversation_id or session_id, diff --git a/src/agent_env/agents/agents/antigravity/antigravity_date.py b/src/agent_env/agents/agents/antigravity/antigravity_date.py index 3d9335824..ffd9bd8ad 100644 --- a/src/agent_env/agents/agents/antigravity/antigravity_date.py +++ b/src/agent_env/agents/agents/antigravity/antigravity_date.py @@ -4,7 +4,7 @@ time is: .`` in each turn's user message, and the ``Created At:`` and ``Completed At:`` stamps that head a command's result. While this agent follows an armed clock the turn's model relay puts the env's time in the line and shifts the stamps by the env's offset from real time when it first sees them, so a command keeps its duration. Each -keeps what it was first given, recorded in ``EnvTimes`` beside the conversations by the time and the message it is in, +keeps what it was first given, recorded in ``Records`` beside the conversations by the time and the message it is in, which the harness sends again as it stored it, so the earlier turns a resumed conversation sends again keep theirs. tst/integration/agent/antigravity_env_date_test.py checks the SDK's model calls hold the machine's date nowhere else.""" @@ -20,6 +20,7 @@ import threading from datetime import datetime, timezone from pathlib import Path +from typing import Any from agent_egress import clock_armed from model_relay import Refusal @@ -29,40 +30,43 @@ # The harness's head of a command's result: when the command started and, once it has, when it ended. RUN_TIMES = re.compile(rf"^((?:Created|Completed) At: )({_STAMP})$", re.MULTILINE) _DATE_TIMEOUT_S = 5 +# The hex digits of a message's digest a key holds. +_KEY_DIGEST_CHARS = 16 _SHOWN_CHARS = 200 -class EnvTimes: - """Each turn's local-time line and the env time it was given, and each command result's env and real time when - the relay first saw it, in ``path``, keyed by ``line_key``.""" +class Records: + """A JSON object of records beside the conversations, in ``path``, written whole by a rename: the env time each + turn's local-time line was given and each command result's env and real time when the relay first saw it, keyed by + ``line_key``, or the images each turn's message carries.""" def __init__(self, path: Path) -> None: self.path = path self._lock = threading.Lock() - def get(self, line: str) -> str | None: - return self._read().get(line) + def get(self, key: str) -> Any: + return self._read().get(key) - def all(self) -> dict[str, str]: + def all(self) -> dict[str, Any]: return self._read() - def put(self, line: str, env: str) -> None: + def put(self, key: str, value: Any) -> None: with self._lock: times = self._read() - times[line] = env + times[key] = value self.path.parent.mkdir(parents=True, exist_ok=True) staged = self.path.with_suffix(".tmp") staged.write_text(json.dumps(times)) staged.replace(self.path) - def merge(self, other: dict[str, str]) -> None: + def merge(self, other: dict[str, Any]) -> None: """Add a snapshot's times, its own winning over none.""" with self._lock: times = {**other, **self._read()} self.path.parent.mkdir(parents=True, exist_ok=True) self.path.write_text(json.dumps(times)) - def _read(self) -> dict[str, str]: + def _read(self) -> dict[str, Any]: try: times = json.loads(self.path.read_text()) except (OSError, ValueError): @@ -70,14 +74,16 @@ def _read(self) -> dict[str, str]: return times if isinstance(times, dict) else {} -def env_time_rewrite(times: EnvTimes): +def env_time_rewrite(times: Records): """The relay's rewrite for a turn: while the agent follows an armed clock, every local-time line of a user message - gets the env time recorded for it, and the last one, the turn's own, the env's time now when none is recorded; + gets the env time recorded for it, and the last one, the turn's own, the env's time when the turn first sends it; every command result's stamps are shifted by the offset recorded for it, a result of the turn's own recording the env's offset now. A line or result of an earlier turn with none recorded is left as written: the agent followed no clock then. Unchanged otherwise; a call that isn't JSON, or whose env time can't be read, is refused, so the model is never told the machine's time instead.""" + given: set[str] = set() + async def rewrite(body: bytes) -> bytes: if not clock_armed(): return body @@ -100,8 +106,9 @@ async def rewrite(body: bytes) -> bytes: if lines: latest = lines[-1][0][lines[-1][1]] current = line_key(latest, LOCAL_TIME.findall(latest)[-1][1]) - if times.get(current) is None: + if current not in given: times.put(current, (await now())[0]) + given.add(current) for holder, key in lines: text = holder[key] holder[key] = LOCAL_TIME.sub(lambda match: _placed(match, line_key(text, match.group(2)), times), text) @@ -121,10 +128,14 @@ async def rewrite(body: bytes) -> bytes: def line_key(text: str, real: str) -> str: """A local-time line's or a command result's key: its time and the message text it is in, so two turns that start in one second keep their own env times.""" - return f"{real}#{hashlib.sha256(text.encode('utf-8', 'surrogatepass')).hexdigest()[:16]}" + return f"{real}#{message_digest(text)}" + + +def message_digest(text: str) -> str: + return hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest()[:_KEY_DIGEST_CHARS] -def _placed(match: re.Match, line: str, times: EnvTimes) -> str: +def _placed(match: re.Match, line: str, times: Records) -> str: env = times.get(line) return match.group(0) if env is None else f"{match.group(1)}{env}{match.group(3)}" diff --git a/src/agent_env/agents/agents/antigravity/antigravity_kit.py b/src/agent_env/agents/agents/antigravity/antigravity_kit.py index dff504841..dae217fe9 100644 --- a/src/agent_env/agents/agents/antigravity/antigravity_kit.py +++ b/src/agent_env/agents/agents/antigravity/antigravity_kit.py @@ -6,6 +6,7 @@ import json import logging +import re import shutil from pathlib import Path @@ -19,6 +20,9 @@ logger = logging.getLogger(__name__) _REFS_ATTR = "_durable_session_refs" +# A SKILL.md's YAML frontmatter: a block between `---` lines that names the skill or describes it. +_FRONTMATTER = re.compile(r"\A---[ \t]*\n(?P.*?)\n---[ \t]*(?:\n|\Z)", re.DOTALL) +_FRONTMATTER_KEY = re.compile(r"^(?:name|description)[ \t]*:", re.MULTILINE) class DurableSessionRefs: @@ -33,6 +37,9 @@ def set_session_ref_for_context(self, context_id: str, session_ref: str) -> None super().set_session_ref_for_context(context_id, session_ref) self.__dict__.setdefault(_REFS_ATTR, {})[context_id] = session_ref + def contexts_bound_to(self, session_ref: str) -> list[str]: + return [context for context, ref in self.__dict__.get(_REFS_ATTR, {}).items() if ref == session_ref] + _NO_BODY_STATUSES = frozenset({204, 205, 304}) @@ -78,9 +85,11 @@ async def install_skill(request: InlineSkillRequest | BundleSkillRequest, skills def with_frontmatter(skill_md: str, name: str, description: str | None) -> str: - """``skill_md`` as written when it opens with YAML frontmatter, else with a ``name`` and ``description`` one before - it: the SDK lists a skill to the model only by its frontmatter, so one without it would never be found.""" - if skill_md.lstrip().startswith("---"): + """``skill_md`` as written when it opens with YAML frontmatter that names or describes it, else with a ``name`` and + ``description`` one before it: the SDK lists a skill to the model only by its frontmatter, so one without it, or + whose body merely opens with a horizontal rule, would never be found.""" + block = _FRONTMATTER.match(skill_md.lstrip()) + if block and _FRONTMATTER_KEY.search(block.group("block")): return skill_md summary = " ".join((description or name).split()) return f"---\nname: {json.dumps(name)}\ndescription: {json.dumps(summary)}\n---\n\n{skill_md}" diff --git a/tst/integration/agent/antigravity_env_date_test.py b/tst/integration/agent/antigravity_env_date_test.py index 6788f559a..ff184418c 100644 --- a/tst/integration/agent/antigravity_env_date_test.py +++ b/tst/integration/agent/antigravity_env_date_test.py @@ -21,7 +21,9 @@ pytestmark = [pytest.mark.integration] -ENV_TIMES = ("1950-01-01T09:30:00Z", "1950-01-02T08:15:00Z") +ENV_TIMES = ("1950-01-01T09:30:00Z", "1950-01-02T08:15:00Z", "1950-01-03T07:00:00Z") +# How long the endpoint holds the stalled turn's second model call: past that turn's 20 s. +_STALL_S = 40 # The tools the first turn calls, in order, by a word of the name the model is offered each by: a command, the # harness's own skill listing, which its hooks never decide, and the workspace's file. TOOLS = ("command", "list_skills", "view_file") @@ -29,7 +31,8 @@ _PT_INTERP = 3 # Two turns of one conversation through the bridge, on an armed clock whose time is the next of argv's, with the real -# SDK; their results, trajectories and what the SDK holds, as JSON. +# SDK, then the first turn of another that runs past its time; their results, trajectories and what the SDK holds, as +# JSON. DRIVER = ''' import asyncio, json, sys from pathlib import Path @@ -43,19 +46,22 @@ async def env_now(): return current antigravity_date._env_now = env_now -async def turn(prompt, session_id): +async def turn(prompt, session_id, timeout_s=300): events = [] result = await antigravity_bridge.run_antigravity( - prompt, model="m", session_id=session_id, mcp_servers=None, system_prompt=None, timeout_s=300, role=None, + prompt, model="m", session_id=session_id, mcp_servers=None, system_prompt=None, timeout_s=timeout_s, role=None, builtin_tools=None, max_turns=None, workspace=sys.argv[1], event_callback=events.append) - return {"response": result.response, "error": result.error, "session_id": result.session_id, - "tool_calls": result.tool_call_count, "usage": result.usage.to_dict(), "events": events} + return {"response": result.response, "error": result.error, "error_code": result.error_code, + "session_id": result.session_id, "tool_calls": result.tool_call_count, "usage": result.usage.to_dict(), + "events": events, "stored": antigravity_bridge.conversation_store_exists(result.session_id)} current = next(times) first = asyncio.run(turn("Run the shell command `echo 42` and reply with what it prints.", None)) current = next(times) second = asyncio.run(turn("Thanks. Reply with the word done.", first["session_id"])) -print(json.dumps({"turns": [first, second], "tools": sorted(tool.value for tool in agt.BuiltinTools), +current = next(times) +stalled = asyncio.run(turn("STALL: run the shell command `echo 42`.", None, timeout_s=20)) +print(json.dumps({"turns": [first, second, stalled], "tools": sorted(tool.value for tool in agt.BuiltinTools), "harness": str(Path(ag.__file__).parent / "bin" / "localharness")})) ''' @@ -133,6 +139,9 @@ def respond(body: dict) -> fake_openai.Text | fake_openai.ToolCall: if any("done" in text for text in _user_texts(body)[-1:]): return fake_openai.Text("done") ran = sum(message.get("role") == "tool" for message in body.get("messages") or []) + if ran and any("STALL" in text for text in _user_texts(body)[-1:]): + time.sleep(_STALL_S) + return fake_openai.Text("late") if ran == len(TOOLS): return fake_openai.Text("It printed 42.") offered = [tool["function"] for tool in body.get("tools") or [] if TOOLS[ran] in tool["function"]["name"]] @@ -170,7 +179,8 @@ def test_the_sdks_tools_are_the_ones_a_task_selects_and_the_three_it_cant(run): def test_on_an_armed_clock_the_model_is_told_the_env_time_and_no_other(run): result, endpoint = run bodies = [seen.body for seen in endpoint.completions()] - first = [body for body in bodies if len(_user_texts(body)) == 1] + stalled = [body for body in bodies if any("STALL" in text for text in _user_texts(body))] + first = [body for body in bodies if len(_user_texts(body)) == 1 and body not in stalled] second = [body for body in bodies if len(_user_texts(body)) >= 2] assert first and second, [len(_user_texts(body)) for body in bodies] @@ -180,6 +190,7 @@ def test_on_an_armed_clock_the_model_is_told_the_env_time_and_no_other(run): earlier, latest = _user_texts(body)[0], _user_texts(body)[-1] assert f"The current local time is: {ENV_TIMES[0]}." in earlier assert f"The current local time is: {ENV_TIMES[1]}." in latest + assert stalled and all(f"The current local time is: {ENV_TIMES[2]}." in _user_texts(body)[0] for body in stalled) machine = _machine_dates() for body in bodies: written = json.dumps(body) @@ -188,7 +199,7 @@ def test_on_an_armed_clock_the_model_is_told_the_env_time_and_no_other(run): def test_each_tool_result_is_tied_to_the_call_the_sdk_streamed(run): - first, _second = run[0]["turns"] + first = run[0]["turns"][0] assert not first["error"], first["error"] calls = [event for event in first["events"] if event.get("type") == "ToolCall"] @@ -203,10 +214,19 @@ def test_each_tool_result_is_tied_to_the_call_the_sdk_streamed(run): def test_the_turns_usage_is_every_model_call_the_harness_made_with_the_endpoints_key(run): result, endpoint = run completions = endpoint.completions() - usage = [turn["usage"] for turn in result["turns"]] + usage = [turn["usage"] for turn in result["turns"][:2]] + completions = [seen for seen in completions if not any("STALL" in text for text in _user_texts(seen.body))] assert sum(turn["provider_details"]["model_calls"] for turn in usage) == len(completions) assert sum(turn["input_tokens"] for turn in usage) == fake_openai.USAGE["prompt_tokens"] * len(completions) assert {seen.headers.get("authorization") for seen in completions} == {"Bearer sk-fake"} assert result["turns"][1]["session_id"] == result["turns"][0]["session_id"] assert result["turns"][1]["response"] == "done" + + +def test_a_first_turn_past_its_time_leaves_the_conversation_the_sdk_started_for_the_next(run): + stalled = run[0]["turns"][2] + + assert stalled["error_code"] == "timeout", stalled + assert stalled["session_id"] and stalled["stored"], stalled + assert stalled["session_id"] != run[0]["turns"][0]["session_id"] diff --git a/tst/unit/agents/antigravity/conftest.py b/tst/unit/agents/antigravity/conftest.py index bb534a6ad..d7b07da39 100644 --- a/tst/unit/agents/antigravity/conftest.py +++ b/tst/unit/agents/antigravity/conftest.py @@ -71,11 +71,13 @@ def folders(monkeypatch, tmp_path): workspace = tmp_path / "workspace" workspace.mkdir() conversations = tmp_path / "home" / "conversations" - times = antigravity_date.EnvTimes(conversations / "env-times.json") + times = antigravity_date.Records(conversations / "env-times.json") + images = antigravity_date.Records(conversations / "turn-images.json") for module in (a2a_server, antigravity_bridge): monkeypatch.setattr(module, "SAVE_DIR", conversations) monkeypatch.setattr(module, "SKILLS_DIR", tmp_path / "home" / "skills") monkeypatch.setattr(module, "ENV_TIMES", times) + monkeypatch.setattr(module, "TURN_IMAGES", images) monkeypatch.setattr(a2a_server, "WORKSPACE_DIR", workspace) monkeypatch.setattr(a2a_server, "INPUTS_DIR", workspace / "inputs") monkeypatch.setattr(a2a_server, "_CHANGELOG_DIR", tmp_path / "changelog") diff --git a/tst/unit/agents/antigravity/fake_sdk.py b/tst/unit/agents/antigravity/fake_sdk.py index bd1217cad..4d2dabb0c 100644 --- a/tst/unit/agents/antigravity/fake_sdk.py +++ b/tst/unit/agents/antigravity/fake_sdk.py @@ -127,6 +127,8 @@ async def _play(self): hooks = getattr(self._agent.config, "hooks", None) or [] for kind, value in self._turn.steps: if kind == "chunk": + # As the SDK does: the conversation has its id, and its store, from the turn's first streamed step. + self._agent.conversation_id = self._turn.conversation_id yield value elif kind == "call": for hook in hooks: diff --git a/tst/unit/agents/antigravity/test_antigravity_bridge.py b/tst/unit/agents/antigravity/test_antigravity_bridge.py index 00b28d89a..497bdb4d3 100644 --- a/tst/unit/agents/antigravity/test_antigravity_bridge.py +++ b/tst/unit/agents/antigravity/test_antigravity_bridge.py @@ -311,11 +311,27 @@ def test_a_result_whose_call_never_streamed_is_kept_unlinked(): assert [(event["id"], event["call_ref"]) for event in events] == [("h9", None), ("h1", None)] -def test_a_turn_past_its_time_fails_with_what_it_streamed_kept(): - result, events = _run(Turn(steps=[("chunk", Text(step_index=0, text="working")), ("sleep", 5)]), timeout_s=0.2) +def test_a_turn_past_its_time_fails_with_what_it_streamed_kept_and_its_conversation_for_the_next(): + antigravity_bridge.SAVE_DIR.mkdir(parents=True) + (antigravity_bridge.SAVE_DIR / "conv-new.db").write_bytes(b"") + + result, events = _run(Turn(steps=[("chunk", Text(step_index=0, text="working")), ("sleep", 5)], + conversation_id="conv-new"), timeout_s=0.2) assert (result.error_code, result.error) == ("timeout", "the turn ran past its 0.2 s") assert events == [{"type": "Text", "step_index": 0, "text": "working"}] + assert result.session_id == "conv-new" + + +@pytest.mark.parametrize("session_id", [None, "conv-1"]) +def test_a_turn_that_fails_before_its_first_step_keeps_the_conversation_it_resumed(session_id): + antigravity_bridge.SAVE_DIR.mkdir(parents=True) + (antigravity_bridge.SAVE_DIR / "conv-1.db").write_bytes(b"") + + result, _ = _run(Turn(steps=[("raise", fake_sdk.AntigravityExecutionError("harness exited 2"))], + conversation_id="conv-2"), session_id=session_id) + + assert result.session_id == session_id @pytest.mark.parametrize("message, code, infra", [ @@ -348,21 +364,40 @@ def test_the_effort_goes_as_reasoning_effort(effort, sent): assert rewritten.get("reasoning_effort") == sent -def test_an_image_goes_with_the_turns_own_message_once(tmp_path): +def _rewritten(rewrite, messages: list[dict]) -> list[dict]: + return json.loads(asyncio.run(rewrite(json.dumps({"model": "m", "messages": messages}).encode())))["messages"] + + +def test_an_image_goes_with_its_turns_message_once_and_with_it_in_the_turns_after(tmp_path): image = tmp_path / "chart.png" image.write_bytes(b"\x89PNG") part = antigravity_bridge.media_part(str(image)) - rewrite = antigravity_bridge.turn_rewrite(None, [part]) - body = {"model": "m", "messages": [{"role": "user", "content": "earlier"}, {"role": "assistant", "content": "ok"}, - {"role": "user", "content": "look"}]} + first = antigravity_bridge.turn_rewrite(None, [str(image)]) + asked = [{"role": "user", "content": "earlier"}, {"role": "assistant", "content": "ok"}, + {"role": "user", "content": "look"}] - once = json.loads(asyncio.run(rewrite(json.dumps(body).encode()))) - twice = json.loads(asyncio.run(rewrite(json.dumps(once).encode()))) + once = _rewritten(first, asked) + twice = _rewritten(first, once) + later = _rewritten(antigravity_bridge.turn_rewrite(None, []), [ + *asked, {"role": "assistant", "content": "a chart"}, {"role": "user", "content": "its other label?"}]) assert part == {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw=="}} - assert once["messages"][0]["content"] == "earlier" - assert once["messages"][2]["content"] == [{"type": "text", "text": "look"}, part] + assert once[0]["content"] == "earlier" + assert once[2]["content"] == [{"type": "text", "text": "look"}, part] assert twice == once + assert later[2]["content"] == [{"type": "text", "text": "look"}, part] + assert later[4]["content"] == "its other label?" + + +def test_an_image_that_is_gone_is_left_out(tmp_path): + image = tmp_path / "chart.png" + image.write_bytes(b"\x89PNG") + _rewritten(antigravity_bridge.turn_rewrite(None, [str(image)]), [{"role": "user", "content": "look"}]) + image.unlink() + + later = _rewritten(antigravity_bridge.turn_rewrite(None, []), [{"role": "user", "content": "look"}]) + + assert later[0]["content"] == "look" assert antigravity_bridge.media_part(str(tmp_path / "notes.txt")) is None diff --git a/tst/unit/agents/antigravity/test_antigravity_date.py b/tst/unit/agents/antigravity/test_antigravity_date.py index e9781b2a6..8c8ce1209 100644 --- a/tst/unit/agents/antigravity/test_antigravity_date.py +++ b/tst/unit/agents/antigravity/test_antigravity_date.py @@ -31,8 +31,8 @@ def _call(*users, parts: bool = False) -> dict: @pytest.fixture -def times(tmp_path) -> antigravity_date.EnvTimes: - return antigravity_date.EnvTimes(tmp_path / "conversations" / "env-times.json") +def times(tmp_path) -> antigravity_date.Records: + return antigravity_date.Records(tmp_path / "conversations" / "env-times.json") @pytest.fixture @@ -89,17 +89,29 @@ def test_date_runs_on_the_envs_clock_not_the_servers(env_clock, monkeypatch, tim assert "AGENTENV_REAL_TIME=" not in (env_clock / "date.env").read_text() -def test_a_turns_line_keeps_the_env_time_it_was_first_given(env_clock, monkeypatch, times): +def test_a_turns_line_keeps_the_env_time_it_was_first_given_for_the_rest_of_the_turn(env_clock, monkeypatch, times): + rewrite = antigravity_date.env_time_rewrite(times) + call = json.dumps(_call(_line(REAL) + "go")).encode() monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-03T23:06:07-06:00") - first = _rewrite(times, _call(_line(REAL) + "go")) + first = asyncio.run(rewrite(call)) monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-03T23:09:00-06:00") - again = _rewrite(times, _call(_line(REAL) + "go")) + again = asyncio.run(rewrite(call)) assert again == first assert _runs(env_clock) == 1 +def test_a_turn_whose_message_matches_an_earlier_ones_to_the_second_gets_the_time_now(env_clock, monkeypatch, times): + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-03T23:06:07-06:00") + _rewrite(times, _call(_line(REAL) + "go")) + monkeypatch.setenv("FAKE_DATE_OUT", "2031-03-04T02:00:00-06:00") + + again = _rewrite(times, _call(_line(REAL) + "go")) + + assert again["messages"][1]["content"] == _line("2031-03-04T02:00:00-06:00") + "go" + + def test_a_resumed_conversations_earlier_turns_keep_their_times_and_the_new_one_gets_now(env_clock, monkeypatch, times): times.put(antigravity_date.line_key(_line(EARLIER) + "one", EARLIER), "2031-03-02T08:00:00-06:00") diff --git a/tst/unit/agents/antigravity/test_message_contract.py b/tst/unit/agents/antigravity/test_message_contract.py index a9a903701..bb39df760 100644 --- a/tst/unit/agents/antigravity/test_message_contract.py +++ b/tst/unit/agents/antigravity/test_message_contract.py @@ -261,6 +261,12 @@ def test_a_skill_with_its_own_frontmatter_is_written_as_given(): written = "---\nname: mine\ndescription: d\n---\nbody" assert antigravity_kit.with_frontmatter(written, "other", "x") == written + + +@pytest.mark.parametrize("skill_md", ["---\n\n# Report\nSteps.", "---\n\n# Report\n\n---\n\nMore steps."]) +def test_a_skill_that_opens_with_a_horizontal_rule_gets_frontmatter(skill_md): + assert antigravity_kit.with_frontmatter(skill_md, "report", "Write it.") == ( + f'---\nname: "report"\ndescription: "Write it."\n---\n\n{skill_md}') assert antigravity_kit.with_frontmatter("body", 'a "quoted" name', None).startswith( '---\nname: "a \\"quoted\\" name"\ndescription: "a \\"quoted\\" name"\n---') diff --git a/tst/unit/agents/antigravity/test_snapshot.py b/tst/unit/agents/antigravity/test_snapshot.py index ab15d16e9..4835ce5a4 100644 --- a/tst/unit/agents/antigravity/test_snapshot.py +++ b/tst/unit/agents/antigravity/test_snapshot.py @@ -13,6 +13,7 @@ from agentenv_protocol.a2a_agent import Uploaded from tst.unit.agents.antigravity.agent import a2a_server, antigravity_bridge +from tst.unit.agents.antigravity.conftest import Harness _GRANT = {"expires_at": "2099-01-01T00:00:00Z", "url": "https://objects.example/o"} _WRITE = {"media_type": "application/octet-stream", "max_bytes": 1 << 20, "write": {"kind": "http-put", **_GRANT}} @@ -44,13 +45,14 @@ def _members(archive: bytes) -> list[str]: @pytest.mark.asyncio -async def test_a_conversation_and_its_workspace_load_into_another_context(ag, objects, folders): +async def test_a_conversation_and_its_workspace_load_into_another_agents_context(ag, objects, folders): store = antigravity_bridge.SAVE_DIR store.mkdir(parents=True) (store / "conv-1.db").write_bytes(b"sqlite") (store / "conv-1.db-wal").write_bytes(b"wal") (store / "conv-2.db").write_bytes(b"another") antigravity_bridge.ENV_TIMES.put("2026-11-25T10:00:00-08:00", "2031-03-03T23:06:07-06:00") + antigravity_bridge.TURN_IMAGES.put("3f2a", [str(folders / "inputs" / "t1" / "chart.png")]) (folders / "report.md").write_text("draft") ag.agent.set_session_ref_for_context("ctx-source", "conv-1") @@ -59,27 +61,30 @@ async def test_a_conversation_and_its_workspace_load_into_another_context(ag, ob "trajectory": _WRITE, "workspace": _WRITE}}) assert saved.status_code == 200, saved.text assert _members(objects["conversation.tgz"]) == ["env-times.json", "manifest.json", "store/conv-1.db", - "store/conv-1.db-wal"] + "store/conv-1.db-wal", "turn-images.json"] for path in store.iterdir(): path.unlink() (folders / "report.md").write_text("changed since") (folders / "stray.txt").write_text("stray") + other = Harness(a2a_server.AntigravityChangelogAgent()) + async with other.client() as client: loaded = await client.put("/ext/snapshot", json={"target_context_id": "ctx-target", "objects": { "trajectory": _READ, "workspace": _READ}}) assert loaded.status_code == 200, loaded.text assert loaded.json() == {"context_id": "ctx-target"} - assert ag.agent.session_ref_for_context("ctx-target") == "conv-1" + assert other.agent.session_ref_for_context("ctx-target") == "conv-1" assert {path.name: path.read_bytes() for path in store.glob("conv-*")} == {"conv-1.db": b"sqlite", "conv-1.db-wal": b"wal"} assert antigravity_bridge.ENV_TIMES.all() == {"2026-11-25T10:00:00-08:00": "2031-03-03T23:06:07-06:00"} + assert antigravity_bridge.TURN_IMAGES.all() == {"3f2a": [str(folders / "inputs" / "t1" / "chart.png")]} assert sorted(path.name for path in folders.iterdir()) == ["report.md"] assert (folders / "report.md").read_text() == "draft" @pytest.mark.asyncio -async def test_a_loaded_conversation_replaces_a_stale_store_of_its_own(ag, objects): +async def test_a_context_loaded_with_its_own_conversation_goes_back_to_it(ag, objects): store = antigravity_bridge.SAVE_DIR store.mkdir(parents=True) (store / "conv-1.db").write_bytes(b"saved") @@ -88,11 +93,29 @@ async def test_a_loaded_conversation_replaces_a_stale_store_of_its_own(ag, objec await client.post("/ext/snapshot", json={"context_id": "ctx", "objects": {"trajectory": _WRITE}}) (store / "conv-1.db").write_bytes(b"later") (store / "conv-1.db-shm").write_bytes(b"stale") - loaded = await client.put("/ext/snapshot", json={"objects": {"trajectory": _READ}}) + loaded = await client.put("/ext/snapshot", json={"target_context_id": "ctx", "objects": {"trajectory": _READ}}) assert loaded.status_code == 200, loaded.text assert {path.name: path.read_bytes() for path in store.glob("conv-1.db*")} == {"conv-1.db": b"saved"} - assert ag.agent.session_ref_for_context(loaded.json()["context_id"]) == "conv-1" + assert ag.agent.session_ref_for_context("ctx") == "conv-1" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("target", [{"target_context_id": "ctx-other"}, {}]) +async def test_a_conversation_another_context_of_the_agent_holds_isnt_loaded_beside_it(ag, objects, target): + store = antigravity_bridge.SAVE_DIR + store.mkdir(parents=True) + (store / "conv-1.db").write_bytes(b"saved") + ag.agent.set_session_ref_for_context("ctx", "conv-1") + async with ag.client() as client: + await client.post("/ext/snapshot", json={"context_id": "ctx", "objects": {"trajectory": _WRITE}}) + (store / "conv-1.db").write_bytes(b"later") + loaded = await client.put("/ext/snapshot", json={**target, "objects": {"trajectory": _READ}}) + + assert loaded.status_code == 409, loaded.text + assert "load it into another agent" in loaded.json()["detail"] + assert (store / "conv-1.db").read_bytes() == b"later" + assert ag.agent.contexts_bound_to("conv-1") == ["ctx"] def _archive(members: dict[str, bytes]) -> bytes: From f07f4c79207bc48b283bf89113e72e28ad7a546f Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Wed, 25 Nov 2026 11:26:06 -0800 Subject: [PATCH 3/3] fix(agents): Antigravity replays a turn's images as they were given Each turn's images are kept beside the conversations, named by their content, and replayed from there, so the agent editing an attachment in the workspace never changes what the user showed the model. Snapshots carry the copies. Co-Authored-By: Claude Opus 5.5 --- .../agents/agents/antigravity/README.md | 2 +- .../agents/agents/antigravity/a2a_server.py | 13 ++++++- .../agents/antigravity/antigravity_bridge.py | 39 ++++++++++++++----- tst/unit/agents/antigravity/conftest.py | 1 + .../antigravity/test_antigravity_bridge.py | 15 ++++--- tst/unit/agents/antigravity/test_snapshot.py | 17 +++++--- 6 files changed, 62 insertions(+), 25 deletions(-) diff --git a/src/agent_env/agents/agents/antigravity/README.md b/src/agent_env/agents/agents/antigravity/README.md index 6ccce2081..2bb384888 100644 --- a/src/agent_env/agents/agents/antigravity/README.md +++ b/src/agent_env/agents/agents/antigravity/README.md @@ -9,7 +9,7 @@ Each task is one `Agent.chat()` of the SDK in the A2A server's process, in `/app `localharness`, a static Go binary that runs the tools and calls the model. A context's first task starts an SDK conversation, and each later task resumes it by its id; the SDK keeps each conversation in a SQLite store under `$ANTIGRAVITY_HOME/conversations/`. Text parts are the prompt, and file parts are written under `/app/inputs//` -and named in it; an image goes to the model inline too, with its message in every later turn, and a PDF as its +and named in it; an image goes to the model inline too, as it was given, with its message in every later turn, and a PDF as its pages' PNGs, rendered with `pdftoppm`. Turns of different contexts run at once, a context's turns one at a time. diff --git a/src/agent_env/agents/agents/antigravity/a2a_server.py b/src/agent_env/agents/agents/antigravity/a2a_server.py index d4c1d1662..0fda6bb6e 100644 --- a/src/agent_env/agents/agents/antigravity/a2a_server.py +++ b/src/agent_env/agents/agents/antigravity/a2a_server.py @@ -69,6 +69,7 @@ from antigravity_bridge import ( ENV_TIMES, ERROR_MESSAGE_LIMIT, + IMAGES_DIR, SAVE_DIR, SKILLS_DIR, TURN_IMAGES, @@ -107,6 +108,7 @@ _MANIFEST = "manifest.json" _ENV_TIMES_MEMBER = "env-times.json" _TURN_IMAGES_MEMBER = "turn-images.json" +_IMAGES_MEMBER = "images" class AntigravityConfig(AgentConfig): @@ -386,7 +388,7 @@ async def probe_attribution(self) -> AttributionProbeResponse: @extension(SNAPSHOT_V1.save) async def save_snapshot(self, request: ObjectSnapshotSaveRequest) -> dict[str, Any]: """The context's conversation, its SDK store whole with the env times its turns were given and the images their - messages carry, and the workspace.""" + messages carry, as they were given, and the workspace.""" with tempfile.TemporaryDirectory(prefix="antigravity-snapshot-") as directory: conversation = Path(directory) / "conversation.tgz" workspace = Path(directory) / "workspace.tgz" @@ -518,6 +520,10 @@ def _archive_conversation(conversation_id: str, archive: Path) -> None: with tarfile.open(archive, "w:gz") as tar: for member in (_MANIFEST, _ENV_TIMES_MEMBER, _TURN_IMAGES_MEMBER): tar.add(Path(directory) / member, arcname=member) + kept = {name for names in TURN_IMAGES.all().values() if isinstance(names, list) for name in names} + for name in sorted(kept): + if isinstance(name, str) and (IMAGES_DIR / name).is_file(): + tar.add(IMAGES_DIR / name, arcname=f"{_IMAGES_MEMBER}/{name}") for path in _conversation_files(conversation_id): tar.add(path, arcname=f"store/{path.name}") @@ -556,6 +562,11 @@ def _restore_conversation(staged: Path, conversation_id: str) -> None: restored = {} if isinstance(restored, dict): records.merge({str(key): value for key, value in restored.items()}) + if (staged / _IMAGES_MEMBER).is_dir(): + IMAGES_DIR.mkdir(parents=True, exist_ok=True) + for path in (staged / _IMAGES_MEMBER).iterdir(): + if path.is_file() and not (IMAGES_DIR / path.name).exists(): + shutil.copyfile(path, IMAGES_DIR / path.name) def _backup_exclusions() -> list[str]: diff --git a/src/agent_env/agents/agents/antigravity/antigravity_bridge.py b/src/agent_env/agents/agents/antigravity/antigravity_bridge.py index 5a15c3112..09674800a 100644 --- a/src/agent_env/agents/agents/antigravity/antigravity_bridge.py +++ b/src/agent_env/agents/agents/antigravity/antigravity_bridge.py @@ -15,6 +15,7 @@ import asyncio import base64 +import hashlib import json import logging import mimetypes @@ -56,6 +57,9 @@ SKILLS_DIR = HOME_DIR / "skills" ENV_TIMES = Records(SAVE_DIR / "env-times.json") TURN_IMAGES = Records(SAVE_DIR / "turn-images.json") +# Each turn's images as the turn was given them, by their content, so the agent editing an attachment never changes what +# the user showed the model. +IMAGES_DIR = SAVE_DIR / "images" # The characters of a value the SDK can't serialize that the trajectory keeps. _REPR_CHARS = 2000 @@ -188,23 +192,40 @@ def is_image(path: str) -> bool: return (mimetypes.guess_type(path)[0] or "").startswith("image/") -def media_part(path: str) -> dict | None: +def media_part(path: str | Path) -> dict | None: """An image the model sees inline, as a chat-completions image part with a data URL; None for any other file, which the prompt names for the model's own tools to read, or one that is gone.""" - if not is_image(path): + if not is_image(str(path)): return None try: data = base64.b64encode(Path(path).read_bytes()).decode() except OSError: logger.warning(f"image {path} is gone: the model's message goes without it") return None - return {"type": "image_url", "image_url": {"url": f"data:{mimetypes.guess_type(path)[0]};base64,{data}"}} + return {"type": "image_url", "image_url": {"url": f"data:{mimetypes.guess_type(str(path))[0]};base64,{data}"}} + + +def kept_image(path: str) -> str | None: + """A copy of the image at ``path`` in ``IMAGES_DIR``, named by its content, which no edit of the original reaches; + its name, or None when the image is gone.""" + try: + data = Path(path).read_bytes() + except OSError: + logger.warning(f"image {path} is gone: the model's message goes without it") + return None + name = hashlib.sha256(data).hexdigest() + Path(path).suffix.lower() + if not (IMAGES_DIR / name).is_file(): + IMAGES_DIR.mkdir(parents=True, exist_ok=True) + staged = IMAGES_DIR / f".{name}.tmp" + staged.write_bytes(data) + staged.replace(IMAGES_DIR / name) + return name def _with_images(request: dict, images: list[str], recorded: Records) -> bool: """Every user message's images, which the SDK's chat-completions backend drops: the turn's own go with its message, - the last user message, and are recorded by that message's text, so the turns after it, which send it again from a - store that never saw them, carry them too. Whether it changed the request.""" + the last user message, kept as they were (``kept_image``) and recorded by that message's text, so the turns after + it, which send it again from a store that never saw them, carry them too. Whether it changed the request.""" users = [message for message in request.get("messages") or [] if isinstance(message, dict) and message.get("role") == "user"] if not users: @@ -212,16 +233,16 @@ def _with_images(request: dict, images: list[str], recorded: Records) -> bool: if images: key = message_digest(_text_of(users[-1])) if recorded.get(key) is None: - recorded.put(key, images) + recorded.put(key, [name for name in map(kept_image, images) if name is not None]) changed = False for message in users: - paths = recorded.get(message_digest(_text_of(message))) - if not paths: + names = recorded.get(message_digest(_text_of(message))) + if not names: continue content = message.get("content") parts = [{"type": "text", "text": content}] if isinstance(content, str) else list(content or []) present = {json.dumps(part, sort_keys=True) for part in parts if isinstance(part, dict)} - added = [part for part in (media_part(path) for path in paths) + added = [part for part in (media_part(IMAGES_DIR / name) for name in names) if part is not None and json.dumps(part, sort_keys=True) not in present] if added: message["content"] = [*parts, *added] diff --git a/tst/unit/agents/antigravity/conftest.py b/tst/unit/agents/antigravity/conftest.py index d7b07da39..f3590f60e 100644 --- a/tst/unit/agents/antigravity/conftest.py +++ b/tst/unit/agents/antigravity/conftest.py @@ -78,6 +78,7 @@ def folders(monkeypatch, tmp_path): monkeypatch.setattr(module, "SKILLS_DIR", tmp_path / "home" / "skills") monkeypatch.setattr(module, "ENV_TIMES", times) monkeypatch.setattr(module, "TURN_IMAGES", images) + monkeypatch.setattr(module, "IMAGES_DIR", conversations / "images") monkeypatch.setattr(a2a_server, "WORKSPACE_DIR", workspace) monkeypatch.setattr(a2a_server, "INPUTS_DIR", workspace / "inputs") monkeypatch.setattr(a2a_server, "_CHANGELOG_DIR", tmp_path / "changelog") diff --git a/tst/unit/agents/antigravity/test_antigravity_bridge.py b/tst/unit/agents/antigravity/test_antigravity_bridge.py index 497bdb4d3..01d186248 100644 --- a/tst/unit/agents/antigravity/test_antigravity_bridge.py +++ b/tst/unit/agents/antigravity/test_antigravity_bridge.py @@ -368,7 +368,7 @@ def _rewritten(rewrite, messages: list[dict]) -> list[dict]: return json.loads(asyncio.run(rewrite(json.dumps({"model": "m", "messages": messages}).encode())))["messages"] -def test_an_image_goes_with_its_turns_message_once_and_with_it_in_the_turns_after(tmp_path): +def test_an_image_goes_with_its_turns_message_once_and_as_it_was_given_in_the_turns_after(tmp_path): image = tmp_path / "chart.png" image.write_bytes(b"\x89PNG") part = antigravity_bridge.media_part(str(image)) @@ -378,6 +378,7 @@ def test_an_image_goes_with_its_turns_message_once_and_with_it_in_the_turns_afte once = _rewritten(first, asked) twice = _rewritten(first, once) + image.write_bytes(b"GIF89a, edited by the agent") later = _rewritten(antigravity_bridge.turn_rewrite(None, []), [ *asked, {"role": "assistant", "content": "a chart"}, {"role": "user", "content": "its other label?"}]) @@ -389,15 +390,13 @@ def test_an_image_goes_with_its_turns_message_once_and_with_it_in_the_turns_afte assert later[4]["content"] == "its other label?" -def test_an_image_that_is_gone_is_left_out(tmp_path): - image = tmp_path / "chart.png" - image.write_bytes(b"\x89PNG") - _rewritten(antigravity_bridge.turn_rewrite(None, [str(image)]), [{"role": "user", "content": "look"}]) - image.unlink() +def test_an_image_gone_before_its_turn_sends_it_is_left_out(tmp_path): + asked = [{"role": "user", "content": "look"}] - later = _rewritten(antigravity_bridge.turn_rewrite(None, []), [{"role": "user", "content": "look"}]) + once = _rewritten(antigravity_bridge.turn_rewrite(None, [str(tmp_path / "chart.png")]), asked) + later = _rewritten(antigravity_bridge.turn_rewrite(None, []), asked) - assert later[0]["content"] == "look" + assert once == later == asked assert antigravity_bridge.media_part(str(tmp_path / "notes.txt")) is None diff --git a/tst/unit/agents/antigravity/test_snapshot.py b/tst/unit/agents/antigravity/test_snapshot.py index 4835ce5a4..33b5b5f57 100644 --- a/tst/unit/agents/antigravity/test_snapshot.py +++ b/tst/unit/agents/antigravity/test_snapshot.py @@ -6,6 +6,7 @@ import io import json +import shutil import tarfile from pathlib import Path @@ -52,7 +53,10 @@ async def test_a_conversation_and_its_workspace_load_into_another_agents_context (store / "conv-1.db-wal").write_bytes(b"wal") (store / "conv-2.db").write_bytes(b"another") antigravity_bridge.ENV_TIMES.put("2026-11-25T10:00:00-08:00", "2031-03-03T23:06:07-06:00") - antigravity_bridge.TURN_IMAGES.put("3f2a", [str(folders / "inputs" / "t1" / "chart.png")]) + antigravity_bridge.TURN_IMAGES.put("3f2a", ["c0ffee.png"]) + antigravity_bridge.IMAGES_DIR.mkdir() + (antigravity_bridge.IMAGES_DIR / "c0ffee.png").write_bytes(b"\x89PNG") + (antigravity_bridge.IMAGES_DIR / "unused.png").write_bytes(b"\x89PNG") (folders / "report.md").write_text("draft") ag.agent.set_session_ref_for_context("ctx-source", "conv-1") @@ -60,10 +64,10 @@ async def test_a_conversation_and_its_workspace_load_into_another_agents_context saved = await client.post("/ext/snapshot", json={"context_id": "ctx-source", "objects": { "trajectory": _WRITE, "workspace": _WRITE}}) assert saved.status_code == 200, saved.text - assert _members(objects["conversation.tgz"]) == ["env-times.json", "manifest.json", "store/conv-1.db", - "store/conv-1.db-wal", "turn-images.json"] - for path in store.iterdir(): - path.unlink() + assert _members(objects["conversation.tgz"]) == ["env-times.json", "images/c0ffee.png", "manifest.json", + "store/conv-1.db", "store/conv-1.db-wal", "turn-images.json"] + shutil.rmtree(store) + store.mkdir() (folders / "report.md").write_text("changed since") (folders / "stray.txt").write_text("stray") @@ -78,7 +82,8 @@ async def test_a_conversation_and_its_workspace_load_into_another_agents_context assert {path.name: path.read_bytes() for path in store.glob("conv-*")} == {"conv-1.db": b"sqlite", "conv-1.db-wal": b"wal"} assert antigravity_bridge.ENV_TIMES.all() == {"2026-11-25T10:00:00-08:00": "2031-03-03T23:06:07-06:00"} - assert antigravity_bridge.TURN_IMAGES.all() == {"3f2a": [str(folders / "inputs" / "t1" / "chart.png")]} + assert antigravity_bridge.TURN_IMAGES.all() == {"3f2a": ["c0ffee.png"]} + assert [path.name for path in antigravity_bridge.IMAGES_DIR.iterdir()] == ["c0ffee.png"] assert sorted(path.name for path in folders.iterdir()) == ["report.md"] assert (folders / "report.md").read_text() == "draft"