Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
27f442f
feat(env-providers): tear down one slot of a shared VM
mandykwok-scale Nov 19, 2026
7b8f7cb
feat(sandbox-providers): a shared Modal VM is ended only by terminate…
mandykwok-scale Nov 19, 2026
35fbb0c
fix(sandbox-providers): never reboot a shared box, and check every Mo…
mandykwok-scale Nov 19, 2026
1e5da7a
feat(sandbox-providers): a shared box runs gVisor behind slot walls, …
mandykwok-scale Nov 20, 2026
d8821a1
feat(env-providers): a slot's compose fits its walls, and every door …
mandykwok-scale Nov 21, 2026
ecf36a8
fix(sandbox-providers): the walls apply atomically, match slots by br…
mandykwok-scale Nov 21, 2026
d24cfca
fix(env-providers): the door is no open proxy, the slot check allows …
mandykwok-scale Nov 21, 2026
ff047c4
fix(sandbox-providers): no slot forges a reply into another, IPv6 is …
mandykwok-scale Nov 21, 2026
b24271f
feat(sandbox-providers): a shared box is tagged walls-verified only a…
mandykwok-scale Nov 21, 2026
70e6740
fix(sandbox-providers): the private-range probe skips public resolver…
mandykwok-scale Nov 21, 2026
14d300a
fix(sandbox-providers): a shared box's runsc writes container files t…
mandykwok-scale Nov 21, 2026
e61cee5
fix(sandbox-providers): name the shared-box timeout default, and keep…
mandykwok-scale Nov 23, 2026
3ac525f
fix(env-providers): quoted secrets are masked in the logged compose, …
mandykwok-scale Nov 23, 2026
bcfc436
test(env-providers): a quoted or multiline secret rendered by the rea…
mandykwok-scale Nov 23, 2026
4241fb0
Merge origin/main into mandy/shared-slot-teardown
mandykwok-scale Nov 23, 2026
c189276
fix(sandbox-providers): name the walls probes' time limits, wait for …
mandykwok-scale Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions packages/agentenv-protocol/src/agentenv_protocol/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,16 +120,18 @@ async def get_data(
return GetDataResponse.model_validate(await _rpc(base_url, METHOD_GET, params, timeout, verify, headers))


async def get_card(base_url: str, timeout: int = 10, verify: bool = True) -> dict:
async def get_card(base_url: str, timeout: int = 10, verify: bool = True, *,
headers: dict[str, str] | None = None) -> dict:
"""The env card at ``base_url``, read with ``headers`` alone: unlike an RPC, a card read takes nothing from a grant."""
async with httpx.AsyncClient(verify=verify) as client:
response = await client.get(f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}", timeout=timeout)
response = await client.get(f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}", timeout=timeout, headers=headers)
response.raise_for_status()
return response.json()


async def supports_v1(base_url: str, verify: bool = True) -> bool:
async def supports_v1(base_url: str, verify: bool = True, *, headers: dict[str, str] | None = None) -> bool:
try:
await get_card(base_url, verify=verify)
await get_card(base_url, verify=verify, headers=headers)
return True
except httpx.HTTPStatusError as e:
if e.response.status_code != 404:
Expand Down
12 changes: 7 additions & 5 deletions src/agent_env/a2a_agent/a2a_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
NetworkPolicyUnsupportedError,
port_bindings,
)
from agent_env.artifact.artifacts.cli import GATEWAY_ENV_FILE
from agent_env.artifact.artifacts.cli import GATEWAY_ENV_FILE, SLOT_TOKEN_ENV_VAR
from agent_env.artifact.artifacts.docker_image import DockerImageArtifact
from agent_env.a2a_agent.object_transfer import (
TRANSFER_TIMEOUT_SECONDS,
Expand Down Expand Up @@ -297,29 +297,31 @@ def _skill_extension(deployed: "DeployedA2AAgent") -> dict:
@staticmethod
async def install_cli(
deployed: "DeployedA2AAgent", cli_artifact: "CliArtifact", gateway_url: str, container: str | None = None,
on_host: bool = False,
on_host: bool = False, slot_token: str | None = None,
) -> str:
"""Install a CliArtifact bundle into the agent's filesystem at /opt/cli/<command>/, in ``container`` when
install_agent put the agent in one, or on the VM host, ``on_host``, when it put it there. Writes a sidecar
bin/.env with the gateway URL and chmod +x's the entrypoint. Idempotent. Returns the path to the entrypoint."""
bin/.env with the gateway URL, and the door token of a gateway in a slot (``slot_token``), and chmod +x's
the entrypoint. Idempotent. Returns the path to the entrypoint."""
from agent_env.providers.sandbox_providers.sandbox import VmSandbox, into_container, stage_files_into_container
from agent_env.providers.sandbox_providers.sandbox_provider import build_sandbox_provider, get_agent_sandbox_provider
provider = build_sandbox_provider(deployed.sandbox_type) if deployed.sandbox_type else get_agent_sandbox_provider()
sandbox = await provider.get_sandbox(deployed.sandbox_id)
target_root = f"/opt/cli/{cli_artifact.command_name}"
entrypoint_path = f"{target_root}/{cli_artifact.entrypoint}"
env_dir = posixpath.dirname(entrypoint_path)
env_file = f"AGENT_ENV_GATEWAY_URL={gateway_url}\n" + (f"{SLOT_TOKEN_ENV_VAR}={slot_token}\n" if slot_token else "")

if on_host:
await sandbox.write_host_file(f"AGENT_ENV_GATEWAY_URL={gateway_url}\n".encode(), f"{env_dir}/{GATEWAY_ENV_FILE}")
await sandbox.write_host_file(env_file.encode(), f"{env_dir}/{GATEWAY_ENV_FILE}")
await stage_files_into_container(
sandbox, cli_artifact.get_cli_files().get_file_artifacts(), target_root, on_host=True)
await sandbox.exec_script(f"chmod +x {shlex.quote(entrypoint_path)}")
logger.info(f"Installed CliArtifact '{cli_artifact.id}' v{cli_artifact.version} on the host at {entrypoint_path}")
return entrypoint_path

# write .env first — write_file_from_text creates the parent dir; write_file_from_object does not.
await sandbox.write_file_from_text(f"AGENT_ENV_GATEWAY_URL={gateway_url}\n", f"{env_dir}/{GATEWAY_ENV_FILE}",
await sandbox.write_file_from_text(env_file, f"{env_dir}/{GATEWAY_ENV_FILE}",
**into_container(container))

for rel_path, file_artifact in cli_artifact.get_cli_files().get_file_artifacts().items():
Expand Down
3 changes: 3 additions & 0 deletions src/agent_env/artifact/artifacts/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
_COMMAND_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9._-]*")
# The file installing a CLI writes the gateway URL to, beside its entrypoint.
GATEWAY_ENV_FILE = ".env"
# The door token of a gateway in a slot of a shared VM, which an installed CLI sends as the door's header on every call;
# unset for the default stack.
SLOT_TOKEN_ENV_VAR = "AGENT_ENV_SLOT_TOKEN"


class CliArtifact(Artifact):
Expand Down
28 changes: 28 additions & 0 deletions src/agent_env/env/door_headers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""The header a slot's door takes (``gateway.door``), picked out of what a call is granted.

A slot's grant (``DeployedGatewayEnv.grants``) gives the door's header on every address of the slot, beside the
control token on the gateway's. A call that today sends no credential sends only the door's header, so the door lets
it in and the service behind it sees nothing it didn't before; outside a slot that is nothing at all.
"""

from __future__ import annotations

from agentenv_protocol import client as protocol_v1

from agent_env.env.gateway.constants import SLOT_TOKEN_HEADER


def slot_token_headers(token: str | None) -> dict[str, str]:
"""The header that carries a slot's door token; none without one, as for the default stack."""
return {SLOT_TOKEN_HEADER: token} if token else {}


def door_headers(headers: dict[str, str]) -> dict[str, str]:
"""The slot door's header among ``headers``, alone; none when they don't carry it."""
return {SLOT_TOKEN_HEADER: headers[SLOT_TOKEN_HEADER]} if SLOT_TOKEN_HEADER in headers else {}


def granted_door_headers(url: str) -> dict[str, str]:
"""The slot door's header the running step's grant gives a call to ``url`` (``protocol_v1.authorized``); none
outside a slot or a grant."""
return door_headers(protocol_v1.request_headers(url))
44 changes: 39 additions & 5 deletions src/agent_env/env/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from agent_env.utils.paths import validate_relative_filename

from .gateway import GatewayMode
from .door_headers import door_headers, slot_token_headers
from .gateway.console_session import LINK_DEFAULT_SECONDS, LINK_PARAM, ConsoleSession
from .gateway.constants import WELL_KNOWN_PATH
from .store import get_env_store
Expand Down Expand Up @@ -119,10 +120,20 @@ def control_headers(self) -> dict[str, str]:
"""What a call to the env's framework-only routes sends: its control token, when it has one."""
return protocol_v1.control_headers(self.control_token)

@property
def grants(self) -> dict[str, dict[str, str]]:
"""What a call under each of the env's addresses sends, by address: ``control_headers`` under its own, as a
step's grant (``protocol_v1.authorized``) gives them."""
return {self.environment_url: self.control_headers} if self.environment_url and self.control_headers else {}

def control_headers_for(self, url: str) -> dict[str, str]:
"""What a call to ``url`` sends of the env's control token: ``control_headers`` when ``url`` is the env's
address or under it, as a step's grant gives them, and none anywhere else, an override's address say."""
return protocol_v1.granted_headers(url, {self.environment_url: self.control_headers})
"""What a call to ``url`` sends: what ``grants`` gives the address it is or is under, and none anywhere else,
an override's address say."""
return protocol_v1.granted_headers(url, self.grants)

def door_headers_for(self, url: str) -> dict[str, str]:
"""The slot door's header of what a call to ``url`` sends (``door_headers``); none for an env not in a slot."""
return door_headers(self.control_headers_for(url))

def supports(self, uri: str, method: str) -> bool:
"""Whether the stored env card offers `method` on the extension at `uri`; no network."""
Expand Down Expand Up @@ -182,7 +193,8 @@ async def readiness(self, timeout: float = READY_TIMEOUT_S) -> WebsiteReadiness:
raise EnvCapabilityUnsupported(WEBSITE_EXTENSION_URI, WEBSITE_READY_OP, self.env_id, self.instance_id)
card = self.environment_card
if card is None:
card = await protocol_v1.get_card(self.environment_url, timeout=timeout)
card = await protocol_v1.get_card(self.environment_url, timeout=timeout,
headers=self.door_headers_for(self.environment_url))
return await env_readiness(self.environment_url, card, timeout=timeout, headers=self.control_headers)

@classmethod
Expand Down Expand Up @@ -248,6 +260,26 @@ class DeployedGatewayEnv(DeployedSandboxEnv):
# Where the gateway's stack lives when it is one slot of a VM other runs share (StackLayout.to_record); None for
# the default stack, which has the VM to itself.
stack_layout: Optional[dict] = None
# The token the door of a slot's stack takes on every request to its addresses; None for the default stack.
door_token: Optional[str] = None

@property
def control_headers(self) -> dict[str, str]:
"""What a call to the env's framework-only routes sends: in a slot, the door's header too."""
return {**self._door_header, **super().control_headers}

@property
def grants(self) -> dict[str, dict[str, str]]:
"""In a slot, the gateway's address takes the door's header with the control token, pgweb's and db-mcp's
``/svc`` routes under it among them."""
grants = super().grants
if self._door_header and self.gateway_url:
grants.setdefault(self.gateway_url.rstrip("/"), self.control_headers)
return grants

@property
def _door_header(self) -> dict[str, str]:
return slot_token_headers(self.door_token)

@classmethod
def _fields_from(cls, data: dict) -> dict:
Expand All @@ -265,6 +297,7 @@ def _fields_from(cls, data: dict) -> dict:
"env_state_instance_ids": data.get("env_state_instance_ids") or [],
"child_envs": data.get("child_envs") or {},
"stack_layout": data.get("stack_layout"),
"door_token": data.get("door_token"),
}

def pgweb_link(self, seconds: int = LINK_DEFAULT_SECONDS) -> Optional[str]:
Expand Down Expand Up @@ -604,4 +637,5 @@ def _record_class(data: dict) -> type[DeployedEnv]:

# A record carrying any of these is a gateway's. Not gateway_mode: an older kernel writes its default into any record it round-trips.
_GATEWAY_ONLY_FIELDS = ("gateway_url", "db_web_url", "db_mcp_url", "db_web_gateway_url", "db_mcp_gateway_url",
"website_frontend_urls", "vnc_url", "env_state_instance_ids", "child_envs", "stack_layout")
"website_frontend_urls", "vnc_url", "env_state_instance_ids", "child_envs", "stack_layout",
"door_token")
3 changes: 2 additions & 1 deletion src/agent_env/env/envs/multi_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -1133,7 +1133,8 @@ def _record_grant(deployed: Optional[DeployedEnv]):
name it shares with another keeps from the record (``_hand_record_to_child_envs``), whose calls go to the gateway."""
if deployed is None:
return protocol_v1.authorized({})
return protocol_v1.authorized({url: deployed.control_headers for url in (deployed.environment_url, gateway_url_of(deployed))})
return protocol_v1.authorized({**{url: deployed.control_headers for url in (deployed.environment_url, gateway_url_of(deployed))},
**deployed.grants})


def _hand_record_to_child_envs(env: MultiEnv, deployed: DeployedEnv) -> None:
Expand Down
7 changes: 7 additions & 0 deletions src/agent_env/env/gateway/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,3 +339,10 @@ def random_mcp_server_name() -> str:
"required": False,
},
]

# A slot's door (``gateway.door``): the one container of a slot of a shared VM that publishes host ports. It takes a
# request only with the slot's token in this header, which it removes before forwarding, and refuses every other.
SLOT_TOKEN_HEADER = "X-Agentenv-Slot-Token"
# The door's token, and its routes: comma-separated ``<listen port>=<host>:<port>``, one per port the slot publishes.
DOOR_TOKEN_ENV = "AGENTENV_SLOT_TOKEN"
DOOR_ROUTES_ENV = "AGENTENV_DOOR_ROUTES"
Loading
Loading