mirror of
https://github.com/usestrix/strix.git
synced 2026-08-21 02:45:31 +02:00
Audit found 8 behavioral gaps between post-migration and the legacy ``BaseAgent.agent_loop``. All 8 are now closed using SDK-native primitives — no custom workarounds, no shadow state machines. What was broken / different: - G1: ``inherit_context`` was dead code; children always started fresh. - G2: TUI user message couldn't interrupt an in-flight LLM/tool turn. - G3: ``llm_failed`` state never set; hard failures propagated as crashes. - G4: No graceful ``stop_agent`` tool. - G5: Parked subagents waited forever (no auto-resume timeout). - G6: Inter-agent messages used a plain header instead of legacy XML. - G7: Completion reports used JSON instead of legacy XML. - G11/G12: Turn counter reset per cycle; budget warnings could re-fire. What we did: Bus extensions (``orchestration/bus.py``): - ``streams`` registry + ``attach_stream`` ctx manager + ``request_interrupt`` for SDK-native ``RunResultStreaming.cancel(mode="after_turn")``. - ``mark_llm_failed`` + ``wait_for_user_message`` (filtered: only ``from="user"`` satisfies; peer messages don't unstick a stuck model). - ``stopping: set[str]`` for graceful programmatic exit. - ``cancel_descendants_graceful`` — leaves-first via ``request_interrupt``. - ``record_usage`` increments ``calls`` unconditionally so it doubles as the per-agent-lifetime turn counter (legacy ``state.iteration`` parity). - ``warned_85`` / ``warned_final`` flags on ``stats_live`` for once-fire budget warnings. Run loop rewrite (``orchestration/run_loop.py``): - ``Runner.run`` → ``Runner.run_streamed`` with ``bus.attach_stream`` so cancel has a target. Catch ``(AgentsException, APIError)`` after retries exhaust; in interactive mode call ``mark_llm_failed`` + wait for user. - ``UserError`` / ``MaxTurnsExceeded`` / ``CancelledError`` propagate. - Outer loop: ``asyncio.wait_for(bus.wait_for_message, timeout=300)`` for interactive subagents (root waits forever). ``TimeoutError`` injects ``"Waiting timeout reached. Resuming execution."``. - Honors ``bus.stopping`` at top of each iteration. Hooks (``orchestration/hooks.py``): - Counter source moved from per-cycle ``ctx["turn_count"]`` to per-lifetime ``bus.stats_live[agent_id]["calls"]``. - Warnings guarded by once-flags — exactly-once across all cycles. Filter (``orchestration/filter.py``): - Restored legacy ``<inter_agent_message>`` XML envelope with the ``<delivery_notice>DO NOT echo back</delivery_notice>`` instruction. Agents-graph (``tools/agents_graph/tools.py``): - G1: ``create_agent`` reads ``ctx.turn_input`` (SDK populates it before tool execution at ``run_internal/turn_resolution.py:806``). Wraps as one ``<inherited_context_from_parent>`` block. - G7: ``agent_finish`` emits the legacy ``<agent_completion_report>`` XML. ``child_ctx["task"] = task`` threaded so the report echoes the original task. - G4: New ``stop_agent`` tool — refuses self-stop, refuses already- finalized targets, ``cascade=True`` uses ``cancel_descendants_graceful``. TUI (``interface/tui.py``): - ``_send_user_message`` schedules ``bus.send`` AND ``bus.request_interrupt(target, mode="after_turn")`` — SDK finishes current turn cleanly, next cycle picks up the user's message. Factory (``agents/factory.py``): - Registered ``stop_agent`` in ``_BASE_TOOLS``. Out of scope: - G8 (``[ABORTED BY USER]`` marker) is auto-resolved by G2 — the SDK saves the full assistant message before honoring ``cancel(mode="after_turn")``, so partial content is preserved in the session. Verified all bus behaviors with a smoke test. Lint at baseline.
160 lines
5.3 KiB
Python
160 lines
5.3 KiB
Python
"""``make_run_config`` — assemble a Strix-flavored ``RunConfig`` for ``Runner.run``.
|
|
|
|
Every scan goes through here so defaults apply uniformly. Per-call
|
|
overrides land via ``model_settings_override``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import TYPE_CHECKING, Any, Literal
|
|
|
|
from agents import RunConfig
|
|
from agents.model_settings import ModelSettings
|
|
from agents.retry import (
|
|
ModelRetryBackoffSettings,
|
|
ModelRetrySettings,
|
|
retry_policies,
|
|
)
|
|
from agents.sandbox import SandboxRunConfig
|
|
from openai.types.shared import Reasoning
|
|
|
|
from strix.llm.multi_provider_setup import build_multi_provider
|
|
from strix.orchestration.filter import inject_messages_filter
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
from agents.sandbox.session.base_sandbox_session import BaseSandboxSession
|
|
|
|
from strix.orchestration.bus import AgentMessageBus
|
|
|
|
|
|
#: Default ``max_turns`` callers should pass to ``Runner.run``.
|
|
STRIX_DEFAULT_MAX_TURNS = 300
|
|
|
|
# Retry: 5 attempts with ``min(90, 2*2^n)`` backoff. 4xx auth/validation
|
|
# errors are excluded from the retryable status list — they can't be
|
|
# fixed by retrying and should fail fast. Public so the dedupe path
|
|
# (and any other one-shot LLM call outside ``Runner.run``) reuses the
|
|
# same policy.
|
|
DEFAULT_RETRY = ModelRetrySettings(
|
|
max_retries=5,
|
|
backoff=ModelRetryBackoffSettings(
|
|
initial_delay=2.0,
|
|
max_delay=90.0,
|
|
multiplier=2.0,
|
|
jitter=False,
|
|
),
|
|
policy=retry_policies.any(
|
|
retry_policies.provider_suggested(),
|
|
retry_policies.network_error(),
|
|
retry_policies.http_status((429, 500, 502, 503, 504)),
|
|
),
|
|
)
|
|
|
|
|
|
def make_run_config(
|
|
*,
|
|
sandbox_session: BaseSandboxSession | None,
|
|
model: str,
|
|
reasoning_effort: Literal["low", "medium", "high"] | None = None,
|
|
model_settings_override: ModelSettings | None = None,
|
|
sandbox_client: Any | None = None,
|
|
) -> RunConfig:
|
|
"""Build a ``RunConfig`` with Strix defaults.
|
|
|
|
Note: ``max_turns`` is not a ``RunConfig`` field — pass it directly
|
|
to ``Runner.run``. ``STRIX_DEFAULT_MAX_TURNS`` is the budget Strix
|
|
uses.
|
|
|
|
Args:
|
|
sandbox_session: Live sandbox session shared by every agent in
|
|
this scan (one container per scan; see
|
|
:mod:`strix.runtime.session_manager`). ``None`` is allowed
|
|
for unit tests and dry runs.
|
|
model: Litellm model alias passed to ``MultiProvider``. Caller
|
|
resolves from :attr:`Settings.llm.model`.
|
|
reasoning_effort: ``"low" | "medium" | "high"``; routes to
|
|
``ModelSettings.reasoning``.
|
|
model_settings_override: Optional per-run ``ModelSettings``
|
|
merged over factory defaults.
|
|
sandbox_client: Optional pre-built sandbox client (Strix Docker
|
|
subclass). The SDK instantiates its built-in if a session is
|
|
supplied without a client.
|
|
"""
|
|
base_settings = ModelSettings(
|
|
parallel_tool_calls=False,
|
|
tool_choice="required",
|
|
retry=DEFAULT_RETRY,
|
|
)
|
|
if reasoning_effort is not None:
|
|
base_settings = base_settings.resolve(
|
|
ModelSettings(reasoning=Reasoning(effort=reasoning_effort)),
|
|
)
|
|
if model_settings_override is not None:
|
|
base_settings = base_settings.resolve(model_settings_override)
|
|
|
|
sandbox_config = (
|
|
SandboxRunConfig(client=sandbox_client, session=sandbox_session)
|
|
if sandbox_session is not None
|
|
else None
|
|
)
|
|
|
|
return RunConfig(
|
|
model=model,
|
|
model_provider=build_multi_provider(),
|
|
model_settings=base_settings,
|
|
sandbox=sandbox_config,
|
|
call_model_input_filter=inject_messages_filter,
|
|
tracing_disabled=False,
|
|
trace_include_sensitive_data=False,
|
|
)
|
|
|
|
|
|
def make_agent_context(
|
|
*,
|
|
bus: AgentMessageBus,
|
|
sandbox_session: BaseSandboxSession | None,
|
|
agent_id: str,
|
|
parent_id: str | None,
|
|
tracer: Any | None,
|
|
model: str,
|
|
model_settings: ModelSettings | None = None,
|
|
max_turns: int = 300,
|
|
is_whitebox: bool = False,
|
|
interactive: bool = False,
|
|
diff_scope: dict[str, Any] | None = None,
|
|
run_id: str | None = None,
|
|
sandbox_client: Any | None = None,
|
|
agent_factory: Any | None = None,
|
|
caido_client: Any | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Build the per-agent ``context`` dict passed to ``Runner.run(context=...)``.
|
|
|
|
The canonical place where bus, sandbox handles, identity, tracer
|
|
reference, and per-agent toggles live. Tools, hooks, and
|
|
``inject_messages_filter`` reach in via ``ctx.context.get(...)``.
|
|
|
|
``agent_factory`` is a callable ``(name, skills) -> agents.Agent`` —
|
|
the ``create_agent`` graph tool uses it to spin up children that
|
|
inherit the same wiring. ``sandbox_client`` is the host-side Docker
|
|
subclass, reused across child runs.
|
|
"""
|
|
return {
|
|
"bus": bus,
|
|
"sandbox_session": sandbox_session,
|
|
"sandbox_client": sandbox_client,
|
|
"caido_client": caido_client,
|
|
"agent_id": agent_id,
|
|
"parent_id": parent_id,
|
|
"tracer": tracer,
|
|
"model": model,
|
|
"model_settings": model_settings,
|
|
"max_turns": max_turns,
|
|
"agent_finish_called": False,
|
|
"is_whitebox": is_whitebox,
|
|
"interactive": interactive,
|
|
"diff_scope": diff_scope,
|
|
"run_id": run_id,
|
|
"agent_factory": agent_factory,
|
|
}
|