Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:ARCANGEL0 EVA run agent turn

From Leeroopedia
Knowledge Sources
Domains Agentic_Systems, LLM, Security_Automation
Last Updated 2026-10-29 14:00 GMT

Overview

Concrete tool for executing iterative agent turns — reasoning, tool dispatch, mode enforcement, and interrupt handling — provided by the Mitsu agent runtime.

Description

The run_agent_turn async generator is the core agent turn loop. It receives an operator message, appends it to history, then enters a loop of: system prompt construction (augmented with operator messages, Intel context, mode directives), provider request dispatch, tool call execution, and history update. It yields AgentEvent objects (`assistant_turn`, `tool_started`, `tool_finished`, `usage`, `api_retry`, `done`, `limit`) that the TUI consumes for real-time rendering.

The loop enforces:

  • 48-tool-call budget per turn — at exhaustion, forces a summary and pauses.
  • Guided checkpointing — after one investigation action in Guided mode, blocks further actions until the operator responds via dialog.
  • Recon approval gating — non-low-impact commands in Recon mode require operator approval.
  • Failed-call deduplication — identical failed `bash` or `armory_run` commands are not retried within the same turn.
  • Binary grep limits — max 3 `strings|grep` searches per artifact per turn.
  • Interrupt handling — checks `interrupt_requested()` before each provider request and tool call; raises `asyncio.CancelledError` to exit.
  • Transient error retry — retries 429 and 5xx provider errors up to 10 times with 10s backoff.

Usage

  • Standard agent turn: Called by the session screen when the operator sends a chat message or triggers a slash command.
  • Mode-aware engagement: The `mode` parameter ("Recon", "Guided", "AutoPwn") controls tool availability and approval gating.
  • Interruptible execution: Pass `interrupt_requested` callback to allow operator cancellation mid-turn.
  • Dynamic mode/prompt: Pass `get_mode` and `get_system_prompt` callbacks for runtime changes via `/mode` command.

Code Reference

Source Location

  • Repository: Mitsu
  • File: agents/runtime.py

Signature

async def run_agent_turn(
    profile: dict[str, Any],
    system_prompt: str,
    history: list[dict[str, Any]],
    prompt: str,
    tool_host: AgentToolHost,
    mode: str,
    approve: ApprovalHandler,
    on_history: HistoryHandler,
    request_turn: RequestTurn | None = None,
    get_mode: Callable[[], str] | None = None,
    get_system_prompt: Callable[[], str] | None = None,
    image_paths: list[str] | None = None,
    pause_after_response: bool = False,
    interrupt_requested: Callable[[], bool] | None = None,
    operator_messages: list[str] | None = None,
    get_session_intel: Callable[[], dict[str, Any]] | None = None,
) -> AsyncIterator[AgentEvent]:

Import

from mitsu.agents.runtime import run_agent_turn, AgentEvent

I/O Contract

Inputs

Name Type Required Description
profile dict[str, Any] Yes Provider config with base_url, model, api_key, protocol
system_prompt str Yes Base system prompt for the agent
history list[dict] Yes Conversation history (mutated in place)
prompt str Yes Operator's message for this turn
tool_host AgentToolHost Yes Tool dispatcher with registered tools
mode str Yes Operational mode: "Recon", "Guided", or "AutoPwn"
approve ApprovalHandler Yes Async callback for approval gating
on_history HistoryHandler Yes Callback to persist history after changes
request_turn RequestTurn No Inject custom provider request function
get_mode Callable[[], str] No Dynamic mode getter (runtime /mode changes)
get_system_prompt Callable[[], str] No Dynamic system prompt getter
image_paths list[str] No Attached image file paths
pause_after_response bool No Force a pause after the first response
interrupt_requested Callable[[], bool] No Interrupt check callback
operator_messages list[str] No Operator directive history for prompt injection
get_session_intel Callable[[], dict] No Session Intel accessor for validated access injection

Outputs

Name Type Description
AgentEvent stream AsyncIterator[AgentEvent] Yields events: assistant_turn, tool_started, tool_finished, usage, api_retry, api_retrying, done, limit
history (mutated) list[dict] Conversation history with new messages and tool results

Usage Examples

Basic Agent Turn

import asyncio
from mitsu.agents.runtime import run_agent_turn, AgentEvent
from mitsu.tools import AgentToolHost

async def handle_message(profile, history, prompt, tool_host):
    """Run one agent turn and print events."""
    async def approve(name, arguments):
        print(f"Approving: {name}")
        return True

    def on_history():
        pass  # Persist history here

    async for event in run_agent_turn(
        profile=profile,
        system_prompt="You are a pentest assistant.",
        history=history,
        prompt=prompt,
        tool_host=tool_host,
        mode="Guided",
        approve=approve,
        on_history=on_history,
    ):
        if event.kind == "assistant_turn":
            print(f"Assistant: {event.data['text']}")
        elif event.kind == "tool_started":
            print(f"Tool started: {event.data['name']}")
        elif event.kind == "tool_finished":
            print(f"Tool finished: {event.data['result'][:200]}")
        elif event.kind == "done":
            print("Turn complete.")
            break

asyncio.run(handle_message(profile, history, "Scan 10.0.0.1", tool_host))

With Interrupt Support

import asyncio
from mitsu.agents.runtime import run_agent_turn

interrupted = False

async def run_with_interrupt(profile, history, prompt, tool_host):
    """Run an interruptible agent turn."""
    async for event in run_agent_turn(
        profile=profile,
        system_prompt="You are a pentest assistant.",
        history=history,
        prompt=prompt,
        tool_host=tool_host,
        mode="AutoPwn",
        approve=lambda n, a: asyncio.coroutine(lambda: True)(),
        on_history=lambda: None,
        interrupt_requested=lambda: interrupted,
    ):
        yield event

# Set interrupted = True from another thread to cancel

Related Pages

Implements Principle

Requires Environment

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment