Skip to content
Merged
33 changes: 32 additions & 1 deletion agent/tool_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,36 @@
logger = logging.getLogger(__name__)



def _hook_args_with_terminal_cwd(function_name, function_args, task_id):
"""Return hook-facing args, enriched with the terminal session's effective
cwd when the model omitted workdir (repo_ecosystem_agents#700).

Security plugins (consent-boundary's script-file email lane) resolve
RELATIVE script paths against args cwd/workdir; the live session cwd is
tracked in the terminal environment (``env.cwd``), not the model args, so
without this the lane never sees it. A COPY is returned — the execution
args are never mutated (an unexpected ``cwd`` key must not reach the tool).
Best-effort: any failure returns the original args unchanged.
"""
if function_name != "terminal" or not isinstance(function_args, dict):
return function_args
if function_args.get("workdir") or function_args.get("cwd"):
return function_args
try:
from tools.terminal_tool import get_active_env

env = get_active_env(task_id)
live = getattr(env, "cwd", None)
if isinstance(live, str) and live.strip():
enriched = dict(function_args)
enriched["cwd"] = live
return enriched
except Exception:
pass
return function_args


def _budget_for_agent(agent) -> BudgetConfig:
"""Resolve a tool-result BudgetConfig scaled to the agent's context window.

Expand Down Expand Up @@ -418,7 +448,8 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe
from hermes_cli.plugins import get_pre_tool_call_block_message
block_message = get_pre_tool_call_block_message(
function_name,
function_args,
_hook_args_with_terminal_cwd(
function_name, function_args, effective_task_id or ""),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Enrich the sequential terminal hook

Terminal calls never reach this concurrent hook: _should_parallelize_tool_batch() returns false for every terminal batch because terminal is neither parallel-safe nor path-scoped, and single calls are also always sequential. Consequently the intended consent-boundary fix remains inert in production while execute_tool_calls_sequential() still passes the original args; apply the enrichment at that hook call as well and exercise the real dispatch path in the test.

AGENTS.md reference: AGENTS.md:L54-L57

Useful? React with 👍 / 👎.

task_id=effective_task_id or "",
session_id=getattr(agent, "session_id", "") or "",
tool_call_id=getattr(tool_call, "id", "") or "",
Expand Down
122 changes: 109 additions & 13 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -2921,6 +2921,8 @@ def __init__(self, config: Optional[GatewayConfig] = None):
# Track platforms that failed to connect for background reconnection.
# Key: Platform enum, Value: {"config": platform_config, "attempts": int, "next_retry": float}
self._failed_platforms: Dict[Platform, Dict[str, Any]] = {}
# Supervised reconnect-watcher task (see _start_reconnect_watcher).
self._reconnect_watcher_task: Optional[asyncio.Task] = None

# Track pending /update prompt responses per session.
# Key: session_key, Value: True when a prompt is waiting for user input.
Expand Down Expand Up @@ -3971,8 +3973,21 @@ async def _handle_adapter_fatal_error(self, adapter: BasePlatformAdapter) -> Non

# Queue retryable failures for background reconnection
if adapter.fatal_error_retryable:
# Plugin/runtime-registered platforms can be absent from the
# static config map — fall back to the config the adapter was
# built with. A silent drop here left photon stuck on "retrying"
# with nothing ever retrying (2026-07-30, 3-day iMessage outage).
platform_config = self.config.platforms.get(adapter.platform)
if platform_config and adapter.platform not in self._failed_platforms:
if platform_config is None:
platform_config = getattr(adapter, "config", None)
Comment on lines 4387 to +4389

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the profile when re-queuing adapter config

When a runtime-fatal adapter belongs to a secondary multiplexed profile and the default profile does not configure that platform, this fallback puts the secondary profile's config into the global retry queue. _reconnect_pass() then recreates it outside _profile_runtime_scope, assigns the default _handle_message, and installs it in self.adapters rather than the secondary profile map, so subsequent traffic can run under the wrong profile/home; carry the originating profile through the retry queue and restore it through the profile-specific path.

AGENTS.md reference: AGENTS.md:L147-L154

Useful? React with 👍 / 👎.

if platform_config is None:
logger.error(
"%s fatal error is retryable but no platform config is "
"available — cannot queue for reconnection; platform "
"stays down until gateway restart",
adapter.platform.value,
)
elif adapter.platform not in self._failed_platforms:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Queue Photon before its disconnect cancels the notifier

When Photon reports a runtime failure from _monitor_sidecar_health() or _supervise_sidecar(), this handler runs inside a task that PhotonAdapter.disconnect() cancels—directly for the health task and through _stop_sidecar() for the supervisor. The next await raises CancelledError, so execution never reaches this queue insertion after the adapter has already been removed from self.adapters, leaving Photon down without a reconnect attempt. Queue the retry before teardown or prevent disconnect() from cancelling its current notifier task, and test the real Photon callback/disconnect path rather than a fake adapter.

AGENTS.md reference: AGENTS.md:L84-L87

Useful? React with 👍 / 👎.

self._failed_platforms[adapter.platform] = {
"config": platform_config,
"attempts": 0,
Expand All @@ -3982,6 +3997,17 @@ async def _handle_adapter_fatal_error(self, adapter: BasePlatformAdapter) -> Non
"%s queued for background reconnection",
adapter.platform.value,
)
else:
# Already queued (e.g. a second fatal from the same outage) —
# refresh the retry clock so the watcher acts promptly instead
# of waiting out a stale backoff, unless the operator paused it.
info = self._failed_platforms[adapter.platform]
if not info.get("paused"):
info["next_retry"] = time.monotonic()
logger.info(
"%s already queued for reconnection — retry refreshed",
adapter.platform.value,
)

if not self.adapters and not self._failed_platforms:
self._exit_reason = adapter.fatal_error_message or "All messaging adapters disconnected"
Expand Down Expand Up @@ -7172,7 +7198,7 @@ async def start(self) -> bool:
len(self._failed_platforms),
", ".join(p.value for p in self._failed_platforms),
)
asyncio.create_task(self._platform_reconnect_watcher())
self._start_reconnect_watcher()

# Start background handoff watcher — picks up CLI sessions marked
# handoff_state='pending' in state.db and re-binds them to the
Expand Down Expand Up @@ -7651,6 +7677,62 @@ def _active_profile_name(self) -> str:
# self state, so inheriting the mixin keeps every self._kanban_* call site
# working unchanged while lifting ~1,000 LOC out of this file.

_WATCHER_RESTART_DELAY = 5.0 # base delay before respawning a crashed watcher
_WATCHER_RESTART_DELAY_CAP = 300.0 # backoff ceiling for a crash-looping watcher
_WATCHER_STABLE_RUN_S = 60.0 # a run this long clears the crash streak

def _start_reconnect_watcher(self) -> None:
"""Spawn the reconnect watcher under supervision.

The watcher used to be a bare ``asyncio.create_task`` — any exception
escaping the loop killed it silently and nothing ever reconnected
again for the life of the gateway, while platform state stayed on
"retrying" (2026-07-30 photon outage). The done-callback respawns it,
backing off exponentially if it crash-loops (never giving up — a capped
slow respawn beats recreating the permanent silent outage).
"""
self._watcher_started_at = time.monotonic()
task = asyncio.create_task(self._platform_reconnect_watcher())
self._reconnect_watcher_task = task
task.add_done_callback(self._on_reconnect_watcher_done)

def _watcher_restart_backoff(self) -> float:
streak = getattr(self, "_watcher_crash_streak", 0)
return min(
self._WATCHER_RESTART_DELAY * (2 ** min(streak, 8)),
self._WATCHER_RESTART_DELAY_CAP,
)

def _on_reconnect_watcher_done(self, task: "asyncio.Task") -> None:
if task.cancelled() or not self._running:
return
ran_for = time.monotonic() - getattr(self, "_watcher_started_at", 0.0)
if ran_for >= self._WATCHER_STABLE_RUN_S:
self._watcher_crash_streak = 0
delay = self._watcher_restart_backoff()
self._watcher_crash_streak = getattr(self, "_watcher_crash_streak", 0) + 1
exc = task.exception()
if exc is not None:
logger.error(
"Platform reconnect watcher crashed (%s) — restarting in %.0fs",
exc,
delay,
exc_info=exc,
)
else:
logger.error(
"Platform reconnect watcher exited unexpectedly — "
"restarting in %.0fs",
delay,
)
asyncio.get_running_loop().call_later(
delay, self._maybe_restart_reconnect_watcher
)

def _maybe_restart_reconnect_watcher(self) -> None:
if self._running:
self._start_reconnect_watcher()

async def _platform_reconnect_watcher(self) -> None:
"""Background task that periodically retries connecting failed platforms.

Expand All @@ -7665,8 +7747,6 @@ async def _platform_reconnect_watcher(self) -> None:
automatically — auto-pausing a recovered platform was the cause of
bots silently staying dead after a transient DNS failure.
"""
_BACKOFF_CAP = 300 # 5 minutes max between retries

await asyncio.sleep(10) # initial delay — let startup finish
while self._running:
if not self._failed_platforms:
Expand All @@ -7679,11 +7759,33 @@ async def _platform_reconnect_watcher(self) -> None:
await asyncio.sleep(1)
continue

now = time.monotonic()
for platform in list(self._failed_platforms.keys()):
await self._reconnect_pass()

# Check every 10 seconds for platforms that need reconnection
for _ in range(10):
if not self._running:
return
await asyncio.sleep(1)

async def _reconnect_pass(self) -> None:
"""One retry sweep over the failed-platform queue.

Extracted from the watcher loop for unit-testability. Tolerates
concurrent mutation of ``_failed_platforms``: a platform removed
while an earlier entry's reconnect was being awaited used to raise
KeyError outside the per-attempt try/except, killing the watcher.
"""
_BACKOFF_CAP = 300 # 5 minutes max between retries
now = time.monotonic()
for platform in list(self._failed_platforms.keys()):
if not self._running:
return
info = self._failed_platforms[platform]
info = self._failed_platforms.get(platform)
if info is None:
# Removed concurrently (reconnected via another path or
# unqueued) while an earlier entry's reconnect was
# awaited — skip, never KeyError.
continue
# Skip paused platforms entirely — they need explicit
# /platform resume to come back.
if info.get("paused"):
Expand Down Expand Up @@ -7835,12 +7937,6 @@ async def _platform_reconnect_watcher(self) -> None:
# resolution failure, etc.) is inherently transient — keep
# retrying at the backoff cap rather than auto-pausing.

# Check every 10 seconds for platforms that need reconnection
for _ in range(10):
if not self._running:
return
await asyncio.sleep(1)

async def stop(
self,
*,
Expand Down
31 changes: 28 additions & 3 deletions plugins/platforms/photon/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import base64
import json
import logging
import math
import os
import re
import secrets
Expand Down Expand Up @@ -91,6 +92,27 @@
# connect path indefinitely.
_NPM_REINSTALL_TIMEOUT = 600

# Sidecar readiness window. Healthy baseline startup is ~3s, but the node
# process's module import + top-level Spectrum init stretches well past 15s
# when the host is under load (observed at loadavg 25+ on 2026-08-02, where
# the old hardcoded 15s window failed every reconnect attempt).
_DEFAULT_SIDECAR_READY_TIMEOUT = 60.0
# Upper bound: past this the sidecar is dead, not slow — an unbounded wait
# would stall the whole reconnect pass on one platform.
_MAX_SIDECAR_READY_TIMEOUT = 600.0


def _sidecar_ready_timeout() -> float:
"""Readiness window in seconds; PHOTON_SIDECAR_READY_TIMEOUT overrides."""
raw = os.environ.get("PHOTON_SIDECAR_READY_TIMEOUT", "")
try:
Comment on lines +105 to +108

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Store the readiness timeout in config.yaml

This introduces a user-facing environment variable for a non-secret behavioral timeout, bypassing the project's configuration and setup UX. Define the Photon readiness timeout in config.yaml and resolve it through the normal config path rather than requiring operators to manage PHOTON_SIDECAR_READY_TIMEOUT out of band.

AGENTS.md reference: AGENTS.md:L102-L107

Useful? React with 👍 / 👎.

value = float(raw)
except ValueError:
return _DEFAULT_SIDECAR_READY_TIMEOUT
if not math.isfinite(value) or value <= 0:
return _DEFAULT_SIDECAR_READY_TIMEOUT
Comment on lines +108 to +113

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject non-finite readiness timeout values

Values such as PHOTON_SIDECAR_READY_TIMEOUT=nan or inf are accepted because both parse as floats and fail the value <= 0 check. nan makes the deadline comparison false immediately, so a healthy sidecar is reported failed without a single health probe, while inf can make this wait unbounded when the gateway's outer timeout is disabled; require math.isfinite(value) before accepting the override.

Useful? React with 👍 / 👎.

return min(value, _MAX_SIDECAR_READY_TIMEOUT)

# Photon / Envoy / spectrum-ts error substrings that indicate a transient
# upstream overload rather than a permanent failure. These are not in the
# core _RETRYABLE_ERROR_PATTERNS because they are specific to this adapter.
Expand Down Expand Up @@ -981,8 +1003,10 @@ async def _start_sidecar(self) -> None:
self._supervise_sidecar(self._sidecar_proc)
)

# Wait for /healthz to come up — give it up to 15s on cold start.
deadline = time.time() + 15.0
# Wait for /healthz to come up. Env-configurable: the sidecar's
# cold start is ~3s idle but scales with host load.
ready_timeout = _sidecar_ready_timeout()
deadline = time.time() + ready_timeout
Comment on lines +1025 to +1026

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep the outer connect timeout above the readiness window

The new 60-second default is still wrapped by GatewayRunner._connect_adapter_with_timeout(), whose default gateway.platform_connect_timeout is 30 seconds, so Photon startup is cancelled after 30 seconds and can never use the advertised readiness window. On the loaded hosts this change targets, any healthy startup taking 30–60 seconds will therefore continue to fail and re-enter the reconnect loop; coordinate these timeouts or derive the sidecar deadline from the existing outer connect budget.

AGENTS.md reference: AGENTS.md:L155-L164

Useful? React with 👍 / 👎.

last_err: Optional[Exception] = None
async with httpx.AsyncClient(timeout=2.0) as client:
while time.time() < deadline:
Expand All @@ -1002,7 +1026,8 @@ async def _start_sidecar(self) -> None:
last_err = e
await asyncio.sleep(0.2)
raise RuntimeError(
f"Photon sidecar did not become ready within 15s: {last_err}"
f"Photon sidecar did not become ready within "
f"{ready_timeout:.0f}s: {last_err}"
)

async def _supervise_sidecar(self, proc: subprocess.Popen) -> None:
Expand Down
6 changes: 3 additions & 3 deletions tests/agent/test_anthropic_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -682,7 +682,7 @@ def test_returns_token_from_credential_files(self, monkeypatch, tmp_path):
monkeypatch.setattr("agent.anthropic_adapter.Path.home", lambda: tmp_path)

with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0)
mock_run.return_value = MagicMock(returncode=0, stdout="")
token = run_oauth_setup_token()

assert token == "from-cred-file"
Expand All @@ -700,7 +700,7 @@ def test_returns_token_from_env_var(self, monkeypatch, tmp_path):
monkeypatch.setattr("agent.anthropic_adapter.Path.home", lambda: tmp_path)

with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0)
mock_run.return_value = MagicMock(returncode=0, stdout="")
token = run_oauth_setup_token()

assert token == "from-env-var"
Expand All @@ -713,7 +713,7 @@ def test_returns_none_when_no_creds_found(self, monkeypatch, tmp_path):
monkeypatch.setattr("agent.anthropic_adapter.Path.home", lambda: tmp_path)

with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0)
mock_run.return_value = MagicMock(returncode=0, stdout="")
token = run_oauth_setup_token()

assert token is None
Expand Down
47 changes: 47 additions & 0 deletions tests/agent/test_hook_args_terminal_cwd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""pre_tool_call hook args carry the terminal session's effective cwd
(repo_ecosystem_agents#700): the consent-boundary plugin's script-file email
lane resolves RELATIVE script paths against args cwd/workdir — without this
enrichment the lane is inert whenever the model omits workdir."""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[2]))

from agent.tool_executor import _hook_args_with_terminal_cwd # noqa: E402


class _Env:
def __init__(self, cwd):
self.cwd = cwd


def test_terminal_without_workdir_gains_session_cwd(monkeypatch):
import tools.terminal_tool as tt
monkeypatch.setattr(tt, "get_active_env", lambda tid: _Env("/srv/daemon"))
args = {"command": "python3 send.py"}
out = _hook_args_with_terminal_cwd("terminal", args, "t1")
assert out["cwd"] == "/srv/daemon"
assert "cwd" not in args # original execution args never mutated


def test_explicit_workdir_wins(monkeypatch):
import tools.terminal_tool as tt
monkeypatch.setattr(tt, "get_active_env", lambda tid: _Env("/other"))
args = {"command": "x", "workdir": "/explicit"}
assert _hook_args_with_terminal_cwd("terminal", args, "t1") is args


def test_non_terminal_passthrough(monkeypatch):
args = {"command": "x"}
assert _hook_args_with_terminal_cwd("todo", args, "t1") is args


def test_no_env_or_error_degrades_to_original(monkeypatch):
import tools.terminal_tool as tt
monkeypatch.setattr(tt, "get_active_env", lambda tid: None)
args = {"command": "x"}
assert _hook_args_with_terminal_cwd("terminal", args, "t1") is args
def boom(tid):
raise RuntimeError("env store down")
monkeypatch.setattr(tt, "get_active_env", boom)
assert _hook_args_with_terminal_cwd("terminal", args, "t1") is args
Loading