Skip to main content

agent86_core/
agent.rs

1//! The ReAct loop, ported from Python's `orchestration/loop.py` and
2//! `orchestration/circuit.py`.
3//!
4//! One user turn: call the model, run the tools it asks for, feed the results
5//! back, and repeat until it answers without tools. A circuit breaker bounds the
6//! turn by steps, cost, wall-clock time, and consecutive tool errors. Tool
7//! activity is reported inline as `[tool] ...` lines, exactly as Python streams it.
8//!
9//! Side-effecting calls pass through the approval gate before they run.
10//!
11//! Guardrails scan the goal, each answer, and each tool observation.
12//!
13//! A turn can be cancelled from another thread or task ([`CancelToken`]). It stops at
14//! the next safe point: before a model call, while a response streams, and between
15//! tool calls, never in the middle of one. The partial exchange is kept.
16//!
17//! Every request is fitted to the model's context window (`memory::working`).
18//! Before a model call, a conversation over budget has its oldest span replaced
19//! by a model-written summary (`[limits] compaction = "summarize"`), or dropped.
20//!
21//! `delegate` runs a sub-agent (`crate::subagent`) inside the batch's sequential
22//! part, and what it spends is added to the turn.
23
24use crate::approval::ApprovalGate;
25use crate::config::EgressMode;
26use crate::config::{AgentsConfig, CompactionMode, LimitsConfig};
27use crate::guardrails::Guardrails;
28use crate::limits::LimitKind;
29use crate::memory::working::{
30    apply_summary, compacted_notice, compaction_cut, compaction_failed_notice, conversation_budget,
31    count_spec_tokens, count_tokens, fit, fits, python_strip, render_transcript, KEEP_RECENT,
32    SUMMARY_MAX_TOKENS, SUMMARY_SYSTEM_PROMPT,
33};
34use crate::observability::Recorder;
35use crate::prompt::time_note;
36use crate::provider::reasoning::REASONING_LOOP;
37use crate::provider::{Provider, ProviderError};
38use crate::pyjson::{python_float_repr, python_json_dumps};
39use crate::router::Router;
40use crate::session::AgentState;
41use crate::tools::{ToolContext, ToolRegistry};
42use crate::turn::TurnSummary;
43use crate::types::{
44    python_repr, AgentPhase, CompletionRequest, Message, Role, Step, ToolCall, ToolResult,
45    ToolSpec, Usage,
46};
47use crate::vault::StreamRedactor;
48use futures_util::StreamExt;
49use serde_json::{json, Value};
50use std::sync::atomic::{AtomicBool, Ordering};
51use std::sync::Arc;
52use std::time::{Duration, Instant};
53use thiserror::Error;
54
55/// What the harness says to a model that ran out of output tokens mid-answer.
56pub const CONTINUE_PROMPT: &str = "Continue exactly where you left off; do not repeat.";
57
58/// How many times one turn may ask for more after hitting the output cap.
59pub const MAX_CONTINUATIONS: u64 = 3;
60
61/// The user-visible line announcing continuation `index`.
62pub fn continuation_notice(index: u64) -> String {
63    format!("\n[continuation {index}/{MAX_CONTINUATIONS}]\n")
64}
65
66/// What the harness asks, once, of a model whose final reply was empty. Beyond Python.
67pub const ANSWER_PROMPT: &str =
68    "Your last reply was empty. Give the user your answer now, as plain text.";
69
70/// Said when an empty final reply is sent back for an answer.
71pub const EMPTY_ANSWER_NOTICE: &str = "\n[no answer; asking the model again]\n";
72
73/// Said when the model still gave no answer and its reasoning is shown instead.
74pub const THINKING_ANSWER_NOTICE: &str = "\n[no answer; showing the model's reasoning]\n";
75
76/// Said when the model still gave no answer and had no reasoning to show.
77pub const NO_ANSWER_NOTICE: &str = "\n[the model gave no answer]\n";
78
79/// Said when the provider stopped a reply whose reasoning kept repeating itself.
80/// Beyond Python.
81pub const REASONING_LOOP_NOTICE: &str =
82    "\n[the model's reasoning was repeating itself; stopped it]\n";
83
84/// What a cancelled turn says, as Python's `_cancelled`.
85pub const CANCELLED_NOTICE: &str = "\n[cancelled]\n";
86
87/// Asks the in-flight turn to stop at its next safe point, as Python's `Harness.cancel`.
88///
89/// Clones share one flag, so a signal handler or another task can hold one. Cancelling
90/// when no turn is running is harmless: every turn clears the flag on entry.
91#[derive(Clone, Default)]
92pub struct CancelToken {
93    inner: Arc<CancelInner>,
94}
95
96impl std::fmt::Debug for CancelToken {
97    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        formatter
99            .debug_struct("CancelToken")
100            .field("cancelled", &self.is_cancelled())
101            .finish()
102    }
103}
104
105#[derive(Default)]
106struct CancelInner {
107    flag: AtomicBool,
108    notify: tokio::sync::Notify,
109}
110
111impl CancelToken {
112    pub fn cancel(&self) {
113        self.inner.flag.store(true, Ordering::SeqCst);
114        self.inner.notify.notify_waiters();
115    }
116
117    pub fn is_cancelled(&self) -> bool {
118        self.inner.flag.load(Ordering::SeqCst)
119    }
120
121    pub fn clear(&self) {
122        self.inner.flag.store(false, Ordering::SeqCst);
123    }
124
125    /// Resolves once [`CancelToken::cancel`] has been called.
126    pub async fn cancelled(&self) {
127        loop {
128            let notified = self.inner.notify.notified();
129            tokio::pin!(notified);
130            // Registered before the flag is read, so a cancel in between is not missed.
131            notified.as_mut().enable();
132            if self.is_cancelled() {
133                return;
134            }
135            notified.await;
136        }
137    }
138}
139
140/// One thing a running turn reports. Each event carries the text that `run` and the
141/// plain REPL stream for it, so every surface sees the same output.
142#[derive(Debug, Clone, Copy)]
143pub enum TurnEvent<'a> {
144    /// The model's text (or the ingress guardrail's refusal, which stands in for it).
145    Text(&'a str),
146    /// A notice from the harness (`[cancelled]`, `[guardrail] ...`, a continuation or
147    /// compaction note): part of the output, but never part of the answer, so `run`
148    /// can keep it off stdout.
149    Notice(&'a str),
150    /// A piece of the model's reasoning, already redacted. Not part of the turn's
151    /// output: only the interface shows it.
152    Thinking(&'a str),
153    /// A tool call, announced before its batch runs; `text` is its `[tool] name(...)` line.
154    ToolCall { call: &'a ToolCall, text: &'a str },
155    /// A call's result, in call order. `observation` is what the model is shown, after
156    /// the observation guardrail; `text` is the `[tool] name -> summary` line.
157    ToolResult {
158        call: &'a ToolCall,
159        result: &'a ToolResult,
160        observation: &'a str,
161        text: &'a str,
162    },
163    /// Beyond Python: a model call finished. `step` is what it used; `session` is
164    /// the session's usage with it added (sub-agents' spend joins when their batch
165    /// ends). Adds nothing to the turn's output.
166    Usage {
167        step: &'a crate::types::Usage,
168        session: &'a crate::types::Usage,
169    },
170    /// The history was compacted: `notice` is what the other surfaces stream (a
171    /// notice, as before), and `summary` the summary written, `None` when it could
172    /// not be and the history was trimmed instead (beyond Python: an editor shows it
173    /// as ACP's `compaction_update`).
174    Compacted {
175        notice: &'a str,
176        summary: Option<&'a str>,
177    },
178}
179
180impl<'a> TurnEvent<'a> {
181    /// The text this event adds to the turn's output.
182    pub fn text(&self) -> &'a str {
183        match *self {
184            Self::Text(text)
185            | Self::Notice(text)
186            | Self::ToolCall { text, .. }
187            | Self::ToolResult { text, .. }
188            | Self::Compacted { notice: text, .. } => text,
189            Self::Thinking(_) | Self::Usage { .. } => "",
190        }
191    }
192}
193
194/// A turn could not be completed.
195#[derive(Debug, Clone, PartialEq, Error)]
196pub enum HarnessError {
197    #[error(transparent)]
198    Provider(#[from] ProviderError),
199
200    #[error("Circuit tripped: {0}")]
201    CircuitTripped(String),
202
203    #[error(
204        "The '{provider}' provider ended its stream for model {} without a final completion. \
205         The response was truncated; retry, or check the endpoint's streaming implementation.",
206        python_repr(model)
207    )]
208    NoFinalCompletion { provider: String, model: String },
209}
210
211impl HarnessError {
212    /// The name of the exception Python raises for this failure, which its
213    /// full-screen interface shows (`error: ProviderError: ...`).
214    pub fn python_type(&self) -> &'static str {
215        match self {
216            Self::Provider(_) => "ProviderError",
217            Self::CircuitTripped(_) | Self::NoFinalCompletion { .. } => "HarnessError",
218        }
219    }
220}
221
222/// Bounds one turn: steps, cumulative cost, wall-clock time, and the tool-error streak.
223pub struct CircuitBreaker {
224    limits: LimitsConfig,
225    steps: u32,
226    cost_usd: f64,
227    consecutive_errors: u32,
228    started: Instant,
229}
230
231impl CircuitBreaker {
232    pub fn new(limits: &LimitsConfig) -> Self {
233        Self {
234            limits: limits.clone(),
235            steps: 0,
236            cost_usd: 0.0,
237            consecutive_errors: 0,
238            started: Instant::now(),
239        }
240    }
241
242    pub fn steps(&self) -> u32 {
243        self.steps
244    }
245
246    /// The step budget.
247    pub fn max_steps(&self) -> u32 {
248        self.limits.max_steps
249    }
250
251    /// Raise (or lower) the step budget mid-run, when the user raises it.
252    pub fn set_max_steps(&mut self, max_steps: u32) {
253        self.limits.max_steps = max_steps;
254    }
255
256    /// The step budget is spent, so the next [`CircuitBreaker::before_step`] trips.
257    pub fn out_of_steps(&self) -> bool {
258        self.steps >= self.limits.max_steps
259    }
260
261    /// Fail if starting another model call would breach a bound.
262    pub fn before_step(&self) -> Result<(), HarnessError> {
263        let limits = &self.limits;
264        if self.steps >= limits.max_steps {
265            return Err(trip(format!(
266                "step budget reached ({} steps)",
267                limits.max_steps
268            )));
269        }
270        if limits.max_cost_usd > 0.0 && self.cost_usd >= limits.max_cost_usd {
271            return Err(trip(format!(
272                "cost cap reached (${:.4} >= ${})",
273                self.cost_usd,
274                python_float_repr(limits.max_cost_usd)
275            )));
276        }
277        let wall_clock = Duration::from_secs(limits.max_wall_clock_s);
278        if limits.max_wall_clock_s > 0 && self.started.elapsed() >= wall_clock {
279            return Err(trip(format!(
280                "wall-clock limit reached ({}s)",
281                limits.max_wall_clock_s
282            )));
283        }
284        Ok(())
285    }
286
287    pub fn record_step(&mut self, usage: &Usage) {
288        self.steps += 1;
289        self.cost_usd += usage.cost_usd;
290    }
291
292    /// Count spending that is not a step, such as a compaction summary.
293    /// What the turn has spent so far.
294    pub fn cost(&self) -> f64 {
295        self.cost_usd
296    }
297
298    pub fn record_cost(&mut self, cost_usd: f64) {
299        self.cost_usd += cost_usd;
300    }
301
302    pub fn record_tool_result(&mut self, ok: bool) -> Result<(), HarnessError> {
303        if ok {
304            self.consecutive_errors = 0;
305            return Ok(());
306        }
307        self.consecutive_errors += 1;
308        if self.consecutive_errors > self.limits.max_consecutive_errors {
309            return Err(trip(format!(
310                "aborted after {} consecutive tool errors",
311                self.consecutive_errors
312            )));
313        }
314        Ok(())
315    }
316}
317
318fn trip(reason: String) -> HarnessError {
319    HarnessError::CircuitTripped(reason)
320}
321
322/// Everything one turn needs.
323pub struct Harness {
324    /// The session's model; the REPL's `/model` replaces it between turns. With
325    /// triage routing on, each turn may use another (see [`Harness::active_provider`]).
326    pub provider: Arc<dyn Provider>,
327    /// Triage routing (`crate::router`); [`Router::default`] never routes.
328    pub router: Router,
329    /// OpenTelemetry spans (`crate::otel`); [`crate::otel::Tracer::default`] records none.
330    pub tracer: crate::otel::Tracer,
331    pub registry: ToolRegistry,
332    pub context: ToolContext,
333    pub limits: LimitsConfig,
334    /// `[agents]`: whether `delegate` runs sub-agents, how deep, and how long.
335    pub agents: AgentsConfig,
336    pub system: Message,
337    /// The configured output cap, as Python's `max_output_tokens_for`; a session
338    /// override may replace it (see [`Harness::output_cap`]).
339    pub max_tokens: u32,
340    /// Limits overridden for the session, and the hook that offers to raise one
341    /// when a turn reaches it (`crate::limits`).
342    pub session_limits: crate::limits::SessionLimits,
343    /// Tokens of context the model can hold (`context_window_for`); the REPL's
344    /// `/model` updates it with the provider.
345    pub context_window: u64,
346    /// Decides whether side-effecting calls may run.
347    pub gate: ApprovalGate,
348    /// Ingress, egress, and observation scanning.
349    pub guardrails: Guardrails,
350    /// The flight recorder; [`Recorder::disabled`] writes nothing.
351    pub recorder: Recorder,
352    /// Live MCP servers; their section of the system message is rebuilt for every
353    /// request, because servers drop, reconnect, and change their tools mid-turn.
354    pub mcp: Option<std::sync::Arc<crate::mcp::McpManager>>,
355    /// Long-term memory: past episodes are recalled into each turn's system
356    /// message and every finished turn is recorded; `None` runs statelessly.
357    pub memory: Option<crate::session::SessionStore>,
358    /// Stops the running turn at its next safe point.
359    pub cancel: CancelToken,
360    /// Specialist sub-agents' state (beyond Python): notices for the user and the
361    /// approvals of project specialties (`crate::subagent`).
362    pub subagents: crate::subagent::SubagentState,
363}
364
365impl Harness {
366    /// The system message for the next request: the prompt plus, when MCP servers
367    /// are live, their section, then the turn's recall note, as Python's
368    /// `_system_content`. Beyond Python, the names of the secrets the user entered
369    /// come before the recall note, when there are any.
370    pub(crate) fn system_message(&self, extra: Option<&str>) -> Message {
371        let offered = self.delegation_offered(&self.context, 0);
372        // Beyond Python: under `run --agent`, the specialty's filtered prompt.
373        if let Some((persona, preloaded)) = self.subagents.main() {
374            return self.filtered_system(&persona, &self.context, &preloaded, offered, extra);
375        }
376        self.system_for(&self.context, offered, extra)
377    }
378
379    /// [`Harness::system_message`] for `ctx`, an unrestricted context (the main
380    /// loop's, or a plain sub-agent's fork of it). Beyond Python, when `delegate`
381    /// is offered, the specialist sub-agents are listed after the MCP section.
382    pub(crate) fn system_for(
383        &self,
384        ctx: &ToolContext,
385        delegation_offered: bool,
386        extra: Option<&str>,
387    ) -> Message {
388        let mut system = self.system.clone();
389        if let Some(section) = self
390            .mcp
391            .as_ref()
392            .map(|mcp| mcp.prompt_section())
393            .filter(|section| !section.is_empty())
394        {
395            system.content = format!("{}\n\n{section}", system.content);
396        }
397        if delegation_offered {
398            if let Some(section) = self.specialty_listing(ctx) {
399                system.content = format!("{}\n\n{section}", system.content);
400            }
401        }
402        if let Some(section) = ctx.secrets.prompt_section() {
403            system.content = format!("{}\n\n{section}", system.content);
404        }
405        if let Some(extra) = extra.filter(|extra| !extra.is_empty()) {
406            system.content = format!("{}\n\n{extra}", system.content);
407        }
408        system
409    }
410
411    /// Conversation tokens available for this request, as Python's
412    /// `_context_budget`: the window minus what the request spends before any
413    /// history (the system message and the tool catalogue, both of which change at
414    /// runtime), minus the room the response needs.
415    pub(crate) fn context_budget(&self, system: &Message, specs: &[ToolSpec]) -> u64 {
416        self.context_budget_with(
417            system,
418            specs,
419            self.active_context_window(),
420            self.output_cap(),
421        )
422    }
423
424    /// [`Harness::context_budget`] for a model with this window and output cap (a
425    /// specialist sub-agent on a model of its own).
426    pub(crate) fn context_budget_with(
427        &self,
428        system: &Message,
429        specs: &[ToolSpec],
430        window: u64,
431        output_cap: u32,
432    ) -> u64 {
433        let overhead = count_tokens(std::slice::from_ref(system)) + count_spec_tokens(specs);
434        conversation_budget(
435            window,
436            overhead,
437            self.limits.context_reserve_tokens,
438            u64::from(output_cap),
439            self.limits.max_context_tokens,
440        )
441    }
442
443    /// Replace the oldest over-budget span with a summary, in place, before a model
444    /// call, as Python's `_compact_if_needed`. Dropping the oldest turns (still
445    /// available as `compaction = "drop"`) makes a long session forget its own
446    /// goal; a summary keeps the goal, the decisions, and the paths found.
447    ///
448    /// Never fails the turn: a summary that cannot be written falls back to the drop
449    /// that fitting the request does anyway, and says so. Returns the notice to
450    /// stream, how many messages the history lost, so indices into it can follow,
451    /// and the summary when one was written.
452    async fn compact_if_needed(
453        &self,
454        state: &mut AgentState,
455        extra_system: Option<&str>,
456        summary: &mut TurnSummary,
457        breaker: &mut CircuitBreaker,
458        protect_from: usize,
459    ) -> Option<(String, usize, Option<String>)> {
460        if self.limits.compaction != CompactionMode::Summarize {
461            return None;
462        }
463        let system = self.system_message(extra_system);
464        let budget = self.context_budget(&system, &self.registry.specs());
465        if fits(&state.messages, budget) {
466            return None;
467        }
468        let cut = compaction_cut(&state.messages, budget, KEEP_RECENT, Some(protect_from));
469        if cut == 0 {
470            // Everything left is the current turn or its tool blocks: nothing is old
471            // enough to compact, so fitting trims and the provider's limits take over.
472            return None;
473        }
474        let sid = state.session_id.clone();
475        let prefix = &state.messages[..cut];
476        let dropped_tokens = count_tokens(prefix);
477        let summarizer = self.summary_provider();
478        let request = CompletionRequest {
479            model: summarizer.model().to_owned(),
480            messages: vec![
481                message(Role::System, SUMMARY_SYSTEM_PROMPT),
482                message(Role::User, &render_transcript(prefix)),
483            ],
484            tools: Vec::new(),
485            temperature: 0.0,
486            // A summary is a bounded artefact; it should not cost more than the span.
487            max_tokens: Some(SUMMARY_MAX_TOKENS * 2),
488            stream: false,
489        };
490        let completion = tokio::select! {
491            biased;
492            // The next safe point sees the cancel and closes the turn out.
493            () = self.cancel.cancelled() => return None,
494            completion = summarizer.complete(request) => completion,
495        };
496        let failed = |status: &str, error: Option<String>| {
497            let mut fields = vec![
498                ("status", json!(status)),
499                ("fallback", json!("drop")),
500                ("dropped", json!(cut)),
501            ];
502            if let Some(error) = error {
503                fields.push(("error", json!(error)));
504            }
505            self.recorder.event(&sid, "compaction", fields);
506            Some((compaction_failed_notice(cut), 0, None))
507        };
508        let completion = match completion {
509            Ok(completion) => completion,
510            Err(error) => return failed("failed", Some(format!("ProviderError: {error}"))),
511        };
512        let text = python_strip(&completion.text).to_owned();
513        if text.is_empty() {
514            return failed("empty", None);
515        }
516
517        // The originals are archived before they leave the live conversation.
518        if let Some(memory) = &self.memory {
519            let _ = memory.record_compaction(&sid, &text, prefix);
520        }
521        let before = state.messages.len();
522        let kept = state.messages.split_off(cut);
523        state.messages = apply_summary(&text, kept);
524        summary.compactions += 1;
525        summary.add_usage(&completion.usage);
526        breaker.record_cost(completion.usage.cost_usd);
527        self.recorder.event(
528            &sid,
529            "compaction",
530            vec![
531                ("status", json!("ok")),
532                ("dropped", json!(cut)),
533                ("dropped_tokens", json!(dropped_tokens)),
534                (
535                    "summary_tokens",
536                    json!(count_tokens(&[message(Role::User, &text)])),
537                ),
538                ("kept", json!(state.messages.len())),
539                ("model", json!(summarizer.model())),
540            ],
541        );
542        // Saved at once: a resume must see the compacted history, not a stale copy
543        // that would re-inflate the context on the next turn.
544        if let Some(memory) = &self.memory {
545            let _ = memory.persist(state);
546        }
547        Some((
548            compacted_notice(cut),
549            before - state.messages.len(),
550            Some(text),
551        ))
552    }
553
554    /// Run one user turn on `state`, passing every piece of streamed text,
555    /// including tool notices, to `on_text`, and return everything streamed.
556    ///
557    /// The turn's messages and steps are appended to `state`, its usage added,
558    /// and its summary left on `state.last_turn`. A failed turn still leaves
559    /// `state` in the `error` phase with its summary, so it can be persisted.
560    pub async fn run_turn(
561        &self,
562        state: &mut AgentState,
563        goal: &str,
564        on_text: impl FnMut(&str),
565    ) -> Result<String, HarnessError> {
566        self.run_turn_as(state, goal, goal, on_text).await
567    }
568
569    /// [`Harness::run_turn`] where the model sees `user_text` (for a prompt with
570    /// `@file` mentions, the expanded text) and the trace records `display_text`,
571    /// what the user typed, as Python's `display_text` argument.
572    pub async fn run_turn_as(
573        &self,
574        state: &mut AgentState,
575        user_text: &str,
576        display_text: &str,
577        mut on_text: impl FnMut(&str),
578    ) -> Result<String, HarnessError> {
579        self.run_turn_events(state, user_text, display_text, |event| {
580            on_text(event.text())
581        })
582        .await
583    }
584
585    /// [`Harness::run_turn_as`] reporting [`TurnEvent`]s, so an interface can show
586    /// tool calls without parsing the `[tool] ...` lines. Every event carries the text
587    /// the other entry points stream, in the same order.
588    pub async fn run_turn_events(
589        &self,
590        state: &mut AgentState,
591        user_text: &str,
592        display_text: &str,
593        on_event: impl FnMut(TurnEvent<'_>),
594    ) -> Result<String, HarnessError> {
595        self.run_turn_with(state, user_text, display_text, None, on_event)
596            .await
597    }
598
599    /// A turn with `skill` chosen by the user (`/<name> [task]`, `/skill <name>`,
600    /// `run --skill`), beyond Python: the model gets the skill's instructions ahead
601    /// of `task` in the user's message ([`crate::skills::skill_request`]), and the
602    /// skill is active from the first step, so its `allowed-tools` apply at once.
603    /// Everything else is [`Harness::run_turn_events`]; `display_text` is what the
604    /// user typed, for the trace.
605    pub async fn run_skill_turn(
606        &self,
607        state: &mut AgentState,
608        skill: &Arc<crate::skills::Skill>,
609        task: &str,
610        display_text: &str,
611        on_event: impl FnMut(TurnEvent<'_>),
612    ) -> Result<String, HarnessError> {
613        let user_text = crate::skills::skill_request(skill, task);
614        self.run_turn_with(state, &user_text, display_text, Some(skill), on_event)
615            .await
616    }
617
618    async fn run_turn_with(
619        &self,
620        state: &mut AgentState,
621        user_text: &str,
622        display_text: &str,
623        skill: Option<&Arc<crate::skills::Skill>>,
624        on_event: impl FnMut(TurnEvent<'_>),
625    ) -> Result<String, HarnessError> {
626        // A cancel requested while no turn was running must not kill this one.
627        self.cancel.clear();
628        // A skill activated with `use_skill` restricts tools for its turn only: the
629        // restriction is lifted on entry and on every exit, so it can never keep
630        // refusing tools for the rest of the session. A skill the user ran is then
631        // made active for this turn alone.
632        self.context.clear_skill();
633        if let Some(skill) = skill {
634            self.context.activate_skill(skill);
635        }
636        let started = Instant::now();
637        // One `turn` span per user turn, parent of its model and tool spans.
638        let mut span = self.tracer.start(
639            "turn",
640            vec![
641                ("session.id", json!(state.session_id)),
642                (
643                    "gen_ai.request.model",
644                    json!(self.active_provider().model()),
645                ),
646            ],
647        );
648        let mut summary = TurnSummary::default();
649        // A secret the user pasted anyway (or an `@file` that holds one) goes no
650        // further than this: not to the model, the history, nor the trace.
651        let secrets = &self.context.secrets;
652        let (user_text, display_text) = (secrets.redact(user_text), secrets.redact(display_text));
653        let result = self
654            .turn(state, &user_text, &display_text, &mut summary, on_event)
655            .await;
656        self.context.clear_skill();
657        summary.duration_s = (started.elapsed().as_secs_f64() * 1000.0).round() / 1000.0;
658        state.last_turn = Some(summary);
659        if let Err(error) = &result {
660            state.phase = AgentPhase::Error;
661            let reason = match error {
662                HarnessError::CircuitTripped(detail) => format!("circuit tripped: {detail}"),
663                HarnessError::Provider(detail) => {
664                    format!("provider stream failed: ProviderError: {detail}")
665                }
666                HarnessError::NoFinalCompletion { .. } => {
667                    "provider stream ended without a final completion".to_owned()
668                }
669            };
670            self.recorder.event(
671                &state.session_id,
672                "turn_end",
673                vec![("status", json!("error")), ("reason", json!(reason))],
674            );
675        }
676        // Closed with what the turn spent, on every exit, so a backend sees the cost
677        // of an aborted turn too.
678        span.set(turn_attributes(state, self.active_provider().model()));
679        if let Err(error) = &result {
680            span.fail(error.python_type(), &error.to_string());
681        }
682        self.tracer.end(span);
683        result
684    }
685
686    async fn turn(
687        &self,
688        state: &mut AgentState,
689        goal: &str,
690        display_text: &str,
691        summary: &mut TurnSummary,
692        mut on_event: impl FnMut(TurnEvent<'_>),
693    ) -> Result<String, HarnessError> {
694        let mut output = String::new();
695        let mut emit = |event: TurnEvent<'_>| {
696            output.push_str(event.text());
697            on_event(event);
698        };
699
700        let sid = state.session_id.clone();
701        self.recorder
702            .event(&sid, "turn_start", vec![("task", json!(display_text))]);
703
704        // Ingress guardrail on the user's input.
705        let report = self.guardrails.inspect_ingress(goal);
706        if report.flagged() {
707            self.recorder.event(
708                &sid,
709                "guardrail",
710                vec![
711                    ("stage", json!("ingress_input")),
712                    ("findings", json!(report.summary())),
713                ],
714            );
715            if self.guardrails.should_block(&report) {
716                let refusal = format!(
717                    "Refused: input tripped the ingress guardrail ({}).",
718                    report.summary()
719                );
720                state.messages.push(message(Role::User, goal));
721                state.messages.push(message(Role::Assistant, &refusal));
722                state.phase = AgentPhase::Error;
723                self.recorder
724                    .event(&sid, "turn_end", vec![("status", json!("blocked"))]);
725                emit(TurnEvent::Text(&refusal));
726                return Ok(output);
727            }
728            emit(TurnEvent::Notice(&format!(
729                "[guardrail] input flagged: {}\n",
730                report.summary()
731            )));
732        }
733
734        // Redact mode cannot stream: text inspected only after it was shown has
735        // already leaked. Each step's text is held back and replayed redacted.
736        let buffering = self.guardrails.egress == EgressMode::Redact;
737
738        // Pick this turn's model (triage routing), after the input was let through.
739        self.route(goal, &sid)?;
740        let provider = self.active_provider();
741
742        // What happened last time a task like this came up.
743        let recall_note = self
744            .memory
745            .as_ref()
746            .and_then(|memory| memory.recall_note(goal));
747        // Beyond Python: the time the turn started, then what was recalled.
748        let time = time_note(&jiff::ZonedDateTime::now());
749        let recall_note = Some(match recall_note {
750            Some(recalled) => format!("{time}\n\n{recalled}"),
751            None => time,
752        });
753        // Where this turn begins: compaction never reaches past it, so the ask being
754        // answered right now is never summarized away.
755        let mut turn_start = state.messages.len();
756        state.messages.push(message(Role::User, goal));
757        let mut limits = self.limits.clone();
758        limits.max_steps = self.max_steps();
759        let mut breaker = CircuitBreaker::new(&limits);
760        // Where the first partial answer went, and the pieces collected so far.
761        let mut continuation_start: Option<usize> = None;
762        let mut continuation_parts: Vec<String> = Vec::new();
763        // Beyond Python: an empty final reply is asked about once (`ask_again` puts
764        // ANSWER_PROMPT on the next request only, never in the history), and the
765        // reasoning it came with is kept in case the second try is empty too.
766        let mut nudged = false;
767        let mut ask_again = false;
768        let mut unanswered_thinking = String::new();
769
770        loop {
771            // Never start another model call once cancelled: that is the expensive,
772            // long-latency step the user is trying to escape.
773            if self.cancel.is_cancelled() {
774                self.cancelled(state, breaker.steps(), &mut emit);
775                return Ok(output);
776            }
777            // Beyond Python: the interface may offer to raise a spent budget.
778            if breaker.out_of_steps() {
779                match self.raise_limit(LimitKind::Steps, None, &sid, breaker.max_steps(), false) {
780                    Some(raised) => breaker.set_max_steps(raised),
781                    // Ctrl+C at the offer stops it and cancels the turn.
782                    None if self.cancel.is_cancelled() => {
783                        self.cancelled(state, breaker.steps(), &mut emit);
784                        return Ok(output);
785                    }
786                    None => {}
787                }
788            }
789            breaker.before_step()?;
790
791            // Compact before the request is built, so the model call sees the
792            // compacted history. Once per step, never nested.
793            if let Some((notice, removed, compacted)) = self
794                .compact_if_needed(
795                    state,
796                    recall_note.as_deref(),
797                    summary,
798                    &mut breaker,
799                    turn_start,
800                )
801                .await
802            {
803                // Indices into the history move with it. (Python keeps the old
804                // ones, which go stale after a compaction mid-turn.)
805                turn_start -= removed;
806                if let Some(start) = continuation_start.as_mut() {
807                    *start -= removed;
808                }
809                // Said out loud: a conversation that quietly lost its oldest turns
810                // looks, from the user's seat, like a model that forgot.
811                emit(TurnEvent::Compacted {
812                    notice: &notice,
813                    summary: compacted.as_deref(),
814                });
815            }
816
817            let mut completion = {
818                let system = self.system_message(recall_note.as_deref());
819                let mut tools = self.registry.specs();
820                // Under `run --agent`, only what the specialty may call is offered.
821                tools.retain(|spec| self.context.scope_allows(&spec.name));
822                let budget = self.context_budget(&system, &tools);
823                let conversation = fit(&state.messages, budget);
824                let mut request_messages = Vec::with_capacity(conversation.len() + 1);
825                request_messages.push(system);
826                request_messages.extend(conversation.iter().cloned());
827                if std::mem::take(&mut ask_again) {
828                    request_messages.push(message(Role::User, ANSWER_PROMPT));
829                }
830                let request = CompletionRequest {
831                    model: provider.model().to_owned(),
832                    messages: request_messages,
833                    tools,
834                    temperature: 0.0,
835                    max_tokens: Some(self.output_cap()),
836                    stream: true,
837                };
838                // GenAI semantic conventions where a name exists, `agent86.*` otherwise.
839                let mut span = self.tracer.start(
840                    "model_call",
841                    vec![
842                        ("gen_ai.system", json!(provider.name())),
843                        ("gen_ai.request.model", json!(provider.model())),
844                        ("agent86.step", json!(breaker.steps() + 1)),
845                    ],
846                );
847                let mut stream = provider.stream(request);
848                let mut completion = None;
849                let mut buffered = String::new();
850                // The model never saw a secret's value, but should it produce one
851                // anyway, it is not shown.
852                let mut redactor = StreamRedactor::default();
853                let mut thinking_redactor = StreamRedactor::default();
854                loop {
855                    // A long or stalled response stops mid-flight, not after it ends.
856                    // Dropping the stream drops the HTTP response.
857                    let next = tokio::select! {
858                        biased;
859                        () = self.cancel.cancelled() => None,
860                        delta = stream.next() => Some(delta),
861                    };
862                    let Some(Some(delta)) = next else { break };
863                    let delta = match delta {
864                        Ok(delta) => delta,
865                        Err(error) => {
866                            span.set(model_call_attributes(None));
867                            span.fail("ProviderError", &error.to_string());
868                            self.tracer.end(span);
869                            return Err(error.into());
870                        }
871                    };
872                    // Reasoning is shown only as it streams. Redact mode holds text
873                    // back until the guardrail has seen it, so it shows none.
874                    if !delta.thinking.is_empty() && !buffering {
875                        let shown = thinking_redactor.push(&self.context.secrets, &delta.thinking);
876                        if !shown.is_empty() {
877                            emit(TurnEvent::Thinking(&shown));
878                        }
879                    }
880                    if !delta.text.is_empty() {
881                        if buffering {
882                            buffered.push_str(&delta.text);
883                        } else {
884                            let shown = redactor.push(&self.context.secrets, &delta.text);
885                            if !shown.is_empty() {
886                                emit(TurnEvent::Text(&shown));
887                            }
888                        }
889                    }
890                    if delta.done && delta.completion.is_some() {
891                        completion = delta.completion;
892                    }
893                }
894                drop(stream);
895                let held = thinking_redactor.finish(&self.context.secrets);
896                if !held.is_empty() {
897                    emit(TurnEvent::Thinking(&held));
898                }
899                let held = redactor.finish(&self.context.secrets);
900                if !held.is_empty() {
901                    emit(TurnEvent::Text(&held));
902                }
903                span.set(model_call_attributes(completion.as_ref()));
904                self.tracer.end(span);
905                if self.cancel.is_cancelled() {
906                    // Whatever was held back still belongs to the user: redacted, then shown.
907                    let partial = self
908                        .guardrails
909                        .inspect_egress(&self.context.secrets.redact(&buffered))
910                        .1;
911                    if !partial.is_empty() {
912                        emit(TurnEvent::Text(&partial));
913                    }
914                    self.cancelled(state, breaker.steps(), &mut emit);
915                    return Ok(output);
916                }
917                completion.ok_or_else(|| HarnessError::NoFinalCompletion {
918                    provider: provider.name().to_owned(),
919                    model: provider.model().to_owned(),
920                })?
921            };
922
923            breaker.record_step(&completion.usage);
924            summary.steps = u64::from(breaker.steps());
925            summary.add_usage(&completion.usage);
926            // Beyond Python: what this call used, and the session so far, for a
927            // surface that shows it as it goes (an editor's `usage_update`).
928            emit(TurnEvent::Usage {
929                step: &completion.usage,
930                session: &(state.usage + completion.usage),
931            });
932            let names: Vec<&str> = completion
933                .tool_calls
934                .iter()
935                .map(|call| call.name.as_str())
936                .collect();
937            self.recorder.event(
938                &sid,
939                "model_call",
940                vec![
941                    ("step", json!(breaker.steps())),
942                    ("model", json!(provider.model())),
943                    ("input_tokens", json!(completion.usage.input_tokens)),
944                    ("output_tokens", json!(completion.usage.output_tokens)),
945                    ("cost_usd", json!(completion.usage.cost_usd)),
946                    ("stop_reason", json!(completion.stop_reason)),
947                    ("tool_calls", json!(names)),
948                ],
949            );
950
951            if completion.stop_reason.as_deref() == Some(REASONING_LOOP) {
952                emit(TurnEvent::Notice(REASONING_LOOP_NOTICE));
953            }
954            // Beyond Python: the provider ended the reply itself (Gemini's SAFETY,
955            // RECITATION, ...). Said once, and not asked about again.
956            let stopped = completion
957                .stop_reason
958                .as_deref()
959                .and_then(|reason| reason.strip_prefix(crate::provider::google::STOPPED_PREFIX))
960                .map(str::to_owned);
961            if let Some(reason) = &stopped {
962                emit(TurnEvent::Notice(&format!(
963                    "\n[{} stopped the reply: {reason}]\n",
964                    provider.name()
965                )));
966            }
967
968            // Beyond Python: a reply that ends cleanly with nothing to say (a thinking
969            // model can put its whole answer in its reasoning) is asked about once.
970            // The empty step stays out of the history. If the second reply is empty
971            // too, the reasoning stands in for the answer. A reply cut off at the cap
972            // is the continuation path's, and a model out of steps is not asked again.
973            let mut from_thinking = false;
974            if completion.tool_calls.is_empty()
975                && completion.stop_reason.as_deref() != Some("max_tokens")
976                && stopped.is_none()
977                && completion.text.trim().is_empty()
978                && continuation_start.is_none()
979            {
980                if !completion.thinking.trim().is_empty() {
981                    unanswered_thinking = std::mem::take(&mut completion.thinking);
982                }
983                if !nudged && !breaker.out_of_steps() {
984                    nudged = true;
985                    ask_again = true;
986                    self.recorder.event(
987                        &sid,
988                        "empty_answer",
989                        vec![
990                            ("step", json!(breaker.steps())),
991                            ("model", json!(provider.model())),
992                            ("thinking_chars", json!(unanswered_thinking.chars().count())),
993                        ],
994                    );
995                    record_step(
996                        state,
997                        Step {
998                            index: state.steps.len() as u64 + 1,
999                            phase: AgentPhase::Execute,
1000                            thought: String::new(),
1001                            tool_calls: Vec::new(),
1002                            results: Vec::new(),
1003                            usage: completion.usage,
1004                        },
1005                    );
1006                    self.checkpoint(state);
1007                    emit(TurnEvent::Notice(EMPTY_ANSWER_NOTICE));
1008                    continue;
1009                }
1010                if unanswered_thinking.trim().is_empty() {
1011                    emit(TurnEvent::Notice(NO_ANSWER_NOTICE));
1012                    // Beyond Python: LM Studio has been seen to answer a request that
1013                    // overflows the loaded context with nothing at all.
1014                    if provider.name() == crate::provider::ServerKind::LmStudio.name() {
1015                        emit(TurnEvent::Notice(&format!(
1016                            "{}\n",
1017                            crate::provider::hints::LMSTUDIO_EMPTY_ANSWER
1018                        )));
1019                    }
1020                } else {
1021                    completion.text = std::mem::take(&mut unanswered_thinking);
1022                    from_thinking = true;
1023                    emit(TurnEvent::Notice(THINKING_ANSWER_NOTICE));
1024                }
1025            }
1026
1027            // Egress guardrail on the model's text. In redact mode the redacted copy
1028            // is what everything downstream sees: the output, the history, and the step.
1029            let answer = self.context.secrets.redact(&completion.text);
1030            let (egress, redacted) = self.guardrails.inspect_egress(&answer);
1031            let text = if buffering {
1032                if !redacted.is_empty() {
1033                    emit(TurnEvent::Text(&redacted));
1034                }
1035                redacted
1036            } else {
1037                // Reasoning standing in for the answer was never streamed as text.
1038                if from_thinking {
1039                    emit(TurnEvent::Text(&answer));
1040                }
1041                answer
1042            };
1043            if egress.flagged() {
1044                self.recorder.event(
1045                    &sid,
1046                    "guardrail",
1047                    vec![
1048                        ("stage", json!("egress")),
1049                        ("findings", json!(egress.summary())),
1050                    ],
1051                );
1052                emit(TurnEvent::Notice(&format!(
1053                    "\n[guardrail] output flagged: {}\n",
1054                    egress.summary()
1055                )));
1056            }
1057            let tool_calls = completion.tool_calls;
1058            self.scan_tool_arguments(&tool_calls, &sid);
1059            let cut_off = completion.stop_reason.as_deref() == Some("max_tokens");
1060            // Beyond Python: a reply that reached the cap before writing anything (a
1061            // thinking model can spend all of it reasoning) has nothing to continue
1062            // from. The interface may offer a larger cap and ask again; the empty
1063            // reply is kept out of the history.
1064            if cut_off
1065                && tool_calls.is_empty()
1066                && text.trim().is_empty()
1067                && continuation_start.is_none()
1068            {
1069                let cap = self.output_cap();
1070                if self
1071                    .raise_limit(LimitKind::Output, None, &sid, cap, false)
1072                    .is_some()
1073                {
1074                    record_step(
1075                        state,
1076                        Step {
1077                            index: state.steps.len() as u64 + 1,
1078                            phase: AgentPhase::Execute,
1079                            thought: String::new(),
1080                            tool_calls: Vec::new(),
1081                            results: Vec::new(),
1082                            usage: completion.usage,
1083                        },
1084                    );
1085                    self.checkpoint(state);
1086                    continue;
1087                }
1088            }
1089            let mut step = Step {
1090                index: state.steps.len() as u64 + 1,
1091                phase: AgentPhase::Execute,
1092                thought: text.clone(),
1093                tool_calls: tool_calls.clone(),
1094                results: Vec::new(),
1095                usage: completion.usage,
1096            };
1097            state.messages.push(Message {
1098                tool_calls: tool_calls.clone(),
1099                ..message(Role::Assistant, &text)
1100            });
1101
1102            if tool_calls.is_empty() {
1103                if cut_off && summary.continuations < MAX_CONTINUATIONS {
1104                    summary.continuations += 1;
1105                    continuation_start.get_or_insert(state.messages.len() - 1);
1106                    continuation_parts.push(text);
1107                    state.messages.push(message(Role::User, CONTINUE_PROMPT));
1108                    record_step(state, step);
1109                    self.checkpoint(state);
1110                    self.recorder.event(
1111                        &sid,
1112                        "continuation",
1113                        vec![
1114                            ("index", json!(summary.continuations)),
1115                            ("step", json!(breaker.steps())),
1116                            ("model", json!(provider.model())),
1117                            (
1118                                "chars",
1119                                json!(continuation_parts
1120                                    .last()
1121                                    .map_or(0, |part| part.chars().count())),
1122                            ),
1123                        ],
1124                    );
1125                    emit(TurnEvent::Notice(&continuation_notice(
1126                        summary.continuations,
1127                    )));
1128                    continue;
1129                }
1130                if let Some(start) = continuation_start {
1131                    // Collapse [partial, "continue", partial, ...] into one answer.
1132                    continuation_parts.push(text);
1133                    let joined = continuation_parts.concat();
1134                    state.messages.truncate(start);
1135                    state.messages.push(message(Role::Assistant, &joined));
1136                    step.thought = joined;
1137                }
1138                let outcome = step.thought.clone();
1139                record_step(state, step);
1140                state.phase = AgentPhase::Done;
1141                self.recorder.event(
1142                    &sid,
1143                    "turn_end",
1144                    vec![
1145                        ("status", json!("done")),
1146                        ("steps", json!(breaker.steps())),
1147                        ("continuations", json!(summary.continuations)),
1148                    ],
1149                );
1150                if let Some(memory) = &self.memory {
1151                    // A failed write loses one episode, never the turn.
1152                    let _ = memory.add_episode(&sid, goal, &outcome, &Default::default());
1153                }
1154                return Ok(output);
1155            }
1156
1157            // A step that wants tools ends any continuation in progress.
1158            continuation_start = None;
1159            continuation_parts.clear();
1160
1161            // Before the batch, never mid-execution. Python leaves these calls
1162            // unanswered, which providers reject on the next request; each is
1163            // answered here as not executed, as a cancel mid-batch does.
1164            if self.cancel.is_cancelled() {
1165                for call in &tool_calls {
1166                    let result = not_executed(call, "cancelled");
1167                    state.messages.push(Message {
1168                        tool_call_id: Some(call.id.clone()),
1169                        name: Some(call.name.clone()),
1170                        ..message(Role::Tool, &observation(&result))
1171                    });
1172                    step.results.push(result);
1173                }
1174                record_step(state, step);
1175                self.cancelled(state, breaker.steps(), &mut emit);
1176                return Ok(output);
1177            }
1178
1179            // The whole batch is announced up front, then observed strictly in call order.
1180            for call in &tool_calls {
1181                let text = format!(
1182                    "\n[tool] {}({})\n",
1183                    call.name,
1184                    preview_arguments(&call.arguments)
1185                );
1186                emit(TurnEvent::ToolCall { call, text: &text });
1187            }
1188            let results = self.execute_batch(&tool_calls, &sid, breaker.cost()).await;
1189            // Beyond Python: what a sub-agent had to tell the user (a specialty's
1190            // model that could not be built), as notices, so `run`'s stdout keeps
1191            // only the answer.
1192            for notice in self.take_notices() {
1193                emit(TurnEvent::Notice(&format!("{notice}\n")));
1194            }
1195            for (call, (result, delegated)) in tool_calls.iter().zip(results) {
1196                summary.tool_calls += 1;
1197                // What a sub-agent spent is what this turn spent: in the summary, the
1198                // step, and the cost cap, but not as one of this turn's steps.
1199                summary.add_usage(&delegated);
1200                step.usage = step.usage + delegated;
1201                breaker.record_cost(delegated.cost_usd);
1202                let (content, findings) = self.guardrails.observe(observation(&result));
1203                if let Some(findings) = findings {
1204                    self.recorder.event(
1205                        &sid,
1206                        "guardrail",
1207                        vec![
1208                            ("stage", json!("observation")),
1209                            ("tool", json!(call.name)),
1210                            ("findings", json!(findings)),
1211                        ],
1212                    );
1213                }
1214                emit(TurnEvent::ToolResult {
1215                    call,
1216                    result: &result,
1217                    observation: &content,
1218                    text: &format!("[tool] {} -> {}\n", call.name, summarize(&result)),
1219                });
1220                state.messages.push(Message {
1221                    tool_call_id: Some(call.id.clone()),
1222                    name: Some(call.name.clone()),
1223                    ..message(Role::Tool, &content)
1224                });
1225                let ok = result.ok;
1226                step.results.push(result);
1227                if let Err(tripped) = breaker.record_tool_result(ok) {
1228                    record_step(state, step);
1229                    return Err(tripped);
1230                }
1231            }
1232            // Every call has an observation by now, including any skipped because
1233            // the cancel landed mid-batch.
1234            record_step(state, step);
1235            self.checkpoint(state);
1236            if self.cancel.is_cancelled() {
1237                self.cancelled(state, breaker.steps(), &mut emit);
1238                return Ok(output);
1239            }
1240        }
1241    }
1242
1243    /// Save the session at a step boundary (beyond Python; checkpointing tier 1,
1244    /// `docs/checkpointing.md`), so a process that dies mid-turn keeps the steps it
1245    /// finished. Only called once every tool call in the history has its answer.
1246    /// The phase reads `execute` until the turn ends, when every exit sets `done`
1247    /// or `error`, so a saved state that still says `execute` is a turn cut off.
1248    /// A failed write loses one checkpoint, never the turn.
1249    fn checkpoint(&self, state: &mut AgentState) {
1250        state.phase = AgentPhase::Execute;
1251        if let Some(memory) = &self.memory {
1252            let _ = memory.persist(state);
1253        }
1254    }
1255
1256    /// Close out a cancelled turn and say so, as Python's `_cancelled`. The partial
1257    /// exchange is kept: the user stopped the agent, they did not undo it. The phase
1258    /// is `error`; "cancelled" is carried by the trace's `status` and `reason`.
1259    fn cancelled(&self, state: &mut AgentState, steps: u32, emit: &mut impl FnMut(TurnEvent<'_>)) {
1260        state.phase = AgentPhase::Error;
1261        self.recorder.event(
1262            &state.session_id,
1263            "turn_end",
1264            vec![
1265                ("status", json!("cancelled")),
1266                ("reason", json!("cancelled")),
1267                ("steps", json!(steps)),
1268            ],
1269        );
1270        emit(TurnEvent::Notice(CANCELLED_NOTICE));
1271    }
1272
1273    /// Run a step's tool calls and return their results in call order.
1274    ///
1275    /// Read-only calls may run concurrently with each other; side-effecting calls
1276    /// run sequentially, in the order the model asked for them, after the reads.
1277    /// Every approval is settled first, on this thread, because the gate may
1278    /// prompt a human.
1279    ///
1280    /// Beyond Python, adjacent delegations to specialist sub-agents among the
1281    /// calls left after the reads run at once (`Harness::fan_out`, `[agents]
1282    /// max_parallel`), so a write listed before a delegation still happens first.
1283    /// A batch with any specialty delegation takes this reads-first path whatever
1284    /// the number of reads; `spent` is what the turn has spent so far, for the
1285    /// fan-out's cost cap.
1286    async fn execute_batch(
1287        &self,
1288        calls: &[ToolCall],
1289        sid: &str,
1290        spent: f64,
1291    ) -> Vec<(ToolResult, Usage)> {
1292        let eligible = calls
1293            .iter()
1294            .filter(|call| self.parallel_eligible(call))
1295            .count();
1296        let specialty: Vec<bool> = calls
1297            .iter()
1298            .map(|call| self.is_specialty_delegation(call))
1299            .collect();
1300        let any_specialty = specialty.contains(&true);
1301        if !self.limits.parallel_tools || (eligible < 2 && !any_specialty) {
1302            // Strictly sequential: each call is resolved and run before the next.
1303            let mut results = Vec::with_capacity(calls.len());
1304            for call in calls {
1305                results.push(if self.cancel.is_cancelled() {
1306                    (not_executed(call, "cancelled"), Usage::default())
1307                } else {
1308                    self.execute_tool(call, sid).await
1309                });
1310            }
1311            return results;
1312        }
1313
1314        let mut settled: Vec<Option<(ToolResult, Usage)>> = Vec::with_capacity(calls.len());
1315        let mut may_parallel = Vec::with_capacity(calls.len());
1316        for call in calls {
1317            let (result, parallel) = self.resolve_call(call);
1318            settled.push(result.map(|result| (result, Usage::default())));
1319            may_parallel.push(parallel);
1320        }
1321        let pending = || (0..calls.len()).filter(|&index| settled[index].is_none());
1322        let reads: Vec<usize> = pending().filter(|&index| may_parallel[index]).collect();
1323        let writes: Vec<usize> = pending().filter(|&index| !may_parallel[index]).collect();
1324
1325        if reads.len() > 1 {
1326            let collected: Vec<(usize, ToolResult)> = std::thread::scope(|scope| {
1327                let handles: Vec<_> = reads
1328                    .iter()
1329                    .map(|&index| {
1330                        (
1331                            index,
1332                            scope.spawn(move || self.dispatch(&calls[index], sid)),
1333                        )
1334                    })
1335                    .collect();
1336                handles
1337                    .into_iter()
1338                    .map(|(index, handle)| {
1339                        let result = handle
1340                            .join()
1341                            .unwrap_or_else(|_| not_executed(&calls[index], "the tool panicked"));
1342                        (index, result)
1343                    })
1344                    .collect()
1345            });
1346            for (index, result) in collected {
1347                settled[index] = Some((result, Usage::default()));
1348            }
1349        } else {
1350            for &index in &reads {
1351                settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
1352            }
1353        }
1354        // Between calls, never mid-execution: a tool that started is allowed to finish.
1355        // A run of adjacent specialty delegations goes together; anything else
1356        // (a write, a plain delegation) runs alone and separates them.
1357        let mut next = 0;
1358        while next < writes.len() {
1359            let index = writes[next];
1360            let run_end = writes[next..]
1361                .iter()
1362                .position(|&index| !specialty[index])
1363                .map_or(writes.len(), |offset| next + offset);
1364            if specialty[index] && run_end - next > 1 {
1365                let group: Vec<usize> = writes[next..run_end].to_vec();
1366                let results = if self.cancel.is_cancelled() {
1367                    group
1368                        .iter()
1369                        .map(|&index| (not_executed(&calls[index], "cancelled"), Usage::default()))
1370                        .collect()
1371                } else {
1372                    let members: Vec<&ToolCall> =
1373                        group.iter().map(|&index| &calls[index]).collect();
1374                    self.fan_out(&members, sid, spent)
1375                };
1376                for (index, result) in group.into_iter().zip(results) {
1377                    settled[index] = Some(result);
1378                }
1379                next = run_end;
1380            } else {
1381                settled[index] = Some(self.dispatch_unless_cancelled(&calls[index], sid).await);
1382                next += 1;
1383            }
1384        }
1385
1386        settled
1387            .into_iter()
1388            .zip(calls)
1389            .map(|(result, call)| {
1390                result.unwrap_or_else(|| (not_executed(call, "skipped"), Usage::default()))
1391            })
1392            .collect()
1393    }
1394
1395    /// Could this call share a step with its siblings? Decided from the tool alone,
1396    /// never the gate, which may prompt and must be consulted exactly once.
1397    fn parallel_eligible(&self, call: &ToolCall) -> bool {
1398        call.invalid_arguments().is_none()
1399            && self
1400                .registry
1401                .get(&call.name)
1402                .is_some_and(|tool| !tool.side_effecting() && tool.parallel_safe())
1403    }
1404
1405    /// Decide one call without running it: `(settled result, may run in parallel)`.
1406    ///
1407    /// Arguments the provider could not parse are answered here, before the
1408    /// registry, the approval gate, or any tool sees them.
1409    fn resolve_call(&self, call: &ToolCall) -> (Option<ToolResult>, bool) {
1410        if let Some(raw) = call.invalid_arguments() {
1411            return (Some(invalid_arguments_result(call, raw)), false);
1412        }
1413        let Some(tool) = self.registry.get(&call.name) else {
1414            // The registry's own "Unknown tool" answer.
1415            return (Some(self.registry.dispatch(call, &self.context)), false);
1416        };
1417        // Under `run --agent`, a call outside the specialty's tools gets the
1418        // registry's refusal, which says so, before the gate is consulted.
1419        if !self.context.scope_allows(&call.name) {
1420            return (Some(self.registry.dispatch(call, &self.context)), false);
1421        }
1422        let decision = self.gate.decide(tool.as_ref(), call, &self.context);
1423        if !decision.approved {
1424            return (Some(not_executed(call, decision.reason)), false);
1425        }
1426        (None, !tool.side_effecting() && tool.parallel_safe())
1427    }
1428
1429    async fn dispatch_unless_cancelled(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1430        if self.cancel.is_cancelled() {
1431            (not_executed(call, "cancelled"), Usage::default())
1432        } else {
1433            self.dispatch_call(call, sid).await
1434        }
1435    }
1436
1437    /// Run one approved call: a delegation runs its sub-agent here, on this
1438    /// runtime; anything else goes to the registry.
1439    async fn dispatch_call(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1440        let request = match self.delegation(call, &self.context) {
1441            Some(request) => request,
1442            None => return (self.dispatch(call, sid), Usage::default()),
1443        };
1444        let mut span = self.tool_span(call);
1445        let (result, usage) = match request {
1446            Ok(request) => self.delegate(call, request, 1, &self.context).await,
1447            Err(invalid) => (invalid, Usage::default()),
1448        };
1449        span.set(vec![("tool.ok", json!(result.ok))]);
1450        self.tracer.end(span);
1451        self.record_tool_call(call, &result, sid);
1452        (result, usage)
1453    }
1454
1455    /// Run one approved call and record it in the flight recorder.
1456    fn dispatch(&self, call: &ToolCall, sid: &str) -> ToolResult {
1457        let mut span = self.tool_span(call);
1458        let result = self.registry.dispatch(call, &self.context);
1459        span.set(vec![("tool.ok", json!(result.ok))]);
1460        self.tracer.end(span);
1461        self.record_tool_call(call, &result, sid);
1462        result
1463    }
1464
1465    /// A `tool_call` span for `call`, as Python's `_dispatch_call` opens.
1466    pub(crate) fn tool_span(&self, call: &ToolCall) -> crate::otel::Span {
1467        self.tracer.start(
1468            "tool_call",
1469            vec![
1470                ("tool.name", json!(call.name)),
1471                ("gen_ai.tool.name", json!(call.name)),
1472            ],
1473        )
1474    }
1475
1476    pub(crate) fn record_tool_call(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
1477        self.recorder.event(
1478            sid,
1479            "tool_call",
1480            vec![
1481                ("tool", json!(call.name)),
1482                ("ok", json!(result.ok)),
1483                ("arguments", Value::Object(call.arguments.clone())),
1484                ("error", json!(result.error)),
1485            ],
1486        );
1487        self.record_repair(call, result, sid);
1488    }
1489
1490    /// Beyond Python: note a call whose JSON-string arguments the registry repaired
1491    /// (`tools::repair_arguments`). The call itself is recorded as the model sent it.
1492    pub(crate) fn record_repair(&self, call: &ToolCall, result: &ToolResult, sid: &str) {
1493        if let Some(repaired) = result.metadata.get(crate::tools::ARGS_REPAIRED_KEY) {
1494            self.recorder.event(
1495                sid,
1496                "tool_args_repaired",
1497                vec![("tool", json!(call.name)), ("arguments", repaired.clone())],
1498            );
1499        }
1500    }
1501
1502    /// Egress-scan tool-call arguments, the other way a secret leaves the harness.
1503    /// Findings are recorded, not acted on; the approval gate stops side effects.
1504    fn scan_tool_arguments(&self, calls: &[ToolCall], sid: &str) {
1505        if self.guardrails.egress == EgressMode::Off {
1506            return;
1507        }
1508        for call in calls {
1509            let payload = python_json_dumps(&Value::Object(call.arguments.clone()), false);
1510            let (report, _) = self.guardrails.inspect_egress(&payload);
1511            if report.flagged() {
1512                self.recorder.event(
1513                    sid,
1514                    "guardrail",
1515                    vec![
1516                        ("stage", json!("egress_tool_args")),
1517                        ("tool", json!(call.name)),
1518                        ("findings", json!(report.summary())),
1519                    ],
1520                );
1521            }
1522        }
1523    }
1524
1525    /// Resolve and run one call.
1526    async fn execute_tool(&self, call: &ToolCall, sid: &str) -> (ToolResult, Usage) {
1527        match self.resolve_call(call) {
1528            (Some(result), _) => (result, Usage::default()),
1529            (None, _) => self.dispatch_call(call, sid).await,
1530        }
1531    }
1532}
1533
1534/// The observation for a call that was not run.
1535pub(crate) fn not_executed(call: &ToolCall, reason: &str) -> ToolResult {
1536    ToolResult {
1537        call_id: call.id.clone(),
1538        name: call.name.clone(),
1539        ok: false,
1540        content: String::new(),
1541        error: Some(format!("Not executed: {reason}.")),
1542        metadata: serde_json::Map::new(),
1543    }
1544}
1545
1546/// Closing attributes for a `model_call` span, as Python's `_model_call_attributes`.
1547fn model_call_attributes(
1548    completion: Option<&crate::types::Completion>,
1549) -> Vec<(&'static str, Value)> {
1550    let Some(completion) = completion else {
1551        return vec![("agent86.completed", json!(false))];
1552    };
1553    let finish = completion
1554        .stop_reason
1555        .as_deref()
1556        .filter(|reason| !reason.is_empty())
1557        .map_or(Value::Null, |reason| json!([reason]));
1558    vec![
1559        ("agent86.completed", json!(true)),
1560        (
1561            "gen_ai.usage.input_tokens",
1562            json!(completion.usage.input_tokens),
1563        ),
1564        (
1565            "gen_ai.usage.output_tokens",
1566            json!(completion.usage.output_tokens),
1567        ),
1568        ("gen_ai.response.finish_reasons", finish),
1569        ("agent86.cost_usd", json!(completion.usage.cost_usd)),
1570        ("agent86.tool_calls", json!(completion.tool_calls.len())),
1571    ]
1572}
1573
1574/// Closing attributes for the `turn` span, read off `state.last_turn`, as Python's
1575/// `_turn_attributes`.
1576fn turn_attributes(state: &AgentState, model: &str) -> Vec<(&'static str, Value)> {
1577    let mut attributes = vec![("gen_ai.request.model", json!(model))];
1578    if let Some(summary) = &state.last_turn {
1579        attributes.extend([
1580            ("gen_ai.usage.input_tokens", json!(summary.input_tokens)),
1581            ("gen_ai.usage.output_tokens", json!(summary.output_tokens)),
1582            ("agent86.cost_usd", json!(summary.cost_usd)),
1583            ("agent86.steps", json!(summary.steps)),
1584            ("agent86.tool_calls", json!(summary.tool_calls)),
1585            ("agent86.duration_s", json!(summary.duration_s)),
1586            (
1587                "agent86.phase",
1588                serde_json::to_value(state.phase).unwrap_or(Value::Null),
1589            ),
1590        ]);
1591    }
1592    attributes
1593}
1594
1595/// Append `step` to the session and add its usage, as Python's `AgentState.record_step`.
1596fn record_step(state: &mut AgentState, step: Step) {
1597    state.usage = state.usage + step.usage;
1598    state.steps.push(step);
1599}
1600
1601fn message(role: Role, content: &str) -> Message {
1602    Message {
1603        role,
1604        content: content.to_owned(),
1605        tool_calls: Vec::new(),
1606        tool_call_id: None,
1607        name: None,
1608    }
1609}
1610
1611/// The observation for a tool call whose arguments were not valid JSON.
1612pub fn invalid_arguments_result(call: &ToolCall, raw: &str) -> ToolResult {
1613    let preview = truncate_chars(raw, 200);
1614    ToolResult {
1615        call_id: call.id.clone(),
1616        name: call.name.clone(),
1617        ok: false,
1618        content: String::new(),
1619        error: Some(format!(
1620            "invalid JSON in tool arguments: {} could not be parsed. \
1621             Call the tool again with its arguments as a single valid JSON object.",
1622            python_repr(&preview)
1623        )),
1624        metadata: serde_json::Map::new(),
1625    }
1626}
1627
1628/// The text the model observes for `result`. A failure keeps both its error and
1629/// any output, so the model can see what went wrong.
1630pub fn observation(result: &ToolResult) -> String {
1631    if result.ok {
1632        return result.content.clone();
1633    }
1634    let error = result.error.as_deref().unwrap_or_default().trim();
1635    let body = result.content.trim();
1636    match (error.is_empty(), body.is_empty()) {
1637        (false, false) => format!("{error}\n{body}"),
1638        (false, true) => error.to_owned(),
1639        (true, false) => body.to_owned(),
1640        (true, true) => "error".to_owned(),
1641    }
1642}
1643
1644/// Tool arguments as Python's `json.dumps(..., ensure_ascii=False)`, cut at 160 characters.
1645pub fn preview_arguments(arguments: &serde_json::Map<String, Value>) -> String {
1646    let text = python_json_dumps(&Value::Object(arguments.clone()), false);
1647    truncate_chars(&text, 160)
1648}
1649
1650/// The one-line summary of a result shown after `[tool] name ->`.
1651pub fn summarize(result: &ToolResult) -> String {
1652    if !result.ok {
1653        let error = result.error.as_deref().unwrap_or_default().trim();
1654        let content = result.content.trim();
1655        let detail = [error, content, "(failed)"]
1656            .into_iter()
1657            .find(|text| !text.is_empty())
1658            .unwrap_or("(failed)");
1659        return format!("error: {}", first_chars(first_line(detail), 160));
1660    }
1661    let content = result.content.trim();
1662    let head = if content.is_empty() {
1663        "(no output)"
1664    } else {
1665        first_line(content)
1666    };
1667    first_chars(head, 160)
1668}
1669
1670/// The first line of `text`, splitting on every boundary Python's `splitlines()` uses.
1671fn first_line(text: &str) -> &str {
1672    let is_break = |c: char| {
1673        matches!(
1674            c,
1675            '\n' | '\r'
1676                | '\u{b}'
1677                | '\u{c}'
1678                | '\u{1c}'
1679                | '\u{1d}'
1680                | '\u{1e}'
1681                | '\u{85}'
1682                | '\u{2028}'
1683                | '\u{2029}'
1684        )
1685    };
1686    text.split(is_break).next().unwrap_or_default()
1687}
1688
1689fn first_chars(text: &str, limit: usize) -> String {
1690    text.chars().take(limit).collect()
1691}
1692
1693/// `text` if it has at most `limit` characters, else its first `limit` and `" ..."`.
1694fn truncate_chars(text: &str, limit: usize) -> String {
1695    if text.chars().count() <= limit {
1696        text.to_owned()
1697    } else {
1698        format!("{} ...", first_chars(text, limit))
1699    }
1700}
1701
1702#[cfg(test)]
1703mod tests {
1704    use super::*;
1705    use serde_json::json;
1706
1707    fn limits() -> LimitsConfig {
1708        LimitsConfig {
1709            max_steps: 2,
1710            max_cost_usd: 1.0,
1711            max_wall_clock_s: 900,
1712            max_consecutive_errors: 1,
1713            max_context_tokens: 0,
1714            max_output_tokens: 8192,
1715            context_reserve_tokens: 4096,
1716            compaction: CompactionMode::Summarize,
1717            parallel_tools: true,
1718            tool_timeout_s: 60,
1719        }
1720    }
1721
1722    #[test]
1723    fn the_breaker_trips_on_steps_cost_and_error_streaks() {
1724        let mut breaker = CircuitBreaker::new(&limits());
1725        breaker.before_step().unwrap();
1726        breaker.record_step(&Usage::default());
1727        breaker.record_step(&Usage::default());
1728        assert_eq!(
1729            breaker.before_step().unwrap_err().to_string(),
1730            "Circuit tripped: step budget reached (2 steps)"
1731        );
1732
1733        let mut costly = CircuitBreaker::new(&limits());
1734        costly.record_step(&Usage {
1735            cost_usd: 1.25,
1736            ..Usage::default()
1737        });
1738        assert_eq!(
1739            costly.before_step().unwrap_err().to_string(),
1740            "Circuit tripped: cost cap reached ($1.2500 >= $1.0)"
1741        );
1742
1743        let mut errors = CircuitBreaker::new(&limits());
1744        errors.record_tool_result(false).unwrap();
1745        errors.record_tool_result(true).unwrap();
1746        errors.record_tool_result(false).unwrap();
1747        assert_eq!(
1748            errors.record_tool_result(false).unwrap_err().to_string(),
1749            "Circuit tripped: aborted after 2 consecutive tool errors"
1750        );
1751    }
1752
1753    fn result(ok: bool, content: &str, error: Option<&str>) -> ToolResult {
1754        ToolResult {
1755            call_id: "c".to_owned(),
1756            name: "t".to_owned(),
1757            ok,
1758            content: content.to_owned(),
1759            error: error.map(str::to_owned),
1760            metadata: serde_json::Map::new(),
1761        }
1762    }
1763
1764    #[test]
1765    fn observations_keep_both_error_and_output() {
1766        assert_eq!(observation(&result(true, "data", None)), "data");
1767        assert_eq!(
1768            observation(&result(false, " out ", Some(" bad "))),
1769            "bad\nout"
1770        );
1771        assert_eq!(observation(&result(false, "", Some("bad"))), "bad");
1772        assert_eq!(observation(&result(false, "", None)), "error");
1773    }
1774
1775    #[test]
1776    fn summaries_show_the_first_line() {
1777        assert_eq!(summarize(&result(true, "\n first\nsecond", None)), "first");
1778        assert_eq!(summarize(&result(true, "  ", None)), "(no output)");
1779        assert_eq!(
1780            summarize(&result(false, "", Some("No such file: x\nmore"))),
1781            "error: No such file: x"
1782        );
1783        assert_eq!(summarize(&result(false, "", None)), "error: (failed)");
1784        assert_eq!(summarize(&result(true, &"x".repeat(200), None)).len(), 160);
1785    }
1786
1787    #[test]
1788    fn previews_use_python_json_and_cut_at_160_characters() {
1789        let Value::Object(short) = json!({"path": "src/main.rs"}) else {
1790            unreachable!()
1791        };
1792        assert_eq!(preview_arguments(&short), r#"{"path": "src/main.rs"}"#);
1793
1794        let Value::Object(long) = json!({"path": "a".repeat(300)}) else {
1795            unreachable!()
1796        };
1797        let preview = preview_arguments(&long);
1798        assert!(preview.ends_with(" ..."));
1799        assert_eq!(preview.chars().count(), 164);
1800    }
1801
1802    #[test]
1803    fn invalid_json_is_reported_with_a_python_repr_preview() {
1804        let call = ToolCall {
1805            id: "c1".to_owned(),
1806            name: "read_file".to_owned(),
1807            arguments: serde_json::Map::new(),
1808        };
1809        let result = invalid_arguments_result(&call, "{\"path\": ");
1810        assert_eq!(
1811            result.error.as_deref(),
1812            Some(
1813                "invalid JSON in tool arguments: '{\"path\": ' could not be parsed. \
1814                 Call the tool again with its arguments as a single valid JSON object."
1815            )
1816        );
1817        assert!(!result.ok);
1818        assert_eq!(result.call_id, "c1");
1819    }
1820}