Agent Loop & Tool Lifecycle
A turn begins when the user (or a completed background task) submits input to an idle session and ends when a step finishes without tool calls (or fails) and no further queued inputs remain, or when cancellation stops it. For Chat Completions wire framing, streaming details, and retry rules, see providers.md; for Lua execution and built-in functions, see tool.md and functions.md.
Turn submission and steering queue
- Idle session: Submitting input marks the session busy, starts a fresh generation and cancellation flag, attempts session auto-titling if unnamed (sessions.md), emits
turn_start, and starts the turn loop on a background worker thread. - Busy session (steering): Submitting input while a turn is already running appends it to the session's FIFO input queue and returns
(inputId, queued = true). - Withdrawing queued input: Before the turn loop drains a queued item at the start of the next step, the client can withdraw it by
inputId(in the TUI, editing the dimmed draft withdraws it automatically; in JSON-RPC,turn.withdraw). Withdrawing does not interrupt the running step.
Step execution loop
Each iteration of the turn loop runs one model request and any tool calls it emits:
- Drain queued inputs: All currently queued items are taken in order:
- User inputs emit
user, persist auserrecord, and triggeruser_messagehooks (is_first = trueonly for the firstuserrecord in the session). - Task completion notifications emit
notificationand persist anotificationrecord (they do not triggeruser_messagehooks and are not displayed in the TUI chat).
- User inputs emit
- Assemble prompt and messages:
- System prompt: Built-in system prompt (omitting any built-in host functions disabled with
false) + each string inconfig.systems+ a compaction explanation note if earlier records were dropped. Configuredfunctionsare not listed automatically. - Message history: Built from durable
recordsusing the active compaction bounds (usage.md, providers.md). - Tools: Always advertises a single function tool:
lua(code).
- System prompt: Built-in system prompt (omitting any built-in host functions disabled with
- Resolve provider and call API:
- Splits active
modelon the first/and looks up the provider in the session's loaded provider snapshot. If missing, records and emits anerror(no \connect` entry named `<provider>` for model `<model>``) and treats the step as done. - Sends the Chat Completions request via the HTTP client (providers.md): streams SSE until
data: [DONE]or stream EOF (or parses a single JSON fallback body), emittingreasoningdeltas (fromreasoning_contentand/orreasoning— both emit if both appear),textdeltas, and livetool_deltacode chunks. When the response ends, tool calls with empty names are dropped and remaining calls without IDs receive synthetic IDscall_0,call_1, etc. - Retryable failures (HTTP
429, HTTP5xx, network/transport errors) retry up tomin(settings.retries, 5)times over[2, 5, 10, 20, 30]seconds, emittingstream_resetandflash(Retry A/M in Ds: <error>) before each delay. - Non-retryable or exhausted errors record and emit an
errorand treat the step as done (see step 5: if more inputs are already queued, the turn continues to a new step instead of ending).
- Splits active
- Record assistant step:
- If the response includes
usage, updates sessioncontext = input + outputand persists a mainusagerecord (llm = false). - Persists an
assistantrecord with accumulated text, reasoning, and tool calls. - If text is non-blank or tool calls are present, fires
agent_messagehooks withstatus = "working"(when tool calls exist) or"finished"(when none). - Emits
assistantandusage.
- If the response includes
- Branch on tool calls (and failed steps):
- No tool calls (or step failed with an error): Checks the input queue. If new inputs arrived while the step ran, loops into another step to process them; otherwise marks the session idle, persists a
turn_endrecord (cancelled = false), updates session metadata, and emitsturn_end. - One or more tool calls: Runs each tool call sequentially in order, checks compaction after all calls finish (usage.md), and loops to the next step.
- No tool calls (or step failed with an error): Checks the input queue. If new inputs arrived while the step ran, loops into another step to process them; otherwise marks the session idle, persists a
Tool call lifecycle
For each tool call emitted in a step:
- Parses
argumentsas JSON (extractingcodeas display input when present, otherwise rawarguments) and emitstool_start(timeout = 120,id,tool,input). - Dispatches execution:
- Invalid JSON arguments, any tool name other than
lua, or missing/non-stringcodeimmediately returns an error result (code = 1) without starting a Lua job or emittinglua_start/lua_endhooks. - Valid
luacalls assign a sequential execution ID (lua-1,lua-2, ...), firelua_start(kind = "tool"), run the code as a coroutine in the session's persistent Lua VM with a 120-second deadline and the turn's cancel flag, and firelua_end(kind = "tool", status"success"/"error"/"cancelled", duration in ms).
- Invalid JSON arguments, any tool name other than
- While running, built-in host functions emit transient
statusupdates (<verb> <first line, max 60 chars>..., suppressing consecutive identical strings). File mutations (write,append,edit,delete) accumulate diffs andreadon image files accumulates image data URLs on the active tool job. - If the turn was cancelled mid-call, the stale result is discarded (cancellation already recorded placeholder tool results). Otherwise Tuse increments the turn's call counter, persists a
toolrecord (output, exit code0/1/null, captured images, captured diffs), and emitstool_end.
Cancellation
Cancelling (Esc in TUI when no overlay is open, or turn.cancel in JSON-RPC):
- Stops running custom slash commands and
openhandlers. - Cancels currently running hook invocations (queued follow-up events in a hook's lane are not cleared).
- If a turn is busy: sets the turn's cancel flag, increments generation (so any late API or tool result is discarded), marks the session idle, clears pending queued inputs, appends synthetic
[interrupted: no output]tool records for any unfinished tool calls, persists and emitsturn_endwithcancelled = true, saves metadata, and firesagent_messagehooks with any partial streamed text andstatus = "cancelled".
Cancellation is cooperative for in-flight HTTP requests: SSE streaming checks the cancel flag before reading each line, and retry delays poll every 100 ms, so an ongoing socket connect/read or a non-SSE JSON body read is not immediately aborted at the OS socket level (the session still becomes idle right away and ignores the stale response when it returns).
Background task notifications and llm()
- Task notifications: When a background task started with
spawn()finishes or fails on its own (not stopped viatask_stop), Tuse submits anotificationinput:<notification>Task tN (name) finished|failed. Last line: <last>. Output: \task_get("tN").output`.</notification><last>is derived from the task's **return value or error message** (not lines written viaprint()/io.write()to the task log); a task that returnsnilhas no return text, which yieldsLast line: failed.` even when it finished cleanly (tasks.md). If the session is idle, the notification starts a new turn; if busy, it is queued for the next step. - One-shot
llm(prompt, model?, effort?): Sends a standalone user-message request (no tools, no conversation history) through the same provider and retry client (providers.md).modelandeffortdefault to the session's active values. It yields cooperatively, cancels when its own calling coroutine is cancelled or times out (so cancelling a turn cancelsllm()inside tool calls, hooks, or commands, but not inside background tasks), and records ausagerecord (llm = true) and emitsusageonly if the API reply includes ausageobject.