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