Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/agent_env/env/gateway/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,11 @@ def due_deferred_calls(state: dict) -> list[dict]:
# a server's deferred calls (AGENT_ENV_DEFERRED_CALLS_META_KEY) are made, reported to the triggers, listed in state (each
# `due` once the clock reaches it and until it is made) and counted in its next_event_at.
TRIGGER_DEFERRED_CALLS = "deferred_calls"
TRIGGER_SERVER_CONFIG = "server_config"
TRIGGER_FEATURES = (TRIGGER_NAMED_EXECUTORS, TRIGGER_PROVOKING_ROLES, TRIGGER_ACTION_DELAY, TRIGGER_EXECUTOR_HOURS,
TRIGGER_UNLESS, TRIGGER_WEBSITE, TRIGGER_EXECUTOR_HOURS_TIME_ZONE, TRIGGER_NEXT_EVENT_AT,
TRIGGER_NOTIFY, TRIGGER_WEBSITE_OP, TRIGGER_FIRES_IN_STATE, TRIGGER_DEFERRED_CALLS)
TRIGGER_NOTIFY, TRIGGER_WEBSITE_OP, TRIGGER_FIRES_IN_STATE, TRIGGER_DEFERRED_CALLS,
TRIGGER_SERVER_CONFIG)

# The one `source` a /step call may name instead of step_api, with the id of the hook artifact that made it.
STEP_SOURCE_POST_TURN_HOOK = "post_turn_hook"
Expand Down
54 changes: 54 additions & 0 deletions src/agent_env/env/gateway/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
lowered,
operations,
reaches_child_mcp,
read_child_card,
refuse_websocket,
relay_websocket,
rewrite_child_card,
Expand Down Expand Up @@ -162,6 +163,9 @@ class Gateway:
STARTUP_DISCOVERY_TIMEOUT_S = 60.0 # startup discovery past it fails open, like a failed one; uvicorn must come up
BARRIER_READ_AHEAD_MAX_BYTES = 8 * 1024 * 1024 # a larger sized body held by a barrier streams, its window to the last byte
TRIGGER_BARRIER_TIMEOUT_S = 30.0 # a barrier may ask for less; past it the call is answered anyway
SERVER_CONFIG_TIMEOUT_S = 30.0 # one config extension call, as long as apply_server_config gives one by default
SERVER_CONFIG_REPLY_EXCERPT_CHARS = 200
SERVER_CONFIG_DETAIL_MAX_CHARS = 300
# Must be >= the largest timeout any client can ask for, or the proxy severs a load the
# client was still legitimately waiting on -- the ordering this module's constants file
# documents (client add_data >= gateway REST proxy >= actual load time). Clients now
Expand Down Expand Up @@ -1223,6 +1227,56 @@ async def _serve_env_card(self) -> Response:
}
return self._json_response(card, 200)

async def _configure_servers(self, service: str, uri: str, args: dict, *, tolerate: bool) -> list[dict]:
"""Invoke config extension ``uri`` on the server ``service`` names (an MCP server before a website) or on each for
``*``, at its own address: never through the gateway's routes, which a bundle's lock may have closed."""
if service == WILDCARD:
keys = list(self.rest_proxy_urls)
else:
named = [key for key in self.rest_proxy_urls if self._environment_name(key) == service]
keys = [next((key for key in named if key not in self.website_urls), named[0])] if named else []
if not keys:
detail = "the env has no backing servers" if service == WILDCARD else f"no backing server is named {service!r}"
return [{"service": service, "outcome": "failed", "detail": detail}]
async with httpx.AsyncClient() as client:
return list(await asyncio.gather(*(self._configure_server(client, key, uri, args, broadcast=service == WILDCARD,
tolerate=tolerate) for key in keys)))

async def _configure_server(self, client: httpx.AsyncClient, key: str, uri: str, args: dict, *, broadcast: bool,
tolerate: bool) -> dict:
"""One server's outcome, applied, skipped or failed, as apply_server_config decides it for a directive."""
website = key in self.website_urls
lenient = tolerate or (broadcast and website)
outcome = {"service": self._environment_name(key), **({"website": True} if website else {})}
base = self.rest_proxy_urls[key].rstrip("/")
try:
card = await read_child_card(client, base)
if card is None and lenient:
return {**outcome, "outcome": "skipped", "reason": "no_env_card"}
if card is None:
raise ValueError(f"it serves no env card, so it advertises no {uri!r}")
ext = next((e for e in (card.get("capabilities") or {}).get("extensions") or []
if isinstance(e, dict) and e.get("uri") == uri), None)
if ext is None and lenient:
return {**outcome, "outcome": "skipped", "reason": "extension_not_advertised"}
if ext is None:
raise ValueError(f"its card does not advertise {uri!r}")
ops = operations(ext["params"]) if isinstance(ext.get("params"), dict) else []
if not ops:
raise ValueError(f"its card names no endpoint for {uri!r}")
_, _, _, verb, endpoint = ops[0]
body = {"params": args} if verb == "GET" else {"json": args}
response = await client.request(verb, f"{base}{endpoint}", timeout=self.SERVER_CONFIG_TIMEOUT_S, **body)
if not response.is_success:
excerpt = response.text[:self.SERVER_CONFIG_REPLY_EXCERPT_CHARS]
raise ValueError(f"{uri!r} answered HTTP {response.status_code}: {excerpt}")
except httpx.HTTPStatusError as e:
return {**outcome, "outcome": "failed", "detail": f"its card answered HTTP {e.response.status_code}"}
except Exception as e: # any one server's failure is its outcome, so a broadcast still tries every other
detail = str(e) or type(e).__name__
return {**outcome, "outcome": "failed", "detail": detail[:self.SERVER_CONFIG_DETAIL_MAX_CHARS]}
return {**outcome, "outcome": "applied"}

def _jsonrpc_error(self, request_id: Any, code: int, message: str) -> Response:
return self._json_response({"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}, 200)

Expand Down
27 changes: 16 additions & 11 deletions src/agent_env/env/gateway/rest_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -590,22 +590,27 @@ async def _replay(chunks: list[bytes], failure: Exception | None) -> AsyncIterat

async def fetch_child_card(client: httpx.AsyncClient, key: str, base_url: str) -> dict | None:
"""One backing server's card as it serves it; None (omit) on 404 / error / timeout / malformed JSON."""
url = f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}"
try:
response = await client.get(url, timeout=CARD_FETCH_TIMEOUT_S)
return await read_child_card(client, base_url)
except httpx.HTTPStatusError as e:
logger.warning(f"env card: {key} returned HTTP {e.response.status_code}; omitting")
except ValueError:
logger.warning(f"env card: {key} returned malformed JSON; omitting")
except Exception as e:
logger.warning(f"env card: fetching {key} failed ({type(e).__name__}: {e}); omitting")
return None
return None


async def read_child_card(client: httpx.AsyncClient, base_url: str) -> dict | None:
"""One backing server's card as it serves it, None when it serves none (404); raises on any other failure."""
response = await client.get(f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}", timeout=CARD_FETCH_TIMEOUT_S)
if response.status_code == 404:
return None
if response.status_code >= 400:
logger.warning(f"env card: {key} returned HTTP {response.status_code}; omitting")
return None
try:
return response.json()
except Exception:
logger.warning(f"env card: {key} returned malformed JSON; omitting")
return None
response.raise_for_status()
card = response.json()
if not isinstance(card, dict):
raise ValueError(f"its card is a JSON {type(card).__name__}, not an object")
return card


def rewrite_child_card(key: str, card: dict, gateway_extensions: list[dict]) -> dict:
Expand Down
44 changes: 41 additions & 3 deletions src/agent_env/env/gateway/triggers.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
_CTX_ROOTS = {"action": ("args", "result"), "website": ("args",)}
# RFC 9110's safe methods: a request using one asks for no change, so it prompts no state re-evaluation.
_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "TRACE"})
_ACTION_TYPES = ("nl", "tool", "permission", "notify")
_ACTION_TYPES = ("nl", "tool", "permission", "notify", "server_config")
_TERMINAL_A2A_STATES = ("completed", "failed", "canceled", "rejected")
# Bounds the per-evaluation catch-up burst; the backlog drains on later evaluations.
_MAX_CATCHUP = 1000
Expand Down Expand Up @@ -854,10 +854,12 @@ def _normalize_action(action: Any, w: str, roots: tuple[str, ...], executors: di
raise TriggerError(f"{w}: 'as' is only valid on tool actions")
if "executor" in action and atype != "nl":
raise TriggerError(f"{w}: 'executor' is only valid on nl actions")
if "verify" in action and atype == "notify":
raise TriggerError(f"{w}: a notify action has nothing to verify")
if "verify" in action and atype in ("notify", "server_config"):
raise TriggerError(f"{w}: a {atype} action has nothing to verify")
if "to" in action and atype != "notify":
raise TriggerError(f"{w}: 'to' is only valid on notify actions")
if "tolerate_unadvertised" in action and atype != "server_config":
raise TriggerError(f"{w}: 'tolerate_unadvertised' is only valid on server_config actions")
if action.get("delay") is None:
action.pop("delay", None)
else:
Expand Down Expand Up @@ -903,6 +905,17 @@ def _normalize_action(action: Any, w: str, roots: tuple[str, ...], executors: di
if _VAR_LOOSE_RE.search(acting): # never run through _template, so a placeholder would be sent verbatim
raise TriggerError(f"{w}: 'as' is not templated; name the role literally")
action["as"] = acting # forwarded as-is by _run_action, so stripped here like the header path strips
elif atype == "server_config":
for key in ("service", "uri"):
if not isinstance(action.get(key), str) or not action[key]:
raise TriggerError(f"{w}: {key} must be a non-empty string")
if _VAR_LOOSE_RE.search(action[key]):
raise TriggerError(f"{w}: {key} is not templated; name it literally")
if not isinstance(action.get("args", {}), dict):
raise TriggerError(f"{w}: args must be an object")
_validate_placeholders(action.get("args", {}), f"{w}.args", roots)
if not isinstance(action.get("tolerate_unadvertised", False), bool):
raise TriggerError(f"{w}: tolerate_unadvertised must be true or false")
else:
if action.get("action") not in ("enable", "disable"):
raise TriggerError(f"{w}: action must be 'enable' or 'disable'")
Expand Down Expand Up @@ -1631,6 +1644,11 @@ async def _run_action(self, tid: str, trig: dict, index: int, action: dict, ctx:
# the text may carry what a person wrote, so the log keeps its size, not its words
detail = {"notify": action["channel"], "to": note["to"], "notification_id": note["id"],
"text_len": len(text)}
elif action["type"] == "server_config":
configured = await self._run_server_config(tid, index, action, ctx)
if configured is None:
return False
detail = configured
else:
done = await self._run_nl(tid, trig, index, action, ctx, fire=fire)
if done is None:
Expand All @@ -1651,6 +1669,26 @@ async def _run_action(self, tid: str, trig: dict, index: int, action: dict, ctx:
**_named_executor(action))
return False

async def _run_server_config(self, tid: str, index: int, action: dict, ctx: dict) -> dict | None:
"""Apply a server_config action through the gateway (``_configure_servers``) and record each server's outcome
in the env trajectory; its action_ok detail, or None when it failed on any server."""
target = {"service": action["service"], "uri": action["uri"]}
try:
args = _template(action.get("args", {}), {}, ctx)
except TemplateError as e:
args, servers, detail = None, [], str(e)[:300]
else:
servers = await self._gw._configure_servers(action["service"], action["uri"], args,
tolerate=action.get("tolerate_unadvertised", False))
detail = "; ".join(f"{s['service']}: {s['detail']}" for s in servers if s["outcome"] == "failed")[:300]
await self._gw._log_event({"event_type": "server_config", "source": "trigger_engine", "trigger_id": tid,
"action_index": index, **target, "arguments": args and _echo_args(args),
"servers": servers, "ok": not detail, **({"detail": detail} if detail else {})})
if detail:
self._emit("action_failed", tid, action_index=index, servers=servers, **target, detail=detail)
return None
return {"server_config": action["uri"], "service": action["service"], "servers": servers}

async def _run_verify(self, tid: str, index: int, verify: dict, ctx: dict | None = None,
role: str | None = None) -> bool:
if await self._run_check(verify, ctx, role=role):
Expand Down
10 changes: 8 additions & 2 deletions src/agent_env/task_step/task_steps/register_env_triggers.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
TRIGGER_NAMED_EXECUTORS,
TRIGGER_NOTIFY,
TRIGGER_PROVOKING_ROLES,
TRIGGER_SERVER_CONFIG,
TRIGGER_UNLESS,
TRIGGER_WEBSITE,
TRIGGER_WEBSITE_OP,
Expand Down Expand Up @@ -165,8 +166,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext:
TRIGGER_WEBSITE_OP: any(isinstance(t.get("when"), dict) and t["when"].get("type") == "website"
and t["when"].get("op") is not None for t in self.triggers),
TRIGGER_EXECUTOR_HOURS_TIME_ZONE: _hours_in_a_time_zone(self.executor_hours),
TRIGGER_NOTIFY: any(a.get("type") == "notify" for t in self.triggers
for a in t.get("actions") or [] if isinstance(a, dict))}
TRIGGER_NOTIFY: _acts(self.triggers, "notify"),
TRIGGER_SERVER_CONFIG: _acts(self.triggers, "server_config")}
missing = [feature for feature, needed in used.items() if needed and feature not in _trigger_features(deployed)]
if missing:
raise RuntimeError(
Expand Down Expand Up @@ -276,6 +277,11 @@ def _when_has(triggers: list[dict], key: str) -> bool:
return any(isinstance(trigger.get("when"), dict) and trigger["when"].get(key) for trigger in triggers)


def _acts(triggers: list[dict], action_type: str) -> bool:
return any(isinstance(action, dict) and action.get("type") == action_type
for trigger in triggers for action in trigger.get("actions") or [])


def _delays(triggers: list[dict]) -> bool:
return any(isinstance(action, dict) and action.get("delay") is not None
for trigger in triggers for action in trigger.get("actions") or [])
Expand Down
Loading
Loading