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