How is the agent loop implemented?
Planner vs single loop; tool-call schema; turn structure; stop conditions; sub-agents.
Verdict
For long unattended runs, Codex has the most mature turn engine, and Aider suits approving every step. OpenHands is different: at this commit the repository is a control plane, and the loop runs elsewhere.
Human-driven. Aider parses edit blocks from plain text in Coder.run_one(). Only reflections (a failed SEARCH block, lint errors) loop back, at most three per message.
One tool-calling loop.
- Codex:
run_turnover the Responses API. Stop hooks can veto a stop. - Open Interpreter: a Codex fork that runs each turn through an emulated harness (Claude Code, Qwen Code…).
- Cline: ends on no tool calls, a terminal tool such as
submit_and_exit, ormaxIterations. - Codewhale: one
run_turn. A guard test fails if a second loop is added. - Qwen Code and Gemini CLI:
MAX_TURNS = 100, and the front ends, not core, run the tools. Gemini CLI adds a model call (checkNextSpeaker) to decide whether to continue. - OpenCode: reloads history from SQLite every step.
taskchild sessions nest one level. - PI-Desktop: every tool call crosses into a Rust host. All tools except
Taskrun sequentially. - Pi: a generic loop with steering and follow-up queues, parallel tools, no turn cap and, by design, no sub-agents.
- goose: the default loop stops at
GOOSE_MAX_TURNS(1000). An ordered state-machine pipeline is opt-in. - Continue: in the IDE, recursive Redux thunks in the GUI with no depth cap outside tests. The
cnCLI has a separate loop. - DeepSeek-Reasonix: the only optional planner/executor split, with the plan returned through
submit_plan.
Delegated. OpenHands sends max_iterations (500) and stuck_detection to the Python Agent Server, or hands the work to an ACP agent such as Claude Code. Its planner is read-only because its tool list holds only glob, grep and a PLAN.md editor.
App-builder pipelines.
- VibeSDK: the default Think engine is a model-and-tool loop with bash disabled.
- bolt.diy: one
streamTextcall per request, plus up to two continuation segments. - Open Lovable: one streamed completion parsed for
<file>tags. Truncation recovery is off by default.
Pick: Aider for step-by-step pair programming. Pick: Codex, Codewhale or Cline for unattended work, DeepSeek-Reasonix for plan-then-execute, Pi for a loop you can rewire. Pick: VibeSDK for an app builder that iterates on its own deploy errors.
Per-project answers
anomalyco/opencode
answeredAgent Loop
The agent loop is a single-loop architecture — there is no separate Planner; the model calls tools directly until it decides to stop. The main loop is runLoop in packages/opencode/src/session/prompt.ts (line 1081-1341), which runs inside a while(true) controlled by SessionRunState.ensureRunning (line 1343-1347). Each iteration (step): loads messages from the database, resolves the model and agent, assembles tools via SessionTools.resolve, prepares system prompts (environment, instructions, skills, MCP), and calls LLM.stream which delegates to either the native LLM runtime or the AI SDK (session/llm.ts lines 226-269). The stream events are processed by SessionProcessor.process (processor.ts lines 641-697), which handles tool calls, reasoning, text deltas, and step completion via an event handler (handleEvent, lines 278-551).
Tool-call schema uses the Vercel AI SDK's Tool type (ai package) — tools emit tool-input-start/delta/end, tool-call, tool-result, and tool-error events. Tools execute via SessionTools.resolve (session/tools.ts), which iterates the ToolRegistry to get built-in tools (edit, write, bash, read, grep, glob, task, etc.) and MCP-provided tools. MCP tools' schemas are normalized through ProviderTransform.schema (provider/transform.ts line 1575).
Stop conditions: the loop breaks when the model returns a finish reason other than "tool-calls" or "unknown" (line 1111-1116), or when the processor returns "stop" (line 1319), or when compaction creates a loop (line 1166-1168). If the processor returns "compact", a compaction step is created and the loop continues (line 1321-1328).
Sub-agents use the task tool (tool/task.ts), which spawns a new session with a different agent via handleSubtask (prompt.ts lines 255-449). Agents like general, explore, and custom agents are defined in agent/agent.ts (lines 140-265) with distinct permission rulesets and system prompts. Background sub-agents use BackgroundJob service for async execution.
openai/codex
answeredCodex CLI uses a single-loop architecture without a separate planner; the model itself plans and acts within each turn. The core loop lives in run_turn() in core/src/session/turn.rs:164 which accepts TurnInput (user messages, function-call outputs, inter-agent communications) and runs a loop { ... } (line 427) that repeats until the model produces a final assistant message with no pending input. Inside the loop, the session builds a prompt from its cloned history (line 527), invokes the OpenAI Responses API via run_sampling_request() (line 535), streams the response, and executes any tool calls the model makes through the ToolCallRuntime (line 1633). After each sampling round the loop checks for pending user input (line 431), token-limit thresholds for auto-compaction (line 612), and hook stop/block requests (line 663–719). Tool calls are dispatched through try_run_sampling_request() (line 1679) which invokes the ToolRouter — a registry that maps tool names to CoreToolRuntime implementations in core/src/tools/registry.rs. Sub-agents are supported via a multi-agent V2 system in core/src/tools/handlers/multi_agents_v2.rs:1 where tools like spawn_agent, send_message, and wait let the model create and communicate with child threads, coordinated by the AgentControl trait in core/src/agent/api.rs:41. The turn's tool-call schema is defined by the Responses API's native function-calling format, with tool definitions served by the ToolRouter and filtered per-step based on permissions and feature flags.
earendil-works/pi
answeredThe agent loop lives in packages/agent/ — a single-threaded, turn-based loop with no separate planner component. Single loop, no planner. The runLoop() function in packages/agent/src/agent-loop.ts (line 163) runs an inner loop processing assistant responses and tool calls, and an outer loop that checks for follow-up messages. There is no planning phase: every turn the model produces a response (text + optional tool calls) and the loop executes them. Tool-call schema. Tools are defined via AgentTool<T> in packages/agent/src/types.ts (line 464) with a name, parameters (typebox schema), execute() function, and optional prepareArguments/beforeToolCall/afterToolCall hooks. Tool calls from the model are validated against their schemas before execution; invalid calls produce error results. Execution can be "parallel" (default — concurrent) or "sequential" — see executeToolCalls() at line 508. Turn structure. Each turn: (1) pending messages (steering/follow-up) are emitted, (2) prepareRequest hook runs, (3) streamAssistantResponse() at line 381 converts AgentMessage[] to Message[] via convertToLlm, calls the LLM stream function, and emits streaming events (start, text_delta, toolcall_start, etc.), (4) any tool calls are executed with results pushed back to context, (5) finishTurn decides continuation. Stop conditions. A turn stops on stopReason === "error" or "aborted" (hard stop, line 245-256). Otherwise, if no tool calls remain, no steering/follow-up messages are queued, and finishTurn doesn't request continuation, the loop ends (line 310-318). Sub-agents. Pi explicitly chooses not to implement sub-agents (README line 19). Instead it supports nested tool calls via ctx.executeTool() in extensions (see packages/coding-agent/src/core/extensions/types.ts line 394), codemode scripts, and MCP tool delegation. Each model request is self-contained; the model may call tools that internally call other tools, but no child agent loops exist.
google-gemini/gemini-cli
answeredThe agent loop is implemented as a single, internally recursive loop in GeminiClient.sendMessageStream() (packages/core/src/core/client.ts:924). There is no separate Planner module. The loop begins by calling processTurn() (line 979), which sets up context, routes to a model via ModelRouterService.route(), then yields control to Turn.run() (packages/core/src/core/turn.ts:270). Turn.run() streams events from the Gemini API: text content, tool call requests, thoughts, citations, and finish reasons. Tool call requests are emitted as ServerGeminiToolCallRequestEvent events (line 382-384) with a callId, name, and args. After the Turn finishes, if there are pending tool calls, sendMessageStream passes the request through the scheduler where ToolExecutor.execute() (packages/core/src/scheduler/tool-executor.ts:63) runs each tool and returns results. The tool results are fed back into the model as a new request, and sendMessageStream recurses (line 910 and 1040), decrementing the turn budget. Stop conditions include: exceeding MAX_TURNS (100, line 79 in client.ts), the model finishing with no pending tools, loop detection via LoopDetectionService (lines 761, 827), user cancellation (GeminiEventType.UserCancelled), context window overflow, errors, and hooks returning stop or block decisions. Sub-agents are implemented through the AgentTool (packages/core/src/agents/agent-tool.ts:43), which delegates to invocations like LocalSubagentInvocation or RemoteAgentInvocation, each running a nested GeminiClient.sendMessageStream in a derived AgentLoopContext. The event architecture uses AgentSession (packages/core/src/agent/agent-session.ts:18) wrapping an AgentProtocol with a subscribe/notify pattern, and event-translator.ts converts Gemini's event types into uniform AgentEvent discriminated unions.
GeminiClient.sendMessageStream does one model round and yields ToolCallRequest events; the tool loop lives in the caller (nonInteractiveCli.ts and the UI's useGeminiStream), which runs scheduler.schedule and sends the function responses back. The recursive calls in client.ts are the next-speaker "Please continue." check and the AfterAgent-hook continuation, and subagents run in LocalAgentExecutor with their own GeminiChat, not a nested GeminiClient.OpenHands/OpenHands
answeredAgent Canvas is a frontend that delegates the agent loop to a backend Agent Server (Python, software-agent-sdk). Canvas builds the start-conversation payload in src/api/agent-server-adapter.ts (lines 1072–1091), which selects between two agent kinds: OpenHands (direct LLM via LiteLLM) or ACP (external CLI subprocess like Claude Code/Codex/Gemini). The payload includes max_iterations (default 500, line 147), stuck_detection: true, a confirmation_policy, and a security_analyzer. A second local planner agent is spawned via buildStartPlanningConversationRequest (lines 1450–1572) with a PlanningFileEditorAction tool operating on PLAN.md; it uses its own LLMSummarizingCondenser (max_size: 100, keep_first: 6, lines 1520–1525). Once the conversation is created, the frontend communicates over a WebSocket (conversation-websocket-context.tsx, line 1–86) that streams events: user messages, actions (tool calls), observations (tool results), and conversation state updates. The turn structure flows as: user sends a message → ConversationClient.sendEvent (api line 464–468) → server processes → events stream back over WebSocket → the frontend renders them. The action type system (src/types/agent-server/core/base/action.ts, lines 6–370) defines ~20 tool types including ExecuteBashAction, FileEditorAction, GlobAction, GrepAction, BrowserNavigateAction, TaskAction (for sub-agents), SwitchLLMAction, and MCPToolAction. Sub-agents are launched via TaskAction with fields prompt, subagent_type, description, and resume (lines 282–299); their results arrive as TaskObservation with task_id, subagent, and status (observation.ts lines 305–326). Stop conditions are expressed through ExecutionStatus (common.ts lines 67–75): idle, running, paused, waiting_for_confirmation, finished, error, stuck.
cline/cline
answeredCline implements a single-turn agent loop — there is no Planner/executor split. The core loop lives in AgentRuntime.execute() in @cline/agents (agent-runtime.ts:783). It iterates: prepare the model request → call the LLM provider → extract tool calls → execute each tool → collect results → repeat. Stop conditions are: (1) the assistant returns no tool calls and no completion reminders fire (agent-runtime.ts:936-957), (2) a terminal/completion tool was called (agent-runtime.ts:977-993), (3) maxIterations is exceeded (agent-runtime.ts:831-833), or (4) an error/abort occurs (agent-runtime.ts:1000-1024). The tool-call schema uses AgentToolCallPart objects with typed toolCallId, toolName, and input fields; the model's response is parsed into these structured parts. Sub-agents are supported via the spawn-agent tool (spawn-agent-tool.ts), creating child AgentRuntime instances inside separate session contexts. Each turn goes through beforeModel/afterModel and beforeTool/afterTool hooks for extension points. Output-token-limit recovery and provider-error retry with exponential backoff are built in (agent-runtime.ts:72-91).
openinterpreter/openinterpreter
answeredThe agent loop is two-layer: an outer turn loop and an inner sampling loop. RegularTask (core/src/tasks/regular.rs:31-126) is the SessionTask implementation. Its run() emits TurnStarted, runs turn lifecycle, then enters a loop calling run_turn() while sess.input_queue.has_pending_input() returns true (line 120). Inside run_turn() (core/src/session/turn.rs:163-817), the inner loop builds a StepContext with a ToolRouter and calls run_sampling_request() (line 1592). The Prompt struct (line 1558) contains cloned history, model_visible_specs(), base_instructions, and output_schema. The model streams through ModelClientSession.stream() (line 2491). There is no separate planner -- plan mode (ModeKind::Plan) is a tool-mode flag on the ToolRouter enabling PlanDelta streaming within the same request. Sub-agents use multi-agent collaboration (core/src/tools/handlers/multi_agents.rs:1-78): spawn_agent/send_message create child threads via LocalAgentControl (core/src/agent/control.rs). AgentRegistry (core/src/agent/registry.rs:26-28) tracks agents and enforces depth/session limits. Stop conditions: terminal errors (line 117), no pending input (line 120), turn-stop hooks (line 646-691), context-window compaction (line 602).
aaif-goose/goose
answeredGoose has two agent-loop implementations: the legacy loop in agent.rs and the new state machine in state_machine/. The reply() method dispatches between them via a boolean flag; the state machine is gated by GOOSE_STATE_MACHINE=1 (mod.rs:94-98).
The state machine (goose-agent/src/machine.rs:51) is an ordered pipeline of Steps, each wrapping either an Operation or an Inference. Its run() loop loads the session, then calls step() — which walks the steps in order calling each operation's run() — and then apply() to persist effects. The first operation that returns Applied yields the turn; NotApplicable falls through to the next step. The loop repeats until no step applies or yield_to_client is set (machine.rs:167-182).
goose defines ~20 concrete operations for the state machine (create_state_machine at agent.rs:1694): EntryHookOperation, SteerOperation (queued user guidance delivered between turns), MaxTurnsOperation (default 1000-turn budget, agent.rs:88), BangShellOperation (the ! shortcut), CompactionOperation (auto-compact when context exceeds threshold), ToolApprovalOperation (permission routing), ToolExecutionOperation (dispatch tool calls to extensions/MCP servers), RetryOperation (retry with goal/grind), ExitOnErrorOperation, RecipeOperation, ForegroundSubagentOperation, StopHookOperation, plus prompt-part contributors like ProjectOperation and SkillOperation.
Tool calling flows through ToolExecutionOperation (ops_toolcalling.rs): it collects pending tool requests from the conversation, runs PreToolUse hooks (blocking — can deny execution), categorises the tool (Shell/Read/Write/Other), emits BeforeShellExecution/BeforeReadFile extended hooks per category, dispatches to the ExtensionManager, and emits PostToolUse/PostToolUseFailure on completion. Tool names are prefixed by their owning extension with __ (e.g. developer__shell) and the manager canonicalises name mangling from providers.
Stop conditions are: max turns reached (MaxTurnsOperation), a hard error (ExitOnErrorOperation), explicit yield-to-client from any operation (notably RetryOperation after goal satisfaction), and the turn always ending after the LLM responds without tool calls.
Sub-agents are implemented by ForegroundSubagentOperation (ops_foreground_subagent.rs): it spawns a child Agent with its own Session and recipe, runs it to completion, and captures the final output text. The subagent reuses the same provider and extension manager context. There is also a subagent_execution_tool module for background multi-task sub-agent execution.
Aider-AI/aider
answeredSingle loop with coder subclasses, not a separate planner. The main loop lives in Coder.run() (aider/coders/base_coder.py:876-891). It calls self.get_input() to read a user message, then self.run_one() to process it. run_one() (base_coder.py:924-944) calls send_message() synchronously, then optionally loops on self.reflected_message (up to max_reflections=3) to handle multi-turn self-correction (e.g., file-mention follow-ups, lint-error feedback).
No tool-call schema by default — edits are text-based. The LLM returns SEARCH/REPLACE blocks in plain text for the "diff" edit format (via EditBlockCoder.get_edits(), aider/coders/editblock_coder.py:21-36). There is an alternative function-calling path: WholeFileFunctionCoder and EditBlockFunctionCoder define JSON-schema functions lists (e.g. write_file with path/content params), which are sent as tools in the litellm request (aider/models.py:1006-1009). The architect mode (ArchitectCoder, aider/coders/architect_coder.py) uses a two-stage sub-agent: the architect model plans, then spawns a separate editor sub-coder via Coder.create() to apply changes.
Turn structure. Each turn: user input is preprocessed (URL scraping, file-mention detection via check_for_file_mentions at base_coder.py:1761), formatted into structured message chunks (system + examples + done-messages + repo-map + readonly files + chat files + cur + reminder — see format_chat_chunks() at base_coder.py:1226-1331), sent to the LLM via model.send_completion() (aider/models.py:985-1037), and the response is parsed for edits or shell commands. After the response, edits are applied, auto-commits happen, lint runs, shell commands execute with user confirmation, and tests optionally run.
Stop conditions. The loop runs until EOF (Ctrl-D), double Ctrl-C (keyboard_interrupt() at base_coder.py:986-1000), or /exit. Within a turn, the reflection loop stops when msg is empty or max_reflections is hit.
Sub-agents. Only in architect mode: ArchitectCoder.reply_completed() creates a new Coder instance to execute edits (architect_coder.py:37-44). There is no general sub-agent framework.
codewhale-hq/Codewhale
answeredCodewhale uses a single, unified turn loop — no planner/solver separation. The authoritative turn loop is Engine::run_turn in crates/tui/src/core/engine/turn_loop.rs:1358, and a guard test (crates/core/tests/single_turn_loop.rs) fails if a second loop is introduced.
Turn structure: Each call to run_turn iterates through four sequential phases, looped until a stop condition:
- prepare_model_step (
preparation.rs) — loads the tool catalog, refreshes MCP servers, drains sub-agent completions, processes pending steers (user mid-turn nudges), and applies soft-landing notices at ~80% of the step budget. - run_model_step (
model_step.rs) — dispatches the model request (OpenAI Chat Completions, Anthropic Messages API, or OpenAI Responses API depending on provider), streams the response, decodes SSE events, and handles retries/stream resumes. - continue_model_step (
continuation.rs) — handles output-limit truncation, RLM (reasoning language model) continuation, and prompts the model to continue from where it left off. - run_tool_batch_phase (
tool_batch.rs) — plans tool executions (resolves tool schemas, applies Auto-Review gates, checks permission policy) and then executes them in parallel, collecting results into the session.
Tool-call schema: Tools are registered as ToolSpec implementations with JSON Schema inputs (tools/spec/spec.rs). The catalog for a turn is built from built-in "active native tools" (read, write, edit, bash, agent, workflow, todo_write) plus deferred/discovery tools accessed via tool_search. Tool calls follow the OpenAI/Anthropic function-calling wire format, with aliases for cross-harness parameter spellings (old_string→search, file_path→path, etc.).
Stop conditions: The loop exits when: step budget exhausted (max_steps), per-turn wall-clock timeout, user cancellation, tool-call budget exhausted, consecutive empty model responses, reasoning-only retry limit, no-progress detection from repeated permission denials, or the model stops emitting tool calls.
Sub-agents: Spawned via the agent tool (tools/subagent/mod.rs:11506). The model calls agent with an action (Start, Roster, Status, Message, Followup, etc.), and a background agent session runs with its own filtered toolset and workspace context. Foreground (turn-owned) sub-agents are tracked via ForegroundChildRegistry and cancelled when the turn ends. Background sub-agents complete asynchronously and deliver results via runtime messages. A fleet roster (FleetRoster) provides role-based model assignment for spawned agents.
continuedev/continue
answeredThree modes sharing one streaming loop. Continue has chat, agent, and plan modes — selected via UI, each picking a different system message from core/llm/defaultSystemMessages.ts. All modes flow through llmStreamChat() in core/llm/streamChat.ts which calls model.streamChat() on BaseLLM (core/llm/llms/llm.ts). Tool-call schema. Tools are passed as options.tools to streamChat() (llm.ts line 1105). Each provider converts the generic Tool[] to its format — Anthropic (core/llm/llms/Anthropic.ts line 69) maps via convertToolToAnthropicTool(). For non-native models, interceptSystemToolCalls() (core/tools/systemMessageTools/interceptSystemToolCalls.ts) parses markdown code-block tool calls. Turn structure. Edit tools dispatch via core/tools/callTool.ts routing to callBuiltInTool() (lines 187-230) or callToolFromUri() for MCP (lines 67-185). Stop conditions. No hard step limit. Per-message AbortControllers (core/core.ts lines 98-109) enable cancellation. No sub-agent system in core.
esengine/DeepSeek-Reasonix
answeredThe agent loop is a tool-round loop inside Agent.runToolLoop (internal/runtime/agent/run_loop.go:261). There is no separate planner model by default — the single model both plans and executes. An optional two-model Coordinator (internal/runtime/coordinator/coordinator.go:97) runs a planner model first (via submit_plan, planner tools are read-only), then hands its plan to an executor Agent. The loop in runToolLoop iterates steps up to maxSteps (default from config). Each step: (a) freezes the provider request via prepareSamplingRequest — tool schemas are captured once (ProviderSchemas), prefix shape recorded; (b) streams the model response with streamWithSamplingRecovery (run_loop.go:407), which retries up to maxSamplingAttempts=6 on interruption or context overflow; (c) classifies the response boundary via classifyResponseBoundary (response_boundary.go:27) to drop half-written tool calls; (d) commits assistant message to conversation; (e) for tool calls, runs handleToolRound → executeOne (execute_one.go:95), which resolves the tool (parse, policy, permission gate, sandbox extend, execute, post-write receipt); (f) loops back for another step. Stop conditions: no tool calls → final response handled by handleFinalResponse; max steps reached → armFinalizationRound/gracePause (finalization.go:40,55); task budget exhausted → taskBudgetPause; perseveration detected → cut-and-retry with nudge (settlePerseveration). Sub-agents are spawned via RunSubAgentWithSession (child_run.go:36), each getting its own Agent instance, session, event sink, and session-private temp directory.
firecrawl/open-lovable
answeredThere is no iterative agent loop with tool-calling; it is a linear single-shot pipeline per user request. The flow: (1) user prompt hits /api/generate-ai-code-stream (app/api/generate-ai-code-stream/route.ts:91), (2) for edits, it first calls /api/analyze-edit-intent which uses Vercel AI SDK's generateObject() with a Zod schema to produce a structured search plan, (3) the search plan is executed locally by executeSearchPlan() in lib/file-search-executor.ts:42 which greps file contents line-by-line, (4) a single LLM completion is called via streamText() from the Vercel AI SDK (lib/ai/provider-manager.ts wraps the providers), (5) the text stream is parsed in real-time for XML tags (<file>, <package>, <command>) in generate-ai-code-stream/route.ts:1397-1504, and (6) parsed files are sent to /api/apply-ai-code-stream (app/api/apply-ai-code-stream/route.ts:264) which writes them to the sandbox. The system does NOT use tool/function calling — the code explicitly states: "Neither Groq nor Anthropic models support tool/function calling in this context" (route.ts:1310-1311). Instead it relies on XML tags in text output. Stop conditions are simple: up to 2 retries on rate-limit/service errors with exponential backoff (route.ts:1329-1382), and truncation recovery that fires focused API calls to complete files missing closing braces or tags (route.ts:1658-1810). No sub-agents, no multi-turn planning loop.
QwenLM/qwen-code
answeredThe agent loop centres on LlmClient.sendMessageStream() in packages/core/src/core/client.ts, an async generator that orchestrates one complete model interaction turn at a time. The file caps turns at MAX_TURNS = 100 (line 212) and supports multiple message types — UserQuery, ToolResult, Retry, Cron, Notification, Teammate, and Goal (lines 218–237). Each turn: the model generates text plus tool calls, the CoreToolScheduler (core/coreToolScheduler.ts) executes them, and results are fed back as function responses. The loop ends on model text (no tool calls), turn limit, session token limit, loop detection (LoopDetectionService), user interrupt, or stop hooks. There is no separate Planner loop — plan mode is gated by enterPlanMode/exitPlanMode tools that the model itself calls.
Sub-agents use two modes: forked agent (packages/core/src/agents/forkedAgent.ts) — a single-turn cache-sharing call with or without tools, used for auto-memory tasks — and headless/multi-turn via AgentCore (packages/core/src/agents/runtime/agent-core.ts), which owns runReasoningLoop(), tool scheduling, stats, and event emission. AgentInteractive (packages/core/src/agents/runtime/agent-interactive.ts) composes AgentCore with persistent state (message queue, three-level cancellation). Workflows orchestrate many sub-agents in parallel via workflow-orchestrator.ts. Tool-call schemas follow @google/genai's FunctionDeclaration format throughout.
stackblitz-labs/bolt.diy
answeredThere is no Planner sub-agent — Bolt uses a single-turn streaming LLM loop orchestrated from the server. The entry point is app/routes/api.chat.ts, the server-side action handler for /api/chat. The client (Chat.client.tsx) calls useChat from the @ai-sdk/react SDK which sends a POST to that route. On the server, chatAction creates a SwitchableStream and runs a createDataStream block with an execute callback (line 93). Inside that callback, it first processes MCP tool invocations with mcpService.processToolInvocations (line 103), then optionally runs createSummary (line 122) and selectContext (line 164) — two separate LLM calls that create a chat summary and choose relevant files. The main generation is streamText (line 311) which calls the Vercel AI SDK's streamText with model, system prompt, and messages. Tool calls are exposed to the LLM via mcpService.toolsWithoutExecute set as options.tools (line 214), with toolChoice: 'auto' and maxSteps configurable per request. When the LLM response hits finishReason === 'length', the loop constructs a new user message with CONTINUE_PROMPT and calls streamText again, up to MAX_RESPONSE_SEGMENTS = 2 times (lines 251-298). The client uses @ai-sdk/react's useChat which handles streaming state, abort via stop(), and renders tool-call annotations in the UI.
vastsa/PI-Desktop
answeredPI-Desktop has a turn-structured agent loop built on the pi-agent-core library's Agent class, not a separate Planner. The SessionRuntime class in packages/agent-runtime/src/runtime.ts wraps an Agent instance and drives the conversation turn by turn.
Turn structure — Each user message enters through SessionRuntime.prompt() (runtime.ts:8460), which appends user content, checks context budget (auto-compacting if needed), then calls this.agent.prompt(...) (runtime.ts:8555-8557). The agent streams the model response, collects tool calls, executes them sequentially via toolExecution: "sequential" (subagent.ts:296), and loops back for the next assistant turn via waitForIdle() + model .continue(). Stop conditions include: the model emits no tool call and a stop reason (stop/end_turn); the user aborts (abort(), runtime.ts:8735); a graceful stop is requested (requestGracefulStop(), runtime.ts:8751); or a silent/progress-only turn is auto-recovered once then stopped (SILENT_TURN_NUDGE, PROGRESS_TURN_NUDGE, runtime.ts:828-849).
Tool-call schema — Tools are declared to the model via JSON Schema using pi-ai's Type.Object() helpers. The core tools (Read, Write, Edit, Bash, Glob, Grep, ToolSearch, Task, TaskWait, etc.) are defined in runtime.ts:3154-3263 with schema parameters. The Edit tool uses a line-anchored format with tag, ops (PUT/CUT/REM/MV), and optional legacy old_string/new_string. Bash accepts command + optional timeout.
Sub-agents — The Task tool (SUBAGENT_TOOL_NAME, subagent.ts:83) spawns a SubagentRun class that creates its own Agent instance inside the same sidecar process (subagent.ts:278-298). Delegates have their own system prompt, tool set, and model (possibly pinned). They share the host connection so all permission checks go through host-core. The parent only sees the final report; intermediate messages are filtered out of model context (session-context.ts:33-41). TaskWait converges on running delegates, TaskList reports status, TaskStop stops them. Delegates are bounded: max captures, max tokens, and keep the parent from overflowing.
DesktopAgentRuntime, not SessionRuntime, and the session agent uses toolExecution: "parallel" with every tool except Task marked sequential (runtime.ts L2170-L2179); the sequential setting cited is the subagent's.cloudflare/vibesdk
answeredVibeSDK has three distinct agent-loop architectures, selected per app at creation: Think (model-and-tool loop via @cloudflare/think), Agentic (recursive inference with tool calling), and Phasic (deterministic phase orchestration).
The Think loop is the primary/canonical loop, implemented in ThinkAgent (extends @cloudflare/think) at worker/agents/think/ThinkAgent.ts. It is a single model-and-tool loop, not a planner+executor split. Think.getTools() returns a ToolSet of SpaceDO-backed workspace tools (read, write, edit, list, find, grep, delete) from @cloudflare/think/tools/workspace, plus VibeSDK-specific tools: commit, deploy_space, set_title, ask_questions, get_browser_console_logs. Bash is disabled (workspaceBash = false). Each turn is driven by ThinkAgent.chat(), called from ThinkCodingBehavior.runPrompt() which submits user text to the DO and translates streamed UIMessageChunk frames into WebSocket events. Tools use the OpenAI-compatible function-calling schema.
The Agentic loop (worker/agents/core/behaviors/agentic.ts) uses the infer() function in worker/agents/inferutils/core.ts — a generic inference engine that assembles tool-call requests, streams responses, accumulates tool-call deltas from chat-completions chunks, executes tools via executeToolCallsWithDependencies(), and recurses until a depth limit or CompletionDetector signal fires. Stop conditions include: max tool-calling depth per action key, a max message limit (64000 in constants), and completion signals from specific tools. The Agentic loop also includes conversation compactification triggers every 9 tool calls.
The Phasic loop (worker/agents/core/behaviors/phasic.ts) is a deterministic orchestrator that runs blueprint generation, phase generation, phase implementation, and review cycles in a fixed sequence, then iterates with the user.
Think has no sub-agents in the traditional sense; it issues tool calls to the SpaceDO workspace and other services. The infer() function does support recursive tool calling (model calls tool, tool result feeds back to model), which is its form of sub-loop.
Turn structure (Think): beforeTurn() selects context messages, beforeStep() enforces rate limits and injects a max-steps prompt on the final step. getModel() wraps an OpenAI-compatible provider over AI Gateway with custom SSE patching for Google Gemini compatibility.
How is repository context gathered and kept within the context window? →