Skip to content

Stream agent events

An unattended agent can run for many minutes. This page shows four ways to see what it does: its events as they come, progress reported to the caller, the logs of the task and the report of its launch, and the sandbox kept after the run to look inside.

Stream its events

ctx.agent.stream(prompt) runs the agent as prompt does, and yields what it reports as it goes:

docs_src/agents/follow_progress.py
from pathlib import Path
from typing import Annotated

from fastsandbox import Context, FastSandbox, WorkspaceDir

app = FastSandbox("reviews")


@app.agent("claude", timeout="30m")
async def review(ctx: Context, repo: Annotated[Path, WorkspaceDir(clone=True)]) -> str:
    """Has Claude Code review a project, reporting each step it takes."""
    prompt = "Review this project and list its three main risks."
    steps = 0
    answer = ""
    async for event in ctx.agent.stream(prompt, working_dir=str(repo.resolve())):
        if not isinstance(event, dict):
            continue
        if event.get("type") == "assistant":
            steps += 1
            await ctx.report_progress(steps, message="the agent took a step")
        elif event.get("type") == "result":
            answer = str(event.get("result", ""))
    return answer


def show(progress: float, total: float | None, message: str | None) -> None:
    print(f"step {progress:g}: {message}")


if __name__ == "__main__":
    print(app.run_sync("review", repo=".", on_progress=show))
  • Line 15: each item is a line of the output of the agent, parsed as JSON for the agents that report JSON lines (claude, codex, cursor, droid), a text line for the others.
  • Lines 18 to 22: Claude Code reports an assistant event for each step it takes, and ends with a result event that holds its final answer. The task counts the steps, and keeps the answer as its result.

Report progress to the caller

Line 20: ctx.report_progress sends how far the run got to whoever called it. Lines 26 to 31: the caller receives it through on_progress, here a function that prints it:

$ python docs_src/agents/follow_progress.py
step 1: the agent took a step
step 2: the agent took a step
...

A progress bar, a chat message or a web page take the place of print the same way; the handler may be a plain function or a coroutine function (see Running tasks).

Read the logs

ctx.log(message) logs through the logger of the task, fastsandbox.task.<name>, with the name of its sandbox. The standard logging module shows them: logging.basicConfig(level=logging.INFO) at the start of the program is enough. The run logs there too, as a warning, the credentials the daemon withholds from the sandbox.

What the launch gave the sandbox is in ctx.lease.report: its kits, its network rules, the keys that go to the proxy, those left out and why, and the MCP servers registered in the agent, never the value of a key. An agent that fails for want of its key shows there first (see Tasks).

Look inside after the run

keep=True on the decorator keeps the sandbox after the run instead of deleting it, with what the agent left in it, and keeps it too when its launch fails once it exists, a startup command for instance:

  • sbx ls lists it; the task can log its name, ctx.sandbox.name;
  • ssh -o ProxyCommand="fastsandbox ssh-proxy NAME" agent@NAME opens a shell in it, through the socket (see SSH);
  • client.sandbox(NAME) reaches it from Python.

It stops once nothing holds it running, and it is then yours to delete, with sbx or delete(). Keep it for debugging only: a kept sandbox holds the clone and the work of the agent.

Talk to it

ctx.agent.session() starts the agent in an interactive session, as sbx run does, for a program that relays a terminal or drives the conversation itself (see Interactive sessions).