Merge branch 'simp/r3-05-w2' into simp/r3-05

This commit is contained in:
Teknium
2026-09-02 19:59:49 -07:00
7 changed files with 913 additions and 1834 deletions
+682 -1389
View File
File diff suppressed because it is too large Load Diff
+39 -86
View File
@@ -1,21 +1,15 @@
"""Unified deadline layer — one bounded-execution primitive, one timeout resolver.
"""Unified deadline layer — one bounded-execution primitive, one timeout resolver (#85125).
Shared foundation for the site-local deadline mechanisms (#85125):
* :func:`resolve_timeout` — config-first timeout resolution
(``timeouts:`` in config.yaml > legacy env var > default).
* :func:`clamp_timeout` — platform-safe clamping (huge timeouts overflow
``time_t`` in ``Lock.acquire`` / ``Thread.join`` on macOS, #83220).
* :func:`run_bounded_async` — wall-clock deadline for awaitables driven by a
daemon ``threading.Timer``, so a blocked event loop cannot disable it (the
telegram adapter's ``_await_with_thread_deadline`` generalized).
* :func:`run_bounded_sync` — same contract for synchronous callables.
* :func:`resolve_timeout` — ``timeouts:`` in config.yaml > legacy env var > default.
* :func:`clamp_timeout` — huge timeouts overflow ``time_t`` in ``Lock.acquire`` /
``Thread.join`` on macOS (#83220), so every timeout is capped.
* :func:`run_bounded_async` / :func:`run_bounded_sync` — wall-clock deadlines driven by
a daemon ``threading.Timer`` / worker thread, so a blocked event loop cannot disable them.
* :func:`kill_process_tree` — portable whole-tree termination.
Invariants: operation exceptions propagate unchanged (only the *timeout*
outcome is reified as :class:`BoundedResult`); a timeout from this layer is
OUR deadline, not the provider's (classify :class:`DeadlineExpired` distinctly
from transport timeouts); ``None`` / non-positive timeout means unbounded.
Invariants: operation exceptions propagate unchanged (only the *timeout* outcome is reified
as :class:`BoundedResult`); a timeout here is OUR deadline, not the provider's (classify
:class:`DeadlineExpired` distinctly from transport timeouts); ``None`` / non-positive means unbounded.
"""
from __future__ import annotations
@@ -35,18 +29,11 @@ from typing import Any, Awaitable, Callable, Optional, Protocol
logger = logging.getLogger(__name__)
__all__ = [
"MAX_SAFE_TIMEOUT_S",
"BoundedResult",
"DeadlineExpired",
"clamp_timeout",
"resolve_timeout",
"run_bounded_async",
"run_bounded_sync",
"kill_process_tree",
"MAX_SAFE_TIMEOUT_S", "BoundedResult", "DeadlineExpired", "clamp_timeout", "resolve_timeout",
"run_bounded_async", "run_bounded_sync", "kill_process_tree",
]
# One year: semantically "unbounded" yet far below any platform time_t limit
# (#83220: larger relative timeouts overflow inside Lock.acquire/Thread.join on macOS).
# One year: semantically "unbounded" yet far below any platform time_t limit (#83220).
MAX_SAFE_TIMEOUT_S = 31_536_000.0
# Grace after a deadline fires before concluding the loop thread is blocked and dumping stacks.
@@ -67,14 +54,10 @@ class DeadlineExpired(TimeoutError):
class SuspectableBackend(Protocol):
"""A stateful backend (MCP connection, browser session, LSP client) the deadline layer can flag.
``run_bounded_*`` calls ``mark_suspect`` on timeout so the owner can health-check or
recycle the backend (``ensure_healthy``) before reuse. Backends without the protocol
are simply never marked. ``mark_suspect`` MUST be cheap, non-blocking, and must not
acquire locks the guarded operation may hold — it runs inline on the event loop /
caller's thread while the wedged worker is still alive.
"""
"""A stateful backend (MCP connection, browser session, LSP client) ``run_bounded_*`` flags via
``mark_suspect`` on timeout so the owner can health-check/recycle it before reuse. ``mark_suspect``
MUST be cheap, non-blocking, and must not acquire locks the guarded operation may hold — it runs
inline on the event loop / caller's thread while the wedged worker is still alive."""
def mark_suspect(self, reason: str) -> None: ...
@@ -122,9 +105,7 @@ def clamp_timeout(timeout: Optional[float]) -> Optional[float]:
if value != value: # NaN
logger.warning("clamp_timeout: NaN timeout; treating as unbounded")
return None
if value <= 0:
return None
return min(value, MAX_SAFE_TIMEOUT_S)
return None if value <= 0 else min(value, MAX_SAFE_TIMEOUT_S)
# --- Timeout resolution: config ``timeouts:`` > legacy env var > default ------
@@ -134,7 +115,6 @@ def _timeouts_section() -> dict:
"""Read the ``timeouts:`` root section from config.yaml (read-only, fail-open)."""
try:
from hermes_cli.config import load_config_readonly
section = load_config_readonly().get("timeouts")
return section if isinstance(section, dict) else {}
except Exception:
@@ -152,17 +132,9 @@ def _lookup_dotted(section: dict, key: str) -> Any:
return node
def resolve_timeout(
key: str,
*,
default: Optional[float],
env_var: Optional[str] = None,
) -> Optional[float]:
"""Resolve a timeout (seconds) for dotted ``timeouts.<key>`` > ``env_var`` > ``default``.
The winner goes through :func:`clamp_timeout`; invalid config/env values fall
through to the next source with a warning.
"""
def resolve_timeout(key: str, *, default: Optional[float], env_var: Optional[str] = None) -> Optional[float]:
"""Resolve a timeout (seconds): dotted ``timeouts.<key>`` > ``env_var`` > ``default``; the winner
goes through :func:`clamp_timeout`, invalid config/env values fall through with a warning."""
raw = _lookup_dotted(_timeouts_section(), key)
if raw is not None:
# Explicit float() so invalid config values FALL THROUGH to env/default instead of
@@ -218,14 +190,11 @@ async def _run_abandon_cleanup(on_abandon: Callable[[], Awaitable[Any]]) -> None
def _dump_blocked_loop_diagnostics(label: str, timeout_s: float) -> None:
logger.warning(
"[deadline] %r deadline (%.0fs) expired but the event loop has not "
"processed the expiry after a further %.0fs — the loop thread appears "
"BLOCKED in a synchronous call, which is why no asyncio timeout can "
"fire. Dumping all thread stacks to stderr to identify the blocking "
"frame.",
label,
timeout_s,
_LOOP_BLOCKED_DUMP_GRACE_S,
"[deadline] %r deadline (%.0fs) expired but the event loop has not processed the expiry "
"after a further %.0fs — the loop thread appears BLOCKED in a synchronous call, which is "
"why no asyncio timeout can fire. Dumping all thread stacks to stderr to identify the "
"blocking frame.",
label, timeout_s, _LOOP_BLOCKED_DUMP_GRACE_S,
)
try:
faulthandler.dump_traceback(all_threads=True)
@@ -244,11 +213,9 @@ async def run_bounded_async(
) -> BoundedResult:
"""Await ``awaitable`` under a wall-clock deadline independent of loop timers.
Operation exceptions (incl. ``CancelledError`` from a caller cancelling *us*)
propagate unchanged. On timeout the task is cancelled and **abandoned** (never
awaited — cancellation-shielded scopes are exactly the paths that wedge), and
``on_abandon`` is scheduled as detached best-effort cleanup.
"""
Operation exceptions (incl. ``CancelledError`` from a caller cancelling *us*) propagate
unchanged. On timeout the task is cancelled and **abandoned** (never awaited —
cancellation-shielded scopes are exactly the paths that wedge); ``on_abandon`` runs detached."""
timeout_s = clamp_timeout(timeout)
start = time.monotonic()
if timeout_s is None:
@@ -312,13 +279,10 @@ def run_bounded_sync(
on_timeout: Optional[Callable[[], None]] = None,
backend: object | None = None,
) -> BoundedResult:
"""Run ``fn`` in a daemon worker thread under a wall-clock deadline.
Exceptions re-raise in the caller. On expiry the worker is **abandoned** and
``on_timeout`` runs best-effort in the caller's thread. Every timeout leaks one
daemon thread, so do NOT use per-item in hot loops. The worker runs under
``contextvars.copy_context()`` so secret scope / session id survive the hop.
"""
"""Run ``fn`` in a daemon worker thread under a wall-clock deadline; exceptions re-raise in
the caller. On expiry the worker is **abandoned** (every timeout leaks one daemon thread, so
do NOT use per-item in hot loops) and ``on_timeout`` runs best-effort in the caller's thread.
The worker runs under ``contextvars.copy_context()`` so secret scope / session id survive."""
timeout_s = clamp_timeout(timeout)
start = time.monotonic()
if timeout_s is None:
@@ -336,8 +300,7 @@ def run_bounded_sync(
finally:
done.set()
thread = threading.Thread(target=_worker, name=f"deadline-{label}", daemon=True)
thread.start()
threading.Thread(target=_worker, name=f"deadline-{label}", daemon=True).start()
deadline = start + timeout_s
while not done.is_set():
remaining = deadline - time.monotonic()
@@ -366,30 +329,22 @@ def run_bounded_sync(
def kill_process_tree(pid: int, *, sig: Optional[int] = None) -> bool:
"""Terminate ``pid`` and all its descendants, portably.
"""Terminate ``pid`` and all its descendants, portably; True when anything was signalled.
Windows: ``taskkill /F /T`` (``sig`` ignored). POSIX: descendants are snapshotted
via psutil BEFORE signalling (once the parent dies they reparent and a parent walk
finds nothing), then the process group is signalled when ``pid`` leads one, and
every snapshotted descendant individually — which also reaches children that
``setsid`` into their own session. ``sig`` defaults to ``SIGKILL``.
Returns True when the target (or any of its tree) was signalled.
"""
Windows: ``taskkill /F /T`` (``sig`` ignored). POSIX: descendants are snapshotted via psutil
BEFORE signalling (once the parent dies they reparent and a parent walk finds nothing), then
the process group is signalled when ``pid`` leads one, and every snapshotted descendant
individually — which also reaches ``setsid`` children. ``sig`` defaults to ``SIGKILL``."""
if sys.platform == "win32":
try:
from hermes_cli._subprocess_compat import windows_hide_flags
creationflags = windows_hide_flags()
except Exception:
creationflags = 0
try:
proc = subprocess.run(
["taskkill", "/F", "/T", "/PID", str(pid)],
capture_output=True,
timeout=15,
check=False,
creationflags=creationflags,
capture_output=True, timeout=15, check=False, creationflags=creationflags,
)
# taskkill exits non-zero for not-found / access-denied (False = nothing terminated).
return proc.returncode == 0
@@ -398,13 +353,11 @@ def kill_process_tree(pid: int, *, sig: Optional[int] = None) -> bool:
return False
import signal as _signal
if sig is None:
sig = _signal.SIGKILL
try:
import psutil
descendants = psutil.Process(int(pid)).children(recursive=True)
except Exception:
# Already gone, or psutil unavailable — the group signal still covers same-session descendants.
+21 -34
View File
@@ -1,30 +1,22 @@
"""Deterministic-empty detection and cost-aware retry budgets.
On an empty completion the loop retries up to 3 times, then walks the
fallback chain — each attempt re-bills the full input. Signaled refusals
(``content_filter``, Anthropic ``refusal``, Bedrock guardrails) are already
terminal; this module handles *unsignaled* empties (success, zero output
tokens, generic finish reason — typical of portal-proxied refusals).
On an empty completion the loop retries up to 3 times, then walks the fallback chain —
each attempt re-bills the full input. Signaled refusals (``content_filter``, Anthropic
``refusal``, Bedrock guardrails) are already terminal; this handles *unsignaled* empties
(success, zero output tokens, generic finish reason — typical of portal-proxied refusals).
Two independent guards, both failing OPEN to legacy behaviour:
1. Deterministic-empty: two consecutive empties, both with usage present and
``output_tokens == 0``, from the same (model, provider, finish_reason) →
the same prompt will keep producing the same empty, so skip remaining
retries and go straight to the fallback chain (a different model may
behave differently). Missing usage or ``output_tokens > 0`` (think-block
stripping, whitespace, flaky decoding) never classifies as deterministic.
2. Cost-aware budget: when one empty attempt's estimated input cost exceeds
the threshold (default $0.25), the retry budget drops from 3 to 1.
Unknown pricing / missing usage / included routes leave it untouched.
``output_tokens == 0``, from the same (model, provider, finish_reason) → skip the
remaining retries and go straight to the fallback chain. Missing usage or
``output_tokens > 0`` (think-block stripping, whitespace, flaky decoding) never classifies.
2. Cost-aware budget: when one empty attempt's estimated input cost exceeds the threshold
(default $0.25), the retry budget drops from 3 to 1. Unknown pricing / missing usage /
included routes leave it untouched.
Config (``config.yaml``, resolved once by ``agent_init`` and stashed on the
agent so the hot loop never re-reads config — no env vars)::
agent:
empty_response_guard:
enabled: true # false = legacy fixed 3-retry behaviour
cost_threshold_usd: 0.25 # per-attempt cost that halves the budget
Config ``agent.empty_response_guard.{enabled, cost_threshold_usd}`` is resolved once by
``agent_init`` and stashed on the agent so the hot loop never re-reads config (no env vars).
"""
from __future__ import annotations
@@ -41,10 +33,9 @@ REDUCED_EMPTY_RETRY_BUDGET = 1
DEFAULT_COST_THRESHOLD_USD = Decimal("0.25")
DEFAULT_GUARD_ENABLED = True
# Agent-object attribute names. State is scoped to one consecutive empty
# streak: cleared whenever ``_empty_content_retries == 0`` at record time, so
# every existing counter-reset site (turn start, compaction, tool success,
# fallback activation) is honoured without touching it.
# Agent-object attribute names. State is scoped to one consecutive empty streak: cleared
# whenever ``_empty_content_retries == 0`` at record time, so every existing counter-reset
# site (turn start, compaction, tool success, fallback activation) is honoured.
_ATTEMPTS_ATTR = "_empty_attempt_history"
_STREAK_COST_ATTR = "_empty_streak_cost_usd"
_ENABLED_ATTR = "_empty_guard_enabled"
@@ -115,7 +106,6 @@ def _normalized_usage(agent: Any, response: Any, what: str) -> Any:
return None
try:
from agent.usage_pricing import normalize_usage
return normalize_usage(raw_usage, provider=getattr(agent, "provider", None),
api_mode=getattr(agent, "api_mode", None))
except Exception: # noqa: BLE001 — pricing must never break the loop
@@ -130,7 +120,6 @@ def _estimate_attempt_cost(agent: Any, response: Any) -> Optional[Decimal]:
return None
try:
from agent.usage_pricing import estimate_usage_cost
result = estimate_usage_cost(
getattr(agent, "model", "") or "", canonical, provider=getattr(agent, "provider", None),
base_url=getattr(agent, "base_url", None), api_key=getattr(agent, "api_key", None),
@@ -160,9 +149,8 @@ def _zero_output(agent: Any, response: Any) -> tuple:
def record_empty_attempt(agent: Any, *, finish_reason: str, response: Any) -> None:
"""Record one empty completion in the current streak.
Call BEFORE ``_empty_content_retries`` is incremented: a counter of 0
marks a new streak and clears prior history.
"""
Call BEFORE ``_empty_content_retries`` is incremented: a counter of 0 marks a new
streak and clears prior history."""
attempts = _attempts(agent)
if getattr(agent, "_empty_content_retries", 0) == 0:
attempts.clear()
@@ -181,9 +169,8 @@ def record_empty_attempt(agent: Any, *, finish_reason: str, response: Any) -> No
def deterministic_empty(agent: Any) -> bool:
"""True when >= 2 consecutive attempts ALL have usage present, zero output
and an identical signature. Any missing-usage / non-zero attempt → False
(fail open — transients deserve their retries)."""
"""True when >= 2 consecutive attempts ALL have usage present, zero output and an
identical signature. Any missing-usage / non-zero attempt → False (fail open)."""
if not guard_enabled(agent):
return False
attempts = getattr(agent, _ATTEMPTS_ATTR, None) or []
@@ -193,8 +180,8 @@ def deterministic_empty(agent: Any) -> bool:
def empty_retry_budget(agent: Any, response: Any) -> int:
"""Empty-retry budget for the current streak (3, or 1 when a single
attempt is estimated to cost more than the configured threshold)."""
"""Empty-retry budget for the current streak (3, or 1 when a single attempt is
estimated to cost more than the configured threshold)."""
if not guard_enabled(agent):
return DEFAULT_EMPTY_RETRY_BUDGET
cost = _estimate_attempt_cost(agent, response)
+10 -19
View File
@@ -13,12 +13,9 @@ def _accepts_keyword(callable_obj: Any, name: str) -> bool:
except (TypeError, ValueError):
return False
return any(
parameter.kind is inspect.Parameter.VAR_KEYWORD
or (
parameter.name == name
and parameter.kind is not inspect.Parameter.POSITIONAL_ONLY
)
for parameter in parameters
p.kind is inspect.Parameter.VAR_KEYWORD
or (p.name == name and p.kind is not inspect.Parameter.POSITIONAL_ONLY)
for p in parameters
)
@@ -30,20 +27,14 @@ def request_hard_interrupt(
) -> bool:
"""Request an explicit stop, falling back to the legacy interrupt ABI.
New agents expose ``hard_interrupt(message=None)``. Third-party agents and
old test doubles may only expose ``interrupt(message=None)``; keep those
usable without sending newer keyword arguments they do not know.
``message`` is diagnostic/control-plane text. ``tool_reason`` is a trusted,
fixed category that may be exposed in model-visible tool cancellation
output. It is only forwarded when the modern callable explicitly supports
that channel.
Returns ``False`` only when neither callable is available.
New agents expose ``hard_interrupt(message=None)``; third-party agents and old test
doubles may only expose ``interrupt(message=None)`` and must not receive keyword
arguments they do not know. ``tool_reason`` is a trusted, fixed category that may be
exposed in model-visible tool cancellation output, forwarded only when the callable
explicitly supports it. Returns ``False`` only when neither callable is available.
"""
# Avoid treating a dynamic ``__getattr__`` proxy (notably an unspecced
# ``MagicMock`` or a third-party RPC facade) as if it genuinely implements
# the new ABI. Static lookup proves the attribute exists on the instance or
# its type before normal descriptor binding retrieves the callable.
# Static lookup first: a dynamic ``__getattr__`` proxy (unspecced MagicMock, RPC
# facade) must not be treated as genuinely implementing the new ABI.
try:
inspect.getattr_static(agent, "hard_interrupt")
except AttributeError:
+153 -296
View File
@@ -3,6 +3,7 @@
Soft/hard interrupt requests, tool-thread interrupt propagation, pending steer/redirect queues.
Extracted from ``run_agent.py``; every method resolves through ``AIAgent``'s MRO unchanged.
"""
import contextlib
import logging
import threading
from typing import Optional
@@ -14,204 +15,161 @@ from tools.interrupt import set_interrupt as _set_interrupt
logger = logging.getLogger("run_agent")
def _fence_cancel_before_commit(fence, *, when_in_flight: bool, failure_log: str) -> None:
"""Call ``type(fence).cancel_before_commit(fence)`` when ``commit_in_flight`` matches.
Hard-cancel admission has two halves (#99758 P1). BEFORE the generation claim is
consumed only a commit already in flight is waited out (the call blocks on the fence
lock and returns False WITHOUT setting ``_cancelled``) — cancelling a still-pending
fence there would be irreversible for an abort that may yet be declined. AFTER the
claim survived, only a still-pending commit is cancelled; one that started meanwhile
owns the fence and completes on its own."""
if fence is None or bool(getattr(fence, "commit_in_flight", False)) is not when_in_flight:
return
cancel_before_commit = getattr(type(fence), "cancel_before_commit", None)
if callable(cancel_before_commit):
try:
cancel_before_commit(fence)
except Exception:
logger.debug(failure_log, exc_info=True)
def _ic_lock(agent, attr: str):
"""``with`` the lock stored at ``attr`` when present; __init__-less test stubs run unlocked."""
lock = getattr(agent, attr, None)
return contextlib.nullcontext() if lock is None else lock
def _ic_codex_method(agent, name: str):
"""Codex app-server owns its model/tool loop; return its ``name`` hook or None."""
if getattr(agent, "api_mode", None) != "codex_app_server":
return None
method = getattr(getattr(agent, "_codex_session", None), name, None)
return method if callable(method) else None
def _ic_abort_active_request(agent, reason: str, failure_log: str) -> None:
"""Shut the registered in-flight request's sockets (cron turns register their client here)."""
abort = getattr(agent, "_active_request_abort", None)
if callable(abort):
try:
abort(reason)
except Exception:
logger.debug(failure_log, exc_info=True)
def _ic_signal_tool_workers(agent, active: bool, **kw) -> None:
"""Fan the tool interrupt bit out to concurrent-tool worker tids.
``is_interrupted()`` inside a tool only sees its own tid, so without this a hung
concurrent tool runs to its own timeout (and a stale bit could survive a turn
boundary onto a recycled tid). getattr covers __init__-less stubs."""
tracker = getattr(agent, "_tool_worker_threads", None)
tracker_lock = getattr(agent, "_tool_worker_threads_lock", None)
if tracker is None or tracker_lock is None:
return
with tracker_lock:
worker_tids = list(tracker)
for tid in worker_tids:
try:
_set_interrupt(active, tid, **kw)
except Exception:
pass
class InterruptControlMixin:
"""interrupt()/hard_interrupt()/clear_interrupt()/steer()/redirect() (see module docstring)."""
def interrupt(
self,
message: Optional[str] = None,
*,
hard_cancel: bool = False,
tool_reason: Optional[str] = None,
require_generation: Optional[int] = None,
self, message: Optional[str] = None, *, hard_cancel: bool = False,
tool_reason: Optional[str] = None, require_generation: Optional[int] = None,
) -> bool:
"""Request the agent to interrupt its current tool-calling loop (call from another thread).
``message``: new message to include in the response context. ``hard_cancel``: explicit stop;
compression may honor it even while ordinary interrupts are masked. ``tool_reason``: trusted fixed
category safe for tool output. ``require_generation``: activity-generation claim — the interrupt is
published only if the turn's generation still matches at the final mutation edge (claim reserved under
the activity lock, consumed together with the first observable publication); returns False if the turn
resumed meanwhile.
``hard_cancel``: explicit stop; compression may honor it even while ordinary interrupts are masked.
``tool_reason``: trusted fixed category safe for tool output. ``require_generation``: activity-
generation claim — published only if the turn's generation still matches at the final mutation edge;
returns False if the turn resumed meanwhile.
"""
if require_generation is not None:
# RESERVE the abort's generation claim under the SAME lock `_touch_activity` stamps with. Real
# progress invalidates it; it is CONSUMED at the final mutation edge, so a resumed turn abandons
# the abort.
# RESERVE the claim under the SAME lock `_touch_activity` stamps with; real progress invalidates
# it and it is CONSUMED at the final mutation edge, so a resumed turn abandons the abort.
with self._liveness_activity_lock():
if (
getattr(self, "_turn_liveness_activity_generation", 0)
!= require_generation
):
if getattr(self, "_turn_liveness_activity_generation", 0) != require_generation:
return False
self._turn_liveness_abort_claim = require_generation
# A hard stop and redirect share one lock so /stop cannot race with an
# accepted correction and accidentally turn itself into a retry.
def _wait_for_compression_commit() -> None:
# Pre-claim half of hard-cancel admission (#99758 P1): wait out a commit that already crossed its
# boundary but mutate NOTHING — cancelling a pending fence is irreversible and must wait until the
# generation claim survived the final mutation edge (_cancel_pending_compression_commit).
fence = vars(self).get("_active_compression_commit_fence")
if fence is None:
return
if not getattr(fence, "commit_in_flight", False):
# No commit in flight — cancel_before_commit here WOULD cancel the pending commit; leave it to
# the destructive half.
return
cancel_before_commit = getattr(
type(fence), "cancel_before_commit", None
)
if callable(cancel_before_commit):
try:
# A commit holds the fence lock through finish_commit: this blocks until it finishes and
# returns False WITHOUT setting _cancelled.
cancel_before_commit(fence)
except Exception:
logger.debug(
"Compression hard-cancel fence wait failed",
exc_info=True,
)
def _cancel_pending_compression_commit() -> None:
# Destructive half of hard-cancel admission (#99758 P1): runs only AFTER the claim survived, so a
# declined abort never leaves the fence cancelled. A commit that started meanwhile owns the fence
# and completes on its own; only a still-pending commit is cancelled here.
fence = vars(self).get("_active_compression_commit_fence")
if fence is None:
return
if getattr(fence, "commit_in_flight", False):
return
cancel_before_commit = getattr(
type(fence), "cancel_before_commit", None
)
if callable(cancel_before_commit):
try:
# Marks the fence cancelled (or waits out a just-started commit) without touching the
# hard-stop Event, which was published at the claim edge.
cancel_before_commit(fence)
except Exception:
logger.debug(
"Compression hard-cancel fence admission failed",
exc_info=True,
)
# Tool cancellation attribution stays separate from _interrupt_message, which may carry the user's
# full next message.
tool_interrupt_reason = (
(tool_reason or "explicit stop requested") if hard_cancel
else ("user sent a new message" if message else "user interrupt")
)
def _publish_interrupt_state() -> None:
self._interrupt_requested = True
self._interrupt_message = message
self._tool_interrupt_reason = tool_interrupt_reason
if hard_cancel:
_hard_event = getattr(
self, "_hard_interrupt_requested", None
)
if _hard_event is not None:
_hard_event.set()
_hard_event = getattr(self, "_hard_interrupt_requested", None) if hard_cancel else None
if _hard_event is not None:
_hard_event.set()
def _consume_claim_and_publish_first_state() -> bool:
# Final mutation edge: claim consumption and the FIRST observable interrupt publication are ONE
# activity-lock critical section, so either the claim survives and commits before any later
# activity stamp, or the stamp landed first and the abort declines without publishing.
def _fence(): # re-read each time: a finished commit may replace or clear the slot
return vars(self).get("_active_compression_commit_fence") if hard_cancel else None
# A hard stop and redirect share one lock so /stop cannot race with an accepted correction and
# accidentally turn itself into a retry. The blocking in-flight-commit wait runs BEFORE the atomic
# claim edge (redirect lock still held); the destructive pending-commit cancel runs AFTER the claim
# survives (#99758 P1).
with _ic_lock(self, "_pending_redirect_lock"):
_fence_cancel_before_commit(
_fence(), when_in_flight=True, failure_log="Compression hard-cancel fence wait failed"
)
if require_generation is None:
# No claim to race: publish WITHOUT the liveness lock. Bare AIAgent stand-ins in other suites
# lack the liveness seam and would AttributeError.
# No claim to race: publish WITHOUT the liveness lock (bare AIAgent stand-ins in other
# suites lack the liveness seam and would AttributeError).
_publish_interrupt_state()
return True
with self._liveness_activity_lock():
if (
getattr(self, "_turn_liveness_abort_claim", None)
!= require_generation
):
return False
self._turn_liveness_abort_claim = None
_publish_interrupt_state()
return True
# Tool cancellation attribution stays separate from _interrupt_message, which may carry the user's
# full next message.
tool_interrupt_reason = (
(tool_reason or "explicit stop requested")
if hard_cancel
else ("user sent a new message" if message else "user interrupt")
)
_redirect_lock = getattr(self, "_pending_redirect_lock", None)
if _redirect_lock is not None:
with _redirect_lock:
# The blocking in-flight-commit wait runs BEFORE the atomic claim edge (redirect lock still
# held); the destructive pending-commit cancel runs AFTER the claim survives (#99758 P1).
if hard_cancel:
_wait_for_compression_commit()
if not _consume_claim_and_publish_first_state():
return False
if hard_cancel:
_cancel_pending_compression_commit()
self._pending_redirect = None
else:
if hard_cancel:
_wait_for_compression_commit()
if not _consume_claim_and_publish_first_state():
return False
if hard_cancel:
_cancel_pending_compression_commit()
else:
# Final mutation edge: claim consumption and the FIRST observable publication are ONE
# activity-lock critical section, so either the claim survives and commits before any later
# activity stamp, or the stamp landed first and the abort declines without publishing.
with self._liveness_activity_lock():
if getattr(self, "_turn_liveness_abort_claim", None) != require_generation:
return False
self._turn_liveness_abort_claim = None
_publish_interrupt_state()
_fence_cancel_before_commit(
_fence(), when_in_flight=False, failure_log="Compression hard-cancel fence admission failed"
)
self._pending_redirect = None
# Codex app-server owns its model/tool loop and watches a private
# interrupt event rather than Hermes' per-thread flag.
if getattr(self, "api_mode", None) == "codex_app_server":
_codex_session = getattr(self, "_codex_session", None)
_request_interrupt = getattr(_codex_session, "request_interrupt", None)
if callable(_request_interrupt):
try:
_request_interrupt()
except Exception:
logger.debug(
"Failed to interrupt Codex app-server turn",
exc_info=True,
)
# Codex watches a private interrupt event rather than Hermes' per-thread flag.
_request_interrupt = _ic_codex_method(self, "request_interrupt")
if _request_interrupt is not None:
try:
_request_interrupt()
except Exception:
logger.debug("Failed to interrupt Codex app-server turn", exc_info=True)
# Cron turns request on the conversation thread (no nested interrupt-worker deadlock); their client
# is registered here so this cross-thread interrupt can still shut the sockets.
_abort_active_request = getattr(self, "_active_request_abort", None)
if callable(_abort_active_request):
try:
_abort_active_request("interrupt_abort")
except Exception:
logger.debug("Failed to abort active inline request", exc_info=True)
_ic_abort_active_request(self, "interrupt_abort", "Failed to abort active inline request")
# Scope the tool interrupt to this agent's execution thread so other in-process agents are unaffected.
if self._execution_thread_id is not None:
_set_interrupt(
True,
self._execution_thread_id,
reason=tool_interrupt_reason,
)
_set_interrupt(True, self._execution_thread_id, reason=tool_interrupt_reason)
self._interrupt_thread_signal_pending = False
else:
# Interrupt arrived before run_conversation bound the execution thread: defer the tool-level
# signal instead of targeting the caller thread.
self._interrupt_thread_signal_pending = True
# Fan out to concurrent-tool worker tids: is_interrupted() inside a tool only sees its own tid, so
# without this a hung concurrent tool runs to its own timeout. getattr covers __init__-less stubs.
_tracker = getattr(self, "_tool_worker_threads", None)
_tracker_lock = getattr(self, "_tool_worker_threads_lock", None)
if _tracker is not None and _tracker_lock is not None:
with _tracker_lock:
_worker_tids = list(_tracker)
for _wtid in _worker_tids:
try:
_set_interrupt(True, _wtid, reason=tool_interrupt_reason)
except Exception:
pass
_ic_signal_tool_workers(self, True, reason=tool_interrupt_reason)
# Propagate interrupt to any running child agents (subagent delegation)
with self._active_children_lock:
children_copy = list(self._active_children)
for child in children_copy:
try:
if hard_cancel:
request_hard_interrupt(
child,
message,
tool_reason=tool_interrupt_reason,
)
request_hard_interrupt(child, message, tool_reason=tool_interrupt_reason)
else:
child.interrupt(message)
except Exception as e:
@@ -220,206 +178,105 @@ class InterruptControlMixin:
print("\n⚡ Interrupt requested" + (f": '{message[:40]}...'" if message and len(message) > 40 else f": '{message}'" if message else ""))
return True
def hard_interrupt(
self,
message: Optional[str] = None,
*,
tool_reason: Optional[str] = None,
) -> None:
"""Request an explicit stop while preserving the ``interrupt()`` ABI.
Frontends feature-detect this and fall back to legacy ``interrupt()`` for third-party agents.
"""
# Bypass dynamic dispatch: legacy subclasses may override interrupt(message=None) without hard_cancel.
InterruptControlMixin.interrupt(
self,
message,
hard_cancel=True,
tool_reason=tool_reason,
)
def hard_interrupt(self, message: Optional[str] = None, *, tool_reason: Optional[str] = None) -> None:
"""Explicit stop preserving the ``interrupt()`` ABI (frontends feature-detect this and fall back to
legacy ``interrupt()`` for third-party agents). Bypasses dynamic dispatch: legacy subclasses may
override interrupt(message=None) without hard_cancel."""
InterruptControlMixin.interrupt(self, message, hard_cancel=True, tool_reason=tool_reason)
def clear_interrupt(self, *, preserve_redirect: bool = False) -> bool:
"""Clear the interrupt request and per-thread tool signal.
``preserve_redirect`` is only for the conversation loop rebuilding the same logical turn after
cancelling a model request; public hard-stop paths clear everything.
"""
_redirect_lock = getattr(self, "_pending_redirect_lock", None)
if _redirect_lock is not None:
with _redirect_lock:
if preserve_redirect and not self._pending_redirect:
return False
self._interrupt_requested = False
self._interrupt_message = None
self._tool_interrupt_reason = None
getattr(self, "_hard_interrupt_requested", threading.Event()).clear()
if not preserve_redirect:
self._pending_redirect = None
else:
"""Clear the interrupt request and per-thread tool signal. ``preserve_redirect`` is only for the
conversation loop rebuilding the same logical turn after cancelling a model request."""
with _ic_lock(self, "_pending_redirect_lock"):
if preserve_redirect and not getattr(self, "_pending_redirect", None):
return False
self._interrupt_requested = False
self._interrupt_message = None
self._tool_interrupt_reason = None
self._interrupt_message = self._tool_interrupt_reason = None
getattr(self, "_hard_interrupt_requested", threading.Event()).clear()
if not preserve_redirect:
self._pending_redirect = None
self._interrupt_thread_signal_pending = False
if self._execution_thread_id is not None:
_set_interrupt(False, self._execution_thread_id)
# Also clear worker-thread bits so no stale interrupt survives a turn boundary onto a recycled tid.
# getattr covers __init__-less test stubs.
_tracker = getattr(self, "_tool_worker_threads", None)
_tracker_lock = getattr(self, "_tool_worker_threads_lock", None)
if _tracker is not None and _tracker_lock is not None:
with _tracker_lock:
_worker_tids = list(_tracker)
for _wtid in _worker_tids:
try:
_set_interrupt(False, _wtid)
except Exception:
pass
_ic_signal_tool_workers(self, False)
# A hard interrupt supersedes any pending /steer — its target iteration will no longer happen.
_steer_lock = getattr(self, "_pending_steer_lock", None)
if _steer_lock is not None:
with _steer_lock:
self._pending_steer = None
with _ic_lock(self, "_pending_steer_lock"):
self._pending_steer = None
return True
def steer(self, text: str) -> bool:
"""Inject user text into the next tool result without interrupting the current tool.
The text is appended to the LAST tool result once the batch finishes, so the model sees it on its next
iteration. Thread-safe; multiple calls concatenate with newlines. Returns False for empty text.
"""
"""Append user text to the LAST tool result once the batch finishes (no interrupt); multiple calls
concatenate with newlines. Returns False for empty text."""
if not text or not text.strip():
return False
cleaned = text.strip()
_lock = getattr(self, "_pending_steer_lock", None)
if _lock is None:
# __init__-less test stubs: fall back to a direct attribute set.
with _ic_lock(self, "_pending_steer_lock"):
existing = getattr(self, "_pending_steer", None)
self._pending_steer = (existing + "\n" + cleaned) if existing else cleaned
return True
with _lock:
if self._pending_steer:
self._pending_steer = self._pending_steer + "\n" + cleaned
else:
self._pending_steer = cleaned
return True
def redirect(self, text: str) -> bool:
"""Redirect the active turn without converting it into a new task.
During a model request this cancels only that request: completed messages/tool results are kept, the
displayed partial reasoning becomes assistant context, the correction is appended as a real user
message, and the loop retries. During tool execution it degrades to ``steer()``; Codex app-server uses
native ``turn/steer``. Returns False when there is no live turn or the text is empty.
"""
"""Redirect the active turn without converting it into a new task: during a model request only that
request is cancelled (completed messages kept, partial reasoning becomes assistant context, the
correction is appended as a real user message, the loop retries); during tool execution it degrades
to ``steer()``; Codex app-server uses native ``turn/steer``. False when no live turn / empty text."""
if not text or not text.strip():
return False
cleaned = text.strip()
# Codex owns its internal reasoning/tool loop, so use its first-class
# active-turn steering protocol rather than interrupting the subprocess.
if getattr(self, "api_mode", None) == "codex_app_server":
_codex_session = getattr(self, "_codex_session", None)
_native_steer = getattr(_codex_session, "request_steer", None)
if callable(_native_steer):
_redirect_lock = getattr(self, "_pending_redirect_lock", None)
if _redirect_lock is not None:
with _redirect_lock:
if self._interrupt_requested:
return False
elif self._interrupt_requested:
return False
try:
return bool(_native_steer(cleaned))
except Exception:
logger.debug("Codex app-server turn/steer failed", exc_info=True)
_native_steer = _ic_codex_method(self, "request_steer")
if _native_steer is not None:
with _ic_lock(self, "_pending_redirect_lock"):
if self._interrupt_requested:
return False
try:
return bool(_native_steer(cleaned))
except Exception:
logger.debug("Codex app-server turn/steer failed", exc_info=True)
return False
# Never kill a tool to deliver guidance; the steer drain puts it on the final tool result.
if getattr(self, "_executing_tools", False):
return self.steer(cleaned)
_model_active = getattr(self, "_model_request_active", None)
_redirect_lock = getattr(self, "_pending_redirect_lock", None)
if _redirect_lock is None:
with _ic_lock(self, "_pending_redirect_lock"):
if _model_active is None or not _model_active.is_set():
return False
return False # response completed before we got the lock: surface queues a new turn
existing = getattr(self, "_pending_redirect", None)
if self._interrupt_requested and not existing:
return False
self._pending_redirect = (
f"{existing}\n\n[Additional user correction]\n{cleaned}"
if existing
else cleaned
f"{existing}\n\n[Additional user correction]\n{cleaned}" if existing else cleaned
)
self._interrupt_requested = True
self._interrupt_message = None
else:
with _redirect_lock:
if _model_active is None or not _model_active.is_set():
# The response completed before we acquired the state lock.
# Reject so the surface queues a new turn.
return False
if self._interrupt_requested and not self._pending_redirect:
return False
if self._pending_redirect:
self._pending_redirect = (
f"{self._pending_redirect}\n\n"
f"[Additional user correction]\n{cleaned}"
)
else:
self._pending_redirect = cleaned
self._interrupt_requested = True
self._interrupt_message = None
# Interrupt only the model request. Do not fan out to tool workers or
# child agents as interrupt() does.
# Interrupt only the model request — no fan-out to tool workers / child agents as interrupt() does.
_execution_thread_id = getattr(self, "_execution_thread_id", None)
if _execution_thread_id is not None:
_set_interrupt(True, _execution_thread_id)
self._interrupt_thread_signal_pending = False
else:
self._interrupt_thread_signal_pending = True
_abort_active_request = getattr(self, "_active_request_abort", None)
if callable(_abort_active_request):
try:
_abort_active_request("redirect_abort")
except Exception:
logger.debug("Failed to abort request for redirect", exc_info=True)
_ic_abort_active_request(self, "redirect_abort", "Failed to abort request for redirect")
return True
def _has_pending_redirect(self) -> bool:
"""Return whether an active-turn redirect is waiting to be applied."""
_redirect_lock = getattr(self, "_pending_redirect_lock", None)
if _redirect_lock is None:
with _ic_lock(self, "_pending_redirect_lock"):
return bool(getattr(self, "_pending_redirect", None))
with _redirect_lock:
return bool(self._pending_redirect)
def _drain_pending_redirect(self) -> Optional[str]:
"""Return and clear pending active-turn correction text."""
_redirect_lock = getattr(self, "_pending_redirect_lock", None)
if _redirect_lock is None:
with _ic_lock(self, "_pending_redirect_lock"):
text = getattr(self, "_pending_redirect", None)
self._pending_redirect = None
return text
with _redirect_lock:
text = self._pending_redirect
self._pending_redirect = None
return text
def _drain_pending_steer(self) -> Optional[str]:
"""Return the pending steer text (if any) and clear the slot; None when nothing is pending."""
_lock = getattr(self, "_pending_steer_lock", None)
if _lock is None:
with _ic_lock(self, "_pending_steer_lock"):
text = getattr(self, "_pending_steer", None)
self._pending_steer = None
return text
with _lock:
text = self._pending_steer
self._pending_steer = None
return text
+6 -8
View File
@@ -1,10 +1,9 @@
"""Per-agent iteration budget — thread-safe consume/refund counter.
Each ``AIAgent`` (parent or subagent) holds its own :class:`IterationBudget`:
the parent's cap is ``max_iterations`` (default 500), each subagent's is
``delegation.max_iterations`` (default 50), so total iterations across parent
+ subagents can exceed the parent's cap. ``run_agent`` re-exports the class so
``from run_agent import IterationBudget`` keeps working.
Each ``AIAgent`` (parent or subagent) holds its own :class:`IterationBudget`: the parent's
cap is ``max_iterations`` (default 500), each subagent's ``delegation.max_iterations``
(default 50), so total iterations across parent + subagents can exceed the parent's cap.
``run_agent`` re-exports the class so ``from run_agent import IterationBudget`` keeps working.
"""
from __future__ import annotations
@@ -13,9 +12,8 @@ import threading
class IterationBudget:
"""Thread-safe iteration counter. ``execute_code`` (programmatic tool
calling) iterations are refunded via :meth:`refund` so they don't eat
into the budget."""
"""Thread-safe iteration counter; ``execute_code`` (programmatic tool calling)
iterations are refunded via :meth:`refund` so they don't eat into the budget."""
def __init__(self, max_total: int):
self.max_total = max_total
+2 -2
View File
@@ -185,8 +185,8 @@ def test_conversation_loop_sanitizes_api_kwargs_after_build():
build_idx = src.index("api_kwargs = agent._build_api_kwargs(api_messages)")
sanitize_idx = src.index("_sanitize_structure_surrogates(api_kwargs)")
assert build_idx < sanitize_idx
loop_src = inspect.getsource(cl.run_conversation)
assert loop_src.index("build_api_request(") < loop_src.index("perform_api_call(")
loop_src = inspect.getsource(cl._run_api_retry_loop)
assert loop_src.index("build_api_request,") < loop_src.index("perform_api_call,")
# ---------------------------------------------------------------------------