Skip to main content

Module loop_

Module loop_ 

Structs§

AgentRunOverrides
LoopKnobs
Explicit knobs for per-caller loop behaviour.
ModelSwitchRequested
ParsedToolCall
A single parsed tool call extracted from LLM output.
ResolvedAgentExecution
ResolvedIo
The per-turn I/O wiring half of ResolvedAgentExecution::resolve’s input: the borrowed sinks, channels, and policy handles a path holds for the turn. A grouped input layer (not stored state); resolve spreads it into the bundle.
ResolvedModelAccess
The resolved model binding: which provider, model, and temperature a turn uses. The base layer any LLM call needs; ResolvedAgentExecution composes it. Field names mirror the engine’s former flat fields so the loop body is unchanged after destructuring.
ResolvedRuntimeKnobs
The resolved per-agent runtime knobs half of ResolvedAgentExecution::resolve’s input: the values derived from the agent’s resolved config. A grouped input layer (not stored state); resolve spreads it into the bundle.
SopStepReassembly
Config handle the live SOP driver needs to re-assemble a nested step’s agent when the step delegates to a different agent than the one running the turn.
ToolExecutionOutcome
ToolLoop
ToolLoopCancelled
ToolLoopCostTrackingContext
Context for cost tracking within the tool call loop. Scoped via tokio::task_local! at call sites (channels, gateway).
TurnUsage
Per-scope token/cost accumulator derived from the usage events emitted during a single task-local runtime invocation.

Enums§

MaxIterationBehavior
How to handle max-tool-iteration exhaustion.
StreamDelta
Delta sent from the agent loop to the channel’s draft updater. Append-only — no clear/reset variant exists by design.
ToolProtocolEnvelopeKind
Internal tool protocol envelope variants that must not be treated as user-visible channel text.

Constants§

PROGRESS_MIN_INTERVAL_MS
Minimum interval between progress sends to avoid flooding the draft channel.

Statics§

CLI_CHANNEL_FN
CLI channel factory, injected by the binary. Returns a Box<dyn Channel> for interactive mode.
TOOL_CHOICE_OVERRIDE
Override for tool choice mode, set by the agent loop. Read by model_providers that support native tool calling.
TOOL_LOOP_COST_TRACKING_CONTEXT
TOOL_LOOP_SESSION_KEY
Session key for the currently active session. Scoped by gateway and channel turns, read by SessionsCurrentTool.
TOOL_LOOP_THREAD_ID
Current thread/sender ID for per-sender rate limiting. Set by the agent loop, read by SecurityPolicy.

Functions§

agent_turn
Execute a single turn of the agent loop: send messages, parse tool calls, execute tools, and loop until the LLM produces a final text response. When silent is true, suppresses stdout (for channel use). agent_alias, when the caller has resolved one, is threaded onto the turn’s AgentStart/AgentEnd brackets and onto the inner ToolLoop, so every lifecycle observer event of the turn (agent_start, llm_request, llm_response, tool_call_start, tool_call, agent_end) carries the full (channel, agent_alias, turn_id) correlation triple that observer consumers (Prometheus, OTel, the gateway /api/events stream) rely on for per-agent attribution. None opts out for callers without a resolved alias (tests, benches). turn_id follows the same pattern: Some reuses a caller-minted id so pre-turn events (the process_message RAG retrieval) join the bracket; None self-mints.
append_or_merge_system_message
append_pinned_mcp_section
Append a pre-rendered pinned-MCP-resources section onto the system-prompt MCP accumulator (deferred_section).
apply_policy_tool_filter
apply_text_tool_prompt_policy
build_native_assistant_history_from_parsed_calls
build_tool_instructions
Build the tool instruction block for the system prompt so the LLM knows how to invoke tools.
build_tool_instructions_for_names
Build tool instructions for the subset of registered tools that are effective for the current prompt.
canonicalize_json_for_tool_signature
canonicalize_tool_result_media_markers
Rewrite real local image file paths in tool output into [IMAGE:...] markers so the multimodal pipeline can normalize them before the next provider call. This targets shell/skill outputs that print filesystem paths directly rather than returning explicit media markers.
check_tool_loop_budget
Check budget before an LLM call. Returns None when no cost tracking context is scoped (tests, delegate, CLI without cost config).
classify_tool_protocol_envelope
contains_tool_protocol_tag_call
detect_tool_call_parse_issue
drain_steering_messages
Drain any steering messages the caller pushed since the last round.
eager_mcp_tool_allowed
Whether an MCP tool name is admitted by policy (a None policy admits everything). The risk-profile denylist always wins; the allowlist auto-admits <server>__<tool> names so a restrictive allowlist does not silently drop a configured server’s tools.
estimate_history_tokens
Estimate token count for a message history using ~4 chars/token heuristic. Includes a small overhead per message for role/framing tokens.
filter_by_allowed_tools
filter_tool_specs_for_turn
is_model_switch_requested
is_tool_loop_cancelled
load_interactive_session_history
load_peripheral_tools
Public helper for other crates (e.g. channels orchestrator) to load peripheral tools through the registered factory. Returns empty vec when nothing is registered (hardware feature off or not yet wired).
looks_like_malformed_tool_protocol_envelope
looks_like_malformed_tool_protocol_envelope_for_known_tools
looks_like_tool_protocol_envelope
looks_like_tool_protocol_example
make_query_summary
mcp_tool_access_policy
Build the MCP tool-access policy for an agent from its SecurityPolicy (allowed_tools + excluded_tools) and an optional caller-supplied allowlist. Shared by the runtime agent loop and the channels orchestrator so every MCP registration site gates through identical logic.
native_tool_specs_present_for_turn
normalize_system_messages
parse_tool_calls
process_message
Process a single message through the full agent (with tools, peripherals, memory). Used by channels (Telegram, Discord, etc.) to enable hardware and tool use.
record_tool_loop_cost_usage
Record token usage from an LLM response via the task-local cost tracker. Returns (total_tokens, cost_usd) on success, None when not scoped or no usage.
register_channel_map_fn
Register the channel map factory. Called once at startup by the binary.
register_cli_channel_fn
Register the CLI channel factory. Called once at startup by the binary.
register_eager_mcp_tool_if_allowed
Register an eager MCP tool wrapper into tools (and the delegate handle, when present) only if policy admits it. Returns true when the tool was registered, false when the policy dropped it.
register_peripheral_tools_fn
Register the peripheral tools factory. Called once at startup by the binary.
run
run_tool_call_loop
save_interactive_session_history
scope_session_key
Run a future with the session key set in task-local storage. The scope wraps the entire agent turn, so all tools invoked during the turn (including nested calls) see the same session key. SessionsCurrentTool reads this to identify the active session.
scope_thread_id
Run a future with the thread ID set in task-local storage. Rate-limiting reads this to assign per-sender buckets.
scrub_credentials
should_execute_tools_in_parallel
strip_think_tags
Remove <think>...</think> blocks from model output. Qwen and other reasoning models embed chain-of-thought inline in the response text using <think> tags. These must be removed before parsing tool-call tags or displaying output.
strip_tool_result_blocks
Strip prompt-guided tool artifacts from visible output while preserving raw model text in history for future turns.
tool_protocol_envelope_mentions_known_tool
trim_history
truncate_tool_result

Type Aliases§

DraftEvent
Backwards-compatible alias while callers are migrated.
ModelSwitchCallback
Callback type for checking if model has been switched during tool execution. Returns Some((model_provider, model)) if a switch was requested, None otherwise.
PeripheralToolsFn
Peripheral tools factory type — takes owned config so the returned future is ’static.